6d26b8419c3561dd070623821e62cfca116674f2
[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                         shardActorsStopping.remove(shardName);
535                         notifyOnCompleteTasks(failure, result);
536                     }, ActorRef.noSender());
537                 }
538             };
539
540             shardActorsStopping.put(shardName, onComplete);
541             stopFuture.onComplete(onComplete, new Dispatchers(context().system().dispatchers())
542                     .getDispatcher(Dispatchers.DispatcherType.Client));
543         }
544
545         LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardName);
546         persistShardList();
547     }
548
549     private void onGetSnapshot() {
550         LOG.debug("{}: onGetSnapshot", persistenceId());
551
552         List<String> notInitialized = null;
553         for (ShardInformation shardInfo : localShards.values()) {
554             if (!shardInfo.isShardInitialized()) {
555                 if (notInitialized == null) {
556                     notInitialized = new ArrayList<>();
557                 }
558
559                 notInitialized.add(shardInfo.getShardName());
560             }
561         }
562
563         if (notInitialized != null) {
564             getSender().tell(new Status.Failure(new IllegalStateException(String.format(
565                     "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
566             return;
567         }
568
569         ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
570                 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
571                 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
572
573         for (ShardInformation shardInfo: localShards.values()) {
574             shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
575         }
576     }
577
578     @SuppressWarnings("checkstyle:IllegalCatch")
579     private void onCreateShard(final CreateShard createShard) {
580         LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
581
582         Object reply;
583         try {
584             String shardName = createShard.getModuleShardConfig().getShardName();
585             if (localShards.containsKey(shardName)) {
586                 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
587                 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
588             } else {
589                 doCreateShard(createShard);
590                 reply = new Status.Success(null);
591             }
592         } catch (Exception e) {
593             LOG.error("{}: onCreateShard failed", persistenceId(), e);
594             reply = new Status.Failure(e);
595         }
596
597         if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
598             getSender().tell(reply, getSelf());
599         }
600     }
601
602     private void onPrefixShardCreated(final PrefixShardCreated message) {
603         LOG.debug("{}: onPrefixShardCreated: {}", persistenceId(), message);
604
605         final PrefixShardConfiguration config = message.getConfiguration();
606         final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
607                 ClusterUtils.getCleanShardName(config.getPrefix().getRootIdentifier()));
608         final String shardName = shardId.getShardName();
609
610         if (isPreviousShardActorStopInProgress(shardName, message)) {
611             return;
612         }
613
614         if (localShards.containsKey(shardName)) {
615             LOG.debug("{}: Received create for an already existing shard {}", persistenceId(), shardName);
616             final PrefixShardConfiguration existing =
617                     configuration.getAllPrefixShardConfigurations().get(config.getPrefix());
618
619             if (existing != null && existing.equals(config)) {
620                 // we don't have to do nothing here
621                 return;
622             }
623         }
624
625         doCreatePrefixShard(config, shardId, shardName);
626     }
627
628     private boolean isPreviousShardActorStopInProgress(final String shardName, final Object messageToDefer) {
629         final CompositeOnComplete<Boolean> stopOnComplete = shardActorsStopping.get(shardName);
630         if (stopOnComplete == null) {
631             return false;
632         }
633
634         LOG.debug("{} : Stop is in progress for shard {} - adding OnComplete callback to defer {}", persistenceId(),
635                 shardName, messageToDefer);
636         final ActorRef sender = getSender();
637         stopOnComplete.addOnComplete(new OnComplete<Boolean>() {
638             @Override
639             public void onComplete(final Throwable failure, final Boolean result) {
640                 LOG.debug("{} : Stop complete for shard {} - re-queing {}", persistenceId(), shardName, messageToDefer);
641                 self().tell(messageToDefer, sender);
642             }
643         });
644
645         return true;
646     }
647
648     private void doCreatePrefixShard(final PrefixShardConfiguration config, final ShardIdentifier shardId,
649             final String shardName) {
650         configuration.addPrefixShardConfiguration(config);
651
652         final Builder builder = newShardDatastoreContextBuilder(shardName);
653         builder.logicalStoreType(LogicalDatastoreType.valueOf(config.getPrefix().getDatastoreType().name()))
654                 .storeRoot(config.getPrefix().getRootIdentifier());
655         DatastoreContext shardDatastoreContext = builder.build();
656
657         final Map<String, String> peerAddresses = getPeerAddresses(shardName);
658         final boolean isActiveMember = true;
659
660         LOG.debug("{} doCreatePrefixShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
661                 persistenceId(), shardId, config.getShardMemberNames(), peerAddresses, isActiveMember);
662
663         final ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
664                 shardDatastoreContext, Shard.builder(), peerAddressResolver);
665         info.setActiveMember(isActiveMember);
666         localShards.put(info.getShardName(), info);
667
668         if (schemaContext != null) {
669             info.setSchemaContext(schemaContext);
670             info.setActor(newShardActor(info));
671         }
672     }
673
674     private void onPrefixShardRemoved(final PrefixShardRemoved message) {
675         LOG.debug("{}: onPrefixShardRemoved : {}", persistenceId(), message);
676
677         final DOMDataTreeIdentifier prefix = message.getPrefix();
678         final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
679                 ClusterUtils.getCleanShardName(prefix.getRootIdentifier()));
680
681         configuration.removePrefixShardConfiguration(prefix);
682         removeShard(shardId);
683     }
684
685     private void doCreateShard(final CreateShard createShard) {
686         final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
687         final String shardName = moduleShardConfig.getShardName();
688
689         configuration.addModuleShardConfiguration(moduleShardConfig);
690
691         DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
692         if (shardDatastoreContext == null) {
693             shardDatastoreContext = newShardDatastoreContext(shardName);
694         } else {
695             shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
696                     peerAddressResolver).build();
697         }
698
699         ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
700
701         boolean shardWasInRecoveredSnapshot = currentSnapshot != null
702                 && currentSnapshot.getShardList().contains(shardName);
703
704         Map<String, String> peerAddresses;
705         boolean isActiveMember;
706         if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
707                 .contains(cluster.getCurrentMemberName())) {
708             peerAddresses = getPeerAddresses(shardName);
709             isActiveMember = true;
710         } else {
711             // The local member is not in the static shard member configuration and the shard did not
712             // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
713             // the shard with no peers and with elections disabled so it stays as follower. A
714             // subsequent AddServer request will be needed to make it an active member.
715             isActiveMember = false;
716             peerAddresses = Collections.emptyMap();
717             shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
718                     .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
719         }
720
721         LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
722                 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
723                 isActiveMember);
724
725         ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
726                 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
727         info.setActiveMember(isActiveMember);
728         localShards.put(info.getShardName(), info);
729
730         if (schemaContext != null) {
731             info.setSchemaContext(schemaContext);
732             info.setActor(newShardActor(info));
733         }
734     }
735
736     private DatastoreContext.Builder newShardDatastoreContextBuilder(final String shardName) {
737         return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
738                 .shardPeerAddressResolver(peerAddressResolver);
739     }
740
741     private DatastoreContext newShardDatastoreContext(final String shardName) {
742         return newShardDatastoreContextBuilder(shardName).build();
743     }
744
745     private void checkReady() {
746         if (isReadyWithLeaderId()) {
747             LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
748                     persistenceId(), type, waitTillReadyCountdownLatch.getCount());
749
750             waitTillReadyCountdownLatch.countDown();
751         }
752     }
753
754     private void onLeaderStateChanged(final ShardLeaderStateChanged leaderStateChanged) {
755         LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
756
757         ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
758         if (shardInformation != null) {
759             shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
760             shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
761             if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
762                 primaryShardInfoCache.remove(shardInformation.getShardName());
763             }
764
765             checkReady();
766         } else {
767             LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
768         }
769     }
770
771     private void onShardNotInitializedTimeout(final ShardNotInitializedTimeout message) {
772         ShardInformation shardInfo = message.getShardInfo();
773
774         LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
775                 shardInfo.getShardName());
776
777         shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
778
779         if (!shardInfo.isShardInitialized()) {
780             LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
781             message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
782         } else {
783             LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
784             message.getSender().tell(createNoShardLeaderException(shardInfo.getShardId()), getSelf());
785         }
786     }
787
788     private void onFollowerInitialSyncStatus(final FollowerInitialSyncUpStatus status) {
789         LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
790                 status.getName(), status.isInitialSyncDone());
791
792         ShardInformation shardInformation = findShardInformation(status.getName());
793
794         if (shardInformation != null) {
795             shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
796
797             shardManagerMBean.setSyncStatus(isInSync());
798         }
799
800     }
801
802     private void onRoleChangeNotification(final RoleChangeNotification roleChanged) {
803         LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
804                 roleChanged.getOldRole(), roleChanged.getNewRole());
805
806         ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
807         if (shardInformation != null) {
808             shardInformation.setRole(roleChanged.getNewRole());
809             checkReady();
810             shardManagerMBean.setSyncStatus(isInSync());
811         }
812     }
813
814
815     private ShardInformation findShardInformation(final String memberId) {
816         for (ShardInformation info : localShards.values()) {
817             if (info.getShardId().toString().equals(memberId)) {
818                 return info;
819             }
820         }
821
822         return null;
823     }
824
825     private boolean isReadyWithLeaderId() {
826         boolean isReady = true;
827         for (ShardInformation info : localShards.values()) {
828             if (!info.isShardReadyWithLeaderId()) {
829                 isReady = false;
830                 break;
831             }
832         }
833         return isReady;
834     }
835
836     private boolean isInSync() {
837         for (ShardInformation info : localShards.values()) {
838             if (!info.isInSync()) {
839                 return false;
840             }
841         }
842         return true;
843     }
844
845     private void onActorInitialized(final Object message) {
846         final ActorRef sender = getSender();
847
848         if (sender == null) {
849             return; //why is a non-actor sending this message? Just ignore.
850         }
851
852         String actorName = sender.path().name();
853         //find shard name from actor name; actor name is stringified shardId
854
855         final ShardIdentifier shardId;
856         try {
857             shardId = ShardIdentifier.fromShardIdString(actorName);
858         } catch (IllegalArgumentException e) {
859             LOG.debug("{}: ignoring actor {}", actorName, e);
860             return;
861         }
862
863         markShardAsInitialized(shardId.getShardName());
864     }
865
866     private void markShardAsInitialized(final String shardName) {
867         LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
868
869         ShardInformation shardInformation = localShards.get(shardName);
870         if (shardInformation != null) {
871             shardInformation.setActorInitialized();
872
873             shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
874         }
875     }
876
877     @Override
878     protected void handleRecover(final Object message) throws Exception {
879         if (message instanceof RecoveryCompleted) {
880             onRecoveryCompleted();
881         } else if (message instanceof SnapshotOffer) {
882             applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
883         }
884     }
885
886     @SuppressWarnings("checkstyle:IllegalCatch")
887     private void onRecoveryCompleted() {
888         LOG.info("Recovery complete : {}", persistenceId());
889
890         if (currentSnapshot == null && restoreFromSnapshot != null
891                 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
892             ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
893
894             LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
895
896             applyShardManagerSnapshot(snapshot);
897         }
898
899         createLocalShards();
900     }
901
902     private void sendResponse(final ShardInformation shardInformation, final boolean doWait,
903             final boolean wantShardReady, final Supplier<Object> messageSupplier) {
904         if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
905             if (doWait) {
906                 final ActorRef sender = getSender();
907                 final ActorRef self = self();
908
909                 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
910
911                 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
912                     new OnShardInitialized(replyRunnable);
913
914                 shardInformation.addOnShardInitialized(onShardInitialized);
915
916                 FiniteDuration timeout = shardInformation.getDatastoreContext()
917                         .getShardInitializationTimeout().duration();
918                 if (shardInformation.isShardInitialized()) {
919                     // If the shard is already initialized then we'll wait enough time for the shard to
920                     // elect a leader, ie 2 times the election timeout.
921                     timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
922                             .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
923                 }
924
925                 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
926                         shardInformation.getShardName());
927
928                 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
929                         timeout, getSelf(),
930                         new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
931                         getContext().dispatcher(), getSelf());
932
933                 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
934
935             } else if (!shardInformation.isShardInitialized()) {
936                 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
937                         shardInformation.getShardName());
938                 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
939             } else {
940                 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
941                         shardInformation.getShardName());
942                 getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
943             }
944
945             return;
946         }
947
948         getSender().tell(messageSupplier.get(), getSelf());
949     }
950
951     private static NoShardLeaderException createNoShardLeaderException(final ShardIdentifier shardId) {
952         return new NoShardLeaderException(null, shardId.toString());
953     }
954
955     private static NotInitializedException createNotInitializedException(final ShardIdentifier shardId) {
956         return new NotInitializedException(String.format(
957                 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
958     }
959
960     @VisibleForTesting
961     static MemberName memberToName(final Member member) {
962         return MemberName.forName(member.roles().iterator().next());
963     }
964
965     private void memberRemoved(final ClusterEvent.MemberRemoved message) {
966         MemberName memberName = memberToName(message.member());
967
968         LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
969                 message.member().address());
970
971         peerAddressResolver.removePeerAddress(memberName);
972
973         for (ShardInformation info : localShards.values()) {
974             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
975         }
976     }
977
978     private void memberExited(final ClusterEvent.MemberExited message) {
979         MemberName memberName = memberToName(message.member());
980
981         LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
982                 message.member().address());
983
984         peerAddressResolver.removePeerAddress(memberName);
985
986         for (ShardInformation info : localShards.values()) {
987             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
988         }
989     }
990
991     private void memberUp(final ClusterEvent.MemberUp message) {
992         MemberName memberName = memberToName(message.member());
993
994         LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
995                 message.member().address());
996
997         memberUp(memberName, message.member().address());
998     }
999
1000     private void memberUp(final MemberName memberName, final Address address) {
1001         addPeerAddress(memberName, address);
1002         checkReady();
1003     }
1004
1005     private void memberWeaklyUp(final MemberWeaklyUp message) {
1006         MemberName memberName = memberToName(message.member());
1007
1008         LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
1009                 message.member().address());
1010
1011         memberUp(memberName, message.member().address());
1012     }
1013
1014     private void addPeerAddress(final MemberName memberName, final Address address) {
1015         peerAddressResolver.addPeerAddress(memberName, address);
1016
1017         for (ShardInformation info : localShards.values()) {
1018             String shardName = info.getShardName();
1019             String peerId = getShardIdentifier(memberName, shardName).toString();
1020             info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
1021
1022             info.peerUp(memberName, peerId, getSelf());
1023         }
1024     }
1025
1026     private void memberReachable(final ClusterEvent.ReachableMember message) {
1027         MemberName memberName = memberToName(message.member());
1028         LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
1029
1030         addPeerAddress(memberName, message.member().address());
1031
1032         markMemberAvailable(memberName);
1033     }
1034
1035     private void memberUnreachable(final ClusterEvent.UnreachableMember message) {
1036         MemberName memberName = memberToName(message.member());
1037         LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
1038
1039         markMemberUnavailable(memberName);
1040     }
1041
1042     private void markMemberUnavailable(final MemberName memberName) {
1043         final String memberStr = memberName.getName();
1044         for (ShardInformation info : localShards.values()) {
1045             String leaderId = info.getLeaderId();
1046             // XXX: why are we using String#contains() here?
1047             if (leaderId != null && leaderId.contains(memberStr)) {
1048                 LOG.debug("Marking Leader {} as unavailable.", leaderId);
1049                 info.setLeaderAvailable(false);
1050
1051                 primaryShardInfoCache.remove(info.getShardName());
1052             }
1053
1054             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1055         }
1056     }
1057
1058     private void markMemberAvailable(final MemberName memberName) {
1059         final String memberStr = memberName.getName();
1060         for (ShardInformation info : localShards.values()) {
1061             String leaderId = info.getLeaderId();
1062             // XXX: why are we using String#contains() here?
1063             if (leaderId != null && leaderId.contains(memberStr)) {
1064                 LOG.debug("Marking Leader {} as available.", leaderId);
1065                 info.setLeaderAvailable(true);
1066             }
1067
1068             info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1069         }
1070     }
1071
1072     private void onDatastoreContextFactory(final DatastoreContextFactory factory) {
1073         datastoreContextFactory = factory;
1074         for (ShardInformation info : localShards.values()) {
1075             info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
1076         }
1077     }
1078
1079     private void onGetLocalShardIds() {
1080         final List<String> response = new ArrayList<>(localShards.size());
1081
1082         for (ShardInformation info : localShards.values()) {
1083             response.add(info.getShardId().toString());
1084         }
1085
1086         getSender().tell(new Status.Success(response), getSelf());
1087     }
1088
1089     private void onSwitchShardBehavior(final SwitchShardBehavior message) {
1090         final ShardIdentifier identifier = message.getShardId();
1091
1092         if (identifier != null) {
1093             final ShardInformation info = localShards.get(identifier.getShardName());
1094             if (info == null) {
1095                 getSender().tell(new Status.Failure(
1096                     new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
1097                 return;
1098             }
1099
1100             switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1101         } else {
1102             for (ShardInformation info : localShards.values()) {
1103                 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1104             }
1105         }
1106
1107         getSender().tell(new Status.Success(null), getSelf());
1108     }
1109
1110     private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
1111         final ActorRef actor = info.getActor();
1112         if (actor != null) {
1113             actor.tell(switchBehavior, getSelf());
1114         } else {
1115             LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
1116                 info.getShardName(), switchBehavior.getNewState());
1117         }
1118     }
1119
1120     /**
1121      * Notifies all the local shards of a change in the schema context.
1122      *
1123      * @param message the message to send
1124      */
1125     private void updateSchemaContext(final Object message) {
1126         schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
1127
1128         LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
1129
1130         for (ShardInformation info : localShards.values()) {
1131             info.setSchemaContext(schemaContext);
1132
1133             if (info.getActor() == null) {
1134                 LOG.debug("Creating Shard {}", info.getShardId());
1135                 info.setActor(newShardActor(info));
1136             } else {
1137                 info.getActor().tell(message, getSelf());
1138             }
1139         }
1140     }
1141
1142     @VisibleForTesting
1143     protected ClusterWrapper getCluster() {
1144         return cluster;
1145     }
1146
1147     @VisibleForTesting
1148     protected ActorRef newShardActor(final ShardInformation info) {
1149         return getContext().actorOf(info.newProps().withDispatcher(shardDispatcherPath),
1150                 info.getShardId().toString());
1151     }
1152
1153     private void findPrimary(final FindPrimary message) {
1154         LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1155
1156         final String shardName = message.getShardName();
1157         final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1158
1159         // First see if the there is a local replica for the shard
1160         final ShardInformation info = localShards.get(shardName);
1161         if (info != null && info.isActiveMember()) {
1162             sendResponse(info, message.isWaitUntilReady(), true, () -> {
1163                 String primaryPath = info.getSerializedLeaderActor();
1164                 Object found = canReturnLocalShardState && info.isLeader()
1165                         ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1166                             new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1167
1168                 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1169                 return found;
1170             });
1171
1172             return;
1173         }
1174
1175         final Collection<String> visitedAddresses;
1176         if (message instanceof RemoteFindPrimary) {
1177             visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1178         } else {
1179             visitedAddresses = new ArrayList<>(1);
1180         }
1181
1182         visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1183
1184         for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1185             if (visitedAddresses.contains(address)) {
1186                 continue;
1187             }
1188
1189             LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1190                     persistenceId(), shardName, address, visitedAddresses);
1191
1192             getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1193                     message.isWaitUntilReady(), visitedAddresses), getContext());
1194             return;
1195         }
1196
1197         LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1198
1199         getSender().tell(new PrimaryNotFoundException(
1200                 String.format("No primary shard found for %s.", shardName)), getSelf());
1201     }
1202
1203     private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1204         Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1205                 .getShardInitializationTimeout().duration().$times(2));
1206
1207         Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1208         futureObj.onComplete(new OnComplete<Object>() {
1209             @Override
1210             public void onComplete(final Throwable failure, final Object response) {
1211                 if (failure != null) {
1212                     handler.onFailure(failure);
1213                 } else {
1214                     if (response instanceof RemotePrimaryShardFound) {
1215                         handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1216                     } else if (response instanceof LocalPrimaryShardFound) {
1217                         handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1218                     } else {
1219                         handler.onUnknownResponse(response);
1220                     }
1221                 }
1222             }
1223         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1224     }
1225
1226     /**
1227      * Construct the name of the shard actor given the name of the member on
1228      * which the shard resides and the name of the shard.
1229      *
1230      * @param memberName the member name
1231      * @param shardName the shard name
1232      * @return a b
1233      */
1234     private ShardIdentifier getShardIdentifier(final MemberName memberName, final String shardName) {
1235         return peerAddressResolver.getShardIdentifier(memberName, shardName);
1236     }
1237
1238     /**
1239      * Create shards that are local to the member on which the ShardManager runs.
1240      */
1241     private void createLocalShards() {
1242         MemberName memberName = this.cluster.getCurrentMemberName();
1243         Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1244
1245         Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1246         if (restoreFromSnapshot != null) {
1247             for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1248                 shardSnapshots.put(snapshot.getName(), snapshot);
1249             }
1250         }
1251
1252         restoreFromSnapshot = null; // null out to GC
1253
1254         for (String shardName : memberShardNames) {
1255             ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1256
1257             LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1258
1259             Map<String, String> peerAddresses = getPeerAddresses(shardName);
1260             localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
1261                     newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
1262                         shardSnapshots.get(shardName)), peerAddressResolver));
1263         }
1264     }
1265
1266     /**
1267      * Given the name of the shard find the addresses of all it's peers.
1268      *
1269      * @param shardName the shard name
1270      */
1271     private Map<String, String> getPeerAddresses(final String shardName) {
1272         final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1273         return getPeerAddresses(shardName, members);
1274     }
1275
1276     private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1277         Map<String, String> peerAddresses = new HashMap<>();
1278         MemberName currentMemberName = this.cluster.getCurrentMemberName();
1279
1280         for (MemberName memberName : members) {
1281             if (!currentMemberName.equals(memberName)) {
1282                 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1283                 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1284                 peerAddresses.put(shardId.toString(), address);
1285             }
1286         }
1287         return peerAddresses;
1288     }
1289
1290     @Override
1291     public SupervisorStrategy supervisorStrategy() {
1292
1293         return new OneForOneStrategy(10, Duration.create("1 minute"),
1294                 (Function<Throwable, Directive>) t -> {
1295                     LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1296                     return SupervisorStrategy.resume();
1297                 });
1298     }
1299
1300     @Override
1301     public String persistenceId() {
1302         return persistenceId;
1303     }
1304
1305     @VisibleForTesting
1306     ShardManagerInfoMBean getMBean() {
1307         return shardManagerMBean;
1308     }
1309
1310     private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1311         if (shardReplicaOperationsInProgress.contains(shardName)) {
1312             String msg = String.format("A shard replica operation for %s is already in progress", shardName);
1313             LOG.debug("{}: {}", persistenceId(), msg);
1314             sender.tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1315             return true;
1316         }
1317
1318         return false;
1319     }
1320
1321     private void onAddPrefixShardReplica(final AddPrefixShardReplica message) {
1322         LOG.debug("{}: onAddPrefixShardReplica: {}", persistenceId(), message);
1323
1324         final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1325                 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1326         final String shardName = shardId.getShardName();
1327
1328         // Create the localShard
1329         if (schemaContext == null) {
1330             String msg = String.format(
1331                     "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1332             LOG.debug("{}: {}", persistenceId(), msg);
1333             getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1334             return;
1335         }
1336
1337         findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1338                 getSelf()) {
1339             @Override
1340             public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1341                 final RunnableMessage runnable = (RunnableMessage) () -> addPrefixShard(getShardName(),
1342                         message.getShardPrefix(), response, getSender());
1343                 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1344                     getSelf().tell(runnable, getTargetActor());
1345                 }
1346             }
1347
1348             @Override
1349             public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1350                 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1351             }
1352         });
1353     }
1354
1355     private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1356         final String shardName = shardReplicaMsg.getShardName();
1357
1358         LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1359
1360         // verify the shard with the specified name is present in the cluster configuration
1361         if (!this.configuration.isShardConfigured(shardName)) {
1362             String msg = String.format("No module configuration exists for shard %s", shardName);
1363             LOG.debug("{}: {}", persistenceId(), msg);
1364             getSender().tell(new Status.Failure(new IllegalArgumentException(msg)), getSelf());
1365             return;
1366         }
1367
1368         // Create the localShard
1369         if (schemaContext == null) {
1370             String msg = String.format(
1371                   "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1372             LOG.debug("{}: {}", persistenceId(), msg);
1373             getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1374             return;
1375         }
1376
1377         findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1378                 getSelf()) {
1379             @Override
1380             public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1381                 final RunnableMessage runnable = (RunnableMessage) () ->
1382                     addShard(getShardName(), response, getSender());
1383                 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1384                     getSelf().tell(runnable, getTargetActor());
1385                 }
1386             }
1387
1388             @Override
1389             public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1390                 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1391             }
1392         });
1393     }
1394
1395     private void sendLocalReplicaAlreadyExistsReply(final String shardName, final ActorRef sender) {
1396         String msg = String.format("Local shard %s already exists", shardName);
1397         LOG.debug("{}: {}", persistenceId(), msg);
1398         sender.tell(new Status.Failure(new AlreadyExistsException(msg)), getSelf());
1399     }
1400
1401     private void addPrefixShard(final String shardName, final YangInstanceIdentifier shardPrefix,
1402                                 final RemotePrimaryShardFound response, final ActorRef sender) {
1403         if (isShardReplicaOperationInProgress(shardName, sender)) {
1404             return;
1405         }
1406
1407         shardReplicaOperationsInProgress.add(shardName);
1408
1409         final ShardInformation shardInfo;
1410         final boolean removeShardOnFailure;
1411         ShardInformation existingShardInfo = localShards.get(shardName);
1412         if (existingShardInfo == null) {
1413             removeShardOnFailure = true;
1414             ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1415
1416             final Builder builder = newShardDatastoreContextBuilder(shardName);
1417             builder.storeRoot(shardPrefix).customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1418
1419             DatastoreContext datastoreContext = builder.build();
1420
1421             shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1422                     Shard.builder(), peerAddressResolver);
1423             shardInfo.setActiveMember(false);
1424             shardInfo.setSchemaContext(schemaContext);
1425             localShards.put(shardName, shardInfo);
1426             shardInfo.setActor(newShardActor(shardInfo));
1427         } else {
1428             removeShardOnFailure = false;
1429             shardInfo = existingShardInfo;
1430         }
1431
1432         execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1433     }
1434
1435     private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1436         if (isShardReplicaOperationInProgress(shardName, sender)) {
1437             return;
1438         }
1439
1440         shardReplicaOperationsInProgress.add(shardName);
1441
1442         final ShardInformation shardInfo;
1443         final boolean removeShardOnFailure;
1444         ShardInformation existingShardInfo = localShards.get(shardName);
1445         if (existingShardInfo == null) {
1446             removeShardOnFailure = true;
1447             ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1448
1449             DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1450                     .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1451
1452             shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1453                     Shard.builder(), peerAddressResolver);
1454             shardInfo.setActiveMember(false);
1455             shardInfo.setSchemaContext(schemaContext);
1456             localShards.put(shardName, shardInfo);
1457             shardInfo.setActor(newShardActor(shardInfo));
1458         } else {
1459             removeShardOnFailure = false;
1460             shardInfo = existingShardInfo;
1461         }
1462
1463         execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1464     }
1465
1466     private void execAddShard(final String shardName,
1467                               final ShardInformation shardInfo,
1468                               final RemotePrimaryShardFound response,
1469                               final boolean removeShardOnFailure,
1470                               final ActorRef sender) {
1471
1472         final String localShardAddress =
1473                 peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1474
1475         //inform ShardLeader to add this shard as a replica by sending an AddServer message
1476         LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1477                 response.getPrimaryPath(), shardInfo.getShardId());
1478
1479         final Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1480                 .getShardLeaderElectionTimeout().duration());
1481         final Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1482                 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1483
1484         futureObj.onComplete(new OnComplete<Object>() {
1485             @Override
1486             public void onComplete(final Throwable failure, final Object addServerResponse) {
1487                 if (failure != null) {
1488                     LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1489                             response.getPrimaryPath(), shardName, failure);
1490
1491                     final String msg = String.format("AddServer request to leader %s for shard %s failed",
1492                             response.getPrimaryPath(), shardName);
1493                     self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1494                 } else {
1495                     self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1496                             response.getPrimaryPath(), removeShardOnFailure), sender);
1497                 }
1498             }
1499         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1500     }
1501
1502     private void onAddServerFailure(final String shardName, final String message, final Throwable failure,
1503             final ActorRef sender, final boolean removeShardOnFailure) {
1504         shardReplicaOperationsInProgress.remove(shardName);
1505
1506         if (removeShardOnFailure) {
1507             ShardInformation shardInfo = localShards.remove(shardName);
1508             if (shardInfo.getActor() != null) {
1509                 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1510             }
1511         }
1512
1513         sender.tell(new Status.Failure(message == null ? failure :
1514             new RuntimeException(message, failure)), getSelf());
1515     }
1516
1517     private void onAddServerReply(final ShardInformation shardInfo, final AddServerReply replyMsg,
1518             final ActorRef sender, final String leaderPath, final boolean removeShardOnFailure) {
1519         String shardName = shardInfo.getShardName();
1520         shardReplicaOperationsInProgress.remove(shardName);
1521
1522         LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1523
1524         if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1525             LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1526
1527             // Make the local shard voting capable
1528             shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1529             shardInfo.setActiveMember(true);
1530             persistShardList();
1531
1532             sender.tell(new Status.Success(null), getSelf());
1533         } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1534             sendLocalReplicaAlreadyExistsReply(shardName, sender);
1535         } else {
1536             LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1537                     persistenceId(), shardName, replyMsg.getStatus());
1538
1539             Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1540                     shardInfo.getShardId());
1541
1542             onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1543         }
1544     }
1545
1546     private static Exception getServerChangeException(final Class<?> serverChange,
1547             final ServerChangeStatus serverChangeStatus, final String leaderPath, final ShardIdentifier shardId) {
1548         switch (serverChangeStatus) {
1549             case TIMEOUT:
1550                 return new TimeoutException(String.format(
1551                         "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1552                         + "Possible causes - there was a problem replicating the data or shard leadership changed "
1553                         + "while replicating the shard data", leaderPath, shardId.getShardName()));
1554             case NO_LEADER:
1555                 return createNoShardLeaderException(shardId);
1556             case NOT_SUPPORTED:
1557                 return new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1558                         serverChange.getSimpleName(), shardId.getShardName()));
1559             default :
1560                 return new RuntimeException(String.format("%s request to leader %s for shard %s failed with status %s",
1561                         serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1562         }
1563     }
1564
1565     private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1566         LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1567
1568         findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1569                 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1570             @Override
1571             public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1572                 doRemoveShardReplicaAsync(response.getPrimaryPath());
1573             }
1574
1575             @Override
1576             public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1577                 doRemoveShardReplicaAsync(response.getPrimaryPath());
1578             }
1579
1580             private void doRemoveShardReplicaAsync(final String primaryPath) {
1581                 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1582                         primaryPath, getSender()), getTargetActor());
1583             }
1584         });
1585     }
1586
1587     private void onRemovePrefixShardReplica(final RemovePrefixShardReplica message) {
1588         LOG.debug("{}: onRemovePrefixShardReplica: {}", persistenceId(), message);
1589
1590         final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1591                 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1592         final String shardName = shardId.getShardName();
1593
1594         findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(),
1595                 shardName, persistenceId(), getSelf()) {
1596             @Override
1597             public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1598                 doRemoveShardReplicaAsync(response.getPrimaryPath());
1599             }
1600
1601             @Override
1602             public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1603                 doRemoveShardReplicaAsync(response.getPrimaryPath());
1604             }
1605
1606             private void doRemoveShardReplicaAsync(final String primaryPath) {
1607                 getSelf().tell((RunnableMessage) () -> removePrefixShardReplica(message, getShardName(),
1608                         primaryPath, getSender()), getTargetActor());
1609             }
1610         });
1611     }
1612
1613     private void persistShardList() {
1614         List<String> shardList = new ArrayList<>(localShards.keySet());
1615         for (ShardInformation shardInfo : localShards.values()) {
1616             if (!shardInfo.isActiveMember()) {
1617                 shardList.remove(shardInfo.getShardName());
1618             }
1619         }
1620         LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1621         saveSnapshot(updateShardManagerSnapshot(shardList, configuration.getAllPrefixShardConfigurations()));
1622     }
1623
1624     private ShardManagerSnapshot updateShardManagerSnapshot(
1625             final List<String> shardList,
1626             final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> allPrefixShardConfigurations) {
1627         currentSnapshot = new ShardManagerSnapshot(shardList, allPrefixShardConfigurations);
1628         return currentSnapshot;
1629     }
1630
1631     private void applyShardManagerSnapshot(final ShardManagerSnapshot snapshot) {
1632         currentSnapshot = snapshot;
1633
1634         LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1635
1636         final MemberName currentMember = cluster.getCurrentMemberName();
1637         Set<String> configuredShardList =
1638             new HashSet<>(configuration.getMemberShardNames(currentMember));
1639         for (String shard : currentSnapshot.getShardList()) {
1640             if (!configuredShardList.contains(shard)) {
1641                 // add the current member as a replica for the shard
1642                 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1643                 configuration.addMemberReplicaForShard(shard, currentMember);
1644             } else {
1645                 configuredShardList.remove(shard);
1646             }
1647         }
1648         for (String shard : configuredShardList) {
1649             // remove the member as a replica for the shard
1650             LOG.debug("{}: removing shard {}", persistenceId(), shard);
1651             configuration.removeMemberReplicaForShard(shard, currentMember);
1652         }
1653     }
1654
1655     private void onSaveSnapshotSuccess(final SaveSnapshotSuccess successMessage) {
1656         LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1657             persistenceId());
1658         deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1659             0, 0));
1660     }
1661
1662     private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1663         LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1664
1665         String shardName = changeMembersVotingStatus.getShardName();
1666         Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1667         for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1668             serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1669                     e.getValue());
1670         }
1671
1672         ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1673
1674         findLocalShard(shardName, getSender(),
1675             localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1676             localShardFound.getPath(), getSender()));
1677     }
1678
1679     private void onFlipShardMembersVotingStatus(final FlipShardMembersVotingStatus flipMembersVotingStatus) {
1680         LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1681
1682         ActorRef sender = getSender();
1683         final String shardName = flipMembersVotingStatus.getShardName();
1684         findLocalShard(shardName, sender, localShardFound -> {
1685             Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1686                     Timeout.apply(30, TimeUnit.SECONDS));
1687
1688             future.onComplete(new OnComplete<Object>() {
1689                 @Override
1690                 public void onComplete(final Throwable failure, final Object response) {
1691                     if (failure != null) {
1692                         sender.tell(new Status.Failure(new RuntimeException(
1693                                 String.format("Failed to access local shard %s", shardName), failure)), self());
1694                         return;
1695                     }
1696
1697                     OnDemandRaftState raftState = (OnDemandRaftState) response;
1698                     Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1699                     for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1700                         serverVotingStatusMap.put(e.getKey(), !e.getValue());
1701                     }
1702
1703                     serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1704                             .toString(), !raftState.isVoting());
1705
1706                     changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1707                             shardName, localShardFound.getPath(), sender);
1708                 }
1709             }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1710         });
1711
1712     }
1713
1714     private void findLocalShard(final FindLocalShard message) {
1715         LOG.debug("{}: findLocalShard : {}", persistenceId(), message.getShardName());
1716
1717         final ShardInformation shardInformation = localShards.get(message.getShardName());
1718
1719         if (shardInformation == null) {
1720             LOG.debug("{}: Local shard {} not found - shards present: {}",
1721                     persistenceId(), message.getShardName(), localShards.keySet());
1722
1723             getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1724             return;
1725         }
1726
1727         sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1728             () -> new LocalShardFound(shardInformation.getActor()));
1729     }
1730
1731     private void findLocalShard(final String shardName, final ActorRef sender,
1732             final Consumer<LocalShardFound> onLocalShardFound) {
1733         Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1734                 .getShardInitializationTimeout().duration().$times(2));
1735
1736         Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1737         futureObj.onComplete(new OnComplete<Object>() {
1738             @Override
1739             public void onComplete(final Throwable failure, final Object response) {
1740                 if (failure != null) {
1741                     LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1742                             failure);
1743                     sender.tell(new Status.Failure(new RuntimeException(
1744                             String.format("Failed to find local shard %s", shardName), failure)), self());
1745                 } else {
1746                     if (response instanceof LocalShardFound) {
1747                         getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1748                                 sender);
1749                     } else if (response instanceof LocalShardNotFound) {
1750                         String msg = String.format("Local shard %s does not exist", shardName);
1751                         LOG.debug("{}: {}", persistenceId, msg);
1752                         sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
1753                     } else {
1754                         String msg = String.format("Failed to find local shard %s: received response: %s",
1755                                 shardName, response);
1756                         LOG.debug("{}: {}", persistenceId, msg);
1757                         sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1758                                 new RuntimeException(msg)), self());
1759                     }
1760                 }
1761             }
1762         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1763     }
1764
1765     private void changeShardMembersVotingStatus(final ChangeServersVotingStatus changeServersVotingStatus,
1766             final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1767         if (isShardReplicaOperationInProgress(shardName, sender)) {
1768             return;
1769         }
1770
1771         shardReplicaOperationsInProgress.add(shardName);
1772
1773         DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1774         final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1775
1776         LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1777                 changeServersVotingStatus, shardActorRef.path());
1778
1779         Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1780         Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1781
1782         futureObj.onComplete(new OnComplete<Object>() {
1783             @Override
1784             public void onComplete(final Throwable failure, final Object response) {
1785                 shardReplicaOperationsInProgress.remove(shardName);
1786                 if (failure != null) {
1787                     String msg = String.format("ChangeServersVotingStatus request to local shard %s failed",
1788                             shardActorRef.path());
1789                     LOG.debug("{}: {}", persistenceId(), msg, failure);
1790                     sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
1791                 } else {
1792                     LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1793
1794                     ServerChangeReply replyMsg = (ServerChangeReply) response;
1795                     if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1796                         LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1797                         sender.tell(new Status.Success(null), getSelf());
1798                     } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1799                         sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1800                                 "The requested voting state change for shard %s is invalid. At least one member "
1801                                 + "must be voting", shardId.getShardName()))), getSelf());
1802                     } else {
1803                         LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1804                                 persistenceId(), shardName, replyMsg.getStatus());
1805
1806                         Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1807                                 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1808                         sender.tell(new Status.Failure(error), getSelf());
1809                     }
1810                 }
1811             }
1812         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1813     }
1814
1815     private static final class ForwardedAddServerReply {
1816         ShardInformation shardInfo;
1817         AddServerReply addServerReply;
1818         String leaderPath;
1819         boolean removeShardOnFailure;
1820
1821         ForwardedAddServerReply(final ShardInformation shardInfo, final AddServerReply addServerReply,
1822             final String leaderPath, final boolean removeShardOnFailure) {
1823             this.shardInfo = shardInfo;
1824             this.addServerReply = addServerReply;
1825             this.leaderPath = leaderPath;
1826             this.removeShardOnFailure = removeShardOnFailure;
1827         }
1828     }
1829
1830     private static final class ForwardedAddServerFailure {
1831         String shardName;
1832         String failureMessage;
1833         Throwable failure;
1834         boolean removeShardOnFailure;
1835
1836         ForwardedAddServerFailure(final String shardName, final String failureMessage, final Throwable failure,
1837                 final boolean removeShardOnFailure) {
1838             this.shardName = shardName;
1839             this.failureMessage = failureMessage;
1840             this.failure = failure;
1841             this.removeShardOnFailure = removeShardOnFailure;
1842         }
1843     }
1844
1845     static class OnShardInitialized {
1846         private final Runnable replyRunnable;
1847         private Cancellable timeoutSchedule;
1848
1849         OnShardInitialized(final Runnable replyRunnable) {
1850             this.replyRunnable = replyRunnable;
1851         }
1852
1853         Runnable getReplyRunnable() {
1854             return replyRunnable;
1855         }
1856
1857         Cancellable getTimeoutSchedule() {
1858             return timeoutSchedule;
1859         }
1860
1861         void setTimeoutSchedule(final Cancellable timeoutSchedule) {
1862             this.timeoutSchedule = timeoutSchedule;
1863         }
1864     }
1865
1866     static class OnShardReady extends OnShardInitialized {
1867         OnShardReady(final Runnable replyRunnable) {
1868             super(replyRunnable);
1869         }
1870     }
1871
1872     private interface RunnableMessage extends Runnable {
1873     }
1874
1875     /**
1876      * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1877      * a remote or local find primary message is processed.
1878      */
1879     private interface FindPrimaryResponseHandler {
1880         /**
1881          * Invoked when a Failure message is received as a response.
1882          *
1883          * @param failure the failure exception
1884          */
1885         void onFailure(Throwable failure);
1886
1887         /**
1888          * Invoked when a RemotePrimaryShardFound response is received.
1889          *
1890          * @param response the response
1891          */
1892         void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1893
1894         /**
1895          * Invoked when a LocalPrimaryShardFound response is received.
1896          *
1897          * @param response the response
1898          */
1899         void onLocalPrimaryFound(LocalPrimaryShardFound response);
1900
1901         /**
1902          * Invoked when an unknown response is received. This is another type of failure.
1903          *
1904          * @param response the response
1905          */
1906         void onUnknownResponse(Object response);
1907     }
1908
1909     /**
1910      * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1911      * replica and sends a wrapped Failure response to some targetActor.
1912      */
1913     private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1914         private final ActorRef targetActor;
1915         private final String shardName;
1916         private final String persistenceId;
1917         private final ActorRef shardManagerActor;
1918
1919         /**
1920          * Constructs an instance.
1921          *
1922          * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1923          * @param shardName The name of the shard for which the primary replica had to be found
1924          * @param persistenceId The persistenceId for the ShardManager
1925          * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1926          */
1927         protected AutoFindPrimaryFailureResponseHandler(final ActorRef targetActor, final String shardName,
1928                 final String persistenceId, final ActorRef shardManagerActor) {
1929             this.targetActor = Preconditions.checkNotNull(targetActor);
1930             this.shardName = Preconditions.checkNotNull(shardName);
1931             this.persistenceId = Preconditions.checkNotNull(persistenceId);
1932             this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1933         }
1934
1935         public ActorRef getTargetActor() {
1936             return targetActor;
1937         }
1938
1939         public String getShardName() {
1940             return shardName;
1941         }
1942
1943         @Override
1944         public void onFailure(final Throwable failure) {
1945             LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1946             targetActor.tell(new Status.Failure(new RuntimeException(
1947                     String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1948         }
1949
1950         @Override
1951         public void onUnknownResponse(final Object response) {
1952             String msg = String.format("Failed to find leader for shard %s: received response: %s",
1953                     shardName, response);
1954             LOG.debug("{}: {}", persistenceId, msg);
1955             targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1956                     new RuntimeException(msg)), shardManagerActor);
1957         }
1958     }
1959
1960     /**
1961      * The WrappedShardResponse class wraps a response from a Shard.
1962      */
1963     private static final class WrappedShardResponse {
1964         private final ShardIdentifier shardId;
1965         private final Object response;
1966         private final String leaderPath;
1967
1968         WrappedShardResponse(final ShardIdentifier shardId, final Object response, final String leaderPath) {
1969             this.shardId = shardId;
1970             this.response = response;
1971             this.leaderPath = leaderPath;
1972         }
1973
1974         ShardIdentifier getShardId() {
1975             return shardId;
1976         }
1977
1978         Object getResponse() {
1979             return response;
1980         }
1981
1982         String getLeaderPath() {
1983             return leaderPath;
1984         }
1985     }
1986
1987     private static final class ShardNotInitializedTimeout {
1988         private final ActorRef sender;
1989         private final ShardInformation shardInfo;
1990         private final OnShardInitialized onShardInitialized;
1991
1992         ShardNotInitializedTimeout(final ShardInformation shardInfo, final OnShardInitialized onShardInitialized,
1993             final ActorRef sender) {
1994             this.sender = sender;
1995             this.shardInfo = shardInfo;
1996             this.onShardInitialized = onShardInitialized;
1997         }
1998
1999         ActorRef getSender() {
2000             return sender;
2001         }
2002
2003         ShardInformation getShardInfo() {
2004             return shardInfo;
2005         }
2006
2007         OnShardInitialized getOnShardInitialized() {
2008             return onShardInitialized;
2009         }
2010     }
2011 }
2012
2013
2014

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.