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