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