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