BUG-2138: Create DistributedShardFrontend
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / shardmanager / ShardManager.java
1 /*
2  * Copyright (c) 2014 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.datastore.shardmanager;
10
11 import static akka.actor.ActorRef.noSender;
12 import static akka.pattern.Patterns.ask;
13
14 import akka.actor.ActorRef;
15 import akka.actor.Address;
16 import akka.actor.Cancellable;
17 import akka.actor.OneForOneStrategy;
18 import akka.actor.PoisonPill;
19 import akka.actor.Status;
20 import akka.actor.SupervisorStrategy;
21 import akka.actor.SupervisorStrategy.Directive;
22 import akka.cluster.ClusterEvent;
23 import akka.cluster.ClusterEvent.MemberWeaklyUp;
24 import akka.cluster.Member;
25 import akka.cluster.ddata.DistributedData;
26 import akka.cluster.ddata.ORMap;
27 import akka.cluster.ddata.Replicator.Changed;
28 import akka.cluster.ddata.Replicator.Subscribe;
29 import akka.dispatch.Futures;
30 import akka.dispatch.OnComplete;
31 import akka.japi.Function;
32 import akka.pattern.Patterns;
33 import akka.persistence.RecoveryCompleted;
34 import akka.persistence.SaveSnapshotFailure;
35 import akka.persistence.SaveSnapshotSuccess;
36 import akka.persistence.SnapshotOffer;
37 import akka.persistence.SnapshotSelectionCriteria;
38 import akka.util.Timeout;
39 import com.google.common.annotations.VisibleForTesting;
40 import com.google.common.base.Preconditions;
41 import com.google.common.collect.Sets;
42 import com.google.common.collect.Sets.SetView;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.Collections;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Map.Entry;
51 import java.util.Set;
52 import java.util.concurrent.CountDownLatch;
53 import java.util.concurrent.TimeUnit;
54 import java.util.concurrent.TimeoutException;
55 import java.util.function.Consumer;
56 import java.util.function.Supplier;
57 import java.util.stream.Collectors;
58 import org.opendaylight.controller.cluster.access.concepts.MemberName;
59 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
60 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
61 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
62 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
63 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
64 import org.opendaylight.controller.cluster.datastore.Shard;
65 import org.opendaylight.controller.cluster.datastore.config.Configuration;
66 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
67 import org.opendaylight.controller.cluster.datastore.config.PrefixShardConfiguration;
68 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
69 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
70 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
71 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
72 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
73 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
74 import org.opendaylight.controller.cluster.datastore.messages.AddPrefixShardReplica;
75 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
76 import org.opendaylight.controller.cluster.datastore.messages.ChangeShardMembersVotingStatus;
77 import org.opendaylight.controller.cluster.datastore.messages.CreatePrefixedShard;
78 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
79 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
80 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
81 import org.opendaylight.controller.cluster.datastore.messages.FlipShardMembersVotingStatus;
82 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
83 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
84 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
85 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
86 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
87 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
88 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
89 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
90 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
91 import org.opendaylight.controller.cluster.datastore.persisted.ShardManagerSnapshot;
92 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
93 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
94 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
95 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
96 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
97 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
98 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
99 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
101 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
102 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
103 import org.opendaylight.controller.cluster.raft.messages.AddServer;
104 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
105 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
106 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
107 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
108 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
109 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
110 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
111 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
112 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
113 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
114 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
115 import org.slf4j.Logger;
116 import org.slf4j.LoggerFactory;
117 import scala.concurrent.ExecutionContext;
118 import scala.concurrent.Future;
119 import scala.concurrent.duration.Duration;
120 import scala.concurrent.duration.FiniteDuration;
121
122 /**
123  * Manages the shards for a data store. The ShardManager has the following jobs:
124  * <ul>
125  * <li> Create all the local shard replicas that belong on this cluster member
126  * <li> Find the address of the local shard
127  * <li> Find the primary replica for any given shard
128  * <li> Monitor the cluster members and store their addresses
129  * </ul>
130  */
131 class ShardManager extends AbstractUntypedPersistentActorWithMetering {
132     private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
133
134     // Stores a mapping between a shard name and it's corresponding information
135     // Shard names look like inventory, topology etc and are as specified in
136     // configuration
137     private final Map<String, ShardInformation> localShards = new HashMap<>();
138
139     // The type of a ShardManager reflects the type of the datastore itself
140     // A data store could be of type config/operational
141     private final String type;
142
143     private final ClusterWrapper cluster;
144
145     private final Configuration configuration;
146
147     private final String shardDispatcherPath;
148
149     private final ShardManagerInfo shardManagerMBean;
150
151     private DatastoreContextFactory datastoreContextFactory;
152
153     private final CountDownLatch waitTillReadyCountdownLatch;
154
155     private final PrimaryShardInfoFutureCache primaryShardInfoCache;
156
157     private final ShardPeerAddressResolver peerAddressResolver;
158
159     private SchemaContext schemaContext;
160
161     private DatastoreSnapshot restoreFromSnapshot;
162
163     private ShardManagerSnapshot currentSnapshot;
164
165     private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
166
167     private final String persistenceId;
168
169     private final ActorRef replicator;
170
171     ShardManager(AbstractShardManagerCreator<?> builder) {
172         this.cluster = builder.getCluster();
173         this.configuration = builder.getConfiguration();
174         this.datastoreContextFactory = builder.getDatastoreContextFactory();
175         this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
176         this.shardDispatcherPath =
177                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
178         this.waitTillReadyCountdownLatch = builder.getWaitTillReadyCountDownLatch();
179         this.primaryShardInfoCache = builder.getPrimaryShardInfoCache();
180         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
181
182         String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
183         persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
184
185         peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
186
187         // Subscribe this actor to cluster member events
188         cluster.subscribeToMemberEvents(getSelf());
189
190         shardManagerMBean = new ShardManagerInfo(getSelf(), cluster.getCurrentMemberName(),
191                 "shard-manager-" + this.type,
192                 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
193         shardManagerMBean.registerMBean();
194
195         replicator = DistributedData.get(context().system()).replicator();
196
197     }
198
199     public void preStart() {
200         LOG.info("Starting Shardmanager {}", persistenceId);
201
202         final Subscribe<ORMap<PrefixShardConfiguration>> subscribe =
203                 new Subscribe<>(ClusterUtils.CONFIGURATION_KEY, self());
204         replicator.tell(subscribe, noSender());
205     }
206
207     @Override
208     public void postStop() {
209         LOG.info("Stopping ShardManager {}", persistenceId());
210
211         shardManagerMBean.unregisterMBean();
212     }
213
214     @Override
215     public void handleCommand(Object message) throws Exception {
216         if (message  instanceof FindPrimary) {
217             findPrimary((FindPrimary)message);
218         } else if (message instanceof FindLocalShard) {
219             findLocalShard((FindLocalShard) message);
220         } else if (message instanceof UpdateSchemaContext) {
221             updateSchemaContext(message);
222         } else if (message instanceof ActorInitialized) {
223             onActorInitialized(message);
224         } else if (message instanceof ClusterEvent.MemberUp) {
225             memberUp((ClusterEvent.MemberUp) message);
226         } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
227             memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
228         } else if (message instanceof ClusterEvent.MemberExited) {
229             memberExited((ClusterEvent.MemberExited) message);
230         } else if (message instanceof ClusterEvent.MemberRemoved) {
231             memberRemoved((ClusterEvent.MemberRemoved) message);
232         } else if (message instanceof ClusterEvent.UnreachableMember) {
233             memberUnreachable((ClusterEvent.UnreachableMember) message);
234         } else if (message instanceof ClusterEvent.ReachableMember) {
235             memberReachable((ClusterEvent.ReachableMember) message);
236         } else if (message instanceof DatastoreContextFactory) {
237             onDatastoreContextFactory((DatastoreContextFactory) message);
238         } else if (message instanceof RoleChangeNotification) {
239             onRoleChangeNotification((RoleChangeNotification) message);
240         } else if (message instanceof FollowerInitialSyncUpStatus) {
241             onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
242         } else if (message instanceof ShardNotInitializedTimeout) {
243             onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
244         } else if (message instanceof ShardLeaderStateChanged) {
245             onLeaderStateChanged((ShardLeaderStateChanged) message);
246         } else if (message instanceof SwitchShardBehavior) {
247             onSwitchShardBehavior((SwitchShardBehavior) message);
248         } else if (message instanceof CreateShard) {
249             onCreateShard((CreateShard)message);
250         } else if (message instanceof AddShardReplica) {
251             onAddShardReplica((AddShardReplica) message);
252         } else if (message instanceof CreatePrefixedShard) {
253             onCreatePrefixedShard((CreatePrefixedShard) message);
254         } else if (message instanceof AddPrefixShardReplica) {
255             onAddPrefixShardReplica((AddPrefixShardReplica) message);
256         } else if (message instanceof ForwardedAddServerReply) {
257             ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
258             onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
259                     msg.removeShardOnFailure);
260         } else if (message instanceof ForwardedAddServerFailure) {
261             ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
262             onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
263         } else if (message instanceof RemoveShardReplica) {
264             onRemoveShardReplica((RemoveShardReplica) message);
265         } else if (message instanceof WrappedShardResponse) {
266             onWrappedShardResponse((WrappedShardResponse) message);
267         } else if (message instanceof GetSnapshot) {
268             onGetSnapshot();
269         } else if (message instanceof ServerRemoved) {
270             onShardReplicaRemoved((ServerRemoved) message);
271         } else if (message instanceof ChangeShardMembersVotingStatus) {
272             onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
273         } else if (message instanceof FlipShardMembersVotingStatus) {
274             onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
275         } else if (message instanceof SaveSnapshotSuccess) {
276             onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
277         } else if (message instanceof SaveSnapshotFailure) {
278             LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
279                     ((SaveSnapshotFailure) message).cause());
280         } else if (message instanceof Shutdown) {
281             onShutDown();
282         } else if (message instanceof GetLocalShardIds) {
283             onGetLocalShardIds();
284         } else if (message instanceof RunnableMessage) {
285             ((RunnableMessage)message).run();
286         } else if (message instanceof Changed) {
287             onConfigChanged((Changed) message);
288         } else {
289             unknownMessage(message);
290         }
291     }
292
293     private void onShutDown() {
294         List<Future<Boolean>> stopFutures = new ArrayList<>(localShards.size());
295         for (ShardInformation info : localShards.values()) {
296             if (info.getActor() != null) {
297                 LOG.debug("{}: Issuing gracefulStop to shard {}", persistenceId(), info.getShardId());
298
299                 FiniteDuration duration = info.getDatastoreContext().getShardRaftConfig()
300                         .getElectionTimeOutInterval().$times(2);
301                 stopFutures.add(Patterns.gracefulStop(info.getActor(), duration, Shutdown.INSTANCE));
302             }
303         }
304
305         LOG.info("Shutting down ShardManager {} - waiting on {} shards", persistenceId(), stopFutures.size());
306
307         ExecutionContext dispatcher = new Dispatchers(context().system().dispatchers())
308                 .getDispatcher(Dispatchers.DispatcherType.Client);
309         Future<Iterable<Boolean>> combinedFutures = Futures.sequence(stopFutures, dispatcher);
310
311         combinedFutures.onComplete(new OnComplete<Iterable<Boolean>>() {
312             @Override
313             public void onComplete(Throwable failure, Iterable<Boolean> results) {
314                 LOG.debug("{}: All shards shutdown - sending PoisonPill to self", persistenceId());
315
316                 self().tell(PoisonPill.getInstance(), self());
317
318                 if (failure != null) {
319                     LOG.warn("{}: An error occurred attempting to shut down the shards", persistenceId(), failure);
320                 } else {
321                     int nfailed = 0;
322                     for (Boolean result : results) {
323                         if (!result) {
324                             nfailed++;
325                         }
326                     }
327
328                     if (nfailed > 0) {
329                         LOG.warn("{}: {} shards did not shut down gracefully", persistenceId(), nfailed);
330                     }
331                 }
332             }
333         }, dispatcher);
334     }
335
336     private void onWrappedShardResponse(WrappedShardResponse message) {
337         if (message.getResponse() instanceof RemoveServerReply) {
338             onRemoveServerReply(getSender(), message.getShardId(), (RemoveServerReply) message.getResponse(),
339                     message.getLeaderPath());
340         }
341     }
342
343     private void onConfigChanged(final Changed<ORMap<PrefixShardConfiguration>> change) {
344         LOG.debug("{}, ShardManager {} received config changed {}",
345                 cluster.getCurrentMemberName(), persistenceId, change.dataValue().getEntries());
346
347         final Map<String, PrefixShardConfiguration> changedConfig = change.dataValue().getEntries();
348
349         final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> newConfig =
350                 changedConfig.values().stream().collect(
351                         Collectors.toMap(PrefixShardConfiguration::getPrefix, java.util.function.Function.identity()));
352
353         resolveConfig(newConfig);
354     }
355
356     private void resolveConfig(final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> newConfig) {
357         LOG.debug("{} ShardManager : {}, resolving new shard configuration : {}",
358                 cluster.getCurrentMemberName(), persistenceId, newConfig);
359
360         newConfig.forEach((prefix, config) ->
361                 LOG.debug("{} ShardManager : {}, received shard config "
362                         + "for prefix {}, config {}", cluster.getCurrentMemberName(), persistenceId, prefix, config));
363
364         final SetView<DOMDataTreeIdentifier> removedConfigs =
365                 Sets.difference(configuration.getAllPrefixShardConfigurations().keySet(), newConfig.keySet());
366
367         // resolve removals
368
369         resolveRemovals(removedConfigs);
370
371         final SetView<DOMDataTreeIdentifier> addedConfigs =
372                 Sets.difference(newConfig.keySet(), configuration.getAllPrefixShardConfigurations().keySet());
373         // resolve additions
374
375         resolveAdditions(addedConfigs, newConfig);
376         // iter through to update existing shards, either start/stop replicas or update the shard
377         // to check for more peers
378         resolveUpdates(Collections.emptySet());
379     }
380
381     private void resolveRemovals(final Set<DOMDataTreeIdentifier> removedConfigs) {
382         LOG.debug("{} ShardManager : {}, resolving removed configs : {}",
383                 cluster.getCurrentMemberName(), persistenceId, removedConfigs);
384
385         removedConfigs.forEach(id -> doRemovePrefixedShard(id));
386     }
387
388     private void resolveAdditions(final Set<DOMDataTreeIdentifier> addedConfigs,
389                                   final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> configs) {
390         LOG.debug("{} ShardManager : {}, resolving added configs : {}", addedConfigs);
391
392         addedConfigs.forEach(id -> doCreatePrefixedShard(configs.get(id)));
393     }
394
395     private void resolveUpdates(Set<DOMDataTreeIdentifier> maybeUpdatedConfigs) {
396         LOG.debug("{} ShardManager : {}, resolving potentially updated configs : {}", maybeUpdatedConfigs);
397     }
398
399     private void doRemovePrefixedShard(final DOMDataTreeIdentifier prefix) {
400         LOG.debug("{} ShardManager : {}, removing prefix shard: {}",
401                 cluster.getCurrentMemberName(), persistenceId, prefix);
402         final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(), prefix);
403         final ShardInformation shard = localShards.remove(shardId.getShardName());
404
405         configuration.removePrefixShardConfiguration(prefix);
406
407         if (shard == null) {
408             LOG.warn("Received removal for unconfigured shard: {} , ignoring.. ", prefix);
409             return;
410         }
411
412         if (shard.getActor() != null) {
413             LOG.debug("{} : Sending Shutdown to Shard actor {}", persistenceId(), shard.getActor());
414             shard.getActor().tell(Shutdown.INSTANCE, self());
415         }
416         LOG.debug("{} : {} : Local Shard replica for shard {} has been removed", cluster.getCurrentMemberName(),
417                 persistenceId(), shardId.getShardName());
418         persistShardList();
419     }
420
421     private void onRemoveServerReply(ActorRef originalSender, ShardIdentifier shardId, RemoveServerReply replyMsg,
422             String leaderPath) {
423         shardReplicaOperationsInProgress.remove(shardId.getShardName());
424
425         LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
426
427         if (replyMsg.getStatus() == ServerChangeStatus.OK) {
428             LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
429                     shardId.getShardName());
430             originalSender.tell(new Status.Success(null), getSelf());
431         } else {
432             LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
433                     persistenceId(), shardId, replyMsg.getStatus());
434
435             Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
436             originalSender.tell(new Status.Failure(failure), getSelf());
437         }
438     }
439
440     private void removeShardReplica(RemoveShardReplica contextMessage, final String shardName, final String primaryPath,
441             final ActorRef sender) {
442         if (isShardReplicaOperationInProgress(shardName, sender)) {
443             return;
444         }
445
446         shardReplicaOperationsInProgress.add(shardName);
447
448         final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
449
450         final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
451
452         //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
453         LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
454                 primaryPath, shardId);
455
456         Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
457         Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
458                 new RemoveServer(shardId.toString()), removeServerTimeout);
459
460         futureObj.onComplete(new OnComplete<Object>() {
461             @Override
462             public void onComplete(Throwable failure, Object response) {
463                 if (failure != null) {
464                     shardReplicaOperationsInProgress.remove(shardName);
465                     String msg = String.format("RemoveServer request to leader %s for shard %s failed",
466                             primaryPath, shardName);
467
468                     LOG.debug("{}: {}", persistenceId(), msg, failure);
469
470                     // FAILURE
471                     sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
472                 } else {
473                     // SUCCESS
474                     self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
475                 }
476             }
477         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
478     }
479
480     private void onShardReplicaRemoved(ServerRemoved message) {
481         final ShardIdentifier shardId = new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build();
482         final ShardInformation shardInformation = localShards.remove(shardId.getShardName());
483         if (shardInformation == null) {
484             LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
485             return;
486         } else if (shardInformation.getActor() != null) {
487             LOG.debug("{} : Sending Shutdown to Shard actor {}", persistenceId(), shardInformation.getActor());
488             shardInformation.getActor().tell(Shutdown.INSTANCE, self());
489         }
490         LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardId.getShardName());
491         persistShardList();
492     }
493
494     private void onGetSnapshot() {
495         LOG.debug("{}: onGetSnapshot", persistenceId());
496
497         List<String> notInitialized = null;
498         for (ShardInformation shardInfo : localShards.values()) {
499             if (!shardInfo.isShardInitialized()) {
500                 if (notInitialized == null) {
501                     notInitialized = new ArrayList<>();
502                 }
503
504                 notInitialized.add(shardInfo.getShardName());
505             }
506         }
507
508         if (notInitialized != null) {
509             getSender().tell(new Status.Failure(new IllegalStateException(String.format(
510                     "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
511             return;
512         }
513
514         ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
515                 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
516                 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
517
518         for (ShardInformation shardInfo: localShards.values()) {
519             shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
520         }
521     }
522
523     @SuppressWarnings("checkstyle:IllegalCatch")
524     private void onCreatePrefixedShard(final CreatePrefixedShard createPrefixedShard) {
525         LOG.debug("{}: onCreatePrefixedShard: {}", persistenceId(), createPrefixedShard);
526
527         Object reply;
528         try {
529             final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(),
530                     createPrefixedShard.getConfig().getPrefix());
531             if (localShards.containsKey(shardId.getShardName())) {
532                 LOG.debug("{}: Shard {} already exists", persistenceId(), shardId);
533                 reply = new Status.Success(String.format("Shard with name %s already exists", shardId));
534             } else {
535                 doCreatePrefixedShard(createPrefixedShard);
536                 reply = new Status.Success(null);
537             }
538         } catch (final Exception e) {
539             LOG.error("{}: onCreateShard failed", persistenceId(), e);
540             reply = new Status.Failure(e);
541         }
542
543         if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
544             getSender().tell(reply, getSelf());
545         }
546     }
547
548     @SuppressWarnings("checkstyle:IllegalCatch")
549     private void onCreateShard(CreateShard createShard) {
550         LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
551
552         Object reply;
553         try {
554             String shardName = createShard.getModuleShardConfig().getShardName();
555             if (localShards.containsKey(shardName)) {
556                 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
557                 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
558             } else {
559                 doCreateShard(createShard);
560                 reply = new Status.Success(null);
561             }
562         } catch (Exception e) {
563             LOG.error("{}: onCreateShard failed", persistenceId(), e);
564             reply = new Status.Failure(e);
565         }
566
567         if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
568             getSender().tell(reply, getSelf());
569         }
570     }
571
572     private void doCreatePrefixedShard(final CreatePrefixedShard createPrefixedShard) {
573         doCreatePrefixedShard(createPrefixedShard.getConfig());
574         // do not replicate on this level
575     }
576
577     private void doCreatePrefixedShard(final PrefixShardConfiguration config) {
578         LOG.debug("doCreatePrefixShard : {}", config.getPrefix());
579
580         final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(),
581                 config.getPrefix());
582         final String shardName = shardId.getShardName();
583
584         configuration.addPrefixShardConfiguration(config);
585
586         final Builder builder = newShardDatastoreContextBuilder(shardName);
587         builder.logicalStoreType(LogicalDatastoreType.valueOf(config.getPrefix().getDatastoreType().name()))
588                 .storeRoot(config.getPrefix().getRootIdentifier());
589         DatastoreContext shardDatastoreContext = builder.build();
590
591         final Map<String, String> peerAddresses = Collections.emptyMap();
592         final boolean isActiveMember = true;
593         LOG.debug("{} doCreatePrefixedShard: persistenceId(): {}, memberNames: "
594                         + "{}, peerAddresses: {}, isActiveMember: {}",
595                 shardId, persistenceId(), config.getShardMemberNames(),
596                 peerAddresses, isActiveMember);
597
598         final ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
599                 shardDatastoreContext, Shard.builder(), peerAddressResolver);
600         info.setActiveMember(isActiveMember);
601         localShards.put(info.getShardName(), info);
602
603         if (schemaContext != null) {
604             info.setActor(newShardActor(schemaContext, info));
605         }
606
607         persistShardList();
608     }
609
610     private void doCreateShard(final CreateShard createShard) {
611         final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
612         final String shardName = moduleShardConfig.getShardName();
613
614         configuration.addModuleShardConfiguration(moduleShardConfig);
615
616         DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
617         if (shardDatastoreContext == null) {
618             shardDatastoreContext = newShardDatastoreContext(shardName);
619         } else {
620             shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
621                     peerAddressResolver).build();
622         }
623
624         ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
625
626         boolean shardWasInRecoveredSnapshot = currentSnapshot != null
627                 && currentSnapshot.getShardList().contains(shardName);
628
629         Map<String, String> peerAddresses;
630         boolean isActiveMember;
631         if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
632                 .contains(cluster.getCurrentMemberName())) {
633             peerAddresses = getPeerAddresses(shardName);
634             isActiveMember = true;
635         } else {
636             // The local member is not in the static shard member configuration and the shard did not
637             // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
638             // the shard with no peers and with elections disabled so it stays as follower. A
639             // subsequent AddServer request will be needed to make it an active member.
640             isActiveMember = false;
641             peerAddresses = Collections.emptyMap();
642             shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
643                     .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
644         }
645
646         LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
647                 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
648                 isActiveMember);
649
650         ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
651                 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
652         info.setActiveMember(isActiveMember);
653         localShards.put(info.getShardName(), info);
654
655         if (schemaContext != null) {
656             info.setActor(newShardActor(schemaContext, info));
657         }
658     }
659
660     private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
661         return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
662                 .shardPeerAddressResolver(peerAddressResolver);
663     }
664
665     private DatastoreContext newShardDatastoreContext(String shardName) {
666         return newShardDatastoreContextBuilder(shardName).build();
667     }
668
669     private void checkReady() {
670         if (isReadyWithLeaderId()) {
671             LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
672                     persistenceId(), type, waitTillReadyCountdownLatch.getCount());
673
674             waitTillReadyCountdownLatch.countDown();
675         }
676     }
677
678     private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
679         LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
680
681         ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
682         if (shardInformation != null) {
683             shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
684             shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
685             if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
686                 primaryShardInfoCache.remove(shardInformation.getShardName());
687             }
688
689             checkReady();
690         } else {
691             LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
692         }
693     }
694
695     private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
696         ShardInformation shardInfo = message.getShardInfo();
697
698         LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
699                 shardInfo.getShardName());
700
701         shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
702
703         if (!shardInfo.isShardInitialized()) {
704             LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
705             message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
706         } else {
707             LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
708             message.getSender().tell(createNoShardLeaderException(shardInfo.getShardId()), getSelf());
709         }
710     }
711
712     private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
713         LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
714                 status.getName(), status.isInitialSyncDone());
715
716         ShardInformation shardInformation = findShardInformation(status.getName());
717
718         if (shardInformation != null) {
719             shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
720
721             shardManagerMBean.setSyncStatus(isInSync());
722         }
723
724     }
725
726     private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
727         LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
728                 roleChanged.getOldRole(), roleChanged.getNewRole());
729
730         ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
731         if (shardInformation != null) {
732             shardInformation.setRole(roleChanged.getNewRole());
733             checkReady();
734             shardManagerMBean.setSyncStatus(isInSync());
735         }
736     }
737
738
739     private ShardInformation findShardInformation(String memberId) {
740         for (ShardInformation info : localShards.values()) {
741             if (info.getShardId().toString().equals(memberId)) {
742                 return info;
743             }
744         }
745
746         return null;
747     }
748
749     private boolean isReadyWithLeaderId() {
750         boolean isReady = true;
751         for (ShardInformation info : localShards.values()) {
752             if (!info.isShardReadyWithLeaderId()) {
753                 isReady = false;
754                 break;
755             }
756         }
757         return isReady;
758     }
759
760     private boolean isInSync() {
761         for (ShardInformation info : localShards.values()) {
762             if (!info.isInSync()) {
763                 return false;
764             }
765         }
766         return true;
767     }
768
769     private void onActorInitialized(Object message) {
770         final ActorRef sender = getSender();
771
772         if (sender == null) {
773             return; //why is a non-actor sending this message? Just ignore.
774         }
775
776         String actorName = sender.path().name();
777         //find shard name from actor name; actor name is stringified shardId
778
779         final ShardIdentifier shardId;
780         try {
781             shardId = ShardIdentifier.fromShardIdString(actorName);
782         } catch (IllegalArgumentException e) {
783             LOG.debug("{}: ignoring actor {}", actorName, e);
784             return;
785         }
786
787         markShardAsInitialized(shardId.getShardName());
788     }
789
790     private void markShardAsInitialized(String shardName) {
791         LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
792
793         ShardInformation shardInformation = localShards.get(shardName);
794         if (shardInformation != null) {
795             shardInformation.setActorInitialized();
796
797             shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
798         }
799     }
800
801     @Override
802     protected void handleRecover(Object message) throws Exception {
803         if (message instanceof RecoveryCompleted) {
804             onRecoveryCompleted();
805         } else if (message instanceof SnapshotOffer) {
806             applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
807         }
808     }
809
810     @SuppressWarnings("checkstyle:IllegalCatch")
811     private void onRecoveryCompleted() {
812         LOG.info("Recovery complete : {}", persistenceId());
813
814         // We no longer persist SchemaContext modules so delete all the prior messages from the akka
815         // journal on upgrade from Helium.
816         deleteMessages(lastSequenceNr());
817
818         if (currentSnapshot == null && restoreFromSnapshot != null
819                 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
820             ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
821
822             LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
823
824             applyShardManagerSnapshot(snapshot);
825         }
826
827         createLocalShards();
828     }
829
830     private void sendResponse(ShardInformation shardInformation, boolean doWait,
831             boolean wantShardReady, final Supplier<Object> messageSupplier) {
832         if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
833             if (doWait) {
834                 final ActorRef sender = getSender();
835                 final ActorRef self = self();
836
837                 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
838
839                 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
840                     new OnShardInitialized(replyRunnable);
841
842                 shardInformation.addOnShardInitialized(onShardInitialized);
843
844                 FiniteDuration timeout = shardInformation.getDatastoreContext()
845                         .getShardInitializationTimeout().duration();
846                 if (shardInformation.isShardInitialized()) {
847                     // If the shard is already initialized then we'll wait enough time for the shard to
848                     // elect a leader, ie 2 times the election timeout.
849                     timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
850                             .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
851                 }
852
853                 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
854                         shardInformation.getShardName());
855
856                 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
857                         timeout, getSelf(),
858                         new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
859                         getContext().dispatcher(), getSelf());
860
861                 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
862
863             } else if (!shardInformation.isShardInitialized()) {
864                 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
865                         shardInformation.getShardName());
866                 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
867             } else {
868                 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
869                         shardInformation.getShardName());
870                 getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
871             }
872
873             return;
874         }
875
876         getSender().tell(messageSupplier.get(), getSelf());
877     }
878
879     private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
880         return new NoShardLeaderException(null, shardId.toString());
881     }
882
883     private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
884         return new NotInitializedException(String.format(
885                 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
886     }
887
888     @VisibleForTesting
889     static MemberName memberToName(final Member member) {
890         return MemberName.forName(member.roles().iterator().next());
891     }
892
893     private void memberRemoved(ClusterEvent.MemberRemoved message) {
894         MemberName memberName = memberToName(message.member());
895
896         LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
897                 message.member().address());
898
899         peerAddressResolver.removePeerAddress(memberName);
900
901         for (ShardInformation info : localShards.values()) {
902             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
903         }
904     }
905
906     private void memberExited(ClusterEvent.MemberExited message) {
907         MemberName memberName = memberToName(message.member());
908
909         LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
910                 message.member().address());
911
912         peerAddressResolver.removePeerAddress(memberName);
913
914         for (ShardInformation info : localShards.values()) {
915             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
916         }
917     }
918
919     private void memberUp(ClusterEvent.MemberUp message) {
920         MemberName memberName = memberToName(message.member());
921
922         LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
923                 message.member().address());
924
925         memberUp(memberName, message.member().address());
926     }
927
928     private void memberUp(MemberName memberName, Address address) {
929         addPeerAddress(memberName, address);
930         checkReady();
931     }
932
933     private void memberWeaklyUp(MemberWeaklyUp message) {
934         MemberName memberName = memberToName(message.member());
935
936         LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
937                 message.member().address());
938
939         memberUp(memberName, message.member().address());
940     }
941
942     private void addPeerAddress(MemberName memberName, Address address) {
943         peerAddressResolver.addPeerAddress(memberName, address);
944
945         for (ShardInformation info : localShards.values()) {
946             String shardName = info.getShardName();
947             String peerId = getShardIdentifier(memberName, shardName).toString();
948             info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
949
950             info.peerUp(memberName, peerId, getSelf());
951         }
952     }
953
954     private void memberReachable(ClusterEvent.ReachableMember message) {
955         MemberName memberName = memberToName(message.member());
956         LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
957
958         addPeerAddress(memberName, message.member().address());
959
960         markMemberAvailable(memberName);
961     }
962
963     private void memberUnreachable(ClusterEvent.UnreachableMember message) {
964         MemberName memberName = memberToName(message.member());
965         LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
966
967         markMemberUnavailable(memberName);
968     }
969
970     private void markMemberUnavailable(final MemberName memberName) {
971         final String memberStr = memberName.getName();
972         for (ShardInformation info : localShards.values()) {
973             String leaderId = info.getLeaderId();
974             // XXX: why are we using String#contains() here?
975             if (leaderId != null && leaderId.contains(memberStr)) {
976                 LOG.debug("Marking Leader {} as unavailable.", leaderId);
977                 info.setLeaderAvailable(false);
978
979                 primaryShardInfoCache.remove(info.getShardName());
980             }
981
982             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
983         }
984     }
985
986     private void markMemberAvailable(final MemberName memberName) {
987         final String memberStr = memberName.getName();
988         for (ShardInformation info : localShards.values()) {
989             String leaderId = info.getLeaderId();
990             // XXX: why are we using String#contains() here?
991             if (leaderId != null && leaderId.contains(memberStr)) {
992                 LOG.debug("Marking Leader {} as available.", leaderId);
993                 info.setLeaderAvailable(true);
994             }
995
996             info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
997         }
998     }
999
1000     private void onDatastoreContextFactory(DatastoreContextFactory factory) {
1001         datastoreContextFactory = factory;
1002         for (ShardInformation info : localShards.values()) {
1003             info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
1004         }
1005     }
1006
1007     private void onGetLocalShardIds() {
1008         final List<String> response = new ArrayList<>(localShards.size());
1009
1010         for (ShardInformation info : localShards.values()) {
1011             response.add(info.getShardId().toString());
1012         }
1013
1014         getSender().tell(new Status.Success(response), getSelf());
1015     }
1016
1017     private void onSwitchShardBehavior(final SwitchShardBehavior message) {
1018         final ShardIdentifier identifier = message.getShardId();
1019
1020         if (identifier != null) {
1021             final ShardInformation info = localShards.get(identifier.getShardName());
1022             if (info == null) {
1023                 getSender().tell(new Status.Failure(
1024                     new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
1025                 return;
1026             }
1027
1028             switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1029         } else {
1030             for (ShardInformation info : localShards.values()) {
1031                 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1032             }
1033         }
1034
1035         getSender().tell(new Status.Success(null), getSelf());
1036     }
1037
1038     private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
1039         final ActorRef actor = info.getActor();
1040         if (actor != null) {
1041             actor.tell(switchBehavior, getSelf());
1042         } else {
1043             LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
1044                 info.getShardName(), switchBehavior.getNewState());
1045         }
1046     }
1047
1048     /**
1049      * Notifies all the local shards of a change in the schema context.
1050      *
1051      * @param message the message to send
1052      */
1053     private void updateSchemaContext(final Object message) {
1054         schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
1055
1056         LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
1057
1058         for (ShardInformation info : localShards.values()) {
1059             if (info.getActor() == null) {
1060                 LOG.debug("Creating Shard {}", info.getShardId());
1061                 info.setActor(newShardActor(schemaContext, info));
1062             } else {
1063                 info.getActor().tell(message, getSelf());
1064             }
1065         }
1066     }
1067
1068     @VisibleForTesting
1069     protected ClusterWrapper getCluster() {
1070         return cluster;
1071     }
1072
1073     @VisibleForTesting
1074     protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
1075         return getContext().actorOf(info.newProps(schemaContext)
1076                 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
1077     }
1078
1079     private void findPrimary(FindPrimary message) {
1080         LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1081
1082         final String shardName = message.getShardName();
1083         final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1084
1085         // First see if the there is a local replica for the shard
1086         final ShardInformation info = localShards.get(shardName);
1087         if (info != null && info.isActiveMember()) {
1088             sendResponse(info, message.isWaitUntilReady(), true, () -> {
1089                 String primaryPath = info.getSerializedLeaderActor();
1090                 Object found = canReturnLocalShardState && info.isLeader()
1091                         ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1092                             new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1093
1094                 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1095                 return found;
1096             });
1097
1098             return;
1099         }
1100
1101         final Collection<String> visitedAddresses;
1102         if (message instanceof RemoteFindPrimary) {
1103             visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1104         } else {
1105             visitedAddresses = new ArrayList<>(1);
1106         }
1107
1108         visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1109
1110         for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1111             if (visitedAddresses.contains(address)) {
1112                 continue;
1113             }
1114
1115             LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1116                     persistenceId(), shardName, address, visitedAddresses);
1117
1118             getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1119                     message.isWaitUntilReady(), visitedAddresses), getContext());
1120             return;
1121         }
1122
1123         LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1124
1125         getSender().tell(new PrimaryNotFoundException(
1126                 String.format("No primary shard found for %s.", shardName)), getSelf());
1127     }
1128
1129     private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1130         Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1131                 .getShardInitializationTimeout().duration().$times(2));
1132
1133         Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1134         futureObj.onComplete(new OnComplete<Object>() {
1135             @Override
1136             public void onComplete(Throwable failure, Object response) {
1137                 if (failure != null) {
1138                     handler.onFailure(failure);
1139                 } else {
1140                     if (response instanceof RemotePrimaryShardFound) {
1141                         handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1142                     } else if (response instanceof LocalPrimaryShardFound) {
1143                         handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1144                     } else {
1145                         handler.onUnknownResponse(response);
1146                     }
1147                 }
1148             }
1149         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1150     }
1151
1152     /**
1153      * Construct the name of the shard actor given the name of the member on
1154      * which the shard resides and the name of the shard.
1155      *
1156      * @param memberName the member name
1157      * @param shardName the shard name
1158      * @return a b
1159      */
1160     private ShardIdentifier getShardIdentifier(MemberName memberName, String shardName) {
1161         return peerAddressResolver.getShardIdentifier(memberName, shardName);
1162     }
1163
1164     /**
1165      * Create shards that are local to the member on which the ShardManager runs.
1166      */
1167     private void createLocalShards() {
1168         MemberName memberName = this.cluster.getCurrentMemberName();
1169         Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1170
1171         Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1172         if (restoreFromSnapshot != null) {
1173             for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1174                 shardSnapshots.put(snapshot.getName(), snapshot);
1175             }
1176         }
1177
1178         restoreFromSnapshot = null; // null out to GC
1179
1180         for (String shardName : memberShardNames) {
1181             ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1182
1183             LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1184
1185             Map<String, String> peerAddresses = getPeerAddresses(shardName);
1186             localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
1187                     newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
1188                         shardSnapshots.get(shardName)), peerAddressResolver));
1189         }
1190     }
1191
1192     /**
1193      * Given the name of the shard find the addresses of all it's peers.
1194      *
1195      * @param shardName the shard name
1196      */
1197     private Map<String, String> getPeerAddresses(String shardName) {
1198         final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1199         return getPeerAddresses(shardName, members);
1200     }
1201
1202     private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1203         Map<String, String> peerAddresses = new HashMap<>();
1204         MemberName currentMemberName = this.cluster.getCurrentMemberName();
1205
1206         for (MemberName memberName : members) {
1207             if (!currentMemberName.equals(memberName)) {
1208                 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1209                 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1210                 peerAddresses.put(shardId.toString(), address);
1211             }
1212         }
1213         return peerAddresses;
1214     }
1215
1216     @Override
1217     public SupervisorStrategy supervisorStrategy() {
1218
1219         return new OneForOneStrategy(10, Duration.create("1 minute"),
1220                 (Function<Throwable, Directive>) t -> {
1221                     LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1222                     return SupervisorStrategy.resume();
1223                 });
1224     }
1225
1226     @Override
1227     public String persistenceId() {
1228         return persistenceId;
1229     }
1230
1231     @VisibleForTesting
1232     ShardManagerInfoMBean getMBean() {
1233         return shardManagerMBean;
1234     }
1235
1236     private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1237         if (shardReplicaOperationsInProgress.contains(shardName)) {
1238             String msg = String.format("A shard replica operation for %s is already in progress", shardName);
1239             LOG.debug("{}: {}", persistenceId(), msg);
1240             sender.tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1241             return true;
1242         }
1243
1244         return false;
1245     }
1246
1247
1248     // With this message the shard does NOT have to be preconfigured
1249     // do a dynamic lookup if the shard exists somewhere and replicate
1250     private void onAddPrefixShardReplica(final AddPrefixShardReplica shardReplicaMsg) {
1251         final String shardName = ClusterUtils.getCleanShardName(shardReplicaMsg.getPrefix());
1252
1253         LOG.debug("{}: onAddPrefixShardReplica: {}", persistenceId(), shardReplicaMsg);
1254
1255         if (schemaContext == null) {
1256             final String msg = String.format(
1257                     "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1258             LOG.debug("{}: {}", persistenceId(), msg);
1259             getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1260             return;
1261         }
1262
1263         findPrimary(shardName,
1264                 new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(), getSelf()) {
1265                     @Override
1266                     public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1267                         getSelf().tell((RunnableMessage) () -> addShard(getShardName(), response, getSender()),
1268                                 getTargetActor());
1269                     }
1270
1271                     @Override
1272                     public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1273                         sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1274                     }
1275                 }
1276         );
1277     }
1278
1279     private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1280         final String shardName = shardReplicaMsg.getShardName();
1281
1282         LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1283
1284         // verify the shard with the specified name is present in the cluster configuration
1285         if (!this.configuration.isShardConfigured(shardName)) {
1286             String msg = String.format("No module configuration exists for shard %s", shardName);
1287             LOG.debug("{}: {}", persistenceId(), msg);
1288             getSender().tell(new Status.Failure(new IllegalArgumentException(msg)), getSelf());
1289             return;
1290         }
1291
1292         // Create the localShard
1293         if (schemaContext == null) {
1294             String msg = String.format(
1295                   "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1296             LOG.debug("{}: {}", persistenceId(), msg);
1297             getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1298             return;
1299         }
1300
1301         findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1302                 getSelf()) {
1303             @Override
1304             public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1305                 getSelf().tell((RunnableMessage) () -> addShard(getShardName(), response, getSender()),
1306                         getTargetActor());
1307             }
1308
1309             @Override
1310             public void onLocalPrimaryFound(LocalPrimaryShardFound message) {
1311                 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1312             }
1313
1314         });
1315     }
1316
1317     private void sendLocalReplicaAlreadyExistsReply(String shardName, ActorRef sender) {
1318         String msg = String.format("Local shard %s already exists", shardName);
1319         LOG.debug("{}: {}", persistenceId(), msg);
1320         sender.tell(new Status.Failure(new AlreadyExistsException(msg)), getSelf());
1321     }
1322
1323     private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1324         if (isShardReplicaOperationInProgress(shardName, sender)) {
1325             return;
1326         }
1327
1328         shardReplicaOperationsInProgress.add(shardName);
1329
1330         final ShardInformation shardInfo;
1331         final boolean removeShardOnFailure;
1332         ShardInformation existingShardInfo = localShards.get(shardName);
1333         if (existingShardInfo == null) {
1334             removeShardOnFailure = true;
1335             ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1336
1337             DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1338                     .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1339
1340             shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1341                     Shard.builder(), peerAddressResolver);
1342             shardInfo.setActiveMember(false);
1343             localShards.put(shardName, shardInfo);
1344             shardInfo.setActor(newShardActor(schemaContext, shardInfo));
1345         } else {
1346             removeShardOnFailure = false;
1347             shardInfo = existingShardInfo;
1348         }
1349
1350         String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1351
1352         //inform ShardLeader to add this shard as a replica by sending an AddServer message
1353         LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1354                 response.getPrimaryPath(), shardInfo.getShardId());
1355
1356         Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1357                 .getShardLeaderElectionTimeout().duration());
1358         Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1359             new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1360
1361         futureObj.onComplete(new OnComplete<Object>() {
1362             @Override
1363             public void onComplete(Throwable failure, Object addServerResponse) {
1364                 if (failure != null) {
1365                     LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1366                             response.getPrimaryPath(), shardName, failure);
1367
1368                     String msg = String.format("AddServer request to leader %s for shard %s failed",
1369                             response.getPrimaryPath(), shardName);
1370                     self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1371                 } else {
1372                     self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1373                             response.getPrimaryPath(), removeShardOnFailure), sender);
1374                 }
1375             }
1376         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1377     }
1378
1379     private void onAddServerFailure(String shardName, String message, Throwable failure, ActorRef sender,
1380             boolean removeShardOnFailure) {
1381         shardReplicaOperationsInProgress.remove(shardName);
1382
1383         if (removeShardOnFailure) {
1384             ShardInformation shardInfo = localShards.remove(shardName);
1385             if (shardInfo.getActor() != null) {
1386                 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1387             }
1388         }
1389
1390         sender.tell(new Status.Failure(message == null ? failure :
1391             new RuntimeException(message, failure)), getSelf());
1392     }
1393
1394     private void onAddServerReply(ShardInformation shardInfo, AddServerReply replyMsg, ActorRef sender,
1395             String leaderPath, boolean removeShardOnFailure) {
1396         String shardName = shardInfo.getShardName();
1397         shardReplicaOperationsInProgress.remove(shardName);
1398
1399         LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1400
1401         if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1402             LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1403
1404             // Make the local shard voting capable
1405             shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1406             shardInfo.setActiveMember(true);
1407             persistShardList();
1408
1409             sender.tell(new Status.Success(null), getSelf());
1410         } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1411             sendLocalReplicaAlreadyExistsReply(shardName, sender);
1412         } else {
1413             LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1414                     persistenceId(), shardName, replyMsg.getStatus());
1415
1416             Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1417                     shardInfo.getShardId());
1418
1419             onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1420         }
1421     }
1422
1423     private static Exception getServerChangeException(Class<?> serverChange, ServerChangeStatus serverChangeStatus,
1424                                                String leaderPath, ShardIdentifier shardId) {
1425         Exception failure;
1426         switch (serverChangeStatus) {
1427             case TIMEOUT:
1428                 failure = new TimeoutException(String.format(
1429                         "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1430                         + "Possible causes - there was a problem replicating the data or shard leadership changed "
1431                         + "while replicating the shard data", leaderPath, shardId.getShardName()));
1432                 break;
1433             case NO_LEADER:
1434                 failure = createNoShardLeaderException(shardId);
1435                 break;
1436             case NOT_SUPPORTED:
1437                 failure = new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1438                         serverChange.getSimpleName(), shardId.getShardName()));
1439                 break;
1440             default :
1441                 failure = new RuntimeException(String.format(
1442                         "%s request to leader %s for shard %s failed with status %s",
1443                         serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1444         }
1445         return failure;
1446     }
1447
1448     private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1449         LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1450
1451         findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1452                 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1453             @Override
1454             public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1455                 doRemoveShardReplicaAsync(response.getPrimaryPath());
1456             }
1457
1458             @Override
1459             public void onLocalPrimaryFound(LocalPrimaryShardFound response) {
1460                 doRemoveShardReplicaAsync(response.getPrimaryPath());
1461             }
1462
1463             private void doRemoveShardReplicaAsync(final String primaryPath) {
1464                 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1465                         primaryPath, getSender()), getTargetActor());
1466             }
1467         });
1468     }
1469
1470     private void persistShardList() {
1471         List<String> shardList = new ArrayList<>(localShards.keySet());
1472         for (ShardInformation shardInfo : localShards.values()) {
1473             if (!shardInfo.isActiveMember()) {
1474                 shardList.remove(shardInfo.getShardName());
1475             }
1476         }
1477         LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1478         saveSnapshot(updateShardManagerSnapshot(shardList, configuration.getAllPrefixShardConfigurations()));
1479     }
1480
1481     private ShardManagerSnapshot updateShardManagerSnapshot(
1482             final List<String> shardList,
1483             final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> allPrefixShardConfigurations) {
1484         currentSnapshot = new ShardManagerSnapshot(shardList, allPrefixShardConfigurations);
1485         return currentSnapshot;
1486     }
1487
1488     private void applyShardManagerSnapshot(ShardManagerSnapshot snapshot) {
1489         currentSnapshot = snapshot;
1490
1491         LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1492
1493         final MemberName currentMember = cluster.getCurrentMemberName();
1494         Set<String> configuredShardList =
1495             new HashSet<>(configuration.getMemberShardNames(currentMember));
1496         for (String shard : currentSnapshot.getShardList()) {
1497             if (!configuredShardList.contains(shard)) {
1498                 // add the current member as a replica for the shard
1499                 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1500                 configuration.addMemberReplicaForShard(shard, currentMember);
1501             } else {
1502                 configuredShardList.remove(shard);
1503             }
1504         }
1505         for (String shard : configuredShardList) {
1506             // remove the member as a replica for the shard
1507             LOG.debug("{}: removing shard {}", persistenceId(), shard);
1508             configuration.removeMemberReplicaForShard(shard, currentMember);
1509         }
1510     }
1511
1512     private void onSaveSnapshotSuccess(SaveSnapshotSuccess successMessage) {
1513         LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1514             persistenceId());
1515         deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1516             0, 0));
1517     }
1518
1519     private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1520         LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1521
1522         String shardName = changeMembersVotingStatus.getShardName();
1523         Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1524         for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1525             serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1526                     e.getValue());
1527         }
1528
1529         ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1530
1531         findLocalShard(shardName, getSender(),
1532             localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1533             localShardFound.getPath(), getSender()));
1534     }
1535
1536     private void onFlipShardMembersVotingStatus(FlipShardMembersVotingStatus flipMembersVotingStatus) {
1537         LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1538
1539         ActorRef sender = getSender();
1540         final String shardName = flipMembersVotingStatus.getShardName();
1541         findLocalShard(shardName, sender, localShardFound -> {
1542             Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1543                     Timeout.apply(30, TimeUnit.SECONDS));
1544
1545             future.onComplete(new OnComplete<Object>() {
1546                 @Override
1547                 public void onComplete(Throwable failure, Object response) {
1548                     if (failure != null) {
1549                         sender.tell(new Status.Failure(new RuntimeException(
1550                                 String.format("Failed to access local shard %s", shardName), failure)), self());
1551                         return;
1552                     }
1553
1554                     OnDemandRaftState raftState = (OnDemandRaftState) response;
1555                     Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1556                     for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1557                         serverVotingStatusMap.put(e.getKey(), !e.getValue());
1558                     }
1559
1560                     serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1561                             .toString(), !raftState.isVoting());
1562
1563                     changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1564                             shardName, localShardFound.getPath(), sender);
1565                 }
1566             }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1567         });
1568
1569     }
1570
1571     private void findLocalShard(FindLocalShard message) {
1572         final ShardInformation shardInformation = localShards.get(message.getShardName());
1573
1574         if (shardInformation == null) {
1575             getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1576             return;
1577         }
1578
1579         sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1580             () -> new LocalShardFound(shardInformation.getActor()));
1581     }
1582
1583     private void findLocalShard(final String shardName, final ActorRef sender,
1584             final Consumer<LocalShardFound> onLocalShardFound) {
1585         Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1586                 .getShardInitializationTimeout().duration().$times(2));
1587
1588         Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1589         futureObj.onComplete(new OnComplete<Object>() {
1590             @Override
1591             public void onComplete(Throwable failure, Object response) {
1592                 if (failure != null) {
1593                     LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1594                             failure);
1595                     sender.tell(new Status.Failure(new RuntimeException(
1596                             String.format("Failed to find local shard %s", shardName), failure)), self());
1597                 } else {
1598                     if (response instanceof LocalShardFound) {
1599                         getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1600                                 sender);
1601                     } else if (response instanceof LocalShardNotFound) {
1602                         String msg = String.format("Local shard %s does not exist", shardName);
1603                         LOG.debug("{}: {}", persistenceId, msg);
1604                         sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
1605                     } else {
1606                         String msg = String.format("Failed to find local shard %s: received response: %s",
1607                                 shardName, response);
1608                         LOG.debug("{}: {}", persistenceId, msg);
1609                         sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1610                                 new RuntimeException(msg)), self());
1611                     }
1612                 }
1613             }
1614         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1615     }
1616
1617     private void changeShardMembersVotingStatus(ChangeServersVotingStatus changeServersVotingStatus,
1618             final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1619         if (isShardReplicaOperationInProgress(shardName, sender)) {
1620             return;
1621         }
1622
1623         shardReplicaOperationsInProgress.add(shardName);
1624
1625         DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1626         final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1627
1628         LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1629                 changeServersVotingStatus, shardActorRef.path());
1630
1631         Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1632         Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1633
1634         futureObj.onComplete(new OnComplete<Object>() {
1635             @Override
1636             public void onComplete(Throwable failure, Object response) {
1637                 shardReplicaOperationsInProgress.remove(shardName);
1638                 if (failure != null) {
1639                     String msg = String.format("ChangeServersVotingStatus request to local shard %s failed",
1640                             shardActorRef.path());
1641                     LOG.debug("{}: {}", persistenceId(), msg, failure);
1642                     sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
1643                 } else {
1644                     LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1645
1646                     ServerChangeReply replyMsg = (ServerChangeReply) response;
1647                     if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1648                         LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1649                         sender.tell(new Status.Success(null), getSelf());
1650                     } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1651                         sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1652                                 "The requested voting state change for shard %s is invalid. At least one member "
1653                                 + "must be voting", shardId.getShardName()))), getSelf());
1654                     } else {
1655                         LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1656                                 persistenceId(), shardName, replyMsg.getStatus());
1657
1658                         Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1659                                 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1660                         sender.tell(new Status.Failure(error), getSelf());
1661                     }
1662                 }
1663             }
1664         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1665     }
1666
1667     private static final class ForwardedAddServerReply {
1668         ShardInformation shardInfo;
1669         AddServerReply addServerReply;
1670         String leaderPath;
1671         boolean removeShardOnFailure;
1672
1673         ForwardedAddServerReply(ShardInformation shardInfo, AddServerReply addServerReply, String leaderPath,
1674                 boolean removeShardOnFailure) {
1675             this.shardInfo = shardInfo;
1676             this.addServerReply = addServerReply;
1677             this.leaderPath = leaderPath;
1678             this.removeShardOnFailure = removeShardOnFailure;
1679         }
1680     }
1681
1682     private static final class ForwardedAddServerFailure {
1683         String shardName;
1684         String failureMessage;
1685         Throwable failure;
1686         boolean removeShardOnFailure;
1687
1688         ForwardedAddServerFailure(String shardName, String failureMessage, Throwable failure,
1689                 boolean removeShardOnFailure) {
1690             this.shardName = shardName;
1691             this.failureMessage = failureMessage;
1692             this.failure = failure;
1693             this.removeShardOnFailure = removeShardOnFailure;
1694         }
1695     }
1696
1697     static class OnShardInitialized {
1698         private final Runnable replyRunnable;
1699         private Cancellable timeoutSchedule;
1700
1701         OnShardInitialized(Runnable replyRunnable) {
1702             this.replyRunnable = replyRunnable;
1703         }
1704
1705         Runnable getReplyRunnable() {
1706             return replyRunnable;
1707         }
1708
1709         Cancellable getTimeoutSchedule() {
1710             return timeoutSchedule;
1711         }
1712
1713         void setTimeoutSchedule(Cancellable timeoutSchedule) {
1714             this.timeoutSchedule = timeoutSchedule;
1715         }
1716     }
1717
1718     static class OnShardReady extends OnShardInitialized {
1719         OnShardReady(Runnable replyRunnable) {
1720             super(replyRunnable);
1721         }
1722     }
1723
1724     private interface RunnableMessage extends Runnable {
1725     }
1726
1727     /**
1728      * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1729      * a remote or local find primary message is processed.
1730      */
1731     private interface FindPrimaryResponseHandler {
1732         /**
1733          * Invoked when a Failure message is received as a response.
1734          *
1735          * @param failure the failure exception
1736          */
1737         void onFailure(Throwable failure);
1738
1739         /**
1740          * Invoked when a RemotePrimaryShardFound response is received.
1741          *
1742          * @param response the response
1743          */
1744         void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1745
1746         /**
1747          * Invoked when a LocalPrimaryShardFound response is received.
1748          *
1749          * @param response the response
1750          */
1751         void onLocalPrimaryFound(LocalPrimaryShardFound response);
1752
1753         /**
1754          * Invoked when an unknown response is received. This is another type of failure.
1755          *
1756          * @param response the response
1757          */
1758         void onUnknownResponse(Object response);
1759     }
1760
1761     /**
1762      * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1763      * replica and sends a wrapped Failure response to some targetActor.
1764      */
1765     private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1766         private final ActorRef targetActor;
1767         private final String shardName;
1768         private final String persistenceId;
1769         private final ActorRef shardManagerActor;
1770
1771         /**
1772          * Constructs an instance.
1773          *
1774          * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1775          * @param shardName The name of the shard for which the primary replica had to be found
1776          * @param persistenceId The persistenceId for the ShardManager
1777          * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1778          */
1779         protected AutoFindPrimaryFailureResponseHandler(ActorRef targetActor, String shardName, String persistenceId,
1780                 ActorRef shardManagerActor) {
1781             this.targetActor = Preconditions.checkNotNull(targetActor);
1782             this.shardName = Preconditions.checkNotNull(shardName);
1783             this.persistenceId = Preconditions.checkNotNull(persistenceId);
1784             this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1785         }
1786
1787         public ActorRef getTargetActor() {
1788             return targetActor;
1789         }
1790
1791         public String getShardName() {
1792             return shardName;
1793         }
1794
1795         @Override
1796         public void onFailure(Throwable failure) {
1797             LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1798             targetActor.tell(new Status.Failure(new RuntimeException(
1799                     String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1800         }
1801
1802         @Override
1803         public void onUnknownResponse(Object response) {
1804             String msg = String.format("Failed to find leader for shard %s: received response: %s",
1805                     shardName, response);
1806             LOG.debug("{}: {}", persistenceId, msg);
1807             targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1808                     new RuntimeException(msg)), shardManagerActor);
1809         }
1810     }
1811
1812     /**
1813      * The WrappedShardResponse class wraps a response from a Shard.
1814      */
1815     private static final class WrappedShardResponse {
1816         private final ShardIdentifier shardId;
1817         private final Object response;
1818         private final String leaderPath;
1819
1820         WrappedShardResponse(ShardIdentifier shardId, Object response, String leaderPath) {
1821             this.shardId = shardId;
1822             this.response = response;
1823             this.leaderPath = leaderPath;
1824         }
1825
1826         ShardIdentifier getShardId() {
1827             return shardId;
1828         }
1829
1830         Object getResponse() {
1831             return response;
1832         }
1833
1834         String getLeaderPath() {
1835             return leaderPath;
1836         }
1837     }
1838
1839     private static final class ShardNotInitializedTimeout {
1840         private final ActorRef sender;
1841         private final ShardInformation shardInfo;
1842         private final OnShardInitialized onShardInitialized;
1843
1844         ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1845             this.sender = sender;
1846             this.shardInfo = shardInfo;
1847             this.onShardInitialized = onShardInitialized;
1848         }
1849
1850         ActorRef getSender() {
1851             return sender;
1852         }
1853
1854         ShardInformation getShardInfo() {
1855             return shardInfo;
1856         }
1857
1858         OnShardInitialized getOnShardInitialized() {
1859             return onShardInitialized;
1860         }
1861     }
1862 }
1863
1864
1865