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 java.util.concurrent.TimeUnit;
39 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
40 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
41 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
42 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
43 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
44 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
45 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
46 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
47 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
48 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
49 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
50 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
51 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
52 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
53 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
54 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
55 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
56 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
57 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
58 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
59 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
60 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
61 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
62 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
63 import org.opendaylight.controller.cluster.raft.RaftState;
64 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
65 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
66 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70 import scala.concurrent.duration.Duration;
71 import scala.concurrent.duration.FiniteDuration;
74 * The ShardManager has the following jobs,
76 * <li> Create all the local shard replicas that belong on this cluster member
77 * <li> Find the address of the local shard
78 * <li> Find the primary replica for any given shard
79 * <li> Monitor the cluster members and store their addresses
82 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
84 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
86 // Stores a mapping between a member name and the address of the member
87 // Member names look like "member-1", "member-2" etc and are as specified
89 private final Map<String, Address> memberNameToAddress = new HashMap<>();
91 // Stores a mapping between a shard name and it's corresponding information
92 // Shard names look like inventory, topology etc and are as specified in
94 private final Map<String, ShardInformation> localShards = new HashMap<>();
96 // The type of a ShardManager reflects the type of the datastore itself
97 // A data store could be of type config/operational
98 private final String type;
100 private final String shardManagerIdentifierString;
102 private final ClusterWrapper cluster;
104 private final Configuration configuration;
106 private final String shardDispatcherPath;
108 private ShardManagerInfo mBean;
110 private DatastoreContext datastoreContext;
112 private final CountDownLatch waitTillReadyCountdownLatch;
114 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
118 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
119 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
120 PrimaryShardInfoFutureCache primaryShardInfoCache) {
122 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
123 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
124 this.datastoreContext = datastoreContext;
125 this.type = datastoreContext.getDataStoreType();
126 this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
127 this.shardDispatcherPath =
128 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
129 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
130 this.primaryShardInfoCache = primaryShardInfoCache;
132 // Subscribe this actor to cluster member events
133 cluster.subscribeToMemberEvents(getSelf());
138 public static Props props(
139 final ClusterWrapper cluster,
140 final Configuration configuration,
141 final DatastoreContext datastoreContext,
142 final CountDownLatch waitTillReadyCountdownLatch,
143 final PrimaryShardInfoFutureCache primaryShardInfoCache) {
145 Preconditions.checkNotNull(cluster, "cluster should not be null");
146 Preconditions.checkNotNull(configuration, "configuration should not be null");
147 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
148 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
150 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext,
151 waitTillReadyCountdownLatch, primaryShardInfoCache));
155 public void postStop() {
156 LOG.info("Stopping ShardManager");
158 mBean.unregisterMBean();
162 public void handleCommand(Object message) throws Exception {
163 if (message instanceof FindPrimary) {
164 findPrimary((FindPrimary)message);
165 } else if(message instanceof FindLocalShard){
166 findLocalShard((FindLocalShard) message);
167 } else if (message instanceof UpdateSchemaContext) {
168 updateSchemaContext(message);
169 } else if(message instanceof ActorInitialized) {
170 onActorInitialized(message);
171 } else if (message instanceof ClusterEvent.MemberUp){
172 memberUp((ClusterEvent.MemberUp) message);
173 } else if(message instanceof ClusterEvent.MemberRemoved) {
174 memberRemoved((ClusterEvent.MemberRemoved) message);
175 } else if(message instanceof ClusterEvent.UnreachableMember) {
176 memberUnreachable((ClusterEvent.UnreachableMember)message);
177 } else if(message instanceof ClusterEvent.ReachableMember) {
178 memberReachable((ClusterEvent.ReachableMember) message);
179 } else if(message instanceof DatastoreContext) {
180 onDatastoreContext((DatastoreContext)message);
181 } else if(message instanceof RoleChangeNotification) {
182 onRoleChangeNotification((RoleChangeNotification) message);
183 } else if(message instanceof FollowerInitialSyncUpStatus){
184 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
185 } else if(message instanceof ShardNotInitializedTimeout) {
186 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
187 } else if(message instanceof ShardLeaderStateChanged) {
188 onLeaderStateChanged((ShardLeaderStateChanged) message);
189 } else if(message instanceof SwitchShardBehavior){
190 onSwitchShardBehavior((SwitchShardBehavior) message);
192 unknownMessage(message);
197 private void checkReady(){
198 if (isReadyWithLeaderId()) {
199 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
200 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
202 waitTillReadyCountdownLatch.countDown();
206 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
207 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
209 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
210 if(shardInformation != null) {
211 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
212 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
213 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
214 primaryShardInfoCache.remove(shardInformation.getShardName());
219 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
223 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
224 ShardInformation shardInfo = message.getShardInfo();
226 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
227 shardInfo.getShardName());
229 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
231 if(!shardInfo.isShardInitialized()) {
232 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
233 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
235 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
236 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
240 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
241 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
242 status.getName(), status.isInitialSyncDone());
244 ShardInformation shardInformation = findShardInformation(status.getName());
246 if(shardInformation != null) {
247 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
249 mBean.setSyncStatus(isInSync());
254 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
255 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
256 roleChanged.getOldRole(), roleChanged.getNewRole());
258 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
259 if(shardInformation != null) {
260 shardInformation.setRole(roleChanged.getNewRole());
262 mBean.setSyncStatus(isInSync());
267 private ShardInformation findShardInformation(String memberId) {
268 for(ShardInformation info : localShards.values()){
269 if(info.getShardId().toString().equals(memberId)){
277 private boolean isReadyWithLeaderId() {
278 boolean isReady = true;
279 for (ShardInformation info : localShards.values()) {
280 if(!info.isShardReadyWithLeaderId()){
288 private boolean isInSync(){
289 for (ShardInformation info : localShards.values()) {
290 if(!info.isInSync()){
297 private void onActorInitialized(Object message) {
298 final ActorRef sender = getSender();
300 if (sender == null) {
301 return; //why is a non-actor sending this message? Just ignore.
304 String actorName = sender.path().name();
305 //find shard name from actor name; actor name is stringified shardId
306 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
308 if (shardId.getShardName() == null) {
312 markShardAsInitialized(shardId.getShardName());
315 private void markShardAsInitialized(String shardName) {
316 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
318 ShardInformation shardInformation = localShards.get(shardName);
319 if (shardInformation != null) {
320 shardInformation.setActorInitialized();
322 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
327 protected void handleRecover(Object message) throws Exception {
328 if (message instanceof RecoveryCompleted) {
329 LOG.info("Recovery complete : {}", persistenceId());
331 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
332 // journal on upgrade from Helium.
333 deleteMessages(lastSequenceNr());
337 private void findLocalShard(FindLocalShard message) {
338 final ShardInformation shardInformation = localShards.get(message.getShardName());
340 if(shardInformation == null){
341 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
345 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
347 public Object get() {
348 return new LocalShardFound(shardInformation.getActor());
353 private void sendResponse(ShardInformation shardInformation, boolean doWait,
354 boolean wantShardReady, final Supplier<Object> messageSupplier) {
355 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
357 final ActorRef sender = getSender();
358 final ActorRef self = self();
360 Runnable replyRunnable = new Runnable() {
363 sender.tell(messageSupplier.get(), self);
367 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
368 new OnShardInitialized(replyRunnable);
370 shardInformation.addOnShardInitialized(onShardInitialized);
372 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
374 FiniteDuration timeout = datastoreContext.getShardInitializationTimeout().duration();
375 if(shardInformation.isShardInitialized()) {
376 // If the shard is already initialized then we'll wait enough time for the shard to
377 // elect a leader, ie 2 times the election timeout.
378 timeout = FiniteDuration.create(datastoreContext.getShardRaftConfig()
379 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
382 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
384 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
385 getContext().dispatcher(), getSelf());
387 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
389 } else if (!shardInformation.isShardInitialized()) {
390 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
391 shardInformation.getShardName());
392 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
394 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
395 shardInformation.getShardName());
396 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
402 getSender().tell(messageSupplier.get(), getSelf());
405 private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
406 return new NoShardLeaderException(null, shardId.toString());
409 private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
410 return new NotInitializedException(String.format(
411 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
414 private void memberRemoved(ClusterEvent.MemberRemoved message) {
415 String memberName = message.member().roles().head();
417 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
418 message.member().address());
420 memberNameToAddress.remove(message.member().roles().head());
423 private void memberUp(ClusterEvent.MemberUp message) {
424 String memberName = message.member().roles().head();
426 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
427 message.member().address());
429 memberNameToAddress.put(memberName, message.member().address());
431 for(ShardInformation info : localShards.values()){
432 String shardName = info.getShardName();
433 info.updatePeerAddress(getShardIdentifier(memberName, shardName).toString(),
434 getShardActorPath(shardName, memberName), getSelf());
440 private void memberReachable(ClusterEvent.ReachableMember message) {
441 String memberName = message.member().roles().head();
442 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
444 markMemberAvailable(memberName);
447 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
448 String memberName = message.member().roles().head();
449 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
451 markMemberUnavailable(memberName);
454 private void markMemberUnavailable(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 unavailable.", leaderId);
459 info.setLeaderAvailable(false);
461 primaryShardInfoCache.remove(info.getShardName());
466 private void markMemberAvailable(final String memberName) {
467 for(ShardInformation info : localShards.values()){
468 String leaderId = info.getLeaderId();
469 if(leaderId != null && leaderId.contains(memberName)) {
470 LOG.debug("Marking Leader {} as available.", leaderId);
471 info.setLeaderAvailable(true);
476 private void onDatastoreContext(DatastoreContext context) {
477 datastoreContext = context;
478 for (ShardInformation info : localShards.values()) {
479 if (info.getActor() != null) {
480 info.getActor().tell(datastoreContext, getSelf());
485 private void onSwitchShardBehavior(SwitchShardBehavior message) {
486 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
488 ShardInformation shardInformation = localShards.get(identifier.getShardName());
490 if(shardInformation != null && shardInformation.getActor() != null) {
491 shardInformation.getActor().tell(
492 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
494 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
495 message.getShardName(), message.getNewState());
500 * Notifies all the local shards of a change in the schema context
504 private void updateSchemaContext(final Object message) {
505 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
507 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
509 for (ShardInformation info : localShards.values()) {
510 if (info.getActor() == null) {
511 LOG.debug("Creating Shard {}", info.getShardId());
512 info.setActor(newShardActor(schemaContext, info));
514 info.getActor().tell(message, getSelf());
520 protected ClusterWrapper getCluster() {
525 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
526 return getContext().actorOf(Shard.props(info.getShardId(),
527 info.getPeerAddresses(), datastoreContext, schemaContext)
528 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
531 private void findPrimary(FindPrimary message) {
532 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
534 final String shardName = message.getShardName();
535 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
537 // First see if the there is a local replica for the shard
538 final ShardInformation info = localShards.get(shardName);
540 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
542 public Object get() {
543 String primaryPath = info.getSerializedLeaderActor();
544 Object found = canReturnLocalShardState && info.isLeader() ?
545 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
546 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
548 if(LOG.isDebugEnabled()) {
549 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
559 for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
560 if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
561 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
563 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
566 getContext().actorSelection(path).forward(new RemoteFindPrimary(shardName,
567 message.isWaitUntilReady()), getContext());
572 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
574 getSender().tell(new PrimaryNotFoundException(
575 String.format("No primary shard found for %s.", shardName)), getSelf());
578 private StringBuilder getShardManagerActorPathBuilder(Address address) {
579 StringBuilder builder = new StringBuilder();
580 builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
584 private String getShardActorPath(String shardName, String memberName) {
585 Address address = memberNameToAddress.get(memberName);
586 if(address != null) {
587 StringBuilder builder = getShardManagerActorPathBuilder(address);
589 .append(getShardIdentifier(memberName, shardName));
590 return builder.toString();
596 * Construct the name of the shard actor given the name of the member on
597 * which the shard resides and the name of the shard
603 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
604 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
608 * Create shards that are local to the member on which the ShardManager
612 private void createLocalShards() {
613 String memberName = this.cluster.getCurrentMemberName();
614 List<String> memberShardNames =
615 this.configuration.getMemberShardNames(memberName);
617 List<String> localShardActorNames = new ArrayList<>();
618 for(String shardName : memberShardNames){
619 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
620 Map<String, String> peerAddresses = getPeerAddresses(shardName);
621 localShardActorNames.add(shardId.toString());
622 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
625 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
626 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
628 mBean.setShardManager(this);
632 * Given the name of the shard find the addresses of all it's peers
637 private Map<String, String> getPeerAddresses(String shardName){
639 Map<String, String> peerAddresses = new HashMap<>();
641 List<String> members = this.configuration.getMembersFromShardName(shardName);
643 String currentMemberName = this.cluster.getCurrentMemberName();
645 for(String memberName : members){
646 if(!currentMemberName.equals(memberName)){
647 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
648 String path = getShardActorPath(shardName, currentMemberName);
649 peerAddresses.put(shardId.toString(), path);
652 return peerAddresses;
656 public SupervisorStrategy supervisorStrategy() {
658 return new OneForOneStrategy(10, Duration.create("1 minute"),
659 new Function<Throwable, SupervisorStrategy.Directive>() {
661 public SupervisorStrategy.Directive apply(Throwable t) {
662 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
663 return SupervisorStrategy.resume();
671 public String persistenceId() {
672 return "shard-manager-" + type;
676 ShardManagerInfoMBean getMBean(){
681 protected static class ShardInformation {
682 private final ShardIdentifier shardId;
683 private final String shardName;
684 private ActorRef actor;
685 private ActorPath actorPath;
686 private final Map<String, String> peerAddresses;
687 private Optional<DataTree> localShardDataTree;
688 private boolean leaderAvailable = false;
690 // flag that determines if the actor is ready for business
691 private boolean actorInitialized = false;
693 private boolean followerSyncStatus = false;
695 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
696 private String role ;
697 private String leaderId;
698 private short leaderVersion;
700 private ShardInformation(String shardName, ShardIdentifier shardId,
701 Map<String, String> peerAddresses) {
702 this.shardName = shardName;
703 this.shardId = shardId;
704 this.peerAddresses = peerAddresses;
707 String getShardName() {
715 ActorPath getActorPath() {
719 void setActor(ActorRef actor) {
721 this.actorPath = actor.path();
724 ShardIdentifier getShardId() {
728 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
729 this.localShardDataTree = localShardDataTree;
732 Optional<DataTree> getLocalShardDataTree() {
733 return localShardDataTree;
736 Map<String, String> getPeerAddresses() {
737 return peerAddresses;
740 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
741 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
743 if(peerAddresses.containsKey(peerId)){
744 peerAddresses.put(peerId, peerAddress);
747 if(LOG.isDebugEnabled()) {
748 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
749 peerId, peerAddress, actor.path());
752 actor.tell(new PeerAddressResolved(peerId.toString(), peerAddress), sender);
755 notifyOnShardInitializedCallbacks();
759 boolean isShardReady() {
760 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
763 boolean isShardReadyWithLeaderId() {
764 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
765 (isLeader() || peerAddresses.get(leaderId) != null);
768 boolean isShardInitialized() {
769 return getActor() != null && actorInitialized;
773 return Objects.equal(leaderId, shardId.toString());
776 String getSerializedLeaderActor() {
778 return Serialization.serializedActorPath(getActor());
780 return peerAddresses.get(leaderId);
784 void setActorInitialized() {
785 LOG.debug("Shard {} is initialized", shardId);
787 this.actorInitialized = true;
789 notifyOnShardInitializedCallbacks();
792 private void notifyOnShardInitializedCallbacks() {
793 if(onShardInitializedSet.isEmpty()) {
797 boolean ready = isShardReadyWithLeaderId();
799 if(LOG.isDebugEnabled()) {
800 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
801 ready ? "ready" : "initialized", onShardInitializedSet.size());
804 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
805 while(iter.hasNext()) {
806 OnShardInitialized onShardInitialized = iter.next();
807 if(!(onShardInitialized instanceof OnShardReady) || ready) {
809 onShardInitialized.getTimeoutSchedule().cancel();
810 onShardInitialized.getReplyRunnable().run();
815 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
816 onShardInitializedSet.add(onShardInitialized);
819 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
820 onShardInitializedSet.remove(onShardInitialized);
823 void setRole(String newRole) {
826 notifyOnShardInitializedCallbacks();
829 void setFollowerSyncStatus(boolean syncStatus){
830 this.followerSyncStatus = syncStatus;
834 if(RaftState.Follower.name().equals(this.role)){
835 return followerSyncStatus;
836 } else if(RaftState.Leader.name().equals(this.role)){
843 boolean setLeaderId(String leaderId) {
844 boolean changed = !Objects.equal(this.leaderId, leaderId);
845 this.leaderId = leaderId;
846 if(leaderId != null) {
847 this.leaderAvailable = true;
849 notifyOnShardInitializedCallbacks();
854 String getLeaderId() {
858 void setLeaderAvailable(boolean leaderAvailable) {
859 this.leaderAvailable = leaderAvailable;
862 short getLeaderVersion() {
863 return leaderVersion;
866 void setLeaderVersion(short leaderVersion) {
867 this.leaderVersion = leaderVersion;
871 private static class ShardManagerCreator implements Creator<ShardManager> {
872 private static final long serialVersionUID = 1L;
874 final ClusterWrapper cluster;
875 final Configuration configuration;
876 final DatastoreContext datastoreContext;
877 private final CountDownLatch waitTillReadyCountdownLatch;
878 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
880 ShardManagerCreator(ClusterWrapper cluster, Configuration configuration, DatastoreContext datastoreContext,
881 CountDownLatch waitTillReadyCountdownLatch, PrimaryShardInfoFutureCache primaryShardInfoCache) {
882 this.cluster = cluster;
883 this.configuration = configuration;
884 this.datastoreContext = datastoreContext;
885 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
886 this.primaryShardInfoCache = primaryShardInfoCache;
890 public ShardManager create() throws Exception {
891 return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch,
892 primaryShardInfoCache);
896 private static class OnShardInitialized {
897 private final Runnable replyRunnable;
898 private Cancellable timeoutSchedule;
900 OnShardInitialized(Runnable replyRunnable) {
901 this.replyRunnable = replyRunnable;
904 Runnable getReplyRunnable() {
905 return replyRunnable;
908 Cancellable getTimeoutSchedule() {
909 return timeoutSchedule;
912 void setTimeoutSchedule(Cancellable timeoutSchedule) {
913 this.timeoutSchedule = timeoutSchedule;
917 private static class OnShardReady extends OnShardInitialized {
918 OnShardReady(Runnable replyRunnable) {
919 super(replyRunnable);
923 private static class ShardNotInitializedTimeout {
924 private final ActorRef sender;
925 private final ShardInformation shardInfo;
926 private final OnShardInitialized onShardInitialized;
928 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
929 this.sender = sender;
930 this.shardInfo = shardInfo;
931 this.onShardInitialized = onShardInitialized;
934 ActorRef getSender() {
938 ShardInformation getShardInfo() {
942 OnShardInitialized getOnShardInitialized() {
943 return onShardInitialized;
948 * We no longer persist SchemaContextModules but keep this class around for now for backwards
949 * compatibility so we don't get de-serialization failures on upgrade from Helium.
952 static class SchemaContextModules implements Serializable {
953 private static final long serialVersionUID = -8884620101025936590L;
955 private final Set<String> modules;
957 SchemaContextModules(Set<String> modules){
958 this.modules = modules;
961 public Set<String> getModules() {