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