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