BUG-8494: Cleanup clustering-it-provider
[controller.git] / opendaylight / md-sal / samples / clustering-test-app / provider / src / main / java / org / opendaylight / controller / clustering / it / provider / impl / PrefixShardHandler.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.clustering.it.provider.impl;
10
11 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ID;
12 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ID_INT;
13 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ID_INTS;
14 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ITEM;
15
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.SettableFuture;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.concurrent.CompletionStage;
25 import java.util.stream.Collectors;
26 import javax.annotation.Nullable;
27 import org.opendaylight.controller.cluster.access.concepts.MemberName;
28 import org.opendaylight.controller.cluster.sharding.DistributedShardFactory;
29 import org.opendaylight.controller.cluster.sharding.DistributedShardFactory.DistributedShardRegistration;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
31 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
32 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeService;
38 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingConflictException;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
40 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CreatePrefixShardInput;
41 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemovePrefixShardInput;
42 import org.opendaylight.yangtools.yang.common.RpcError;
43 import org.opendaylight.yangtools.yang.common.RpcResult;
44 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
49 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
50 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
51 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 public class PrefixShardHandler {
56
57     private static final Logger LOG = LoggerFactory.getLogger(PrefixShardHandler.class);
58     private static final int MAX_PREFIX = 4;
59     private static final String PREFIX_TEMPLATE = "prefix-";
60
61     private final DistributedShardFactory shardFactory;
62     private final DOMDataTreeService domDataTreeService;
63     private final BindingNormalizedNodeSerializer serializer;
64
65     private final Map<YangInstanceIdentifier, DistributedShardRegistration> registrations =
66             Collections.synchronizedMap(new HashMap<>());
67
68     public PrefixShardHandler(final DistributedShardFactory shardFactory,
69                               final DOMDataTreeService domDataTreeService,
70                               final BindingNormalizedNodeSerializer serializer) {
71
72         this.shardFactory = shardFactory;
73         this.domDataTreeService = domDataTreeService;
74         this.serializer = serializer;
75     }
76
77     public ListenableFuture<RpcResult<Void>> onCreatePrefixShard(final CreatePrefixShardInput input) {
78
79         final SettableFuture<RpcResult<Void>> future = SettableFuture.create();
80
81         final CompletionStage<DistributedShardRegistration> completionStage;
82         final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());
83
84         try {
85              completionStage = shardFactory.createDistributedShard(
86                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, identifier),
87                     input.getReplicas().stream().map(MemberName::forName).collect(Collectors.toList()));
88
89             completionStage.thenAccept(registration -> {
90                 LOG.debug("Shard[{}] created successfully.", identifier);
91                 registrations.put(identifier, registration);
92
93                 final CheckedFuture<Void, TransactionCommitFailedException> ensureFuture = ensureListExists();
94                 Futures.addCallback(ensureFuture, new FutureCallback<Void>() {
95                     @Override
96                     public void onSuccess(@Nullable final Void result) {
97                         LOG.debug("Initial list write successful.");
98                         future.set(RpcResultBuilder.<Void>success().build());
99                     }
100
101                     @Override
102                     public void onFailure(final Throwable throwable) {
103                         LOG.warn("Shard[{}] creation failed:", identifier, throwable);
104
105                         final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
106                                 "Shard creation failed", "cluster-test-app", "", throwable);
107                         future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
108                     }
109                 });
110
111             });
112             completionStage.exceptionally(throwable -> {
113                 LOG.warn("Shard[{}] creation failed:", identifier, throwable);
114
115                 final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
116                         "Shard creation failed", "cluster-test-app", "", throwable);
117                 future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
118                 return null;
119             });
120         } catch (final DOMDataTreeShardingConflictException e) {
121             LOG.warn("Unable to register shard for: {}.", identifier);
122
123             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
124                     "Sharding conflict", "cluster-test-app", "", e);
125             future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
126         }
127
128         return future;
129     }
130
131     public ListenableFuture<RpcResult<Void>> onRemovePrefixShard(final RemovePrefixShardInput input) {
132
133         final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());
134         final DistributedShardRegistration registration = registrations.get(identifier);
135
136         if (registration == null) {
137             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "registration-missing",
138                     "No shard registered at this prefix.");
139             return Futures.immediateFuture(RpcResultBuilder.<Void>failed().withRpcError(error).build());
140         }
141
142         final SettableFuture<RpcResult<Void>> future = SettableFuture.create();
143
144         final CompletionStage<Void> close = registration.close();
145         close.thenRun(() -> future.set(RpcResultBuilder.<Void>success().build()));
146         close.exceptionally(throwable -> {
147             LOG.warn("Shard[{}] removal failed:", identifier, throwable);
148
149             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "remove-shard-failed",
150                     "Shard removal failed", "cluster-test-app", "", throwable);
151             future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
152             return null;
153         });
154
155         return future;
156     }
157
158     private CheckedFuture<Void, TransactionCommitFailedException> ensureListExists() {
159
160         final CollectionNodeBuilder<MapEntryNode, MapNode> mapBuilder = ImmutableNodes.mapNodeBuilder(ID_INT);
161
162         // hardcoded initial list population for parallel produce-transactions testing on multiple nodes
163         for (int i = 1; i < MAX_PREFIX; i++) {
164             mapBuilder.withChild(
165                     ImmutableNodes.mapEntryBuilder(ID_INT, ID, PREFIX_TEMPLATE + i)
166                             .withChild(ImmutableNodes.mapNodeBuilder(ITEM).build())
167                             .build());
168         }
169         final MapNode mapNode = mapBuilder.build();
170
171         final ContainerNode containerNode = ImmutableContainerNodeBuilder.create()
172                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ID_INTS))
173                 .withChild(mapNode)
174                 .build();
175
176         final DOMDataTreeProducer producer = domDataTreeService.createProducer(Collections.singleton(
177                 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY)));
178
179         final DOMDataTreeCursorAwareTransaction tx = producer.createTransaction(false);
180
181         final DOMDataTreeWriteCursor cursor =
182                 tx.createCursor(new DOMDataTreeIdentifier(
183                         LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY));
184
185         cursor.merge(containerNode.getIdentifier(), containerNode);
186         cursor.close();
187
188         final CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
189         Futures.addCallback(future, new FutureCallback<Void>() {
190             @Override
191             public void onSuccess(@Nullable final Void result) {
192                 try {
193                     LOG.debug("Closing producer for initial list.");
194                     producer.close();
195                 } catch (DOMDataTreeProducerException e) {
196                     LOG.warn("Error while closing producer.", e);
197                 }
198             }
199
200             @Override
201             public void onFailure(final Throwable throwable) {
202                 //NOOP handled by the caller of this method.
203             }
204         });
205         return future;
206     }
207 }