8f711b3337c9fbdfc8087aa138df3d5a2712d007
[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.ProduceTransactionsHandler.ID;
12 import static org.opendaylight.controller.clustering.it.provider.impl.ProduceTransactionsHandler.ID_INT;
13 import static org.opendaylight.controller.clustering.it.provider.impl.ProduceTransactionsHandler.ID_INTS;
14 import static org.opendaylight.controller.clustering.it.provider.impl.ProduceTransactionsHandler.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.ProduceTransactionsOutput;
42 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemovePrefixShardInput;
43 import org.opendaylight.yangtools.yang.common.RpcError;
44 import org.opendaylight.yangtools.yang.common.RpcResult;
45 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
51 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
52 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 public class PrefixShardHandler {
57
58     private static final Logger LOG = LoggerFactory.getLogger(PrefixShardHandler.class);
59     private static final int MAX_PREFIX = 4;
60     private static final String PREFIX_TEMPLATE = "prefix-";
61
62     private final DistributedShardFactory shardFactory;
63     private final DOMDataTreeService domDataTreeService;
64     private final BindingNormalizedNodeSerializer serializer;
65
66     private final Map<YangInstanceIdentifier, DistributedShardRegistration> registrations =
67             Collections.synchronizedMap(new HashMap<>());
68
69     public PrefixShardHandler(final DistributedShardFactory shardFactory,
70                               final DOMDataTreeService domDataTreeService,
71                               final BindingNormalizedNodeSerializer serializer) {
72
73         this.shardFactory = shardFactory;
74         this.domDataTreeService = domDataTreeService;
75         this.serializer = serializer;
76     }
77
78     public ListenableFuture<RpcResult<Void>> onCreatePrefixShard(final CreatePrefixShardInput input) {
79
80         final SettableFuture<RpcResult<Void>> future = SettableFuture.create();
81
82         final CompletionStage<DistributedShardRegistration> completionStage;
83         final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());
84
85         try {
86              completionStage = shardFactory.createDistributedShard(
87                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, identifier),
88                     input.getReplicas().stream().map(MemberName::forName).collect(Collectors.toList()));
89
90             completionStage.thenAccept(registration -> {
91                 LOG.debug("Shard[{}] created successfully.", identifier);
92                 registrations.put(identifier, registration);
93
94                 final CheckedFuture<Void, TransactionCommitFailedException> ensureFuture = ensureListExists();
95                 Futures.addCallback(ensureFuture, new FutureCallback<Void>() {
96                     @Override
97                     public void onSuccess(@Nullable Void result) {
98                         LOG.debug("Initial list write successful.");
99                         future.set(RpcResultBuilder.<Void>success().build());
100                     }
101
102                     @Override
103                     public void onFailure(Throwable throwable) {
104                         LOG.warn("Shard[{}] creation failed:", identifier, throwable);
105
106                         final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
107                                 "Shard creation failed", "cluster-test-app", "", throwable);
108                         future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
109                     }
110                 });
111
112             });
113             completionStage.exceptionally(throwable -> {
114                 LOG.warn("Shard[{}] creation failed:", identifier, throwable);
115
116                 final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
117                         "Shard creation failed", "cluster-test-app", "", throwable);
118                 future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
119                 return null;
120             });
121         } catch (final DOMDataTreeShardingConflictException e) {
122             LOG.warn("Unable to register shard for: {}.", identifier);
123
124             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "create-shard-failed",
125                     "Sharding conflict", "cluster-test-app", "", e);
126             future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
127         }
128
129         return future;
130     }
131
132     public ListenableFuture<RpcResult<Void>> onRemovePrefixShard(final RemovePrefixShardInput input) {
133
134         final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());
135         final DistributedShardRegistration registration = registrations.get(identifier);
136
137         if (registration == null) {
138             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "registration-missing",
139                     "No shard registered at this prefix.");
140             return Futures.immediateFuture(RpcResultBuilder.<Void>failed().withRpcError(error).build());
141         }
142
143         final SettableFuture<RpcResult<Void>> future = SettableFuture.create();
144
145         final CompletionStage<Void> close = registration.close();
146         close.thenRun(() -> future.set(RpcResultBuilder.<Void>success().build()));
147         close.exceptionally(throwable -> {
148             LOG.warn("Shard[{}] removal failed:", identifier, throwable);
149
150             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "remove-shard-failed",
151                     "Shard removal failed", "cluster-test-app", "", throwable);
152             future.set(RpcResultBuilder.<Void>failed().withRpcError(error).build());
153             return null;
154         });
155
156         return future;
157     }
158
159     private CheckedFuture<Void, TransactionCommitFailedException> ensureListExists() {
160
161         final CollectionNodeBuilder<MapEntryNode, MapNode> mapBuilder = ImmutableNodes.mapNodeBuilder(ID_INT);
162
163         // hardcoded initial list population for parallel produce-transactions testing on multiple nodes
164         for (int i = 1; i < MAX_PREFIX; i++) {
165             mapBuilder.withChild(
166                     ImmutableNodes.mapEntryBuilder(ID_INT, ID, PREFIX_TEMPLATE + i)
167                             .withChild(ImmutableNodes.mapNodeBuilder(ITEM).build())
168                             .build());
169         }
170         final MapNode mapNode = mapBuilder.build();
171
172         final ContainerNode containerNode = ImmutableContainerNodeBuilder.create()
173                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ID_INTS))
174                 .withChild(mapNode)
175                 .build();
176
177         final DOMDataTreeProducer producer = domDataTreeService.createProducer(Collections.singleton(
178                 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY)));
179
180         final DOMDataTreeCursorAwareTransaction tx = producer.createTransaction(false);
181
182         final DOMDataTreeWriteCursor cursor =
183                 tx.createCursor(new DOMDataTreeIdentifier(
184                         LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY));
185
186         cursor.merge(containerNode.getIdentifier(), containerNode);
187         cursor.close();
188
189         final CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
190         Futures.addCallback(future, new FutureCallback<Void>() {
191             @Override
192             public void onSuccess(@Nullable Void result) {
193                 try {
194                     LOG.debug("Closing producer for initial list.");
195                     producer.close();
196                 } catch (DOMDataTreeProducerException e) {
197                     LOG.warn("Error while closing producer.", e);
198                 }
199             }
200
201             @Override
202             public void onFailure(Throwable throwable) {
203                 //NOOP handled by the caller of this method.
204             }
205         });
206         return future;
207     }
208 }