9bb2ea8f79d2773124a4fde1b35e865897e21e72
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / 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;
10
11 import static akka.pattern.Patterns.ask;
12 import akka.actor.ActorPath;
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.Props;
19 import akka.actor.SupervisorStrategy;
20 import akka.cluster.ClusterEvent;
21 import akka.dispatch.OnComplete;
22 import akka.japi.Creator;
23 import akka.japi.Function;
24 import akka.persistence.RecoveryCompleted;
25 import akka.serialization.Serialization;
26 import akka.util.Timeout;
27 import com.google.common.annotations.VisibleForTesting;
28 import com.google.common.base.Objects;
29 import com.google.common.base.Optional;
30 import com.google.common.base.Preconditions;
31 import com.google.common.base.Strings;
32 import com.google.common.base.Supplier;
33 import com.google.common.collect.Sets;
34 import java.io.Serializable;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Set;
42 import java.util.concurrent.CountDownLatch;
43 import java.util.concurrent.TimeUnit;
44 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
45 import org.opendaylight.controller.cluster.datastore.config.Configuration;
46 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
47 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
48 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
49 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
50 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
51 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
52 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
53 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
54 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
56 import org.opendaylight.controller.cluster.datastore.messages.CreateShardReply;
57 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
58 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
59 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
60 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
61 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
62 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
63 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
64 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
65 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
66 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
67 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
68 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
69 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
70 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
71 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
72 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
73 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
74 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
75 import org.opendaylight.controller.cluster.raft.RaftState;
76 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
77 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
78 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
79 import org.opendaylight.controller.cluster.raft.messages.AddServer;
80 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
81 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
82 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import scala.concurrent.Future;
88 import scala.concurrent.duration.Duration;
89 import scala.concurrent.duration.FiniteDuration;
90
91 /**
92  * The ShardManager has the following jobs,
93  * <ul>
94  * <li> Create all the local shard replicas that belong on this cluster member
95  * <li> Find the address of the local shard
96  * <li> Find the primary replica for any given shard
97  * <li> Monitor the cluster members and store their addresses
98  * <ul>
99  */
100 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
101
102     private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
103
104     // Stores a mapping between a shard name and it's corresponding information
105     // Shard names look like inventory, topology etc and are as specified in
106     // configuration
107     private final Map<String, ShardInformation> localShards = new HashMap<>();
108
109     // The type of a ShardManager reflects the type of the datastore itself
110     // A data store could be of type config/operational
111     private final String type;
112
113     private final ClusterWrapper cluster;
114
115     private final Configuration configuration;
116
117     private final String shardDispatcherPath;
118
119     private ShardManagerInfo mBean;
120
121     private DatastoreContextFactory datastoreContextFactory;
122
123     private final CountDownLatch waitTillReadyCountdownLatch;
124
125     private final PrimaryShardInfoFutureCache primaryShardInfoCache;
126
127     private final ShardPeerAddressResolver peerAddressResolver;
128
129     private SchemaContext schemaContext;
130
131     /**
132      */
133     protected ShardManager(ClusterWrapper cluster, Configuration configuration,
134             DatastoreContextFactory datastoreContextFactory, CountDownLatch waitTillReadyCountdownLatch,
135             PrimaryShardInfoFutureCache primaryShardInfoCache) {
136
137         this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
138         this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
139         this.datastoreContextFactory = datastoreContextFactory;
140         this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreType();
141         this.shardDispatcherPath =
142                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
143         this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
144         this.primaryShardInfoCache = primaryShardInfoCache;
145
146         peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
147
148         // Subscribe this actor to cluster member events
149         cluster.subscribeToMemberEvents(getSelf());
150
151         createLocalShards();
152     }
153
154     public static Props props(
155             final ClusterWrapper cluster,
156             final Configuration configuration,
157             final DatastoreContextFactory datastoreContextFactory,
158             final CountDownLatch waitTillReadyCountdownLatch,
159             final PrimaryShardInfoFutureCache primaryShardInfoCache) {
160
161         Preconditions.checkNotNull(cluster, "cluster should not be null");
162         Preconditions.checkNotNull(configuration, "configuration should not be null");
163         Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
164         Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
165
166         return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContextFactory,
167                 waitTillReadyCountdownLatch, primaryShardInfoCache));
168     }
169
170     @Override
171     public void postStop() {
172         LOG.info("Stopping ShardManager");
173
174         mBean.unregisterMBean();
175     }
176
177     @Override
178     public void handleCommand(Object message) throws Exception {
179         if (message  instanceof FindPrimary) {
180             findPrimary((FindPrimary)message);
181         } else if(message instanceof FindLocalShard){
182             findLocalShard((FindLocalShard) message);
183         } else if (message instanceof UpdateSchemaContext) {
184             updateSchemaContext(message);
185         } else if(message instanceof ActorInitialized) {
186             onActorInitialized(message);
187         } else if (message instanceof ClusterEvent.MemberUp){
188             memberUp((ClusterEvent.MemberUp) message);
189         } else if (message instanceof ClusterEvent.MemberExited){
190             memberExited((ClusterEvent.MemberExited) message);
191         } else if(message instanceof ClusterEvent.MemberRemoved) {
192             memberRemoved((ClusterEvent.MemberRemoved) message);
193         } else if(message instanceof ClusterEvent.UnreachableMember) {
194             memberUnreachable((ClusterEvent.UnreachableMember)message);
195         } else if(message instanceof ClusterEvent.ReachableMember) {
196             memberReachable((ClusterEvent.ReachableMember) message);
197         } else if(message instanceof DatastoreContextFactory) {
198             onDatastoreContextFactory((DatastoreContextFactory)message);
199         } else if(message instanceof RoleChangeNotification) {
200             onRoleChangeNotification((RoleChangeNotification) message);
201         } else if(message instanceof FollowerInitialSyncUpStatus){
202             onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
203         } else if(message instanceof ShardNotInitializedTimeout) {
204             onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
205         } else if(message instanceof ShardLeaderStateChanged) {
206             onLeaderStateChanged((ShardLeaderStateChanged) message);
207         } else if(message instanceof SwitchShardBehavior){
208             onSwitchShardBehavior((SwitchShardBehavior) message);
209         } else if(message instanceof CreateShard) {
210             onCreateShard((CreateShard)message);
211         } else if(message instanceof AddShardReplica){
212             onAddShardReplica((AddShardReplica)message);
213         } else if(message instanceof RemoveShardReplica){
214             onRemoveShardReplica((RemoveShardReplica)message);
215         } else if(message instanceof GetSnapshot) {
216             onGetSnapshot();
217         } else {
218             unknownMessage(message);
219         }
220
221     }
222
223     private void onGetSnapshot() {
224         LOG.debug("{}: onGetSnapshot", persistenceId());
225
226         List<String> notInitialized = null;
227         for(ShardInformation shardInfo: localShards.values()) {
228             if(!shardInfo.isShardInitialized()) {
229                 if(notInitialized == null) {
230                     notInitialized = new ArrayList<>();
231                 }
232
233                 notInitialized.add(shardInfo.getShardName());
234             }
235         }
236
237         if(notInitialized != null) {
238             getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(String.format(
239                     "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
240             return;
241         }
242
243         byte[] shardManagerSnapshot = null;
244         ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
245                 new ArrayList<>(localShards.keySet()), type, shardManagerSnapshot , getSender(), persistenceId(),
246                 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
247
248         for(ShardInformation shardInfo: localShards.values()) {
249             shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
250         }
251     }
252
253     private void onCreateShard(CreateShard createShard) {
254         Object reply;
255         try {
256             ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
257             if(localShards.containsKey(moduleShardConfig.getShardName())) {
258                 throw new IllegalStateException(String.format("Shard with name %s already exists",
259                         moduleShardConfig.getShardName()));
260             }
261
262             configuration.addModuleShardConfiguration(moduleShardConfig);
263
264             ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), moduleShardConfig.getShardName());
265             Map<String, String> peerAddresses = getPeerAddresses(moduleShardConfig.getShardName()/*,
266                     moduleShardConfig.getShardMemberNames()*/);
267
268             LOG.debug("onCreateShard: shardId: {}, memberNames: {}. peerAddresses: {}", shardId,
269                     moduleShardConfig.getShardMemberNames(), peerAddresses);
270
271             DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
272             if(shardDatastoreContext == null) {
273                 shardDatastoreContext = newShardDatastoreContext(moduleShardConfig.getShardName());
274             } else {
275                 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
276                         peerAddressResolver).build();
277             }
278
279             ShardInformation info = new ShardInformation(moduleShardConfig.getShardName(), shardId, peerAddresses,
280                     shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
281             localShards.put(info.getShardName(), info);
282
283             mBean.addLocalShard(shardId.toString());
284
285             if(schemaContext != null) {
286                 info.setActor(newShardActor(schemaContext, info));
287             }
288
289             reply = new CreateShardReply();
290         } catch (Exception e) {
291             LOG.error("onCreateShard failed", e);
292             reply = new akka.actor.Status.Failure(e);
293         }
294
295         if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
296             getSender().tell(reply, getSelf());
297         }
298     }
299
300     private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
301         return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName)).
302                 shardPeerAddressResolver(peerAddressResolver);
303     }
304
305     private DatastoreContext newShardDatastoreContext(String shardName) {
306         return newShardDatastoreContextBuilder(shardName).build();
307     }
308
309     private void checkReady(){
310         if (isReadyWithLeaderId()) {
311             LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
312                     persistenceId(), type, waitTillReadyCountdownLatch.getCount());
313
314             waitTillReadyCountdownLatch.countDown();
315         }
316     }
317
318     private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
319         LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
320
321         ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
322         if(shardInformation != null) {
323             shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
324             shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
325             if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
326                 primaryShardInfoCache.remove(shardInformation.getShardName());
327             }
328
329             checkReady();
330         } else {
331             LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
332         }
333     }
334
335     private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
336         ShardInformation shardInfo = message.getShardInfo();
337
338         LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
339                 shardInfo.getShardName());
340
341         shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
342
343         if(!shardInfo.isShardInitialized()) {
344             LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
345             message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
346         } else {
347             LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
348             message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
349         }
350     }
351
352     private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
353         LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
354                 status.getName(), status.isInitialSyncDone());
355
356         ShardInformation shardInformation = findShardInformation(status.getName());
357
358         if(shardInformation != null) {
359             shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
360
361             mBean.setSyncStatus(isInSync());
362         }
363
364     }
365
366     private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
367         LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
368                 roleChanged.getOldRole(), roleChanged.getNewRole());
369
370         ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
371         if(shardInformation != null) {
372             shardInformation.setRole(roleChanged.getNewRole());
373             checkReady();
374             mBean.setSyncStatus(isInSync());
375         }
376     }
377
378
379     private ShardInformation findShardInformation(String memberId) {
380         for(ShardInformation info : localShards.values()){
381             if(info.getShardId().toString().equals(memberId)){
382                 return info;
383             }
384         }
385
386         return null;
387     }
388
389     private boolean isReadyWithLeaderId() {
390         boolean isReady = true;
391         for (ShardInformation info : localShards.values()) {
392             if(!info.isShardReadyWithLeaderId()){
393                 isReady = false;
394                 break;
395             }
396         }
397         return isReady;
398     }
399
400     private boolean isInSync(){
401         for (ShardInformation info : localShards.values()) {
402             if(!info.isInSync()){
403                 return false;
404             }
405         }
406         return true;
407     }
408
409     private void onActorInitialized(Object message) {
410         final ActorRef sender = getSender();
411
412         if (sender == null) {
413             return; //why is a non-actor sending this message? Just ignore.
414         }
415
416         String actorName = sender.path().name();
417         //find shard name from actor name; actor name is stringified shardId
418         ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
419
420         if (shardId.getShardName() == null) {
421             return;
422         }
423
424         markShardAsInitialized(shardId.getShardName());
425     }
426
427     private void markShardAsInitialized(String shardName) {
428         LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
429
430         ShardInformation shardInformation = localShards.get(shardName);
431         if (shardInformation != null) {
432             shardInformation.setActorInitialized();
433
434             shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
435         }
436     }
437
438     @Override
439     protected void handleRecover(Object message) throws Exception {
440         if (message instanceof RecoveryCompleted) {
441             LOG.info("Recovery complete : {}", persistenceId());
442
443             // We no longer persist SchemaContext modules so delete all the prior messages from the akka
444             // journal on upgrade from Helium.
445             deleteMessages(lastSequenceNr());
446         }
447     }
448
449     private void findLocalShard(FindLocalShard message) {
450         final ShardInformation shardInformation = localShards.get(message.getShardName());
451
452         if(shardInformation == null){
453             getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
454             return;
455         }
456
457         sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
458             @Override
459             public Object get() {
460                 return new LocalShardFound(shardInformation.getActor());
461             }
462         });
463     }
464
465     private void sendResponse(ShardInformation shardInformation, boolean doWait,
466             boolean wantShardReady, final Supplier<Object> messageSupplier) {
467         if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
468             if(doWait) {
469                 final ActorRef sender = getSender();
470                 final ActorRef self = self();
471
472                 Runnable replyRunnable = new Runnable() {
473                     @Override
474                     public void run() {
475                         sender.tell(messageSupplier.get(), self);
476                     }
477                 };
478
479                 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
480                     new OnShardInitialized(replyRunnable);
481
482                 shardInformation.addOnShardInitialized(onShardInitialized);
483
484                 FiniteDuration timeout = shardInformation.getDatastoreContext().getShardInitializationTimeout().duration();
485                 if(shardInformation.isShardInitialized()) {
486                     // If the shard is already initialized then we'll wait enough time for the shard to
487                     // elect a leader, ie 2 times the election timeout.
488                     timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
489                             .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
490                 }
491
492                 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
493                         shardInformation.getShardName());
494
495                 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
496                         timeout, getSelf(),
497                         new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
498                         getContext().dispatcher(), getSelf());
499
500                 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
501
502             } else if (!shardInformation.isShardInitialized()) {
503                 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
504                         shardInformation.getShardName());
505                 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
506             } else {
507                 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
508                         shardInformation.getShardName());
509                 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
510             }
511
512             return;
513         }
514
515         getSender().tell(messageSupplier.get(), getSelf());
516     }
517
518     private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
519         return new NoShardLeaderException(null, shardId.toString());
520     }
521
522     private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
523         return new NotInitializedException(String.format(
524                 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
525     }
526
527     private void memberRemoved(ClusterEvent.MemberRemoved message) {
528         String memberName = message.member().roles().head();
529
530         LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
531                 message.member().address());
532
533         peerAddressResolver.removePeerAddress(memberName);
534
535         for(ShardInformation info : localShards.values()){
536             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
537         }
538     }
539
540     private void memberExited(ClusterEvent.MemberExited message) {
541         String memberName = message.member().roles().head();
542
543         LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
544                 message.member().address());
545
546         peerAddressResolver.removePeerAddress(memberName);
547
548         for(ShardInformation info : localShards.values()){
549             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
550         }
551     }
552
553     private void memberUp(ClusterEvent.MemberUp message) {
554         String memberName = message.member().roles().head();
555
556         LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
557                 message.member().address());
558
559         addPeerAddress(memberName, message.member().address());
560
561         checkReady();
562     }
563
564     private void addPeerAddress(String memberName, Address address) {
565         peerAddressResolver.addPeerAddress(memberName, address);
566
567         for(ShardInformation info : localShards.values()){
568             String shardName = info.getShardName();
569             String peerId = getShardIdentifier(memberName, shardName).toString();
570             info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
571
572             info.peerUp(memberName, peerId, getSelf());
573         }
574     }
575
576     private void memberReachable(ClusterEvent.ReachableMember message) {
577         String memberName = message.member().roles().head();
578         LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
579
580         addPeerAddress(memberName, message.member().address());
581
582         markMemberAvailable(memberName);
583     }
584
585     private void memberUnreachable(ClusterEvent.UnreachableMember message) {
586         String memberName = message.member().roles().head();
587         LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
588
589         markMemberUnavailable(memberName);
590     }
591
592     private void markMemberUnavailable(final String memberName) {
593         for(ShardInformation info : localShards.values()){
594             String leaderId = info.getLeaderId();
595             if(leaderId != null && leaderId.contains(memberName)) {
596                 LOG.debug("Marking Leader {} as unavailable.", leaderId);
597                 info.setLeaderAvailable(false);
598
599                 primaryShardInfoCache.remove(info.getShardName());
600             }
601
602             info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
603         }
604     }
605
606     private void markMemberAvailable(final String memberName) {
607         for(ShardInformation info : localShards.values()){
608             String leaderId = info.getLeaderId();
609             if(leaderId != null && leaderId.contains(memberName)) {
610                 LOG.debug("Marking Leader {} as available.", leaderId);
611                 info.setLeaderAvailable(true);
612             }
613
614             info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
615         }
616     }
617
618     private void onDatastoreContextFactory(DatastoreContextFactory factory) {
619         datastoreContextFactory = factory;
620         for (ShardInformation info : localShards.values()) {
621             info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
622         }
623     }
624
625     private void onSwitchShardBehavior(SwitchShardBehavior message) {
626         ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
627
628         ShardInformation shardInformation = localShards.get(identifier.getShardName());
629
630         if(shardInformation != null && shardInformation.getActor() != null) {
631             shardInformation.getActor().tell(
632                     new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
633         } else {
634             LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
635                     message.getShardName(), message.getNewState());
636         }
637     }
638
639     /**
640      * Notifies all the local shards of a change in the schema context
641      *
642      * @param message
643      */
644     private void updateSchemaContext(final Object message) {
645         schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
646
647         LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
648
649         for (ShardInformation info : localShards.values()) {
650             if (info.getActor() == null) {
651                 LOG.debug("Creating Shard {}", info.getShardId());
652                 info.setActor(newShardActor(schemaContext, info));
653             } else {
654                 info.getActor().tell(message, getSelf());
655             }
656         }
657     }
658
659     @VisibleForTesting
660     protected ClusterWrapper getCluster() {
661         return cluster;
662     }
663
664     @VisibleForTesting
665     protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
666         return getContext().actorOf(info.newProps(schemaContext)
667                 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
668     }
669
670     private void findPrimary(FindPrimary message) {
671         LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
672
673         final String shardName = message.getShardName();
674         final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
675
676         // First see if the there is a local replica for the shard
677         final ShardInformation info = localShards.get(shardName);
678         if (info != null) {
679             sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
680                 @Override
681                 public Object get() {
682                     String primaryPath = info.getSerializedLeaderActor();
683                     Object found = canReturnLocalShardState && info.isLeader() ?
684                             new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
685                                 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
686
687                             if(LOG.isDebugEnabled()) {
688                                 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
689                             }
690
691                             return found;
692                 }
693             });
694
695             return;
696         }
697
698         for(String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
699             LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
700                     shardName, address);
701
702             getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
703                     message.isWaitUntilReady()), getContext());
704             return;
705         }
706
707         LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
708
709         getSender().tell(new PrimaryNotFoundException(
710                 String.format("No primary shard found for %s.", shardName)), getSelf());
711     }
712
713     /**
714      * Construct the name of the shard actor given the name of the member on
715      * which the shard resides and the name of the shard
716      *
717      * @param memberName
718      * @param shardName
719      * @return
720      */
721     private ShardIdentifier getShardIdentifier(String memberName, String shardName){
722         return peerAddressResolver.getShardIdentifier(memberName, shardName);
723     }
724
725     /**
726      * Create shards that are local to the member on which the ShardManager
727      * runs
728      *
729      */
730     private void createLocalShards() {
731         String memberName = this.cluster.getCurrentMemberName();
732         Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
733
734         List<String> localShardActorNames = new ArrayList<>();
735         for(String shardName : memberShardNames){
736             ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
737             Map<String, String> peerAddresses = getPeerAddresses(shardName);
738             localShardActorNames.add(shardId.toString());
739             localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
740                     newShardDatastoreContext(shardName), Shard.builder(), peerAddressResolver));
741         }
742
743         mBean = ShardManagerInfo.createShardManagerMBean(memberName, "shard-manager-" + this.type,
744                 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType(), localShardActorNames);
745
746         mBean.setShardManager(this);
747     }
748
749     /**
750      * Given the name of the shard find the addresses of all it's peers
751      *
752      * @param shardName
753      */
754     private Map<String, String> getPeerAddresses(String shardName) {
755         Collection<String> members = configuration.getMembersFromShardName(shardName);
756         Map<String, String> peerAddresses = new HashMap<>();
757
758         String currentMemberName = this.cluster.getCurrentMemberName();
759
760         for(String memberName : members) {
761             if(!currentMemberName.equals(memberName)) {
762                 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
763                 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
764                 peerAddresses.put(shardId.toString(), address);
765             }
766         }
767         return peerAddresses;
768     }
769
770     @Override
771     public SupervisorStrategy supervisorStrategy() {
772
773         return new OneForOneStrategy(10, Duration.create("1 minute"),
774                 new Function<Throwable, SupervisorStrategy.Directive>() {
775             @Override
776             public SupervisorStrategy.Directive apply(Throwable t) {
777                 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
778                 return SupervisorStrategy.resume();
779             }
780         }
781                 );
782
783     }
784
785     @Override
786     public String persistenceId() {
787         return "shard-manager-" + type;
788     }
789
790     @VisibleForTesting
791     ShardManagerInfoMBean getMBean(){
792         return mBean;
793     }
794
795     private void checkLocalShardExists(final String shardName, final ActorRef sender) {
796         if (localShards.containsKey(shardName)) {
797             String msg = String.format("Local shard %s already exists", shardName);
798             LOG.debug ("{}: {}", persistenceId(), msg);
799             sender.tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
800         }
801     }
802
803     private void onAddShardReplica (AddShardReplica shardReplicaMsg) {
804         final String shardName = shardReplicaMsg.getShardName();
805
806         // verify the local shard replica is already available in the controller node
807         LOG.debug ("onAddShardReplica: {}", shardReplicaMsg);
808
809         checkLocalShardExists(shardName, getSender());
810
811         // verify the shard with the specified name is present in the cluster configuration
812         if (!(this.configuration.isShardConfigured(shardName))) {
813             String msg = String.format("No module configuration exists for shard %s", shardName);
814             LOG.debug ("{}: {}", persistenceId(), msg);
815             getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
816             return;
817         }
818
819         // Create the localShard
820         if (schemaContext == null) {
821             String msg = String.format(
822                   "No SchemaContext is available in order to create a local shard instance for %s", shardName);
823             LOG.debug ("{}: {}", persistenceId(), msg);
824             getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
825             return;
826         }
827
828         Map<String, String> peerAddresses = getPeerAddresses(shardName);
829         if (peerAddresses.isEmpty()) {
830             String msg = String.format("Cannot add replica for shard %s because no peer is available", shardName);
831             LOG.debug ("{}: {}", persistenceId(), msg);
832             getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
833             return;
834         }
835
836         Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext().
837                 getShardInitializationTimeout().duration().$times(2));
838
839         final ActorRef sender = getSender();
840         Future<Object> futureObj = ask(getSelf(), new RemoteFindPrimary(shardName, true), findPrimaryTimeout);
841         futureObj.onComplete(new OnComplete<Object>() {
842             @Override
843             public void onComplete(Throwable failure, Object response) {
844                 if (failure != null) {
845                     LOG.debug ("{}: Received failure from FindPrimary for shard {}", persistenceId(), shardName, failure);
846                     sender.tell(new akka.actor.Status.Failure(new RuntimeException(
847                         String.format("Failed to find leader for shard %s", shardName), failure)),
848                         getSelf());
849                 } else {
850                     if (!(response instanceof RemotePrimaryShardFound)) {
851                         String msg = String.format("Failed to find leader for shard %s: received response: %s",
852                                 shardName, response);
853                         LOG.debug ("{}: {}", persistenceId(), msg);
854                         sender.tell(new akka.actor.Status.Failure(new RuntimeException(msg)), getSelf());
855                         return;
856                     }
857
858                     RemotePrimaryShardFound message = (RemotePrimaryShardFound)response;
859                     addShard (shardName, message, sender);
860                 }
861             }
862         }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
863     }
864
865     private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
866         checkLocalShardExists(shardName, sender);
867
868         ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
869         String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
870
871         DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).customRaftPolicyImplementation(
872                 DisableElectionsRaftPolicy.class.getName()).build();
873
874         final ShardInformation shardInfo = new ShardInformation(shardName, shardId,
875                           getPeerAddresses(shardName), datastoreContext,
876                           Shard.builder(), peerAddressResolver);
877         localShards.put(shardName, shardInfo);
878         shardInfo.setActor(newShardActor(schemaContext, shardInfo));
879
880         //inform ShardLeader to add this shard as a replica by sending an AddServer message
881         LOG.debug ("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
882                 response.getPrimaryPath(), shardId);
883
884         Timeout addServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(4));
885         Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
886             new AddServer(shardId.toString(), localShardAddress, true), addServerTimeout);
887
888         futureObj.onComplete(new OnComplete<Object>() {
889             @Override
890             public void onComplete(Throwable failure, Object addServerResponse) {
891                 if (failure != null) {
892                     LOG.debug ("{}: AddServer request to {} for {} failed", persistenceId(),
893                             response.getPrimaryPath(), shardName, failure);
894
895                     // Remove the shard
896                     localShards.remove(shardName);
897                     if (shardInfo.getActor() != null) {
898                         shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
899                     }
900
901                     sender.tell(new akka.actor.Status.Failure(new RuntimeException(
902                         String.format("AddServer request to leader %s for shard %s failed",
903                             response.getPrimaryPath(), shardName), failure)), getSelf());
904                 } else {
905                     AddServerReply reply = (AddServerReply)addServerResponse;
906                     onAddServerReply(shardName, shardInfo, reply, sender, response.getPrimaryPath());
907                 }
908             }
909         }, new Dispatchers(context().system().dispatchers()).
910             getDispatcher(Dispatchers.DispatcherType.Client));
911         return;
912     }
913
914     private void onAddServerReply (String shardName, ShardInformation shardInfo,
915                                    AddServerReply replyMsg, ActorRef sender, String leaderPath) {
916         LOG.debug ("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
917
918         if (replyMsg.getStatus() == ServerChangeStatus.OK) {
919             LOG.debug ("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
920
921             // Make the local shard voting capable
922             shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
923
924             mBean.addLocalShard(shardInfo.getShardId().toString());
925             sender.tell(new akka.actor.Status.Success(true), getSelf());
926         } else {
927             LOG.warn ("{}: Leader failed to add shard replica {} with status {} - removing the local shard",
928                     persistenceId(), shardName, replyMsg.getStatus());
929
930             //remove the local replica created
931             localShards.remove(shardName);
932             if (shardInfo.getActor() != null) {
933                 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
934             }
935             switch (replyMsg.getStatus()) {
936                 case TIMEOUT:
937                     sender.tell(new akka.actor.Status.Failure(new RuntimeException(
938                         String.format("The shard leader %s timed out trying to replicate the initial data to the new shard %s. Possible causes - there was a problem replicating the data or shard leadership changed while replicating the shard data",
939                             leaderPath, shardName))), getSelf());
940                     break;
941                 case NO_LEADER:
942                     sender.tell(new akka.actor.Status.Failure(new RuntimeException(String.format(
943                         "There is no shard leader available for shard %s", shardName))), getSelf());
944                     break;
945                 default :
946                     sender.tell(new akka.actor.Status.Failure(new RuntimeException(String.format(
947                         "AddServer request to leader %s for shard %s failed with status %s",
948                         leaderPath, shardName, replyMsg.getStatus()))), getSelf());
949             }
950         }
951     }
952
953     private void onRemoveShardReplica (RemoveShardReplica shardReplicaMsg) {
954         String shardName = shardReplicaMsg.getShardName();
955
956         // verify the local shard replica is available in the controller node
957         if (!localShards.containsKey(shardName)) {
958             String msg = String.format("Local shard %s does not", shardName);
959             LOG.debug ("{}: {}", persistenceId(), msg);
960             getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
961             return;
962         }
963         // call RemoveShard for the shardName
964         getSender().tell(new akka.actor.Status.Success(true), getSelf());
965         return;
966     }
967
968     @VisibleForTesting
969     protected static class ShardInformation {
970         private final ShardIdentifier shardId;
971         private final String shardName;
972         private ActorRef actor;
973         private ActorPath actorPath;
974         private final Map<String, String> initialPeerAddresses;
975         private Optional<DataTree> localShardDataTree;
976         private boolean leaderAvailable = false;
977
978         // flag that determines if the actor is ready for business
979         private boolean actorInitialized = false;
980
981         private boolean followerSyncStatus = false;
982
983         private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
984         private String role ;
985         private String leaderId;
986         private short leaderVersion;
987
988         private DatastoreContext datastoreContext;
989         private final Shard.AbstractBuilder<?, ?> builder;
990         private final ShardPeerAddressResolver addressResolver;
991
992         private ShardInformation(String shardName, ShardIdentifier shardId,
993                 Map<String, String> initialPeerAddresses, DatastoreContext datastoreContext,
994                 Shard.AbstractBuilder<?, ?> builder, ShardPeerAddressResolver addressResolver) {
995             this.shardName = shardName;
996             this.shardId = shardId;
997             this.initialPeerAddresses = initialPeerAddresses;
998             this.datastoreContext = datastoreContext;
999             this.builder = builder;
1000             this.addressResolver = addressResolver;
1001         }
1002
1003         Props newProps(SchemaContext schemaContext) {
1004             return builder.id(shardId).peerAddresses(initialPeerAddresses).datastoreContext(datastoreContext).
1005                     schemaContext(schemaContext).props();
1006         }
1007
1008         String getShardName() {
1009             return shardName;
1010         }
1011
1012         ActorRef getActor(){
1013             return actor;
1014         }
1015
1016         ActorPath getActorPath() {
1017             return actorPath;
1018         }
1019
1020         void setActor(ActorRef actor) {
1021             this.actor = actor;
1022             this.actorPath = actor.path();
1023         }
1024
1025         ShardIdentifier getShardId() {
1026             return shardId;
1027         }
1028
1029         void setLocalDataTree(Optional<DataTree> localShardDataTree) {
1030             this.localShardDataTree = localShardDataTree;
1031         }
1032
1033         Optional<DataTree> getLocalShardDataTree() {
1034             return localShardDataTree;
1035         }
1036
1037         DatastoreContext getDatastoreContext() {
1038             return datastoreContext;
1039         }
1040
1041         void setDatastoreContext(DatastoreContext datastoreContext, ActorRef sender) {
1042             this.datastoreContext = datastoreContext;
1043             if (actor != null) {
1044                 LOG.debug ("Sending new DatastoreContext to {}", shardId);
1045                 actor.tell(this.datastoreContext, sender);
1046             }
1047         }
1048
1049         void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
1050             LOG.info("updatePeerAddress for peer {} with address {}", peerId, peerAddress);
1051
1052             if(actor != null) {
1053                 if(LOG.isDebugEnabled()) {
1054                     LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
1055                             peerId, peerAddress, actor.path());
1056                 }
1057
1058                 actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
1059             }
1060
1061             notifyOnShardInitializedCallbacks();
1062         }
1063
1064         void peerDown(String memberName, String peerId, ActorRef sender) {
1065             if(actor != null) {
1066                 actor.tell(new PeerDown(memberName, peerId), sender);
1067             }
1068         }
1069
1070         void peerUp(String memberName, String peerId, ActorRef sender) {
1071             if(actor != null) {
1072                 actor.tell(new PeerUp(memberName, peerId), sender);
1073             }
1074         }
1075
1076         boolean isShardReady() {
1077             return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
1078         }
1079
1080         boolean isShardReadyWithLeaderId() {
1081             return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
1082                     (isLeader() || addressResolver.resolve(leaderId) != null);
1083         }
1084
1085         boolean isShardInitialized() {
1086             return getActor() != null && actorInitialized;
1087         }
1088
1089         boolean isLeader() {
1090             return Objects.equal(leaderId, shardId.toString());
1091         }
1092
1093         String getSerializedLeaderActor() {
1094             if(isLeader()) {
1095                 return Serialization.serializedActorPath(getActor());
1096             } else {
1097                 return addressResolver.resolve(leaderId);
1098             }
1099         }
1100
1101         void setActorInitialized() {
1102             LOG.debug("Shard {} is initialized", shardId);
1103
1104             this.actorInitialized = true;
1105
1106             notifyOnShardInitializedCallbacks();
1107         }
1108
1109         private void notifyOnShardInitializedCallbacks() {
1110             if(onShardInitializedSet.isEmpty()) {
1111                 return;
1112             }
1113
1114             boolean ready = isShardReadyWithLeaderId();
1115
1116             if(LOG.isDebugEnabled()) {
1117                 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
1118                         ready ? "ready" : "initialized", onShardInitializedSet.size());
1119             }
1120
1121             Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
1122             while(iter.hasNext()) {
1123                 OnShardInitialized onShardInitialized = iter.next();
1124                 if(!(onShardInitialized instanceof OnShardReady) || ready) {
1125                     iter.remove();
1126                     onShardInitialized.getTimeoutSchedule().cancel();
1127                     onShardInitialized.getReplyRunnable().run();
1128                 }
1129             }
1130         }
1131
1132         void addOnShardInitialized(OnShardInitialized onShardInitialized) {
1133             onShardInitializedSet.add(onShardInitialized);
1134         }
1135
1136         void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
1137             onShardInitializedSet.remove(onShardInitialized);
1138         }
1139
1140         void setRole(String newRole) {
1141             this.role = newRole;
1142
1143             notifyOnShardInitializedCallbacks();
1144         }
1145
1146         void setFollowerSyncStatus(boolean syncStatus){
1147             this.followerSyncStatus = syncStatus;
1148         }
1149
1150         boolean isInSync(){
1151             if(RaftState.Follower.name().equals(this.role)){
1152                 return followerSyncStatus;
1153             } else if(RaftState.Leader.name().equals(this.role)){
1154                 return true;
1155             }
1156
1157             return false;
1158         }
1159
1160         boolean setLeaderId(String leaderId) {
1161             boolean changed = !Objects.equal(this.leaderId, leaderId);
1162             this.leaderId = leaderId;
1163             if(leaderId != null) {
1164                 this.leaderAvailable = true;
1165             }
1166             notifyOnShardInitializedCallbacks();
1167
1168             return changed;
1169         }
1170
1171         String getLeaderId() {
1172             return leaderId;
1173         }
1174
1175         void setLeaderAvailable(boolean leaderAvailable) {
1176             this.leaderAvailable = leaderAvailable;
1177         }
1178
1179         short getLeaderVersion() {
1180             return leaderVersion;
1181         }
1182
1183         void setLeaderVersion(short leaderVersion) {
1184             this.leaderVersion = leaderVersion;
1185         }
1186     }
1187
1188     private static class ShardManagerCreator implements Creator<ShardManager> {
1189         private static final long serialVersionUID = 1L;
1190
1191         final ClusterWrapper cluster;
1192         final Configuration configuration;
1193         final DatastoreContextFactory datastoreContextFactory;
1194         private final CountDownLatch waitTillReadyCountdownLatch;
1195         private final PrimaryShardInfoFutureCache primaryShardInfoCache;
1196
1197         ShardManagerCreator(ClusterWrapper cluster, Configuration configuration,
1198                 DatastoreContextFactory datastoreContextFactory, CountDownLatch waitTillReadyCountdownLatch,
1199                 PrimaryShardInfoFutureCache primaryShardInfoCache) {
1200             this.cluster = cluster;
1201             this.configuration = configuration;
1202             this.datastoreContextFactory = datastoreContextFactory;
1203             this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
1204             this.primaryShardInfoCache = primaryShardInfoCache;
1205         }
1206
1207         @Override
1208         public ShardManager create() throws Exception {
1209             return new ShardManager(cluster, configuration, datastoreContextFactory, waitTillReadyCountdownLatch,
1210                     primaryShardInfoCache);
1211         }
1212     }
1213
1214     private static class OnShardInitialized {
1215         private final Runnable replyRunnable;
1216         private Cancellable timeoutSchedule;
1217
1218         OnShardInitialized(Runnable replyRunnable) {
1219             this.replyRunnable = replyRunnable;
1220         }
1221
1222         Runnable getReplyRunnable() {
1223             return replyRunnable;
1224         }
1225
1226         Cancellable getTimeoutSchedule() {
1227             return timeoutSchedule;
1228         }
1229
1230         void setTimeoutSchedule(Cancellable timeoutSchedule) {
1231             this.timeoutSchedule = timeoutSchedule;
1232         }
1233     }
1234
1235     private static class OnShardReady extends OnShardInitialized {
1236         OnShardReady(Runnable replyRunnable) {
1237             super(replyRunnable);
1238         }
1239     }
1240
1241     private static class ShardNotInitializedTimeout {
1242         private final ActorRef sender;
1243         private final ShardInformation shardInfo;
1244         private final OnShardInitialized onShardInitialized;
1245
1246         ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1247             this.sender = sender;
1248             this.shardInfo = shardInfo;
1249             this.onShardInitialized = onShardInitialized;
1250         }
1251
1252         ActorRef getSender() {
1253             return sender;
1254         }
1255
1256         ShardInformation getShardInfo() {
1257             return shardInfo;
1258         }
1259
1260         OnShardInitialized getOnShardInitialized() {
1261             return onShardInitialized;
1262         }
1263     }
1264
1265     /**
1266      * We no longer persist SchemaContextModules but keep this class around for now for backwards
1267      * compatibility so we don't get de-serialization failures on upgrade from Helium.
1268      */
1269     @Deprecated
1270     static class SchemaContextModules implements Serializable {
1271         private static final long serialVersionUID = -8884620101025936590L;
1272
1273         private final Set<String> modules;
1274
1275         SchemaContextModules(Set<String> modules){
1276             this.modules = modules;
1277         }
1278
1279         public Set<String> getModules() {
1280             return modules;
1281         }
1282     }
1283 }
1284
1285
1286