6e53a2791234977ce4e8362fbc07f01d79d88af5
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / sharding / DistributedShardedDOMDataTree.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.cluster.sharding;
10
11 import static akka.actor.ActorRef.noSender;
12
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;
37 import java.util.Set;
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;
89
90 /**
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.
93  */
94 public class DistributedShardedDOMDataTree implements DOMDataTreeService, DOMDataTreeShardingService,
95         DistributedShardFactory {
96
97     private static final Logger LOG = LoggerFactory.getLogger(DistributedShardedDOMDataTree.class);
98
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);
106
107     static final String ACTOR_ID = "ShardedDOMDataTreeFrontend";
108
109     private final ShardedDOMDataTree shardedDOMDataTree;
110     private final ActorSystem actorSystem;
111     private final DistributedDataStore distributedOperDatastore;
112     private final DistributedDataStore distributedConfigDatastore;
113
114     private final ActorRef shardedDataTreeActor;
115     private final MemberName memberName;
116
117     @GuardedBy("shards")
118     private final DOMDataTreePrefixTable<DOMDataTreeShardRegistration<DOMDataTreeShard>> shards =
119             DOMDataTreePrefixTable.create();
120
121     private final EnumMap<LogicalDatastoreType, DistributedShardRegistration> defaultShardRegistrations =
122             new EnumMap<>(LogicalDatastoreType.class);
123
124     private final EnumMap<LogicalDatastoreType, Entry<DataStoreClient, ActorRef>> configurationShardMap =
125             new EnumMap<>(LogicalDatastoreType.class);
126
127     private final EnumMap<LogicalDatastoreType, PrefixedShardConfigWriter> writerMap =
128             new EnumMap<>(LogicalDatastoreType.class);
129
130     private final PrefixedShardConfigUpdateHandler updateHandler;
131
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();
139
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),
148                 ACTOR_ID);
149
150         this.memberName = distributedConfigDatastore.getActorContext().getCurrentMemberName();
151
152         updateHandler = new PrefixedShardConfigUpdateHandler(shardedDataTreeActor,
153                 distributedConfigDatastore.getActorContext().getCurrentMemberName());
154
155         LOG.debug("{} - Starting prefix configuration shards", memberName);
156         createPrefixConfigShard(distributedConfigDatastore);
157         createPrefixConfigShard(distributedOperDatastore);
158     }
159
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,
166                         memberNames),
167                         Shard.builder(), dataStore.getActorContext().getDatastoreContext());
168
169         dataStore.getActorContext().getShardManager().tell(createShardMessage, noSender());
170     }
171
172     /**
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.
178      *
179      * <p>
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.
182      *
183      * <p>
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.
187      */
188     void init() {
189         // create our writers to the configuration
190         try {
191             LOG.debug("{} - starting config shard lookup.",
192                     distributedConfigDatastore.getActorContext().getCurrentMemberName());
193
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());
197
198             LOG.debug("Prefix configuration shards ready - creating clients");
199
200         } catch (InterruptedException | ExecutionException | TimeoutException e) {
201             throw new IllegalStateException("Prefix config shards not found", e);
202         }
203
204         try {
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);
212         }
213
214         try {
215             configurationShardMap.put(LogicalDatastoreType.OPERATIONAL,
216                     createDatastoreClient(ClusterUtils.PREFIX_CONFIG_SHARD_ID,
217                             distributedOperDatastore.getActorContext()));
218
219         } catch (final DOMDataTreeShardCreationFailedException e) {
220             throw new IllegalStateException(
221                         "Unable to create datastoreClient for oper DS prefix configuration shard.", e);
222         }
223
224         writerMap.put(LogicalDatastoreType.CONFIGURATION, new PrefixedShardConfigWriter(
225                 configurationShardMap.get(LogicalDatastoreType.CONFIGURATION).getKey()));
226
227         writerMap.put(LogicalDatastoreType.OPERATIONAL, new PrefixedShardConfigWriter(
228                 configurationShardMap.get(LogicalDatastoreType.OPERATIONAL).getKey()));
229
230         updateHandler.initListener(distributedConfigDatastore, LogicalDatastoreType.CONFIGURATION);
231         updateHandler.initListener(distributedOperDatastore, LogicalDatastoreType.OPERATIONAL);
232
233         distributedConfigDatastore.getActorContext().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
234         distributedOperDatastore.getActorContext().getShardManager().tell(InitConfigListener.INSTANCE, noSender());
235
236
237         //create shard registration for DEFAULT_SHARD
238         try {
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);
243         }
244
245         try {
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);
250         }
251     }
252
253     private ListenableFuture<List<Void>> handleConfigShardLookup() {
254
255         final ListenableFuture<Void> configFuture = lookupConfigShard(LogicalDatastoreType.CONFIGURATION);
256         final ListenableFuture<Void> operFuture = lookupConfigShard(LogicalDatastoreType.OPERATIONAL);
257
258         return Futures.allAsList(configFuture, operFuture);
259     }
260
261     private ListenableFuture<Void> lookupConfigShard(final LogicalDatastoreType type) {
262         final SettableFuture<Void> future = SettableFuture.create();
263
264         final Future<Object> ask =
265                 Patterns.ask(shardedDataTreeActor, new StartConfigShardLookup(type), SHARD_FUTURE_TIMEOUT);
266
267         ask.onComplete(new OnComplete<Object>() {
268             @Override
269             public void onComplete(final Throwable throwable, final Object result) throws Throwable {
270                 if (throwable != null) {
271                     future.setException(throwable);
272                 } else {
273                     future.set(null);
274                 }
275             }
276         }, actorSystem.dispatcher());
277
278         return future;
279     }
280
281     @Nonnull
282     @Override
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);
288     }
289
290     @Nonnull
291     @Override
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);
296
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);
307         } else {
308             closeProducer(producer);
309             throw new RuntimeException("Unexpected response to create producer received." + response);
310         }
311     }
312
313     @Override
314     public CompletionStage<DistributedShardRegistration> createDistributedShard(
315             final DOMDataTreeIdentifier prefix, final Collection<MemberName> replicaMembers)
316             throws DOMDataTreeShardingConflictException {
317
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.");
324             }
325         }
326
327         final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
328
329         final ListenableFuture<Void> writeFuture =
330                 writer.writeConfig(prefix.getRootIdentifier(), replicaMembers);
331
332         final Promise<DistributedShardRegistration> shardRegistrationPromise = akka.dispatch.Futures.promise();
333         Futures.addCallback(writeFuture, new FutureCallback<Void>() {
334             @Override
335             public void onSuccess(@Nullable final Void result) {
336
337                 final Future<Object> ask =
338                         Patterns.ask(shardedDataTreeActor, new LookupPrefixShard(prefix), SHARD_FUTURE_TIMEOUT);
339
340                 shardRegistrationPromise.completeWith(ask.transform(
341                         new Mapper<Object, DistributedShardRegistration>() {
342                             @Override
343                             public DistributedShardRegistration apply(final Object parameter) {
344                                 return new DistributedShardRegistrationImpl(
345                                         prefix, shardedDataTreeActor, DistributedShardedDOMDataTree.this);
346                             }
347                         },
348                         new Mapper<Throwable, Throwable>() {
349                             @Override
350                             public Throwable apply(final Throwable throwable) {
351                                 return new DOMDataTreeShardCreationFailedException(
352                                         "Unable to create a cds shard.", throwable);
353                             }
354                         }, actorSystem.dispatcher()));
355             }
356
357             @Override
358             public void onFailure(final Throwable throwable) {
359                 shardRegistrationPromise.failure(
360                         new DOMDataTreeShardCreationFailedException("Unable to create a cds shard.", throwable));
361             }
362         });
363
364         return FutureConverters.toJava(shardRegistrationPromise.future());
365     }
366
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()) {
373                 return -1;
374             } else if (o1.getRootIdentifier().getPathArguments().size()
375                     == o2.getRootIdentifier().getPathArguments().size()) {
376                 return 0;
377             } else {
378                 return 1;
379             }
380         });
381         list.forEach(this::createShardFrontend);
382     }
383
384     void resolveShardRemovals(final Set<DOMDataTreeIdentifier> removals) {
385         LOG.debug("Member {}: Resolving removals : {}", memberName, removals);
386
387         // do we need to go from bottom to top?
388         removals.forEach(this::despawnShardFrontend);
389     }
390
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;
397
398         try (final DOMDataTreeProducer producer = localCreateProducer(Collections.singletonList(prefix))) {
399             final Entry<DataStoreClient, ActorRef> entry =
400                     createDatastoreClient(shardName, distributedDataStore.getActorContext());
401
402             final DistributedShardFrontend shard =
403                     new DistributedShardFrontend(distributedDataStore, entry.getKey(), prefix);
404
405             @SuppressWarnings("unchecked")
406             final DOMDataTreeShardRegistration<DOMDataTreeShard> reg =
407                     (DOMDataTreeShardRegistration) shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
408
409             synchronized (shards) {
410                 shards.store(prefix, reg);
411             }
412
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);
420         }
421     }
422
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);
428         }
429
430         if (lookup == null || !lookup.getValue().getPrefix().equals(prefix)) {
431             LOG.debug("Member {}: Received despawn for non-existing CDS shard frontend, prefix: {}, ignoring..",
432                     memberName, prefix);
433             return;
434         }
435
436         lookup.getValue().close();
437         // need to remove from our local table thats used for tracking
438         synchronized (shards) {
439             shards.remove(prefix);
440         }
441
442         final PrefixedShardConfigWriter writer = writerMap.get(prefix.getDatastoreType());
443         final ListenableFuture<Void> future = writer.removeConfig(prefix.getRootIdentifier());
444
445         Futures.addCallback(future, new FutureCallback<Void>() {
446             @Override
447             public void onSuccess(@Nullable Void result) {
448                 LOG.debug("{} - Succesfuly removed shard for {}", memberName, prefix);
449             }
450
451             @Override
452             public void onFailure(Throwable throwable) {
453                 LOG.error("Removal of shard {} from configuration failed.", prefix, throwable);
454             }
455         });
456     }
457
458     DOMDataTreePrefixTableEntry<DOMDataTreeShardRegistration<DOMDataTreeShard>> lookupShardFrontend(
459             final DOMDataTreeIdentifier prefix) {
460         return shards.lookup(prefix);
461
462     }
463
464     DOMDataTreeProducer localCreateProducer(final Collection<DOMDataTreeIdentifier> prefix) {
465         return shardedDOMDataTree.createProducer(prefix);
466     }
467
468     @Nonnull
469     @Override
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 {
475
476         LOG.debug("Registering shard[{}] at prefix: {}", shard, prefix);
477
478         if (producer instanceof ProxyProducer) {
479             return shardedDOMDataTree.registerDataTreeShard(prefix, shard, ((ProxyProducer) producer).delegate());
480         }
481
482         return shardedDOMDataTree.registerDataTreeShard(prefix, shard, producer);
483     }
484
485     @SuppressWarnings("checkstyle:IllegalCatch")
486     private Entry<DataStoreClient, ActorRef> createDatastoreClient(
487             final String shardName, final ActorContext actorContext)
488             throws DOMDataTreeShardCreationFailedException {
489
490         LOG.debug("Creating distributed datastore client for shard {}", shardName);
491         final Props distributedDataStoreClientProps =
492                 SimpleDataStoreClientActor.props(memberName, "Shard-" + shardName, actorContext, shardName);
493
494         final ActorRef clientActor = actorSystem.actorOf(distributedDataStoreClientProps);
495         try {
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);
503         }
504     }
505
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();
511
512         final PrefixedShardConfigWriter writer = writerMap.get(logicalDatastoreType);
513
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);
520         } else {
521             try {
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();
529
530                 final Optional<ActorRef> defaultLocalShardOptional =
531                         actorContext.findLocalShard(ClusterUtils.getCleanShardName(YangInstanceIdentifier.EMPTY));
532
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);
539                 }
540
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);
553             }
554         }
555     }
556
557     private static void closeProducer(final DOMDataTreeProducer producer) {
558         try {
559             producer.close();
560         } catch (final DOMDataTreeProducerException e) {
561             LOG.error("Unable to close producer", e);
562         }
563     }
564
565     @SuppressWarnings("checkstyle:IllegalCatch")
566     private static ActorRef createShardedDataTreeActor(final ActorSystem actorSystem,
567                                                        final ShardedDataTreeActorCreator creator,
568                                                        final String shardDataTreeActorId) {
569         Exception lastException = null;
570
571         for (int i = 0; i < MAX_ACTOR_CREATION_RETRIES; i++) {
572             try {
573                 return actorSystem.actorOf(creator.props(), shardDataTreeActorId);
574             } catch (final Exception e) {
575                 lastException = 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);
580             }
581         }
582
583         throw new IllegalStateException("Failed to create actor for ShardedDOMDataTree", lastException);
584     }
585
586     private class DistributedShardRegistrationImpl implements DistributedShardRegistration {
587
588         private final DOMDataTreeIdentifier prefix;
589         private final ActorRef shardedDataTreeActor;
590         private final DistributedShardedDOMDataTree distributedShardedDOMDataTree;
591
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;
598         }
599
600         @Override
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);
607
608             final Future<Void> closeFuture = ask.transform(
609                     new Mapper<Object, Void>() {
610                         @Override
611                         public Void apply(Object parameter) {
612                             return null;
613                         }
614                     },
615                     new Mapper<Throwable, Throwable>() {
616                         @Override
617                         public Throwable apply(Throwable throwable) {
618                             return throwable;
619                         }
620                     }, actorSystem.dispatcher());
621
622             return FutureConverters.toJava(closeFuture);
623         }
624     }
625
626     private static final class ProxyProducer extends ForwardingObject implements DOMDataTreeProducer {
627
628         private final DOMDataTreeProducer delegate;
629         private final Collection<DOMDataTreeIdentifier> subtrees;
630         private final ActorRef shardDataTreeActor;
631         private final ActorContext actorContext;
632
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);
641         }
642
643         @Nonnull
644         @Override
645         public DOMDataTreeCursorAwareTransaction createTransaction(final boolean isolated) {
646             return delegate.createTransaction(isolated);
647         }
648
649         @Nonnull
650         @Override
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);
655         }
656
657         @Override
658         public void close() throws DOMDataTreeProducerException {
659             delegate.close();
660
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);
666             }
667         }
668
669         @Override
670         protected DOMDataTreeProducer delegate() {
671             return delegate;
672         }
673     }
674 }