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