Reduce JSR305 proliferation
[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 package org.opendaylight.controller.clustering.it.provider.impl;
9
10 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ID;
11 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ID_INT;
12 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ID_INTS;
13 import static org.opendaylight.controller.clustering.it.provider.impl.AbstractTransactionHandler.ITEM;
14
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import com.google.common.util.concurrent.SettableFuture;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.concurrent.CompletionStage;
24 import java.util.stream.Collectors;
25 import org.opendaylight.controller.cluster.access.concepts.MemberName;
26 import org.opendaylight.controller.cluster.sharding.DistributedShardFactory;
27 import org.opendaylight.controller.cluster.sharding.DistributedShardFactory.DistributedShardRegistration;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
30 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
31 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
32 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeService;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingConflictException;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor;
37 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CreatePrefixShardInput;
38 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CreatePrefixShardOutput;
39 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CreatePrefixShardOutputBuilder;
40 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemovePrefixShardInput;
41 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemovePrefixShardOutput;
42 import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemovePrefixShardOutputBuilder;
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<CreatePrefixShardOutput>> onCreatePrefixShard(
79             final CreatePrefixShardInput input) {
80
81         final SettableFuture<RpcResult<CreatePrefixShardOutput>> future = SettableFuture.create();
82
83         final CompletionStage<DistributedShardRegistration> completionStage;
84         final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());
85
86         try {
87             completionStage = shardFactory.createDistributedShard(
88                     new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, identifier),
89                     input.getReplicas().stream().map(MemberName::forName).collect(Collectors.toList()));
90
91             completionStage.thenAccept(registration -> {
92                 LOG.debug("Shard[{}] created successfully.", identifier);
93                 registrations.put(identifier, registration);
94
95                 final ListenableFuture<?> ensureFuture = ensureListExists();
96                 Futures.addCallback(ensureFuture, new FutureCallback<Object>() {
97                     @Override
98                     public void onSuccess(final Object result) {
99                         LOG.debug("Initial list write successful.");
100                         future.set(RpcResultBuilder.success(new CreatePrefixShardOutputBuilder().build()).build());
101                     }
102
103                     @Override
104                     public void onFailure(final Throwable throwable) {
105                         LOG.warn("Shard[{}] creation failed:", identifier, throwable);
106
107                         final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION,
108                                 "create-shard-failed", "Shard creation failed", "cluster-test-app", "", throwable);
109                         future.set(RpcResultBuilder.<CreatePrefixShardOutput>failed().withRpcError(error).build());
110                     }
111                 }, MoreExecutors.directExecutor());
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.<CreatePrefixShardOutput>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.<CreatePrefixShardOutput>failed().withRpcError(error).build());
127         }
128
129         return future;
130     }
131
132     public ListenableFuture<RpcResult<RemovePrefixShardOutput>> onRemovePrefixShard(
133             final RemovePrefixShardInput input) {
134
135         final YangInstanceIdentifier identifier = serializer.toYangInstanceIdentifier(input.getPrefix());
136         final DistributedShardRegistration registration = registrations.get(identifier);
137
138         if (registration == null) {
139             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "registration-missing",
140                     "No shard registered at this prefix.");
141             return Futures.immediateFuture(RpcResultBuilder.<RemovePrefixShardOutput>failed().withRpcError(error)
142                 .build());
143         }
144
145         final SettableFuture<RpcResult<RemovePrefixShardOutput>> future = SettableFuture.create();
146
147         final CompletionStage<Void> close = registration.close();
148         close.thenRun(() -> future.set(RpcResultBuilder.success(new RemovePrefixShardOutputBuilder().build()).build()));
149         close.exceptionally(throwable -> {
150             LOG.warn("Shard[{}] removal failed:", identifier, throwable);
151
152             final RpcError error = RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "remove-shard-failed",
153                     "Shard removal failed", "cluster-test-app", "", throwable);
154             future.set(RpcResultBuilder.<RemovePrefixShardOutput>failed().withRpcError(error).build());
155             return null;
156         });
157
158         return future;
159     }
160
161     private ListenableFuture<?> ensureListExists() {
162
163         final CollectionNodeBuilder<MapEntryNode, MapNode> mapBuilder = ImmutableNodes.mapNodeBuilder(ID_INT);
164
165         // hardcoded initial list population for parallel produce-transactions testing on multiple nodes
166         for (int i = 1; i < MAX_PREFIX; i++) {
167             mapBuilder.withChild(
168                     ImmutableNodes.mapEntryBuilder(ID_INT, ID, PREFIX_TEMPLATE + i)
169                             .withChild(ImmutableNodes.mapNodeBuilder(ITEM).build())
170                             .build());
171         }
172         final MapNode mapNode = mapBuilder.build();
173
174         final ContainerNode containerNode = ImmutableContainerNodeBuilder.create()
175                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ID_INTS))
176                 .withChild(mapNode)
177                 .build();
178
179         final DOMDataTreeProducer producer = domDataTreeService.createProducer(Collections.singleton(
180                 new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY)));
181
182         final DOMDataTreeCursorAwareTransaction tx = producer.createTransaction(false);
183
184         final DOMDataTreeWriteCursor cursor =
185                 tx.createCursor(new DOMDataTreeIdentifier(
186                         LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.EMPTY));
187
188         cursor.merge(containerNode.getIdentifier(), containerNode);
189         cursor.close();
190
191         final ListenableFuture<?> future = tx.commit();
192         Futures.addCallback(future, new FutureCallback<Object>() {
193             @Override
194             public void onSuccess(final Object result) {
195                 try {
196                     LOG.debug("Closing producer for initial list.");
197                     producer.close();
198                 } catch (DOMDataTreeProducerException e) {
199                     LOG.warn("Error while closing producer.", e);
200                 }
201             }
202
203             @Override
204             public void onFailure(final Throwable throwable) {
205                 //NOOP handled by the caller of this method.
206             }
207         }, MoreExecutors.directExecutor());
208         return future;
209     }
210 }