Bump versions to 4.0.0-SNAPSHOT
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / sharding / DistributedShardedDOMDataTree.java
1 /*
2  * Copyright (c) 2016, 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.cluster.sharding;
9
10 import static akka.actor.ActorRef.noSender;
11 import static com.google.common.base.Preconditions.checkArgument;
12 import static com.google.common.base.Preconditions.checkState;
13 import static java.util.Objects.requireNonNull;
14
15 import akka.actor.ActorRef;
16 import akka.actor.ActorSystem;
17 import akka.actor.PoisonPill;
18 import akka.actor.Props;
19 import akka.dispatch.Mapper;
20 import akka.dispatch.OnComplete;
21 import akka.pattern.Patterns;
22 import akka.util.Timeout;
23 import com.google.common.base.Throwables;
24 import com.google.common.collect.ClassToInstanceMap;
25 import com.google.common.collect.ForwardingObject;
26 import com.google.common.collect.ImmutableClassToInstanceMap;
27 import com.google.common.util.concurrent.FutureCallback;
28 import com.google.common.util.concurrent.Futures;
29 import com.google.common.util.concurrent.ListenableFuture;
30 import com.google.common.util.concurrent.MoreExecutors;
31 import com.google.common.util.concurrent.SettableFuture;
32 import com.google.common.util.concurrent.Uninterruptibles;
33 import java.util.AbstractMap.SimpleEntry;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.Comparator;
37 import java.util.EnumMap;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Map.Entry;
42 import java.util.Optional;
43 import java.util.Set;
44 import java.util.concurrent.CompletionStage;
45 import java.util.concurrent.ExecutionException;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.TimeoutException;
48 import org.checkerframework.checker.lock.qual.GuardedBy;
49 import org.opendaylight.controller.cluster.ActorSystemProvider;
50 import org.opendaylight.controller.cluster.access.concepts.MemberName;
51 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
52 import org.opendaylight.controller.cluster.databroker.actors.dds.SimpleDataStoreClientActor;
53 import org.opendaylight.controller.cluster.datastore.DistributedDataStoreInterface;
54 import org.opendaylight.controller.cluster.datastore.Shard;
55 import org.opendaylight.controller.cluster.datastore.config.Configuration;
56 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
57 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
58 import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
59 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
60 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
61 import org.opendaylight.controller.cluster.dom.api.CDSDataTreeProducer;
62 import org.opendaylight.controller.cluster.dom.api.CDSShardAccess;
63 import org.opendaylight.controller.cluster.sharding.ShardedDataTreeActor.ShardedDataTreeActorCreator;
64 import org.opendaylight.controller.cluster.sharding.messages.InitConfigListener;
65 import org.opendaylight.controller.cluster.sharding.messages.LookupPrefixShard;
66 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardRemovalLookup;
67 import org.opendaylight.controller.cluster.sharding.messages.ProducerCreated;
68 import org.opendaylight.controller.cluster.sharding.messages.ProducerRemoved;
69 import org.opendaylight.controller.cluster.sharding.messages.StartConfigShardLookup;
70 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
71 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
72 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
73 import org.opendaylight.mdsal.dom.api.DOMDataTreeListener;
74 import org.opendaylight.mdsal.dom.api.DOMDataTreeLoopException;
75 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeService;
78 import org.opendaylight.mdsal.dom.api.DOMDataTreeServiceExtension;
79 import org.opendaylight.mdsal.dom.api.DOMDataTreeShard;
80 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingConflictException;
81 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingService;
82 import org.opendaylight.mdsal.dom.broker.DOMDataTreeShardRegistration;
83 import org.opendaylight.mdsal.dom.broker.ShardedDOMDataTree;
84 import org.opendaylight.mdsal.dom.spi.DOMDataTreePrefixTable;
85 import org.opendaylight.mdsal.dom.spi.DOMDataTreePrefixTableEntry;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.prefix.shard.configuration.rev170110.PrefixShards;
87 import org.opendaylight.yangtools.concepts.ListenerRegistration;
88 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91 import scala.compat.java8.FutureConverters;
92 import scala.concurrent.Future;
93 import scala.concurrent.Promise;
94 import scala.concurrent.duration.FiniteDuration;
95
96 /**
97  * A layer on top of DOMDataTreeService that distributes producer/shard registrations to remote nodes via
98  * {@link ShardedDataTreeActor}. Also provides QoL method for addition of prefix based clustered shard into the system.
99  */
100 @Deprecated(forRemoval = true)
101 public class DistributedShardedDOMDataTree implements DOMDataTreeService, DOMDataTreeShardingService,
102         DistributedShardFactory {
103
104     private static final Logger LOG = LoggerFactory.getLogger(DistributedShardedDOMDataTree.class);
105
106     private static final int MAX_ACTOR_CREATION_RETRIES = 100;
107     private static final int ACTOR_RETRY_DELAY = 100;
108     private static final TimeUnit ACTOR_RETRY_TIME_UNIT = TimeUnit.MILLISECONDS;
109     private static final int LOOKUP_TASK_MAX_RETRIES = 100;
110     static final FiniteDuration SHARD_FUTURE_TIMEOUT_DURATION =
111             new FiniteDuration(LOOKUP_TASK_MAX_RETRIES * LOOKUP_TASK_MAX_RETRIES * 3, TimeUnit.SECONDS);
112     static final Timeout SHARD_FUTURE_TIMEOUT = new Timeout(SHARD_FUTURE_TIMEOUT_DURATION);
113
114     static final String ACTOR_ID = "ShardedDOMDataTreeFrontend";
115
116     private final ShardedDOMDataTree shardedDOMDataTree;
117     private final ActorSystem actorSystem;
118     private final DistributedDataStoreInterface distributedOperDatastore;
119     private final DistributedDataStoreInterface distributedConfigDatastore;
120
121     private final ActorRef shardedDataTreeActor;
122     private final MemberName memberName;
123
124     @GuardedBy("shards")
125     private final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shards =
126             DOMDataTreePrefixTable.create();
127
128     private final EnumMap<LogicalDatastoreType, Entry<DataStoreClient, ActorRef>> configurationShardMap =
129             new EnumMap<>(LogicalDatastoreType.class);
130
131     private final EnumMap<LogicalDatastoreType, PrefixedShardConfigWriter> writerMap =
132             new EnumMap<>(LogicalDatastoreType.class);
133
134     private final PrefixedShardConfigUpdateHandler updateHandler;
135
136     public DistributedShardedDOMDataTree(final ActorSystemProvider actorSystemProvider,
137                                          final DistributedDataStoreInterface distributedOperDatastore,
138                                          final DistributedDataStoreInterface distributedConfigDatastore) {
139         this.actorSystem = requireNonNull(actorSystemProvider).getActorSystem();
140         this.distributedOperDatastore = requireNonNull(distributedOperDatastore);
141         this.distributedConfigDatastore = requireNonNull(distributedConfigDatastore);
142         shardedDOMDataTree = new ShardedDOMDataTree();
143
144         shardedDataTreeActor = createShardedDataTreeActor(actorSystem,
145                 new ShardedDataTreeActorCreator()
146                         .setShardingService(this)
147                         .setActorSystem(actorSystem)
148                         .setClusterWrapper(distributedConfigDatastore.getActorUtils().getClusterWrapper())
149                         .setDistributedConfigDatastore(distributedConfigDatastore)
150                         .setDistributedOperDatastore(distributedOperDatastore)
151                         .setLookupTaskMaxRetries(LOOKUP_TASK_MAX_RETRIES),
152                 ACTOR_ID);
153
154         this.memberName = distributedConfigDatastore.getActorUtils().getCurrentMemberName();
155
156         updateHandler = new PrefixedShardConfigUpdateHandler(shardedDataTreeActor,
157                 distributedConfigDatastore.getActorUtils().getCurrentMemberName());
158
159         LOG.debug("{} - Starting prefix configuration shards", memberName);
160         createPrefixConfigShard(distributedConfigDatastore);
161         createPrefixConfigShard(distributedOperDatastore);
162     }
163
164     private static void createPrefixConfigShard(final DistributedDataStoreInterface dataStore) {
165         Configuration configuration = dataStore.getActorUtils().getConfiguration();
166         Collection<MemberName> memberNames = configuration.getUniqueMemberNamesForAllShards();
167         CreateShard createShardMessage =
168                 new CreateShard(new ModuleShardConfiguration(PrefixShards.QNAME.getNamespace(),
169                         "prefix-shard-configuration", ClusterUtils.PREFIX_CONFIG_SHARD_ID, ModuleShardStrategy.NAME,
170                         memberNames),
171                         Shard.builder(), dataStore.getActorUtils().getDatastoreContext());
172
173         dataStore.getActorUtils().getShardManager().tell(createShardMessage, noSender());
174     }
175
176     /**
177      * This will try to initialize prefix configuration shards upon their
178      * successful start. We need to create writers to these shards, so we can
179      * satisfy future {@link #createDistributedShard} and
180      * {@link #resolveShardAdditions} requests and update prefix configuration
181      * shards accordingly.
182      *
183      * <p>
184      * We also need to initialize listeners on these shards, so we can react
185      * on changes made on them by other cluster members or even by ourselves.
186      *
187      * <p>
188      * Finally, we need to be sure that default shards for both operational and
189      * configuration data stores are up and running and we have distributed
190      * shards frontend created for them.
191      *
192      * <p>
193      * This is intended to be invoked by blueprint as initialization method.
194      */
195     public void init() {
196         // create our writers to the configuration
197         try {
198             LOG.debug("{} - starting config shard lookup.", memberName);
199
200             // We have to wait for prefix config shards to be up and running
201             // so we can create datastore clients for them
202             handleConfigShardLookup().get(SHARD_FUTURE_TIMEOUT_DURATION.length(), SHARD_FUTURE_TIMEOUT_DURATION.unit());
203         } catch (InterruptedException | ExecutionException | TimeoutException e) {
204             throw new IllegalStateException("Prefix config shards not found", e);
205         }
206
207         try {
208             LOG.debug("{}: Prefix configuration shards ready - creating clients", memberName);
209             configurationShardMap.put(LogicalDatastoreType.CONFIGURATION,
210                     createDatastoreClient(ClusterUtils.PREFIX_CONFIG_SHARD_ID,
211                             distributedConfigDatastore.getActorUtils()));
212         } catch (final DOMDataTreeShardCreationFailedException e) {
213             throw new IllegalStateException(
214                     "Unable to create datastoreClient for config DS prefix configuration shard.", e);
215         }
216
217         try {
218             configurationShardMap.put(LogicalDatastoreType.OPERATIONAL,
219                     createDatastoreClient(ClusterUtils.PREFIX_CONFIG_SHARD_ID,
220                             distributedOperDatastore.getActorUtils()));
221
222         } catch (final DOMDataTreeShardCreationFailedException e) {
223             throw new IllegalStateException(
224                         "Unable to create datastoreClient for oper DS prefix configuration shard.", e);
225         }
226
227         writerMap.put(LogicalDatastoreType.CONFIGURATION, new PrefixedShardConfigWriter(
228                 configurationShardMap.get(LogicalDatastoreType.CONFIGURATION).getKey()));
229
230         writerMap.put(LogicalDatastoreType.OPERATIONAL, new PrefixedShardConfigWriter(
231                 configurationShardMap.get(LogicalDatastoreType.OPERATIONAL).getKey()));
232
233         updateHandler.initListener(distributedConfigDatastore, LogicalDatastoreType.CONFIGURATION);
234         updateHandler.initListener(distributedOperDatastore, LogicalDatastoreType.OPERATIONAL);
235
236         distributedConfigDatastore.getActorUtils().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
237         distributedOperDatastore.getActorUtils().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
238
239
240         //create shard registration for DEFAULT_SHARD
241         initDefaultShard(LogicalDatastoreType.CONFIGURATION);
242         initDefaultShard(LogicalDatastoreType.OPERATIONAL);
243     }
244
245     private ListenableFuture<List<Void>> handleConfigShardLookup() {
246
247         final ListenableFuture<Void> configFuture = lookupConfigShard(LogicalDatastoreType.CONFIGURATION);
248         final ListenableFuture<Void> operFuture = lookupConfigShard(LogicalDatastoreType.OPERATIONAL);
249
250         return Futures.allAsList(configFuture, operFuture);
251     }
252
253     private ListenableFuture<Void> lookupConfigShard(final LogicalDatastoreType type) {
254         final SettableFuture<Void> future = SettableFuture.create();
255
256         final Future<Object> ask =
257                 Patterns.ask(shardedDataTreeActor, new StartConfigShardLookup(type), SHARD_FUTURE_TIMEOUT);
258
259         ask.onComplete(new OnComplete<>() {
260             @Override
261             public void onComplete(final Throwable throwable, final Object result) {
262                 if (throwable != null) {
263                     future.setException(throwable);
264                 } else {
265                     future.set(null);
266                 }
267             }
268         }, actorSystem.dispatcher());
269
270         return future;
271     }
272
273     @Override
274     public <T extends DOMDataTreeListener> ListenerRegistration<T> registerListener(
275             final T listener, final Collection<DOMDataTreeIdentifier> subtrees,
276             final boolean allowRxMerges, final Collection<DOMDataTreeProducer> producers)
277             throws DOMDataTreeLoopException {
278         return shardedDOMDataTree.registerListener(listener, subtrees, allowRxMerges, producers);
279     }
280
281     @Override
282     public ClassToInstanceMap<DOMDataTreeServiceExtension> getExtensions() {
283         return ImmutableClassToInstanceMap.of();
284     }
285
286     @Override
287     public DOMDataTreeProducer createProducer(final Collection<DOMDataTreeIdentifier> subtrees) {
288         LOG.debug("{} - Creating producer for {}", memberName, subtrees);
289         final DOMDataTreeProducer producer = shardedDOMDataTree.createProducer(subtrees);
290
291         final Object response = distributedConfigDatastore.getActorUtils()
292                 .executeOperation(shardedDataTreeActor, new ProducerCreated(subtrees));
293         if (response == null) {
294             LOG.debug("{} - Received success from remote nodes, creating producer:{}", memberName, subtrees);
295             return new ProxyProducer(producer, subtrees, shardedDataTreeActor,
296                     distributedConfigDatastore.getActorUtils(), shards);
297         }
298
299         closeProducer(producer);
300
301         if (response instanceof Throwable) {
302             Throwables.throwIfUnchecked((Throwable) response);
303             throw new RuntimeException((Throwable) response);
304         }
305         throw new RuntimeException("Unexpected response to create producer received." + response);
306     }
307
308     @Override
309     public CompletionStage<DistributedShardRegistration> createDistributedShard(
310             final DOMDataTreeIdentifier prefix, final Collection<MemberName> replicaMembers)
311             throws DOMDataTreeShardingConflictException {
312
313         synchronized (shards) {
314             final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup =
315                     shards.lookup(prefix);
316             if (lookup != null && lookup.getValue().getPrefix().equals(prefix)) {
317                 throw new DOMDataTreeShardingConflictException(
318                         "Prefix " + prefix + " is already occupied by another shard.");
319             }
320         }
321
322         final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
323
324         final ListenableFuture<Void> writeFuture =
325                 writer.writeConfig(prefix.getRootIdentifier(), replicaMembers);
326
327         final Promise<DistributedShardRegistration> shardRegistrationPromise = akka.dispatch.Futures.promise();
328         Futures.addCallback(writeFuture, new FutureCallback<Void>() {
329             @Override
330             public void onSuccess(final Void result) {
331
332                 final Future<Object> ask =
333                         Patterns.ask(shardedDataTreeActor, new LookupPrefixShard(prefix), SHARD_FUTURE_TIMEOUT);
334
335                 shardRegistrationPromise.completeWith(ask.transform(
336                         new Mapper<Object, DistributedShardRegistration>() {
337                             @Override
338                             public DistributedShardRegistration apply(final Object parameter) {
339                                 return new DistributedShardRegistrationImpl(
340                                         prefix, shardedDataTreeActor, DistributedShardedDOMDataTree.this);
341                             }
342                         },
343                         new Mapper<Throwable, Throwable>() {
344                             @Override
345                             public Throwable apply(final Throwable throwable) {
346                                 return new DOMDataTreeShardCreationFailedException(
347                                         "Unable to create a cds shard.", throwable);
348                             }
349                         }, actorSystem.dispatcher()));
350             }
351
352             @Override
353             public void onFailure(final Throwable throwable) {
354                 shardRegistrationPromise.failure(
355                         new DOMDataTreeShardCreationFailedException("Unable to create a cds shard.", throwable));
356             }
357         }, MoreExecutors.directExecutor());
358
359         return FutureConverters.toJava(shardRegistrationPromise.future());
360     }
361
362     void resolveShardAdditions(final Set<DOMDataTreeIdentifier> additions) {
363         LOG.debug("{}: Resolving additions : {}", memberName, additions);
364         // we need to register the shards from top to bottom, so we need to atleast make sure the ordering reflects that
365         additions
366             .stream()
367             .sorted(Comparator.comparingInt(o -> o.getRootIdentifier().getPathArguments().size()))
368             .forEachOrdered(this::createShardFrontend);
369     }
370
371     void resolveShardRemovals(final Set<DOMDataTreeIdentifier> removals) {
372         LOG.debug("{}: Resolving removals : {}", memberName, removals);
373
374         // do we need to go from bottom to top?
375         removals.forEach(this::despawnShardFrontend);
376     }
377
378     private void createShardFrontend(final DOMDataTreeIdentifier prefix) {
379         LOG.debug("{}: Creating CDS shard for prefix: {}", memberName, prefix);
380         final String shardName = ClusterUtils.getCleanShardName(prefix.getRootIdentifier());
381         final DistributedDataStoreInterface distributedDataStore =
382                 prefix.getDatastoreType().equals(LogicalDatastoreType.CONFIGURATION)
383                         ? distributedConfigDatastore : distributedOperDatastore;
384
385         try (DOMDataTreeProducer producer = localCreateProducer(Collections.singletonList(prefix))) {
386             final Entry<DataStoreClient, ActorRef> entry =
387                     createDatastoreClient(shardName, distributedDataStore.getActorUtils());
388
389             final DistributedShardFrontend shard =
390                     new DistributedShardFrontend(distributedDataStore, entry.getKey(), prefix);
391
392             final DOMDataTreeShardRegistration<DOMDataTreeShard> reg =
393                     shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
394
395             synchronized (shards) {
396                 shards.store(prefix, reg);
397             }
398
399         } catch (final DOMDataTreeShardingConflictException e) {
400             LOG.error("{}: Prefix {} is already occupied by another shard",
401                     distributedConfigDatastore.getActorUtils().getClusterWrapper().getCurrentMemberName(), prefix, e);
402         } catch (DOMDataTreeProducerException e) {
403             LOG.error("Unable to close producer", e);
404         } catch (DOMDataTreeShardCreationFailedException e) {
405             LOG.error("Unable to create datastore client for shard {}", prefix, e);
406         }
407     }
408
409     private void despawnShardFrontend(final DOMDataTreeIdentifier prefix) {
410         LOG.debug("{}: Removing CDS shard for prefix: {}", memberName, prefix);
411         final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup;
412         synchronized (shards) {
413             lookup = shards.lookup(prefix);
414         }
415
416         if (lookup == null || !lookup.getValue().getPrefix().equals(prefix)) {
417             LOG.debug("{}: Received despawn for non-existing CDS shard frontend, prefix: {}, ignoring..",
418                     memberName, prefix);
419             return;
420         }
421
422         lookup.getValue().close();
423         // need to remove from our local table thats used for tracking
424         synchronized (shards) {
425             shards.remove(prefix);
426         }
427
428         final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
429         final ListenableFuture<Void> future = writer.removeConfig(prefix.getRootIdentifier());
430
431         Futures.addCallback(future, new FutureCallback<Void>() {
432             @Override
433             public void onSuccess(final Void result) {
434                 LOG.debug("{} - Succesfuly removed shard for {}", memberName, prefix);
435             }
436
437             @Override
438             public void onFailure(final Throwable throwable) {
439                 LOG.error("Removal of shard {} from configuration failed.", prefix, throwable);
440             }
441         }, MoreExecutors.directExecutor());
442     }
443
444     DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookupShardFrontend(
445             final DOMDataTreeIdentifier prefix) {
446         synchronized (shards) {
447             return shards.lookup(prefix);
448         }
449     }
450
451     DOMDataTreeProducer localCreateProducer(final Collection<DOMDataTreeIdentifier> prefix) {
452         return shardedDOMDataTree.createProducer(prefix);
453     }
454
455     @Override
456     public <T extends DOMDataTreeShard> ListenerRegistration<T> registerDataTreeShard(
457             final DOMDataTreeIdentifier prefix, final T shard, final DOMDataTreeProducer producer)
458                     throws DOMDataTreeShardingConflictException {
459
460         LOG.debug("Registering shard[{}] at prefix: {}", shard, prefix);
461
462         if (producer instanceof ProxyProducer) {
463             return shardedDOMDataTree.registerDataTreeShard(prefix, shard, ((ProxyProducer) producer).delegate());
464         }
465
466         return shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
467     }
468
469     @SuppressWarnings("checkstyle:IllegalCatch")
470     private Entry<DataStoreClient, ActorRef> createDatastoreClient(final String shardName, final ActorUtils actorUtils)
471             throws DOMDataTreeShardCreationFailedException {
472
473         LOG.debug("{}: Creating distributed datastore client for shard {}", memberName, shardName);
474         final Props distributedDataStoreClientProps =
475                 SimpleDataStoreClientActor.props(memberName, "Shard-" + shardName, actorUtils, shardName);
476
477         final ActorRef clientActor = actorSystem.actorOf(distributedDataStoreClientProps);
478         try {
479             return new SimpleEntry<>(SimpleDataStoreClientActor
480                     .getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS), clientActor);
481         } catch (final Exception e) {
482             LOG.error("{}: Failed to get actor for {}", distributedDataStoreClientProps, memberName, e);
483             clientActor.tell(PoisonPill.getInstance(), noSender());
484             throw new DOMDataTreeShardCreationFailedException(
485                     "Unable to create datastore client for shard{" + shardName + "}", e);
486         }
487     }
488
489     @SuppressWarnings("checkstyle:IllegalCatch")
490     private void initDefaultShard(final LogicalDatastoreType logicalDatastoreType) {
491
492         final PrefixedShardConfigWriter writer = writerMap.get(logicalDatastoreType);
493
494         if (writer.checkDefaultIsPresent()) {
495             LOG.debug("{}: Default shard for {} is already present in the config. Possibly saved in snapshot.",
496                     memberName, logicalDatastoreType);
497         } else {
498             try {
499                 // Currently the default shard configuration is present in the out-of-box modules.conf and is
500                 // expected to be present. So look up the local default shard here and create the frontend.
501
502                 // TODO we don't have to do it for config and operational default shard separately. Just one of them
503                 // should be enough
504                 final ActorUtils actorUtils = logicalDatastoreType == LogicalDatastoreType.CONFIGURATION
505                         ? distributedConfigDatastore.getActorUtils() : distributedOperDatastore.getActorUtils();
506
507                 final Optional<ActorRef> defaultLocalShardOptional =
508                         actorUtils.findLocalShard(ClusterUtils.getCleanShardName(YangInstanceIdentifier.empty()));
509
510                 if (defaultLocalShardOptional.isPresent()) {
511                     LOG.debug("{}: Default shard for {} is already started, creating just frontend", memberName,
512                             logicalDatastoreType);
513                     createShardFrontend(new DOMDataTreeIdentifier(logicalDatastoreType,
514                                 YangInstanceIdentifier.empty()));
515                 }
516
517                 // The local shard isn't present - we assume that means the local member isn't in the replica list
518                 // and will be dynamically created later via an explicit add-shard-replica request. This is the
519                 // bootstrapping mechanism to add a new node into an existing cluster. The following code to create
520                 // the default shard as a prefix shard is problematic in this scenario so it is commented out. Since
521                 // the default shard is a module-based shard by default, it makes sense to always treat it as such,
522                 // ie bootstrap it in the same manner as the special prefix-configuration and EOS shards.
523 //                final Collection<MemberName> names = distributedConfigDatastore.getActorUtils().getConfiguration()
524 //                        .getUniqueMemberNamesForAllShards();
525 //                Await.result(FutureConverters.toScala(createDistributedShard(
526 //                        new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.empty()), names)),
527 //                        SHARD_FUTURE_TIMEOUT_DURATION);
528 //            } catch (DOMDataTreeShardingConflictException e) {
529 //                LOG.debug("{}: Default shard for {} already registered, possibly due to other node doing it faster",
530 //                        memberName, logicalDatastoreType);
531             } catch (Exception e) {
532                 LOG.error("{}: Default shard initialization for {} failed", memberName, logicalDatastoreType, e);
533                 throw new RuntimeException(e);
534             }
535         }
536     }
537
538     private static void closeProducer(final DOMDataTreeProducer producer) {
539         try {
540             producer.close();
541         } catch (final DOMDataTreeProducerException e) {
542             LOG.error("Unable to close producer", e);
543         }
544     }
545
546     @SuppressWarnings("checkstyle:IllegalCatch")
547     private static ActorRef createShardedDataTreeActor(final ActorSystem actorSystem,
548                                                        final ShardedDataTreeActorCreator creator,
549                                                        final String shardDataTreeActorId) {
550         Exception lastException = null;
551
552         for (int i = 0; i < MAX_ACTOR_CREATION_RETRIES; i++) {
553             try {
554                 return actorSystem.actorOf(creator.props(), shardDataTreeActorId);
555             } catch (final Exception e) {
556                 lastException = e;
557                 Uninterruptibles.sleepUninterruptibly(ACTOR_RETRY_DELAY, ACTOR_RETRY_TIME_UNIT);
558                 LOG.debug("Could not create actor {} because of {} -"
559                                 + " waiting for sometime before retrying (retry count = {})",
560                         shardDataTreeActorId, e.getMessage(), i);
561             }
562         }
563
564         throw new IllegalStateException("Failed to create actor for ShardedDOMDataTree", lastException);
565     }
566
567     private class DistributedShardRegistrationImpl implements DistributedShardRegistration {
568
569         private final DOMDataTreeIdentifier prefix;
570         private final ActorRef shardedDataTreeActor;
571         private final DistributedShardedDOMDataTree distributedShardedDOMDataTree;
572
573         DistributedShardRegistrationImpl(final DOMDataTreeIdentifier prefix,
574                                          final ActorRef shardedDataTreeActor,
575                                          final DistributedShardedDOMDataTree distributedShardedDOMDataTree) {
576             this.prefix = prefix;
577             this.shardedDataTreeActor = shardedDataTreeActor;
578             this.distributedShardedDOMDataTree = distributedShardedDOMDataTree;
579         }
580
581         @Override
582         public CompletionStage<Void> close() {
583             // first despawn on the local node
584             distributedShardedDOMDataTree.despawnShardFrontend(prefix);
585             // update the config so the remote nodes are updated
586             final Future<Object> ask =
587                     Patterns.ask(shardedDataTreeActor, new PrefixShardRemovalLookup(prefix), SHARD_FUTURE_TIMEOUT);
588
589             final Future<Void> closeFuture = ask.transform(
590                     new Mapper<Object, Void>() {
591                         @Override
592                         public Void apply(final Object parameter) {
593                             return null;
594                         }
595                     },
596                     new Mapper<Throwable, Throwable>() {
597                         @Override
598                         public Throwable apply(final Throwable throwable) {
599                             return throwable;
600                         }
601                     }, actorSystem.dispatcher());
602
603             return FutureConverters.toJava(closeFuture);
604         }
605     }
606
607     // TODO what about producers created by this producer?
608     // They should also be CDSProducers
609     private static final class ProxyProducer extends ForwardingObject implements CDSDataTreeProducer {
610
611         private final DOMDataTreeProducer delegate;
612         private final Collection<DOMDataTreeIdentifier> subtrees;
613         private final ActorRef shardDataTreeActor;
614         private final ActorUtils actorUtils;
615         @GuardedBy("shardAccessMap")
616         private final Map<DOMDataTreeIdentifier, CDSShardAccessImpl> shardAccessMap = new HashMap<>();
617
618         // We don't have to guard access to shardTable in ProxyProducer.
619         // ShardTable's entries relevant to this ProxyProducer shouldn't
620         // change during producer's lifetime.
621         private final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shardTable;
622
623         ProxyProducer(final DOMDataTreeProducer delegate,
624                       final Collection<DOMDataTreeIdentifier> subtrees,
625                       final ActorRef shardDataTreeActor,
626                       final ActorUtils actorUtils,
627                       final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shardLayout) {
628             this.delegate = requireNonNull(delegate);
629             this.subtrees = requireNonNull(subtrees);
630             this.shardDataTreeActor = requireNonNull(shardDataTreeActor);
631             this.actorUtils = requireNonNull(actorUtils);
632             this.shardTable = requireNonNull(shardLayout);
633         }
634
635         @Override
636         public DOMDataTreeCursorAwareTransaction createTransaction(final boolean isolated) {
637             return delegate.createTransaction(isolated);
638         }
639
640         @Override
641         @SuppressWarnings("checkstyle:hiddenField")
642         public DOMDataTreeProducer createProducer(final Collection<DOMDataTreeIdentifier> subtrees) {
643             // TODO we probably don't need to distribute this on the remote nodes since once we have this producer
644             // open we surely have the rights to all the subtrees.
645             return delegate.createProducer(subtrees);
646         }
647
648         @Override
649         @SuppressWarnings("checkstyle:IllegalCatch")
650         public void close() throws DOMDataTreeProducerException {
651             delegate.close();
652
653             synchronized (shardAccessMap) {
654                 shardAccessMap.values().forEach(CDSShardAccessImpl::close);
655             }
656
657             final Object o = actorUtils.executeOperation(shardDataTreeActor, new ProducerRemoved(subtrees));
658             if (o instanceof DOMDataTreeProducerException) {
659                 throw (DOMDataTreeProducerException) o;
660             } else if (o instanceof Throwable) {
661                 throw new DOMDataTreeProducerException("Unable to close producer", (Throwable) o);
662             }
663         }
664
665         @Override
666         protected DOMDataTreeProducer delegate() {
667             return delegate;
668         }
669
670         @Override
671         public CDSShardAccess getShardAccess(final DOMDataTreeIdentifier subtree) {
672             checkArgument(subtrees.stream().anyMatch(dataTreeIdentifier -> dataTreeIdentifier.contains(subtree)),
673                 "Subtree %s is not controlled by this producer %s", subtree, this);
674
675             final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup =
676                     shardTable.lookup(subtree);
677             checkState(lookup != null, "Subtree %s is not contained in any registered shard.", subtree);
678
679             final DOMDataTreeIdentifier lookupId = lookup.getValue().getPrefix();
680
681             synchronized (shardAccessMap) {
682                 if (shardAccessMap.get(lookupId) != null) {
683                     return shardAccessMap.get(lookupId);
684                 }
685
686                 // TODO Maybe we can have static factory method and return the same instance
687                 // for same subtrees. But maybe it is not needed since there can be only one
688                 // producer attached to some subtree at a time. And also how we can close ShardAccess
689                 // then
690                 final CDSShardAccessImpl shardAccess = new CDSShardAccessImpl(lookupId, actorUtils);
691                 shardAccessMap.put(lookupId, shardAccess);
692                 return shardAccess;
693             }
694         }
695     }
696 }

©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.