2 * Copyright (c) 2016 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.ForwardingObject;
25 import com.google.common.util.concurrent.FutureCallback;
26 import com.google.common.util.concurrent.Futures;
27 import com.google.common.util.concurrent.ListenableFuture;
28 import com.google.common.util.concurrent.SettableFuture;
29 import com.google.common.util.concurrent.Uninterruptibles;
30 import java.util.AbstractMap.SimpleEntry;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.EnumMap;
35 import java.util.List;
36 import java.util.Map.Entry;
38 import java.util.concurrent.CompletionStage;
39 import java.util.concurrent.ExecutionException;
40 import java.util.concurrent.TimeUnit;
41 import java.util.concurrent.TimeoutException;
42 import javax.annotation.Nonnull;
43 import javax.annotation.Nullable;
44 import javax.annotation.concurrent.GuardedBy;
45 import org.opendaylight.controller.cluster.ActorSystemProvider;
46 import org.opendaylight.controller.cluster.access.concepts.MemberName;
47 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
48 import org.opendaylight.controller.cluster.databroker.actors.dds.SimpleDataStoreClientActor;
49 import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
50 import org.opendaylight.controller.cluster.datastore.Shard;
51 import org.opendaylight.controller.cluster.datastore.config.Configuration;
52 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
53 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
54 import org.opendaylight.controller.cluster.datastore.shardstrategy.ModuleShardStrategy;
55 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
56 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
57 import org.opendaylight.controller.cluster.sharding.ShardedDataTreeActor.ShardedDataTreeActorCreator;
58 import org.opendaylight.controller.cluster.sharding.messages.InitConfigListener;
59 import org.opendaylight.controller.cluster.sharding.messages.LookupPrefixShard;
60 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardRemovalLookup;
61 import org.opendaylight.controller.cluster.sharding.messages.ProducerCreated;
62 import org.opendaylight.controller.cluster.sharding.messages.ProducerRemoved;
63 import org.opendaylight.controller.cluster.sharding.messages.StartConfigShardLookup;
64 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
65 import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction;
66 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
67 import org.opendaylight.mdsal.dom.api.DOMDataTreeListener;
68 import org.opendaylight.mdsal.dom.api.DOMDataTreeLoopException;
69 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer;
70 import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException;
71 import org.opendaylight.mdsal.dom.api.DOMDataTreeService;
72 import org.opendaylight.mdsal.dom.api.DOMDataTreeShard;
73 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingConflictException;
74 import org.opendaylight.mdsal.dom.api.DOMDataTreeShardingService;
75 import org.opendaylight.mdsal.dom.broker.DOMDataTreeShardRegistration;
76 import org.opendaylight.mdsal.dom.broker.ShardedDOMDataTree;
77 import org.opendaylight.mdsal.dom.spi.DOMDataTreePrefixTable;
78 import org.opendaylight.mdsal.dom.spi.DOMDataTreePrefixTableEntry;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.clustering.prefix.shard.configuration.rev170110.PrefixShards;
80 import org.opendaylight.yangtools.concepts.ListenerRegistration;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import scala.compat.java8.FutureConverters;
85 import scala.concurrent.Await;
86 import scala.concurrent.Future;
87 import scala.concurrent.Promise;
88 import scala.concurrent.duration.FiniteDuration;
91 * A layer on top of DOMDataTreeService that distributes producer/shard registrations to remote nodes via
92 * {@link ShardedDataTreeActor}. Also provides QoL method for addition of prefix based clustered shard into the system.
94 public class DistributedShardedDOMDataTree implements DOMDataTreeService, DOMDataTreeShardingService,
95 DistributedShardFactory {
97 private static final Logger LOG = LoggerFactory.getLogger(DistributedShardedDOMDataTree.class);
99 private static final int MAX_ACTOR_CREATION_RETRIES = 100;
100 private static final int ACTOR_RETRY_DELAY = 100;
101 private static final TimeUnit ACTOR_RETRY_TIME_UNIT = TimeUnit.MILLISECONDS;
102 private static final int LOOKUP_TASK_MAX_RETRIES = 100;
103 static final FiniteDuration SHARD_FUTURE_TIMEOUT_DURATION =
104 new FiniteDuration(LOOKUP_TASK_MAX_RETRIES * LOOKUP_TASK_MAX_RETRIES * 3, TimeUnit.SECONDS);
105 static final Timeout SHARD_FUTURE_TIMEOUT = new Timeout(SHARD_FUTURE_TIMEOUT_DURATION);
107 static final String ACTOR_ID = "ShardedDOMDataTreeFrontend";
109 private final ShardedDOMDataTree shardedDOMDataTree;
110 private final ActorSystem actorSystem;
111 private final DistributedDataStore distributedOperDatastore;
112 private final DistributedDataStore distributedConfigDatastore;
114 private final ActorRef shardedDataTreeActor;
115 private final MemberName memberName;
118 private final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shards =
119 DOMDataTreePrefixTable.create();
121 private final EnumMap<LogicalDatastoreType, DistributedShardRegistration> defaultShardRegistrations =
122 new EnumMap<>(LogicalDatastoreType.class);
124 private final EnumMap<LogicalDatastoreType, Entry<DataStoreClient, ActorRef>> configurationShardMap =
125 new EnumMap<>(LogicalDatastoreType.class);
127 private final EnumMap<LogicalDatastoreType, PrefixedShardConfigWriter> writerMap =
128 new EnumMap<>(LogicalDatastoreType.class);
130 private final PrefixedShardConfigUpdateHandler updateHandler;
132 public DistributedShardedDOMDataTree(final ActorSystemProvider actorSystemProvider,
133 final DistributedDataStore distributedOperDatastore,
134 final DistributedDataStore distributedConfigDatastore) {
135 this.actorSystem = Preconditions.checkNotNull(actorSystemProvider).getActorSystem();
136 this.distributedOperDatastore = Preconditions.checkNotNull(distributedOperDatastore);
137 this.distributedConfigDatastore = Preconditions.checkNotNull(distributedConfigDatastore);
138 shardedDOMDataTree = new ShardedDOMDataTree();
140 shardedDataTreeActor = createShardedDataTreeActor(actorSystem,
141 new ShardedDataTreeActorCreator()
142 .setShardingService(this)
143 .setActorSystem(actorSystem)
144 .setClusterWrapper(distributedConfigDatastore.getActorContext().getClusterWrapper())
145 .setDistributedConfigDatastore(distributedConfigDatastore)
146 .setDistributedOperDatastore(distributedOperDatastore)
147 .setLookupTaskMaxRetries(LOOKUP_TASK_MAX_RETRIES),
150 this.memberName = distributedConfigDatastore.getActorContext().getCurrentMemberName();
152 updateHandler = new PrefixedShardConfigUpdateHandler(shardedDataTreeActor,
153 distributedConfigDatastore.getActorContext().getCurrentMemberName());
155 LOG.debug("{} - Starting prefix configuration shards", memberName);
156 createPrefixConfigShard(distributedConfigDatastore);
157 createPrefixConfigShard(distributedOperDatastore);
160 private void createPrefixConfigShard(final DistributedDataStore dataStore) {
161 Configuration configuration = dataStore.getActorContext().getConfiguration();
162 Collection<MemberName> memberNames = configuration.getUniqueMemberNamesForAllShards();
163 CreateShard createShardMessage =
164 new CreateShard(new ModuleShardConfiguration(PrefixShards.QNAME.getNamespace(),
165 "prefix-shard-configuration", ClusterUtils.PREFIX_CONFIG_SHARD_ID, ModuleShardStrategy.NAME,
167 Shard.builder(), dataStore.getActorContext().getDatastoreContext());
169 dataStore.getActorContext().getShardManager().tell(createShardMessage, noSender());
173 * This will try to initialize prefix configuration shards upon their
174 * successful start. We need to create writers to these shards, so we can
175 * satisfy future {@link #createDistributedShard} and
176 * {@link #resolveShardAdditions} requests and update prefix configuration
177 * shards accordingly.
180 * We also need to initialize listeners on these shards, so we can react
181 * on changes made on them by other cluster members or even by ourselves.
184 * Finally, we need to be sure that default shards for both operational and
185 * configuration data stores are up and running and we have distributed
186 * shards frontend created for them.
189 // create our writers to the configuration
191 LOG.debug("{} - starting config shard lookup.",
192 distributedConfigDatastore.getActorContext().getCurrentMemberName());
194 // We have to wait for prefix config shards to be up and running
195 // so we can create datastore clients for them
196 handleConfigShardLookup().get(SHARD_FUTURE_TIMEOUT_DURATION.length(), SHARD_FUTURE_TIMEOUT_DURATION.unit());
198 LOG.debug("Prefix configuration shards ready - creating clients");
200 } catch (InterruptedException | ExecutionException | TimeoutException e) {
201 throw new IllegalStateException("Prefix config shards not found", e);
205 LOG.debug("Prefix configuration shards ready - creating clients");
206 configurationShardMap.put(LogicalDatastoreType.CONFIGURATION,
207 createDatastoreClient(ClusterUtils.PREFIX_CONFIG_SHARD_ID,
208 distributedConfigDatastore.getActorContext()));
209 } catch (final DOMDataTreeShardCreationFailedException e) {
210 throw new IllegalStateException(
211 "Unable to create datastoreClient for config DS prefix configuration shard.", e);
215 configurationShardMap.put(LogicalDatastoreType.OPERATIONAL,
216 createDatastoreClient(ClusterUtils.PREFIX_CONFIG_SHARD_ID,
217 distributedOperDatastore.getActorContext()));
219 } catch (final DOMDataTreeShardCreationFailedException e) {
220 throw new IllegalStateException(
221 "Unable to create datastoreClient for oper DS prefix configuration shard.", e);
224 writerMap.put(LogicalDatastoreType.CONFIGURATION, new PrefixedShardConfigWriter(
225 configurationShardMap.get(LogicalDatastoreType.CONFIGURATION).getKey()));
227 writerMap.put(LogicalDatastoreType.OPERATIONAL, new PrefixedShardConfigWriter(
228 configurationShardMap.get(LogicalDatastoreType.OPERATIONAL).getKey()));
230 updateHandler.initListener(distributedConfigDatastore, LogicalDatastoreType.CONFIGURATION);
231 updateHandler.initListener(distributedOperDatastore, LogicalDatastoreType.OPERATIONAL);
233 distributedConfigDatastore.getActorContext().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
234 distributedOperDatastore.getActorContext().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
237 //create shard registration for DEFAULT_SHARD
239 defaultShardRegistrations.put(LogicalDatastoreType.CONFIGURATION,
240 initDefaultShard(LogicalDatastoreType.CONFIGURATION));
241 } catch (final InterruptedException | ExecutionException e) {
242 throw new IllegalStateException("Unable to create default shard frontend for config shard", e);
246 defaultShardRegistrations.put(LogicalDatastoreType.OPERATIONAL,
247 initDefaultShard(LogicalDatastoreType.OPERATIONAL));
248 } catch (final InterruptedException | ExecutionException e) {
249 throw new IllegalStateException("Unable to create default shard frontend for operational shard", e);
253 private ListenableFuture<List<Void>> handleConfigShardLookup() {
255 final ListenableFuture<Void> configFuture = lookupConfigShard(LogicalDatastoreType.CONFIGURATION);
256 final ListenableFuture<Void> operFuture = lookupConfigShard(LogicalDatastoreType.OPERATIONAL);
258 return Futures.allAsList(configFuture, operFuture);
261 private ListenableFuture<Void> lookupConfigShard(final LogicalDatastoreType type) {
262 final SettableFuture<Void> future = SettableFuture.create();
264 final Future<Object> ask =
265 Patterns.ask(shardedDataTreeActor, new StartConfigShardLookup(type), SHARD_FUTURE_TIMEOUT);
267 ask.onComplete(new OnComplete<Object>() {
269 public void onComplete(final Throwable throwable, final Object result) throws Throwable {
270 if (throwable != null) {
271 future.setException(throwable);
276 }, actorSystem.dispatcher());
283 public <T extends DOMDataTreeListener> ListenerRegistration<T> registerListener(
284 final T listener, final Collection<DOMDataTreeIdentifier> subtrees,
285 final boolean allowRxMerges, final Collection<DOMDataTreeProducer> producers)
286 throws DOMDataTreeLoopException {
287 return shardedDOMDataTree.registerListener(listener, subtrees, allowRxMerges, producers);
292 public DOMDataTreeProducer createProducer(@Nonnull final Collection<DOMDataTreeIdentifier> subtrees) {
293 LOG.debug("{} - Creating producer for {}",
294 distributedConfigDatastore.getActorContext().getClusterWrapper().getCurrentMemberName(), subtrees);
295 final DOMDataTreeProducer producer = shardedDOMDataTree.createProducer(subtrees);
297 final Object response = distributedConfigDatastore.getActorContext()
298 .executeOperation(shardedDataTreeActor, new ProducerCreated(subtrees));
299 if (response == null) {
300 LOG.debug("{} - Received success from remote nodes, creating producer:{}",
301 distributedConfigDatastore.getActorContext().getClusterWrapper().getCurrentMemberName(), subtrees);
302 return new ProxyProducer(producer, subtrees, shardedDataTreeActor,
303 distributedConfigDatastore.getActorContext());
304 } else if (response instanceof Exception) {
305 closeProducer(producer);
306 throw Throwables.propagate((Exception) response);
308 closeProducer(producer);
309 throw new RuntimeException("Unexpected response to create producer received." + response);
314 public CompletionStage<DistributedShardRegistration> createDistributedShard(
315 final DOMDataTreeIdentifier prefix, final Collection<MemberName> replicaMembers)
316 throws DOMDataTreeShardingConflictException {
318 synchronized (shards) {
319 final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup =
320 shards.lookup(prefix);
321 if (lookup != null && lookup.getValue().getPrefix().equals(prefix)) {
322 throw new DOMDataTreeShardingConflictException(
323 "Prefix " + prefix + " is already occupied by another shard.");
327 final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
329 final ListenableFuture<Void> writeFuture =
330 writer.writeConfig(prefix.getRootIdentifier(), replicaMembers);
332 final Promise<DistributedShardRegistration> shardRegistrationPromise = akka.dispatch.Futures.promise();
333 Futures.addCallback(writeFuture, new FutureCallback<Void>() {
335 public void onSuccess(@Nullable final Void result) {
337 final Future<Object> ask =
338 Patterns.ask(shardedDataTreeActor, new LookupPrefixShard(prefix), SHARD_FUTURE_TIMEOUT);
340 shardRegistrationPromise.completeWith(ask.transform(
341 new Mapper<Object, DistributedShardRegistration>() {
343 public DistributedShardRegistration apply(final Object parameter) {
344 return new DistributedShardRegistrationImpl(
345 prefix, shardedDataTreeActor, DistributedShardedDOMDataTree.this);
348 new Mapper<Throwable, Throwable>() {
350 public Throwable apply(final Throwable throwable) {
351 return new DOMDataTreeShardCreationFailedException(
352 "Unable to create a cds shard.", throwable);
354 }, actorSystem.dispatcher()));
358 public void onFailure(final Throwable throwable) {
359 shardRegistrationPromise.failure(
360 new DOMDataTreeShardCreationFailedException("Unable to create a cds shard.", throwable));
364 return FutureConverters.toJava(shardRegistrationPromise.future());
367 void resolveShardAdditions(final Set<DOMDataTreeIdentifier> additions) {
368 LOG.debug("Member {}: Resolving additions : {}", memberName, additions);
369 final ArrayList<DOMDataTreeIdentifier> list = new ArrayList<>(additions);
370 // we need to register the shards from top to bottom, so we need to atleast make sure the ordering reflects that
371 Collections.sort(list, (o1, o2) -> {
372 if (o1.getRootIdentifier().getPathArguments().size() < o2.getRootIdentifier().getPathArguments().size()) {
374 } else if (o1.getRootIdentifier().getPathArguments().size()
375 == o2.getRootIdentifier().getPathArguments().size()) {
381 list.forEach(this::createShardFrontend);
384 void resolveShardRemovals(final Set<DOMDataTreeIdentifier> removals) {
385 LOG.debug("Member {}: Resolving removals : {}", memberName, removals);
387 // do we need to go from bottom to top?
388 removals.forEach(this::despawnShardFrontend);
391 private void createShardFrontend(final DOMDataTreeIdentifier prefix) {
392 LOG.debug("Member {}: Creating CDS shard for prefix: {}", memberName, prefix);
393 final String shardName = ClusterUtils.getCleanShardName(prefix.getRootIdentifier());
394 final DistributedDataStore distributedDataStore =
395 prefix.getDatastoreType().equals(org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION)
396 ? distributedConfigDatastore : distributedOperDatastore;
398 try (final DOMDataTreeProducer producer = localCreateProducer(Collections.singletonList(prefix))) {
399 final Entry<DataStoreClient, ActorRef> entry =
400 createDatastoreClient(shardName, distributedDataStore.getActorContext());
402 final DistributedShardFrontend shard =
403 new DistributedShardFrontend(distributedDataStore, entry.getKey(), prefix);
405 @SuppressWarnings("unchecked")
406 final DOMDataTreeShardRegistration<DOMDataTreeShard> reg =
407 (DOMDataTreeShardRegistration) shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
409 synchronized (shards) {
410 shards.store(prefix, reg);
413 } catch (final DOMDataTreeShardingConflictException e) {
414 LOG.error("{}: Prefix {} is already occupied by another shard",
415 distributedConfigDatastore.getActorContext().getClusterWrapper().getCurrentMemberName(), prefix, e);
416 } catch (DOMDataTreeProducerException e) {
417 LOG.error("Unable to close producer", e);
418 } catch (DOMDataTreeShardCreationFailedException e) {
419 LOG.error("Unable to create datastore client for shard {}", prefix, e);
423 private void despawnShardFrontend(final DOMDataTreeIdentifier prefix) {
424 LOG.debug("Member {}: Removing CDS shard for prefix: {}", memberName, prefix);
425 final DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookup;
426 synchronized (shards) {
427 lookup = shards.lookup(prefix);
430 if (lookup == null || !lookup.getValue().getPrefix().equals(prefix)) {
431 LOG.debug("Member {}: Received despawn for non-existing CDS shard frontend, prefix: {}, ignoring..",
436 lookup.getValue().close();
437 // need to remove from our local table thats used for tracking
438 synchronized (shards) {
439 shards.remove(prefix);
442 final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
443 final ListenableFuture<Void> future = writer.removeConfig(prefix.getRootIdentifier());
445 Futures.addCallback(future, new FutureCallback<Void>() {
447 public void onSuccess(@Nullable Void result) {
448 LOG.debug("{} - Succesfuly removed shard for {}", memberName, prefix);
452 public void onFailure(Throwable throwable) {
453 LOG.error("Removal of shard {} from configuration failed.", prefix, throwable);
458 DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookupShardFrontend(
459 final DOMDataTreeIdentifier prefix) {
460 return shards.lookup(prefix);
464 DOMDataTreeProducer localCreateProducer(final Collection<DOMDataTreeIdentifier> prefix) {
465 return shardedDOMDataTree.createProducer(prefix);
470 public <T extends DOMDataTreeShard> ListenerRegistration<T> registerDataTreeShard(
471 @Nonnull final DOMDataTreeIdentifier prefix,
472 @Nonnull final T shard,
473 @Nonnull final DOMDataTreeProducer producer)
474 throws DOMDataTreeShardingConflictException {
476 LOG.debug("Registering shard[{}] at prefix: {}", shard, prefix);
478 if (producer instanceof ProxyProducer) {
479 return shardedDOMDataTree.registerDataTreeShard(prefix, shard, ((ProxyProducer) producer).delegate());
482 return shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
485 @SuppressWarnings("checkstyle:IllegalCatch")
486 private Entry<DataStoreClient, ActorRef> createDatastoreClient(
487 final String shardName, final ActorContext actorContext)
488 throws DOMDataTreeShardCreationFailedException {
490 LOG.debug("Creating distributed datastore client for shard {}", shardName);
491 final Props distributedDataStoreClientProps =
492 SimpleDataStoreClientActor.props(memberName, "Shard-" + shardName, actorContext, shardName);
494 final ActorRef clientActor = actorSystem.actorOf(distributedDataStoreClientProps);
496 return new SimpleEntry<>(SimpleDataStoreClientActor
497 .getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS), clientActor);
498 } catch (final Exception e) {
499 LOG.error("Failed to get actor for {}", distributedDataStoreClientProps, e);
500 clientActor.tell(PoisonPill.getInstance(), noSender());
501 throw new DOMDataTreeShardCreationFailedException(
502 "Unable to create datastore client for shard{" + shardName + "}", e);
506 @SuppressWarnings("checkstyle:IllegalCatch")
507 private DistributedShardRegistration initDefaultShard(final LogicalDatastoreType logicalDatastoreType)
508 throws ExecutionException, InterruptedException {
509 final Collection<MemberName> names =
510 distributedConfigDatastore.getActorContext().getConfiguration().getUniqueMemberNamesForAllShards();
512 final PrefixedShardConfigWriter writer = writerMap.get(logicalDatastoreType);
514 if (writer.checkDefaultIsPresent()) {
515 LOG.debug("Default shard for {} is already present in the config. Possibly saved in snapshot.",
516 logicalDatastoreType);
517 return new DistributedShardRegistrationImpl(
518 new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.EMPTY),
519 shardedDataTreeActor, this);
522 // There can be situation when there is already started default shard
523 // because it is present in modules.conf. In that case we have to create
524 // just frontend for default shard, but not shard itself
525 // TODO we don't have to do it for config and operational default shard
526 // separately. Just one of them should be enough
527 final ActorContext actorContext = logicalDatastoreType == LogicalDatastoreType.CONFIGURATION
528 ? distributedConfigDatastore.getActorContext() : distributedOperDatastore.getActorContext();
530 final Optional<ActorRef> defaultLocalShardOptional =
531 actorContext.findLocalShard(ClusterUtils.getCleanShardName(YangInstanceIdentifier.EMPTY));
533 if (defaultLocalShardOptional.isPresent()) {
534 LOG.debug("{} Default shard is already started, creating just frontend", logicalDatastoreType);
535 createShardFrontend(new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.EMPTY));
536 return new DistributedShardRegistrationImpl(
537 new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.EMPTY),
538 shardedDataTreeActor, this);
541 // we should probably only have one node create the default shards
542 return Await.result(FutureConverters.toScala(createDistributedShard(
543 new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.EMPTY), names)),
544 SHARD_FUTURE_TIMEOUT_DURATION);
545 } catch (DOMDataTreeShardingConflictException e) {
546 LOG.debug("Default shard already registered, possibly due to other node doing it faster");
547 return new DistributedShardRegistrationImpl(
548 new DOMDataTreeIdentifier(logicalDatastoreType, YangInstanceIdentifier.EMPTY),
549 shardedDataTreeActor, this);
550 } catch (Exception e) {
551 LOG.error("{} default shard initialization failed", logicalDatastoreType, e);
552 throw new RuntimeException(e);
557 private static void closeProducer(final DOMDataTreeProducer producer) {
560 } catch (final DOMDataTreeProducerException e) {
561 LOG.error("Unable to close producer", e);
565 @SuppressWarnings("checkstyle:IllegalCatch")
566 private static ActorRef createShardedDataTreeActor(final ActorSystem actorSystem,
567 final ShardedDataTreeActorCreator creator,
568 final String shardDataTreeActorId) {
569 Exception lastException = null;
571 for (int i = 0; i < MAX_ACTOR_CREATION_RETRIES; i++) {
573 return actorSystem.actorOf(creator.props(), shardDataTreeActorId);
574 } catch (final Exception e) {
576 Uninterruptibles.sleepUninterruptibly(ACTOR_RETRY_DELAY, ACTOR_RETRY_TIME_UNIT);
577 LOG.debug("Could not create actor {} because of {} -"
578 + " waiting for sometime before retrying (retry count = {})",
579 shardDataTreeActorId, e.getMessage(), i);
583 throw new IllegalStateException("Failed to create actor for ShardedDOMDataTree", lastException);
586 private class DistributedShardRegistrationImpl implements DistributedShardRegistration {
588 private final DOMDataTreeIdentifier prefix;
589 private final ActorRef shardedDataTreeActor;
590 private final DistributedShardedDOMDataTree distributedShardedDOMDataTree;
592 DistributedShardRegistrationImpl(final DOMDataTreeIdentifier prefix,
593 final ActorRef shardedDataTreeActor,
594 final DistributedShardedDOMDataTree distributedShardedDOMDataTree) {
595 this.prefix = prefix;
596 this.shardedDataTreeActor = shardedDataTreeActor;
597 this.distributedShardedDOMDataTree = distributedShardedDOMDataTree;
601 public CompletionStage<Void> close() {
602 // first despawn on the local node
603 distributedShardedDOMDataTree.despawnShardFrontend(prefix);
604 // update the config so the remote nodes are updated
605 final Future<Object> ask =
606 Patterns.ask(shardedDataTreeActor, new PrefixShardRemovalLookup(prefix), SHARD_FUTURE_TIMEOUT);
608 final Future<Void> closeFuture = ask.transform(
609 new Mapper<Object, Void>() {
611 public Void apply(Object parameter) {
615 new Mapper<Throwable, Throwable>() {
617 public Throwable apply(Throwable throwable) {
620 }, actorSystem.dispatcher());
622 return FutureConverters.toJava(closeFuture);
626 private static final class ProxyProducer extends ForwardingObject implements DOMDataTreeProducer {
628 private final DOMDataTreeProducer delegate;
629 private final Collection<DOMDataTreeIdentifier> subtrees;
630 private final ActorRef shardDataTreeActor;
631 private final ActorContext actorContext;
633 ProxyProducer(final DOMDataTreeProducer delegate,
634 final Collection<DOMDataTreeIdentifier> subtrees,
635 final ActorRef shardDataTreeActor,
636 final ActorContext actorContext) {
637 this.delegate = Preconditions.checkNotNull(delegate);
638 this.subtrees = Preconditions.checkNotNull(subtrees);
639 this.shardDataTreeActor = Preconditions.checkNotNull(shardDataTreeActor);
640 this.actorContext = Preconditions.checkNotNull(actorContext);
645 public DOMDataTreeCursorAwareTransaction createTransaction(final boolean isolated) {
646 return delegate.createTransaction(isolated);
651 public DOMDataTreeProducer createProducer(@Nonnull final Collection<DOMDataTreeIdentifier> subtrees) {
652 // TODO we probably don't need to distribute this on the remote nodes since once we have this producer
653 // open we surely have the rights to all the subtrees.
654 return delegate.createProducer(subtrees);
658 public void close() throws DOMDataTreeProducerException {
661 final Object o = actorContext.executeOperation(shardDataTreeActor, new ProducerRemoved(subtrees));
662 if (o instanceof DOMDataTreeProducerException) {
663 throw ((DOMDataTreeProducerException) o);
664 } else if (o instanceof Throwable) {
665 throw new DOMDataTreeProducerException("Unable to close producer", (Throwable) o);
670 protected DOMDataTreeProducer delegate() {