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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.