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