2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.datastore;
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.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
37 import java.util.concurrent.CountDownLatch;
38 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
39 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
40 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
41 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
42 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
43 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
44 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
45 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
46 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
47 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
48 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
49 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
50 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
51 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
52 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
53 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
54 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
55 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
56 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
57 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
58 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
59 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
60 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
61 import org.opendaylight.controller.cluster.raft.RaftState;
62 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67 import scala.concurrent.duration.Duration;
70 * The ShardManager has the following jobs,
72 * <li> Create all the local shard replicas that belong on this cluster member
73 * <li> Find the address of the local shard
74 * <li> Find the primary replica for any given shard
75 * <li> Monitor the cluster members and store their addresses
78 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
80 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
82 // Stores a mapping between a member name and the address of the member
83 // Member names look like "member-1", "member-2" etc and are as specified
85 private final Map<String, Address> memberNameToAddress = new HashMap<>();
87 // Stores a mapping between a shard name and it's corresponding information
88 // Shard names look like inventory, topology etc and are as specified in
90 private final Map<String, ShardInformation> localShards = new HashMap<>();
92 // The type of a ShardManager reflects the type of the datastore itself
93 // A data store could be of type config/operational
94 private final String type;
96 private final String shardManagerIdentifierString;
98 private final ClusterWrapper cluster;
100 private final Configuration configuration;
102 private final String shardDispatcherPath;
104 private ShardManagerInfo mBean;
106 private DatastoreContext datastoreContext;
108 private final CountDownLatch waitTillReadyCountdownLatch;
110 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
114 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
115 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
116 PrimaryShardInfoFutureCache primaryShardInfoCache) {
118 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
119 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
120 this.datastoreContext = datastoreContext;
121 this.type = datastoreContext.getDataStoreType();
122 this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
123 this.shardDispatcherPath =
124 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
125 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
126 this.primaryShardInfoCache = primaryShardInfoCache;
128 // Subscribe this actor to cluster member events
129 cluster.subscribeToMemberEvents(getSelf());
134 public static Props props(
135 final ClusterWrapper cluster,
136 final Configuration configuration,
137 final DatastoreContext datastoreContext,
138 final CountDownLatch waitTillReadyCountdownLatch,
139 final PrimaryShardInfoFutureCache primaryShardInfoCache) {
141 Preconditions.checkNotNull(cluster, "cluster should not be null");
142 Preconditions.checkNotNull(configuration, "configuration should not be null");
143 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
144 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
146 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext,
147 waitTillReadyCountdownLatch, primaryShardInfoCache));
151 public void postStop() {
152 LOG.info("Stopping ShardManager");
154 mBean.unregisterMBean();
158 public void handleCommand(Object message) throws Exception {
159 if (message instanceof FindPrimary) {
160 findPrimary((FindPrimary)message);
161 } else if(message instanceof FindLocalShard){
162 findLocalShard((FindLocalShard) message);
163 } else if (message instanceof UpdateSchemaContext) {
164 updateSchemaContext(message);
165 } else if(message instanceof ActorInitialized) {
166 onActorInitialized(message);
167 } else if (message instanceof ClusterEvent.MemberUp){
168 memberUp((ClusterEvent.MemberUp) message);
169 } else if(message instanceof ClusterEvent.MemberRemoved) {
170 memberRemoved((ClusterEvent.MemberRemoved) message);
171 } else if(message instanceof ClusterEvent.UnreachableMember) {
172 memberUnreachable((ClusterEvent.UnreachableMember)message);
173 } else if(message instanceof ClusterEvent.ReachableMember) {
174 memberReachable((ClusterEvent.ReachableMember) message);
175 } else if(message instanceof DatastoreContext) {
176 onDatastoreContext((DatastoreContext)message);
177 } else if(message instanceof RoleChangeNotification) {
178 onRoleChangeNotification((RoleChangeNotification) message);
179 } else if(message instanceof FollowerInitialSyncUpStatus){
180 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
181 } else if(message instanceof ShardNotInitializedTimeout) {
182 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
183 } else if(message instanceof ShardLeaderStateChanged) {
184 onLeaderStateChanged((ShardLeaderStateChanged)message);
186 unknownMessage(message);
191 private void checkReady(){
192 if (isReadyWithLeaderId()) {
193 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
194 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
196 waitTillReadyCountdownLatch.countDown();
200 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
201 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
203 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
204 if(shardInformation != null) {
205 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
206 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
207 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
208 primaryShardInfoCache.remove(shardInformation.getShardName());
213 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
217 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
218 ShardInformation shardInfo = message.getShardInfo();
220 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
221 shardInfo.getShardName());
223 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
225 if(!shardInfo.isShardInitialized()) {
226 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
227 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
229 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
230 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
234 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
235 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
236 status.getName(), status.isInitialSyncDone());
238 ShardInformation shardInformation = findShardInformation(status.getName());
240 if(shardInformation != null) {
241 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
243 mBean.setSyncStatus(isInSync());
248 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
249 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
250 roleChanged.getOldRole(), roleChanged.getNewRole());
252 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
253 if(shardInformation != null) {
254 shardInformation.setRole(roleChanged.getNewRole());
256 mBean.setSyncStatus(isInSync());
261 private ShardInformation findShardInformation(String memberId) {
262 for(ShardInformation info : localShards.values()){
263 if(info.getShardId().toString().equals(memberId)){
271 private boolean isReadyWithLeaderId() {
272 boolean isReady = true;
273 for (ShardInformation info : localShards.values()) {
274 if(!info.isShardReadyWithLeaderId()){
282 private boolean isInSync(){
283 for (ShardInformation info : localShards.values()) {
284 if(!info.isInSync()){
291 private void onActorInitialized(Object message) {
292 final ActorRef sender = getSender();
294 if (sender == null) {
295 return; //why is a non-actor sending this message? Just ignore.
298 String actorName = sender.path().name();
299 //find shard name from actor name; actor name is stringified shardId
300 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
302 if (shardId.getShardName() == null) {
306 markShardAsInitialized(shardId.getShardName());
309 private void markShardAsInitialized(String shardName) {
310 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
312 ShardInformation shardInformation = localShards.get(shardName);
313 if (shardInformation != null) {
314 shardInformation.setActorInitialized();
316 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
321 protected void handleRecover(Object message) throws Exception {
322 if (message instanceof RecoveryCompleted) {
323 LOG.info("Recovery complete : {}", persistenceId());
325 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
326 // journal on upgrade from Helium.
327 deleteMessages(lastSequenceNr());
331 private void findLocalShard(FindLocalShard message) {
332 final ShardInformation shardInformation = localShards.get(message.getShardName());
334 if(shardInformation == null){
335 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
339 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
341 public Object get() {
342 return new LocalShardFound(shardInformation.getActor());
347 private void sendResponse(ShardInformation shardInformation, boolean doWait,
348 boolean wantShardReady, final Supplier<Object> messageSupplier) {
349 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
351 final ActorRef sender = getSender();
352 final ActorRef self = self();
354 Runnable replyRunnable = new Runnable() {
357 sender.tell(messageSupplier.get(), self);
361 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
362 new OnShardInitialized(replyRunnable);
364 shardInformation.addOnShardInitialized(onShardInitialized);
366 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
368 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
369 datastoreContext.getShardInitializationTimeout().duration(), getSelf(),
370 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
371 getContext().dispatcher(), getSelf());
373 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
375 } else if (!shardInformation.isShardInitialized()) {
376 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
377 shardInformation.getShardName());
378 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
380 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
381 shardInformation.getShardName());
382 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
388 getSender().tell(messageSupplier.get(), getSelf());
391 private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
392 return new NoShardLeaderException(String.format(
393 "Could not find a leader for shard %s. This typically happens when the system is coming up or " +
394 "recovering and a leader is being elected. Try again later.", shardId));
397 private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
398 return new NotInitializedException(String.format(
399 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
402 private void memberRemoved(ClusterEvent.MemberRemoved message) {
403 String memberName = message.member().roles().head();
405 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
406 message.member().address());
408 memberNameToAddress.remove(message.member().roles().head());
411 private void memberUp(ClusterEvent.MemberUp message) {
412 String memberName = message.member().roles().head();
414 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
415 message.member().address());
417 memberNameToAddress.put(memberName, message.member().address());
419 for(ShardInformation info : localShards.values()){
420 String shardName = info.getShardName();
421 info.updatePeerAddress(getShardIdentifier(memberName, shardName).toString(),
422 getShardActorPath(shardName, memberName), getSelf());
428 private void memberReachable(ClusterEvent.ReachableMember message) {
429 String memberName = message.member().roles().head();
430 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
432 markMemberAvailable(memberName);
435 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
436 String memberName = message.member().roles().head();
437 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
439 markMemberUnavailable(memberName);
442 private void markMemberUnavailable(final String memberName) {
443 for(ShardInformation info : localShards.values()){
444 String leaderId = info.getLeaderId();
445 if(leaderId != null && leaderId.contains(memberName)) {
446 LOG.debug("Marking Leader {} as unavailable.", leaderId);
447 info.setLeaderAvailable(false);
449 primaryShardInfoCache.remove(info.getShardName());
454 private void markMemberAvailable(final String memberName) {
455 for(ShardInformation info : localShards.values()){
456 String leaderId = info.getLeaderId();
457 if(leaderId != null && leaderId.contains(memberName)) {
458 LOG.debug("Marking Leader {} as available.", leaderId);
459 info.setLeaderAvailable(true);
464 private void onDatastoreContext(DatastoreContext context) {
465 datastoreContext = context;
466 for (ShardInformation info : localShards.values()) {
467 if (info.getActor() != null) {
468 info.getActor().tell(datastoreContext, getSelf());
474 * Notifies all the local shards of a change in the schema context
478 private void updateSchemaContext(final Object message) {
479 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
481 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
483 for (ShardInformation info : localShards.values()) {
484 if (info.getActor() == null) {
485 LOG.debug("Creating Shard {}", info.getShardId());
486 info.setActor(newShardActor(schemaContext, info));
488 info.getActor().tell(message, getSelf());
494 protected ClusterWrapper getCluster() {
499 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
500 return getContext().actorOf(Shard.props(info.getShardId(),
501 info.getPeerAddresses(), datastoreContext, schemaContext)
502 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
505 private void findPrimary(FindPrimary message) {
506 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
508 final String shardName = message.getShardName();
509 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
511 // First see if the there is a local replica for the shard
512 final ShardInformation info = localShards.get(shardName);
514 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
516 public Object get() {
517 String primaryPath = info.getSerializedLeaderActor();
518 Object found = canReturnLocalShardState && info.isLeader() ?
519 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
520 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
522 if(LOG.isDebugEnabled()) {
523 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
533 for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
534 if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
535 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
537 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
540 getContext().actorSelection(path).forward(new RemoteFindPrimary(shardName,
541 message.isWaitUntilReady()), getContext());
546 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
548 getSender().tell(new PrimaryNotFoundException(
549 String.format("No primary shard found for %s.", shardName)), getSelf());
552 private StringBuilder getShardManagerActorPathBuilder(Address address) {
553 StringBuilder builder = new StringBuilder();
554 builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
558 private String getShardActorPath(String shardName, String memberName) {
559 Address address = memberNameToAddress.get(memberName);
560 if(address != null) {
561 StringBuilder builder = getShardManagerActorPathBuilder(address);
563 .append(getShardIdentifier(memberName, shardName));
564 return builder.toString();
570 * Construct the name of the shard actor given the name of the member on
571 * which the shard resides and the name of the shard
577 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
578 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
582 * Create shards that are local to the member on which the ShardManager
586 private void createLocalShards() {
587 String memberName = this.cluster.getCurrentMemberName();
588 List<String> memberShardNames =
589 this.configuration.getMemberShardNames(memberName);
591 List<String> localShardActorNames = new ArrayList<>();
592 for(String shardName : memberShardNames){
593 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
594 Map<String, String> peerAddresses = getPeerAddresses(shardName);
595 localShardActorNames.add(shardId.toString());
596 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
599 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
600 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
604 * Given the name of the shard find the addresses of all it's peers
609 private Map<String, String> getPeerAddresses(String shardName){
611 Map<String, String> peerAddresses = new HashMap<>();
613 List<String> members = this.configuration.getMembersFromShardName(shardName);
615 String currentMemberName = this.cluster.getCurrentMemberName();
617 for(String memberName : members){
618 if(!currentMemberName.equals(memberName)){
619 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
620 String path = getShardActorPath(shardName, currentMemberName);
621 peerAddresses.put(shardId.toString(), path);
624 return peerAddresses;
628 public SupervisorStrategy supervisorStrategy() {
630 return new OneForOneStrategy(10, Duration.create("1 minute"),
631 new Function<Throwable, SupervisorStrategy.Directive>() {
633 public SupervisorStrategy.Directive apply(Throwable t) {
634 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
635 return SupervisorStrategy.resume();
643 public String persistenceId() {
644 return "shard-manager-" + type;
648 ShardManagerInfoMBean getMBean(){
653 protected static class ShardInformation {
654 private final ShardIdentifier shardId;
655 private final String shardName;
656 private ActorRef actor;
657 private ActorPath actorPath;
658 private final Map<String, String> peerAddresses;
659 private Optional<DataTree> localShardDataTree;
660 private boolean leaderAvailable = false;
662 // flag that determines if the actor is ready for business
663 private boolean actorInitialized = false;
665 private boolean followerSyncStatus = false;
667 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
668 private String role ;
669 private String leaderId;
670 private short leaderVersion;
672 private ShardInformation(String shardName, ShardIdentifier shardId,
673 Map<String, String> peerAddresses) {
674 this.shardName = shardName;
675 this.shardId = shardId;
676 this.peerAddresses = peerAddresses;
679 String getShardName() {
687 ActorPath getActorPath() {
691 void setActor(ActorRef actor) {
693 this.actorPath = actor.path();
696 ShardIdentifier getShardId() {
700 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
701 this.localShardDataTree = localShardDataTree;
704 Optional<DataTree> getLocalShardDataTree() {
705 return localShardDataTree;
708 Map<String, String> getPeerAddresses() {
709 return peerAddresses;
712 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
713 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
715 if(peerAddresses.containsKey(peerId)){
716 peerAddresses.put(peerId, peerAddress);
719 if(LOG.isDebugEnabled()) {
720 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
721 peerId, peerAddress, actor.path());
724 actor.tell(new PeerAddressResolved(peerId.toString(), peerAddress), sender);
727 notifyOnShardInitializedCallbacks();
731 boolean isShardReady() {
732 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
735 boolean isShardReadyWithLeaderId() {
736 return leaderAvailable && isShardReady() && (isLeader() || peerAddresses.get(leaderId) != null);
739 boolean isShardInitialized() {
740 return getActor() != null && actorInitialized;
744 return Objects.equal(leaderId, shardId.toString());
747 String getSerializedLeaderActor() {
749 return Serialization.serializedActorPath(getActor());
751 return peerAddresses.get(leaderId);
755 void setActorInitialized() {
756 LOG.debug("Shard {} is initialized", shardId);
758 this.actorInitialized = true;
760 notifyOnShardInitializedCallbacks();
763 private void notifyOnShardInitializedCallbacks() {
764 if(onShardInitializedSet.isEmpty()) {
768 boolean ready = isShardReadyWithLeaderId();
770 if(LOG.isDebugEnabled()) {
771 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
772 ready ? "ready" : "initialized", onShardInitializedSet.size());
775 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
776 while(iter.hasNext()) {
777 OnShardInitialized onShardInitialized = iter.next();
778 if(!(onShardInitialized instanceof OnShardReady) || ready) {
780 onShardInitialized.getTimeoutSchedule().cancel();
781 onShardInitialized.getReplyRunnable().run();
786 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
787 onShardInitializedSet.add(onShardInitialized);
790 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
791 onShardInitializedSet.remove(onShardInitialized);
794 void setRole(String newRole) {
797 notifyOnShardInitializedCallbacks();
800 void setFollowerSyncStatus(boolean syncStatus){
801 this.followerSyncStatus = syncStatus;
805 if(RaftState.Follower.name().equals(this.role)){
806 return followerSyncStatus;
807 } else if(RaftState.Leader.name().equals(this.role)){
814 boolean setLeaderId(String leaderId) {
815 boolean changed = !Objects.equal(this.leaderId, leaderId);
816 this.leaderId = leaderId;
817 if(leaderId != null) {
818 this.leaderAvailable = true;
820 notifyOnShardInitializedCallbacks();
825 String getLeaderId() {
829 void setLeaderAvailable(boolean leaderAvailable) {
830 this.leaderAvailable = leaderAvailable;
833 short getLeaderVersion() {
834 return leaderVersion;
837 void setLeaderVersion(short leaderVersion) {
838 this.leaderVersion = leaderVersion;
842 private static class ShardManagerCreator implements Creator<ShardManager> {
843 private static final long serialVersionUID = 1L;
845 final ClusterWrapper cluster;
846 final Configuration configuration;
847 final DatastoreContext datastoreContext;
848 private final CountDownLatch waitTillReadyCountdownLatch;
849 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
851 ShardManagerCreator(ClusterWrapper cluster, Configuration configuration, DatastoreContext datastoreContext,
852 CountDownLatch waitTillReadyCountdownLatch, PrimaryShardInfoFutureCache primaryShardInfoCache) {
853 this.cluster = cluster;
854 this.configuration = configuration;
855 this.datastoreContext = datastoreContext;
856 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
857 this.primaryShardInfoCache = primaryShardInfoCache;
861 public ShardManager create() throws Exception {
862 return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch,
863 primaryShardInfoCache);
867 private static class OnShardInitialized {
868 private final Runnable replyRunnable;
869 private Cancellable timeoutSchedule;
871 OnShardInitialized(Runnable replyRunnable) {
872 this.replyRunnable = replyRunnable;
875 Runnable getReplyRunnable() {
876 return replyRunnable;
879 Cancellable getTimeoutSchedule() {
880 return timeoutSchedule;
883 void setTimeoutSchedule(Cancellable timeoutSchedule) {
884 this.timeoutSchedule = timeoutSchedule;
888 private static class OnShardReady extends OnShardInitialized {
889 OnShardReady(Runnable replyRunnable) {
890 super(replyRunnable);
894 private static class ShardNotInitializedTimeout {
895 private final ActorRef sender;
896 private final ShardInformation shardInfo;
897 private final OnShardInitialized onShardInitialized;
899 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
900 this.sender = sender;
901 this.shardInfo = shardInfo;
902 this.onShardInitialized = onShardInitialized;
905 ActorRef getSender() {
909 ShardInformation getShardInfo() {
913 OnShardInitialized getOnShardInitialized() {
914 return onShardInitialized;
919 * We no longer persist SchemaContextModules but keep this class around for now for backwards
920 * compatibility so we don't get de-serialization failures on upgrade from Helium.
923 static class SchemaContextModules implements Serializable {
924 private static final long serialVersionUID = -8884620101025936590L;
926 private final Set<String> modules;
928 SchemaContextModules(Set<String> modules){
929 this.modules = modules;
932 public Set<String> getModules() {