2 * Copyright (c) 2016, 2017 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.sharding;
11 import static akka.actor.ActorRef.noSender;
13 import akka.actor.ActorRef;
14 import akka.actor.ActorSystem;
15 import akka.actor.PoisonPill;
16 import akka.actor.Props;
17 import akka.dispatch.Mapper;
18 import akka.dispatch.OnComplete;
19 import akka.pattern.Patterns;
20 import akka.util.Timeout;
21 import com.google.common.base.Optional;
22 import com.google.common.base.Preconditions;
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.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.EnumMap;
38 import java.util.HashMap;
39 import java.util.List;
41 import java.util.Map.Entry;
43 import java.util.concurrent.CompletionStage;
44 import java.util.concurrent.ExecutionException;
45 import java.util.concurrent.TimeUnit;
46 import java.util.concurrent.TimeoutException;
47 import javax.annotation.Nonnull;
48 import javax.annotation.Nullable;
49 import javax.annotation.concurrent.GuardedBy;
50 import org.opendaylight.controller.cluster.ActorSystemProvider;
51 import org.opendaylight.controller.cluster.access.concepts.MemberName;
52 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
53 import org.opendaylight.controller.cluster.databroker.actors.dds.SimpleDataStoreClientActor;
54 import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
55 import org.opendaylight.controller.cluster.datastore.Shard;
56 import org.opendaylight.controller.cluster.datastore.config.Configuration;
57 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
58 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
59 import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
60 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
61 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
62 import org.opendaylight.controller.cluster.dom.api.CDSDataTreeProducer;
63 import org.opendaylight.controller.cluster.dom.api.CDSShardAccess;
64 import org.opendaylight.controller.cluster.sharding.ShardedDataTreeActor.ShardedDataTreeActorCreator;
65 import org.opendaylight.controller.cluster.sharding.messages.InitConfigListener;
66 import org.opendaylight.controller.cluster.sharding.messages.LookupPrefixShard;
67 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardRemovalLookup;
68 import org.opendaylight.controller.cluster.sharding.messages.ProducerCreated;
69 import org.opendaylight.controller.cluster.sharding.messages.ProducerRemoved;
70 import org.opendaylight.controller.cluster.sharding.messages.StartConfigShardLookup;
71 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
72 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
73 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
74 import org.opendaylight.mdsal.dom.api.DOMDataTreeListener;
75 import org.opendaylight.mdsal.dom.api.DOMDataTreeLoopException;
76 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
77 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
78 import org.opendaylight.mdsal.dom.api.DOMDataTreeService;
79 import org.opendaylight.mdsal.dom.api.DOMDataTreeServiceExtension;
80 import org.opendaylight.mdsal.dom.api.DOMDataTreeShard;
81 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingConflictException;
82 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingService;
83 import org.opendaylight.mdsal.dom.broker.DOMDataTreeShardRegistration;
84 import org.opendaylight.mdsal.dom.broker.ShardedDOMDataTree;
85 import org.opendaylight.mdsal.dom.spi.DOMDataTreePrefixTable;
86 import org.opendaylight.mdsal.dom.spi.DOMDataTreePrefixTableEntry;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.prefix.shard.configuration.rev170110.PrefixShards;
88 import org.opendaylight.yangtools.concepts.ListenerRegistration;
89 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
92 import scala.compat.java8.FutureConverters;
93 import scala.concurrent.Future;
94 import scala.concurrent.Promise;
95 import scala.concurrent.duration.FiniteDuration;
98 * A layer on top of DOMDataTreeService that distributes producer/shard registrations to remote nodes via
99 * {@link ShardedDataTreeActor}. Also provides QoL method for addition of prefix based clustered shard into the system.
101 public class DistributedShardedDOMDataTree implements DOMDataTreeService, DOMDataTreeShardingService,
102 DistributedShardFactory {
104 private static final Logger LOG = LoggerFactory.getLogger(DistributedShardedDOMDataTree.class);
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);
114 static final String ACTOR_ID = "ShardedDOMDataTreeFrontend";
116 private final ShardedDOMDataTree shardedDOMDataTree;
117 private final ActorSystem actorSystem;
118 private final AbstractDataStore distributedOperDatastore;
119 private final AbstractDataStore distributedConfigDatastore;
121 private final ActorRef shardedDataTreeActor;
122 private final MemberName memberName;
125 private final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shards =
126 DOMDataTreePrefixTable.create();
128 private final EnumMap<LogicalDatastoreType, Entry<DataStoreClient, ActorRef>> configurationShardMap =
129 new EnumMap<>(LogicalDatastoreType.class);
131 private final EnumMap<LogicalDatastoreType, PrefixedShardConfigWriter> writerMap =
132 new EnumMap<>(LogicalDatastoreType.class);
134 private final PrefixedShardConfigUpdateHandler updateHandler;
136 public DistributedShardedDOMDataTree(final ActorSystemProvider actorSystemProvider,
137 final AbstractDataStore distributedOperDatastore,
138 final AbstractDataStore distributedConfigDatastore) {
139 this.actorSystem = Preconditions.checkNotNull(actorSystemProvider).getActorSystem();
140 this.distributedOperDatastore = Preconditions.checkNotNull(distributedOperDatastore);
141 this.distributedConfigDatastore = Preconditions.checkNotNull(distributedConfigDatastore);
142 shardedDOMDataTree = new ShardedDOMDataTree();
144 shardedDataTreeActor = createShardedDataTreeActor(actorSystem,
145 new ShardedDataTreeActorCreator()
146 .setShardingService(this)
147 .setActorSystem(actorSystem)
148 .setClusterWrapper(distributedConfigDatastore.getActorContext().getClusterWrapper())
149 .setDistributedConfigDatastore(distributedConfigDatastore)
150 .setDistributedOperDatastore(distributedOperDatastore)
151 .setLookupTaskMaxRetries(LOOKUP_TASK_MAX_RETRIES),
154 this.memberName = distributedConfigDatastore.getActorContext().getCurrentMemberName();
156 updateHandler = new PrefixedShardConfigUpdateHandler(shardedDataTreeActor,
157 distributedConfigDatastore.getActorContext().getCurrentMemberName());
159 LOG.debug("{} - Starting prefix configuration shards", memberName);
160 createPrefixConfigShard(distributedConfigDatastore);
161 createPrefixConfigShard(distributedOperDatastore);
164 private static void createPrefixConfigShard(final AbstractDataStore dataStore) {
165 Configuration configuration = dataStore.getActorContext().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,
171 Shard.builder(), dataStore.getActorContext().getDatastoreContext());
173 dataStore.getActorContext().getShardManager().tell(createShardMessage, noSender());
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.
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.
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.
193 * This is intended to be invoked by blueprint as initialization method.
196 // create our writers to the configuration
198 LOG.debug("{} - starting config shard lookup.", memberName);
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);
208 LOG.debug("{}: Prefix configuration shards ready - creating clients", memberName);
209 configurationShardMap.put(LogicalDatastoreType.CONFIGURATION,
210 createDatastoreClient(ClusterUtils.PREFIX_CONFIG_SHARD_ID,
211 distributedConfigDatastore.getActorContext()));
212 } catch (final DOMDataTreeShardCreationFailedException e) {
213 throw new IllegalStateException(
214 "Unable to create datastoreClient for config DS prefix configuration shard.", e);
218 configurationShardMap.put(LogicalDatastoreType.OPERATIONAL,
219 createDatastoreClient(ClusterUtils.PREFIX_CONFIG_SHARD_ID,
220 distributedOperDatastore.getActorContext()));
222 } catch (final DOMDataTreeShardCreationFailedException e) {
223 throw new IllegalStateException(
224 "Unable to create datastoreClient for oper DS prefix configuration shard.", e);
227 writerMap.put(LogicalDatastoreType.CONFIGURATION, new PrefixedShardConfigWriter(
228 configurationShardMap.get(LogicalDatastoreType.CONFIGURATION).getKey()));
230 writerMap.put(LogicalDatastoreType.OPERATIONAL, new PrefixedShardConfigWriter(
231 configurationShardMap.get(LogicalDatastoreType.OPERATIONAL).getKey()));
233 updateHandler.initListener(distributedConfigDatastore, LogicalDatastoreType.CONFIGURATION);
234 updateHandler.initListener(distributedOperDatastore, LogicalDatastoreType.OPERATIONAL);
236 distributedConfigDatastore.getActorContext().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
237 distributedOperDatastore.getActorContext().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
240 //create shard registration for DEFAULT_SHARD
242 initDefaultShard(LogicalDatastoreType.CONFIGURATION);
243 } catch (final InterruptedException | ExecutionException e) {
244 throw new IllegalStateException("Unable to create default shard frontend for config shard", e);
248 initDefaultShard(LogicalDatastoreType.OPERATIONAL);
249 } catch (final InterruptedException | ExecutionException e) {
250 throw new IllegalStateException("Unable to create default shard frontend for operational shard", e);
254 private ListenableFuture<List<Void>> handleConfigShardLookup() {
256 final ListenableFuture<Void> configFuture = lookupConfigShard(LogicalDatastoreType.CONFIGURATION);
257 final ListenableFuture<Void> operFuture = lookupConfigShard(LogicalDatastoreType.OPERATIONAL);
259 return Futures.allAsList(configFuture, operFuture);
262 private ListenableFuture<Void> lookupConfigShard(final LogicalDatastoreType type) {
263 final SettableFuture<Void> future = SettableFuture.create();
265 final Future<Object> ask =
266 Patterns.ask(shardedDataTreeActor, new StartConfigShardLookup(type), SHARD_FUTURE_TIMEOUT);
268 ask.onComplete(new OnComplete<Object>() {
270 public void onComplete(final Throwable throwable, final Object result) throws Throwable {
271 if (throwable != null) {
272 future.setException(throwable);
277 }, actorSystem.dispatcher());
284 public <T extends DOMDataTreeListener> ListenerRegistration<T> registerListener(
285 final T listener, final Collection<DOMDataTreeIdentifier> subtrees,
286 final boolean allowRxMerges, final Collection<DOMDataTreeProducer> producers)
287 throws DOMDataTreeLoopException {
288 return shardedDOMDataTree.registerListener(listener, subtrees, allowRxMerges, producers);
292 public ClassToInstanceMap<DOMDataTreeServiceExtension> getExtensions() {
293 return ImmutableClassToInstanceMap.of();
298 public DOMDataTreeProducer createProducer(@Nonnull final Collection<DOMDataTreeIdentifier> subtrees) {
299 LOG.debug("{} - Creating producer for {}", memberName, subtrees);
300 final DOMDataTreeProducer producer = shardedDOMDataTree.createProducer(subtrees);
302 final Object response = distributedConfigDatastore.getActorContext()
303 .executeOperation(shardedDataTreeActor, new ProducerCreated(subtrees));
304 if (response == null) {
305 LOG.debug("{} - Received success from remote nodes, creating producer:{}", memberName, subtrees);
306 return new ProxyProducer(producer, subtrees, shardedDataTreeActor,
307 distributedConfigDatastore.getActorContext(), shards);
310 closeProducer(producer);
312 if (response instanceof Throwable) {
313 Throwables.throwIfUnchecked((Throwable) response);
314 throw new RuntimeException((Throwable) response);
316 throw new RuntimeException("Unexpected response to create producer received." + response);
320 public CompletionStage<DistributedShardRegistration> createDistributedShard(
321 final DOMDataTreeIdentifier prefix, final Collection<MemberName> replicaMembers)
322 throws DOMDataTreeShardingConflictException {
324 synchronized (shards) {
325 final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup =
326 shards.lookup(prefix);
327 if (lookup != null && lookup.getValue().getPrefix().equals(prefix)) {
328 throw new DOMDataTreeShardingConflictException(
329 "Prefix " + prefix + " is already occupied by another shard.");
333 final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
335 final ListenableFuture<Void> writeFuture =
336 writer.writeConfig(prefix.getRootIdentifier(), replicaMembers);
338 final Promise<DistributedShardRegistration> shardRegistrationPromise = akka.dispatch.Futures.promise();
339 Futures.addCallback(writeFuture, new FutureCallback<Void>() {
341 public void onSuccess(@Nullable final Void result) {
343 final Future<Object> ask =
344 Patterns.ask(shardedDataTreeActor, new LookupPrefixShard(prefix), SHARD_FUTURE_TIMEOUT);
346 shardRegistrationPromise.completeWith(ask.transform(
347 new Mapper<Object, DistributedShardRegistration>() {
349 public DistributedShardRegistration apply(final Object parameter) {
350 return new DistributedShardRegistrationImpl(
351 prefix, shardedDataTreeActor, DistributedShardedDOMDataTree.this);
354 new Mapper<Throwable, Throwable>() {
356 public Throwable apply(final Throwable throwable) {
357 return new DOMDataTreeShardCreationFailedException(
358 "Unable to create a cds shard.", throwable);
360 }, actorSystem.dispatcher()));
364 public void onFailure(final Throwable throwable) {
365 shardRegistrationPromise.failure(
366 new DOMDataTreeShardCreationFailedException("Unable to create a cds shard.", throwable));
368 }, MoreExecutors.directExecutor());
370 return FutureConverters.toJava(shardRegistrationPromise.future());
373 void resolveShardAdditions(final Set<DOMDataTreeIdentifier> additions) {
374 LOG.debug("{}: Resolving additions : {}", memberName, additions);
375 final ArrayList<DOMDataTreeIdentifier> list = new ArrayList<>(additions);
376 // we need to register the shards from top to bottom, so we need to atleast make sure the ordering reflects that
377 Collections.sort(list, (o1, o2) -> {
378 if (o1.getRootIdentifier().getPathArguments().size() < o2.getRootIdentifier().getPathArguments().size()) {
380 } else if (o1.getRootIdentifier().getPathArguments().size()
381 == o2.getRootIdentifier().getPathArguments().size()) {
387 list.forEach(this::createShardFrontend);
390 void resolveShardRemovals(final Set<DOMDataTreeIdentifier> removals) {
391 LOG.debug("{}: Resolving removals : {}", memberName, removals);
393 // do we need to go from bottom to top?
394 removals.forEach(this::despawnShardFrontend);
397 private void createShardFrontend(final DOMDataTreeIdentifier prefix) {
398 LOG.debug("{}: Creating CDS shard for prefix: {}", memberName, prefix);
399 final String shardName = ClusterUtils.getCleanShardName(prefix.getRootIdentifier());
400 final AbstractDataStore distributedDataStore =
401 prefix.getDatastoreType().equals(org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION)
402 ? distributedConfigDatastore : distributedOperDatastore;
404 try (DOMDataTreeProducer producer = localCreateProducer(Collections.singletonList(prefix))) {
405 final Entry<DataStoreClient, ActorRef> entry =
406 createDatastoreClient(shardName, distributedDataStore.getActorContext());
408 final DistributedShardFrontend shard =
409 new DistributedShardFrontend(distributedDataStore, entry.getKey(), prefix);
411 final DOMDataTreeShardRegistration<DOMDataTreeShard> reg =
412 shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
414 synchronized (shards) {
415 shards.store(prefix, reg);
418 } catch (final DOMDataTreeShardingConflictException e) {
419 LOG.error("{}: Prefix {} is already occupied by another shard",
420 distributedConfigDatastore.getActorContext().getClusterWrapper().getCurrentMemberName(), prefix, e);
421 } catch (DOMDataTreeProducerException e) {
422 LOG.error("Unable to close producer", e);
423 } catch (DOMDataTreeShardCreationFailedException e) {
424 LOG.error("Unable to create datastore client for shard {}", prefix, e);
428 private void despawnShardFrontend(final DOMDataTreeIdentifier prefix) {
429 LOG.debug("{}: Removing CDS shard for prefix: {}", memberName, prefix);
430 final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup;
431 synchronized (shards) {
432 lookup = shards.lookup(prefix);
435 if (lookup == null || !lookup.getValue().getPrefix().equals(prefix)) {
436 LOG.debug("{}: Received despawn for non-existing CDS shard frontend, prefix: {}, ignoring..",
441 lookup.getValue().close();
442 // need to remove from our local table thats used for tracking
443 synchronized (shards) {
444 shards.remove(prefix);
447 final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
448 final ListenableFuture<Void> future = writer.removeConfig(prefix.getRootIdentifier());
450 Futures.addCallback(future, new FutureCallback<Void>() {
452 public void onSuccess(@Nullable final Void result) {
453 LOG.debug("{} - Succesfuly removed shard for {}", memberName, prefix);
457 public void onFailure(final Throwable throwable) {
458 LOG.error("Removal of shard {} from configuration failed.", prefix, throwable);
460 }, MoreExecutors.directExecutor());
463 DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookupShardFrontend(
464 final DOMDataTreeIdentifier prefix) {
465 synchronized (shards) {
466 return shards.lookup(prefix);
470 DOMDataTreeProducer localCreateProducer(final Collection<DOMDataTreeIdentifier> prefix) {
471 return shardedDOMDataTree.createProducer(prefix);
476 public <T extends DOMDataTreeShard> ListenerRegistration<T> registerDataTreeShard(
477 @Nonnull final DOMDataTreeIdentifier prefix,
478 @Nonnull final T shard,
479 @Nonnull final DOMDataTreeProducer producer)
480 throws DOMDataTreeShardingConflictException {
482 LOG.debug("Registering shard[{}] at prefix: {}", shard, prefix);
484 if (producer instanceof ProxyProducer) {
485 return shardedDOMDataTree.registerDataTreeShard(prefix, shard, ((ProxyProducer) producer).delegate());
488 return shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
491 @SuppressWarnings("checkstyle:IllegalCatch")
492 private Entry<DataStoreClient, ActorRef> createDatastoreClient(
493 final String shardName, final ActorContext actorContext)
494 throws DOMDataTreeShardCreationFailedException {
496 LOG.debug("{}: Creating distributed datastore client for shard {}", memberName, shardName);
497 final Props distributedDataStoreClientProps =
498 SimpleDataStoreClientActor.props(memberName, "Shard-" + shardName, actorContext, shardName);
500 final ActorRef clientActor = actorSystem.actorOf(distributedDataStoreClientProps);
502 return new SimpleEntry<>(SimpleDataStoreClientActor
503 .getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS), clientActor);
504 } catch (final Exception e) {
505 LOG.error("{}: Failed to get actor for {}", distributedDataStoreClientProps, memberName, e);
506 clientActor.tell(PoisonPill.getInstance(), noSender());
507 throw new DOMDataTreeShardCreationFailedException(
508 "Unable to create datastore client for shard{" + shardName + "}", e);
512 @SuppressWarnings("checkstyle:IllegalCatch")
513 private void initDefaultShard(final LogicalDatastoreType logicalDatastoreType)
514 throws ExecutionException, InterruptedException {
516 final PrefixedShardConfigWriter writer = writerMap.get(logicalDatastoreType);
518 if (writer.checkDefaultIsPresent()) {
519 LOG.debug("{}: Default shard for {} is already present in the config. Possibly saved in snapshot.",
520 memberName, logicalDatastoreType);
523 // Currently the default shard configuration is present in the out-of-box modules.conf and is
524 // expected to be present. So look up the local default shard here and create the frontend.
526 // TODO we don't have to do it for config and operational default shard separately. Just one of them
528 final ActorContext actorContext = logicalDatastoreType == LogicalDatastoreType.CONFIGURATION
529 ? distributedConfigDatastore.getActorContext() : distributedOperDatastore.getActorContext();
531 final Optional<ActorRef> defaultLocalShardOptional =
532 actorContext.findLocalShard(ClusterUtils.getCleanShardName(YangInstanceIdentifier.EMPTY));
534 if (defaultLocalShardOptional.isPresent()) {
535 LOG.debug("{}: Default shard for {} is already started, creating just frontend", memberName,
536 logicalDatastoreType);
537 createShardFrontend(new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.EMPTY));
540 // The local shard isn't present - we assume that means the local member isn't in the replica list
541 // and will be dynamically created later via an explicit add-shard-replica request. This is the
542 // bootstrapping mechanism to add a new node into an existing cluster. The following code to create
543 // the default shard as a prefix shard is problematic in this scenario so it is commented out. Since
544 // the default shard is a module-based shard by default, it makes sense to always treat it as such,
545 // ie bootstrap it in the same manner as the special prefix-configuration and EOS shards.
546 // final Collection<MemberName> names = distributedConfigDatastore.getActorContext().getConfiguration()
547 // .getUniqueMemberNamesForAllShards();
548 // Await.result(FutureConverters.toScala(createDistributedShard(
549 // new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.EMPTY), names)),
550 // SHARD_FUTURE_TIMEOUT_DURATION);
551 // } catch (DOMDataTreeShardingConflictException e) {
552 // LOG.debug("{}: Default shard for {} already registered, possibly due to other node doing it faster",
553 // memberName, logicalDatastoreType);
554 } catch (Exception e) {
555 LOG.error("{}: Default shard initialization for {} failed", memberName, logicalDatastoreType, e);
556 throw new RuntimeException(e);
561 private static void closeProducer(final DOMDataTreeProducer producer) {
564 } catch (final DOMDataTreeProducerException e) {
565 LOG.error("Unable to close producer", e);
569 @SuppressWarnings("checkstyle:IllegalCatch")
570 private static ActorRef createShardedDataTreeActor(final ActorSystem actorSystem,
571 final ShardedDataTreeActorCreator creator,
572 final String shardDataTreeActorId) {
573 Exception lastException = null;
575 for (int i = 0; i < MAX_ACTOR_CREATION_RETRIES; i++) {
577 return actorSystem.actorOf(creator.props(), shardDataTreeActorId);
578 } catch (final Exception e) {
580 Uninterruptibles.sleepUninterruptibly(ACTOR_RETRY_DELAY, ACTOR_RETRY_TIME_UNIT);
581 LOG.debug("Could not create actor {} because of {} -"
582 + " waiting for sometime before retrying (retry count = {})",
583 shardDataTreeActorId, e.getMessage(), i);
587 throw new IllegalStateException("Failed to create actor for ShardedDOMDataTree", lastException);
590 private class DistributedShardRegistrationImpl implements DistributedShardRegistration {
592 private final DOMDataTreeIdentifier prefix;
593 private final ActorRef shardedDataTreeActor;
594 private final DistributedShardedDOMDataTree distributedShardedDOMDataTree;
596 DistributedShardRegistrationImpl(final DOMDataTreeIdentifier prefix,
597 final ActorRef shardedDataTreeActor,
598 final DistributedShardedDOMDataTree distributedShardedDOMDataTree) {
599 this.prefix = prefix;
600 this.shardedDataTreeActor = shardedDataTreeActor;
601 this.distributedShardedDOMDataTree = distributedShardedDOMDataTree;
605 public CompletionStage<Void> close() {
606 // first despawn on the local node
607 distributedShardedDOMDataTree.despawnShardFrontend(prefix);
608 // update the config so the remote nodes are updated
609 final Future<Object> ask =
610 Patterns.ask(shardedDataTreeActor, new PrefixShardRemovalLookup(prefix), SHARD_FUTURE_TIMEOUT);
612 final Future<Void> closeFuture = ask.transform(
613 new Mapper<Object, Void>() {
615 public Void apply(final Object parameter) {
619 new Mapper<Throwable, Throwable>() {
621 public Throwable apply(final Throwable throwable) {
624 }, actorSystem.dispatcher());
626 return FutureConverters.toJava(closeFuture);
630 // TODO what about producers created by this producer?
631 // They should also be CDSProducers
632 private static final class ProxyProducer extends ForwardingObject implements CDSDataTreeProducer {
634 private final DOMDataTreeProducer delegate;
635 private final Collection<DOMDataTreeIdentifier> subtrees;
636 private final ActorRef shardDataTreeActor;
637 private final ActorContext actorContext;
638 @GuardedBy("shardAccessMap")
639 private final Map<DOMDataTreeIdentifier, CDSShardAccessImpl> shardAccessMap = new HashMap<>();
641 // We don't have to guard access to shardTable in ProxyProducer.
642 // ShardTable's entries relevant to this ProxyProducer shouldn't
643 // change during producer's lifetime.
644 private final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shardTable;
646 ProxyProducer(final DOMDataTreeProducer delegate,
647 final Collection<DOMDataTreeIdentifier> subtrees,
648 final ActorRef shardDataTreeActor,
649 final ActorContext actorContext,
650 final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shardLayout) {
651 this.delegate = Preconditions.checkNotNull(delegate);
652 this.subtrees = Preconditions.checkNotNull(subtrees);
653 this.shardDataTreeActor = Preconditions.checkNotNull(shardDataTreeActor);
654 this.actorContext = Preconditions.checkNotNull(actorContext);
655 this.shardTable = Preconditions.checkNotNull(shardLayout);
660 public DOMDataTreeCursorAwareTransaction createTransaction(final boolean isolated) {
661 return delegate.createTransaction(isolated);
666 @SuppressWarnings("checkstyle:hiddenField")
667 public DOMDataTreeProducer createProducer(@Nonnull final Collection<DOMDataTreeIdentifier> subtrees) {
668 // TODO we probably don't need to distribute this on the remote nodes since once we have this producer
669 // open we surely have the rights to all the subtrees.
670 return delegate.createProducer(subtrees);
674 @SuppressWarnings("checkstyle:IllegalCatch")
675 public void close() throws DOMDataTreeProducerException {
678 synchronized (shardAccessMap) {
679 shardAccessMap.values().forEach(CDSShardAccessImpl::close);
682 final Object o = actorContext.executeOperation(shardDataTreeActor, new ProducerRemoved(subtrees));
683 if (o instanceof DOMDataTreeProducerException) {
684 throw (DOMDataTreeProducerException) o;
685 } else if (o instanceof Throwable) {
686 throw new DOMDataTreeProducerException("Unable to close producer", (Throwable) o);
691 protected DOMDataTreeProducer delegate() {
697 public CDSShardAccess getShardAccess(@Nonnull final DOMDataTreeIdentifier subtree) {
698 Preconditions.checkArgument(
699 subtrees.stream().anyMatch(dataTreeIdentifier -> dataTreeIdentifier.contains(subtree)),
700 "Subtree %s is not controlled by this producer %s", subtree, this);
702 final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup =
703 shardTable.lookup(subtree);
704 Preconditions.checkState(lookup != null, "Subtree %s is not contained in any registered shard.", subtree);
706 final DOMDataTreeIdentifier lookupId = lookup.getValue().getPrefix();
708 synchronized (shardAccessMap) {
709 if (shardAccessMap.get(lookupId) != null) {
710 return shardAccessMap.get(lookupId);
713 // TODO Maybe we can have static factory method and return the same instance
714 // for same subtrees. But maybe it is not needed since there can be only one
715 // producer attached to some subtree at a time. And also how we can close ShardAccess
717 final CDSShardAccessImpl shardAccess = new CDSShardAccessImpl(lookupId, actorContext);
718 shardAccessMap.put(lookupId, shardAccess);