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.Collection;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.TimeUnit;
40 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
41 import org.opendaylight.controller.cluster.datastore.config.Configuration;
42 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
43 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
44 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
45 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
46 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
47 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
48 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
49 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
50 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
51 import org.opendaylight.controller.cluster.datastore.messages.CreateShardReply;
52 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
53 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
54 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
55 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
56 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
57 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
58 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
59 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
60 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
61 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
62 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
63 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
64 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
65 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
66 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
67 import org.opendaylight.controller.cluster.raft.RaftState;
68 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
69 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74 import scala.concurrent.duration.Duration;
75 import scala.concurrent.duration.FiniteDuration;
78 * The ShardManager has the following jobs,
80 * <li> Create all the local shard replicas that belong on this cluster member
81 * <li> Find the address of the local shard
82 * <li> Find the primary replica for any given shard
83 * <li> Monitor the cluster members and store their addresses
86 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
88 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
90 // Stores a mapping between a member name and the address of the member
91 // Member names look like "member-1", "member-2" etc and are as specified
93 private final Map<String, Address> memberNameToAddress = new HashMap<>();
95 // Stores a mapping between a shard name and it's corresponding information
96 // Shard names look like inventory, topology etc and are as specified in
98 private final Map<String, ShardInformation> localShards = new HashMap<>();
100 // The type of a ShardManager reflects the type of the datastore itself
101 // A data store could be of type config/operational
102 private final String type;
104 private final String shardManagerIdentifierString;
106 private final ClusterWrapper cluster;
108 private final Configuration configuration;
110 private final String shardDispatcherPath;
112 private ShardManagerInfo mBean;
114 private DatastoreContext datastoreContext;
116 private final CountDownLatch waitTillReadyCountdownLatch;
118 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
120 private SchemaContext schemaContext;
124 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
125 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
126 PrimaryShardInfoFutureCache primaryShardInfoCache) {
128 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
129 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
130 this.datastoreContext = datastoreContext;
131 this.type = datastoreContext.getDataStoreType();
132 this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
133 this.shardDispatcherPath =
134 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
135 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
136 this.primaryShardInfoCache = primaryShardInfoCache;
138 // Subscribe this actor to cluster member events
139 cluster.subscribeToMemberEvents(getSelf());
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) {
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");
156 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext,
157 waitTillReadyCountdownLatch, primaryShardInfoCache));
161 public void postStop() {
162 LOG.info("Stopping ShardManager");
164 mBean.unregisterMBean();
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.MemberRemoved) {
180 memberRemoved((ClusterEvent.MemberRemoved) message);
181 } else if(message instanceof ClusterEvent.UnreachableMember) {
182 memberUnreachable((ClusterEvent.UnreachableMember)message);
183 } else if(message instanceof ClusterEvent.ReachableMember) {
184 memberReachable((ClusterEvent.ReachableMember) message);
185 } else if(message instanceof DatastoreContext) {
186 onDatastoreContext((DatastoreContext)message);
187 } else if(message instanceof RoleChangeNotification) {
188 onRoleChangeNotification((RoleChangeNotification) message);
189 } else if(message instanceof FollowerInitialSyncUpStatus){
190 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
191 } else if(message instanceof ShardNotInitializedTimeout) {
192 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
193 } else if(message instanceof ShardLeaderStateChanged) {
194 onLeaderStateChanged((ShardLeaderStateChanged) message);
195 } else if(message instanceof SwitchShardBehavior){
196 onSwitchShardBehavior((SwitchShardBehavior) message);
197 } else if(message instanceof CreateShard) {
198 onCreateShard((CreateShard)message);
200 unknownMessage(message);
205 private void onCreateShard(CreateShard createShard) {
208 if(localShards.containsKey(createShard.getShardName())) {
209 throw new IllegalStateException(String.format("Shard with name %s already exists",
210 createShard.getShardName()));
213 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), createShard.getShardName());
214 Map<String, String> peerAddresses = getPeerAddresses(createShard.getShardName(), createShard.getMemberNames());
216 LOG.debug("onCreateShard: shardId: {}, peerAddresses: {}", shardId, peerAddresses);
218 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
219 if(shardDatastoreContext == null) {
220 shardDatastoreContext = datastoreContext;
223 ShardInformation info = new ShardInformation(createShard.getShardName(), shardId, peerAddresses,
224 shardDatastoreContext, createShard.getShardPropsCreator());
225 localShards.put(createShard.getShardName(), info);
227 mBean.addLocalShard(shardId.toString());
229 if(schemaContext != null) {
230 info.setActor(newShardActor(schemaContext, info));
233 reply = new CreateShardReply();
234 } catch (Exception e) {
235 LOG.error("onCreateShard failed", e);
236 reply = new akka.actor.Status.Failure(e);
239 if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
240 getSender().tell(reply, getSelf());
244 private void checkReady(){
245 if (isReadyWithLeaderId()) {
246 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
247 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
249 waitTillReadyCountdownLatch.countDown();
253 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
254 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
256 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
257 if(shardInformation != null) {
258 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
259 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
260 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
261 primaryShardInfoCache.remove(shardInformation.getShardName());
266 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
270 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
271 ShardInformation shardInfo = message.getShardInfo();
273 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
274 shardInfo.getShardName());
276 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
278 if(!shardInfo.isShardInitialized()) {
279 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
280 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
282 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
283 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
287 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
288 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
289 status.getName(), status.isInitialSyncDone());
291 ShardInformation shardInformation = findShardInformation(status.getName());
293 if(shardInformation != null) {
294 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
296 mBean.setSyncStatus(isInSync());
301 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
302 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
303 roleChanged.getOldRole(), roleChanged.getNewRole());
305 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
306 if(shardInformation != null) {
307 shardInformation.setRole(roleChanged.getNewRole());
309 mBean.setSyncStatus(isInSync());
314 private ShardInformation findShardInformation(String memberId) {
315 for(ShardInformation info : localShards.values()){
316 if(info.getShardId().toString().equals(memberId)){
324 private boolean isReadyWithLeaderId() {
325 boolean isReady = true;
326 for (ShardInformation info : localShards.values()) {
327 if(!info.isShardReadyWithLeaderId()){
335 private boolean isInSync(){
336 for (ShardInformation info : localShards.values()) {
337 if(!info.isInSync()){
344 private void onActorInitialized(Object message) {
345 final ActorRef sender = getSender();
347 if (sender == null) {
348 return; //why is a non-actor sending this message? Just ignore.
351 String actorName = sender.path().name();
352 //find shard name from actor name; actor name is stringified shardId
353 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
355 if (shardId.getShardName() == null) {
359 markShardAsInitialized(shardId.getShardName());
362 private void markShardAsInitialized(String shardName) {
363 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
365 ShardInformation shardInformation = localShards.get(shardName);
366 if (shardInformation != null) {
367 shardInformation.setActorInitialized();
369 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
374 protected void handleRecover(Object message) throws Exception {
375 if (message instanceof RecoveryCompleted) {
376 LOG.info("Recovery complete : {}", persistenceId());
378 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
379 // journal on upgrade from Helium.
380 deleteMessages(lastSequenceNr());
384 private void findLocalShard(FindLocalShard message) {
385 final ShardInformation shardInformation = localShards.get(message.getShardName());
387 if(shardInformation == null){
388 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
392 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
394 public Object get() {
395 return new LocalShardFound(shardInformation.getActor());
400 private void sendResponse(ShardInformation shardInformation, boolean doWait,
401 boolean wantShardReady, final Supplier<Object> messageSupplier) {
402 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
404 final ActorRef sender = getSender();
405 final ActorRef self = self();
407 Runnable replyRunnable = new Runnable() {
410 sender.tell(messageSupplier.get(), self);
414 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
415 new OnShardInitialized(replyRunnable);
417 shardInformation.addOnShardInitialized(onShardInitialized);
419 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
421 FiniteDuration timeout = datastoreContext.getShardInitializationTimeout().duration();
422 if(shardInformation.isShardInitialized()) {
423 // If the shard is already initialized then we'll wait enough time for the shard to
424 // elect a leader, ie 2 times the election timeout.
425 timeout = FiniteDuration.create(datastoreContext.getShardRaftConfig()
426 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
429 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
431 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
432 getContext().dispatcher(), getSelf());
434 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
436 } else if (!shardInformation.isShardInitialized()) {
437 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
438 shardInformation.getShardName());
439 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
441 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
442 shardInformation.getShardName());
443 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
449 getSender().tell(messageSupplier.get(), getSelf());
452 private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
453 return new NoShardLeaderException(null, shardId.toString());
456 private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
457 return new NotInitializedException(String.format(
458 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
461 private void memberRemoved(ClusterEvent.MemberRemoved message) {
462 String memberName = message.member().roles().head();
464 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
465 message.member().address());
467 memberNameToAddress.remove(message.member().roles().head());
470 private void memberUp(ClusterEvent.MemberUp message) {
471 String memberName = message.member().roles().head();
473 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
474 message.member().address());
476 memberNameToAddress.put(memberName, message.member().address());
478 for(ShardInformation info : localShards.values()){
479 String shardName = info.getShardName();
480 info.updatePeerAddress(getShardIdentifier(memberName, shardName).toString(),
481 getShardActorPath(shardName, memberName), getSelf());
487 private void memberReachable(ClusterEvent.ReachableMember message) {
488 String memberName = message.member().roles().head();
489 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
491 markMemberAvailable(memberName);
494 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
495 String memberName = message.member().roles().head();
496 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
498 markMemberUnavailable(memberName);
501 private void markMemberUnavailable(final String memberName) {
502 for(ShardInformation info : localShards.values()){
503 String leaderId = info.getLeaderId();
504 if(leaderId != null && leaderId.contains(memberName)) {
505 LOG.debug("Marking Leader {} as unavailable.", leaderId);
506 info.setLeaderAvailable(false);
508 primaryShardInfoCache.remove(info.getShardName());
513 private void markMemberAvailable(final String memberName) {
514 for(ShardInformation info : localShards.values()){
515 String leaderId = info.getLeaderId();
516 if(leaderId != null && leaderId.contains(memberName)) {
517 LOG.debug("Marking Leader {} as available.", leaderId);
518 info.setLeaderAvailable(true);
523 private void onDatastoreContext(DatastoreContext context) {
524 datastoreContext = context;
525 for (ShardInformation info : localShards.values()) {
526 if (info.getActor() != null) {
527 info.getActor().tell(datastoreContext, getSelf());
532 private void onSwitchShardBehavior(SwitchShardBehavior message) {
533 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
535 ShardInformation shardInformation = localShards.get(identifier.getShardName());
537 if(shardInformation != null && shardInformation.getActor() != null) {
538 shardInformation.getActor().tell(
539 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
541 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
542 message.getShardName(), message.getNewState());
547 * Notifies all the local shards of a change in the schema context
551 private void updateSchemaContext(final Object message) {
552 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
554 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
556 for (ShardInformation info : localShards.values()) {
557 if (info.getActor() == null) {
558 LOG.debug("Creating Shard {}", info.getShardId());
559 info.setActor(newShardActor(schemaContext, info));
561 info.getActor().tell(message, getSelf());
567 protected ClusterWrapper getCluster() {
572 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
573 return getContext().actorOf(info.newProps(schemaContext)
574 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
577 private void findPrimary(FindPrimary message) {
578 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
580 final String shardName = message.getShardName();
581 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
583 // First see if the there is a local replica for the shard
584 final ShardInformation info = localShards.get(shardName);
586 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
588 public Object get() {
589 String primaryPath = info.getSerializedLeaderActor();
590 Object found = canReturnLocalShardState && info.isLeader() ?
591 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
592 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
594 if(LOG.isDebugEnabled()) {
595 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
605 for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
606 if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
607 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
609 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
612 getContext().actorSelection(path).forward(new RemoteFindPrimary(shardName,
613 message.isWaitUntilReady()), getContext());
618 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
620 getSender().tell(new PrimaryNotFoundException(
621 String.format("No primary shard found for %s.", shardName)), getSelf());
624 private StringBuilder getShardManagerActorPathBuilder(Address address) {
625 StringBuilder builder = new StringBuilder();
626 builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
630 private String getShardActorPath(String shardName, String memberName) {
631 Address address = memberNameToAddress.get(memberName);
632 if(address != null) {
633 StringBuilder builder = getShardManagerActorPathBuilder(address);
635 .append(getShardIdentifier(memberName, shardName));
636 return builder.toString();
642 * Construct the name of the shard actor given the name of the member on
643 * which the shard resides and the name of the shard
649 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
650 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
654 * Create shards that are local to the member on which the ShardManager
658 private void createLocalShards() {
659 String memberName = this.cluster.getCurrentMemberName();
660 List<String> memberShardNames =
661 this.configuration.getMemberShardNames(memberName);
663 ShardPropsCreator shardPropsCreator = new DefaultShardPropsCreator();
664 List<String> localShardActorNames = new ArrayList<>();
665 for(String shardName : memberShardNames){
666 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
667 Map<String, String> peerAddresses = getPeerAddresses(shardName);
668 localShardActorNames.add(shardId.toString());
669 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses, datastoreContext,
673 mBean = ShardManagerInfo.createShardManagerMBean(memberName, "shard-manager-" + this.type,
674 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
676 mBean.setShardManager(this);
680 * Given the name of the shard find the addresses of all it's peers
685 private Map<String, String> getPeerAddresses(String shardName) {
686 return getPeerAddresses(shardName, configuration.getMembersFromShardName(shardName));
689 private Map<String, String> getPeerAddresses(String shardName, Collection<String> members) {
691 Map<String, String> peerAddresses = new HashMap<>();
693 String currentMemberName = this.cluster.getCurrentMemberName();
695 for(String memberName : members) {
696 if(!currentMemberName.equals(memberName)) {
697 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
698 String path = getShardActorPath(shardName, currentMemberName);
699 peerAddresses.put(shardId.toString(), path);
702 return peerAddresses;
706 public SupervisorStrategy supervisorStrategy() {
708 return new OneForOneStrategy(10, Duration.create("1 minute"),
709 new Function<Throwable, SupervisorStrategy.Directive>() {
711 public SupervisorStrategy.Directive apply(Throwable t) {
712 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
713 return SupervisorStrategy.resume();
721 public String persistenceId() {
722 return "shard-manager-" + type;
726 ShardManagerInfoMBean getMBean(){
731 protected static class ShardInformation {
732 private final ShardIdentifier shardId;
733 private final String shardName;
734 private ActorRef actor;
735 private ActorPath actorPath;
736 private final Map<String, String> peerAddresses;
737 private Optional<DataTree> localShardDataTree;
738 private boolean leaderAvailable = false;
740 // flag that determines if the actor is ready for business
741 private boolean actorInitialized = false;
743 private boolean followerSyncStatus = false;
745 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
746 private String role ;
747 private String leaderId;
748 private short leaderVersion;
750 private final DatastoreContext datastoreContext;
751 private final ShardPropsCreator shardPropsCreator;
753 private ShardInformation(String shardName, ShardIdentifier shardId,
754 Map<String, String> peerAddresses, DatastoreContext datastoreContext,
755 ShardPropsCreator shardPropsCreator) {
756 this.shardName = shardName;
757 this.shardId = shardId;
758 this.peerAddresses = peerAddresses;
759 this.datastoreContext = datastoreContext;
760 this.shardPropsCreator = shardPropsCreator;
763 Props newProps(SchemaContext schemaContext) {
764 return shardPropsCreator.newProps(shardId, peerAddresses, datastoreContext, schemaContext);
767 String getShardName() {
775 ActorPath getActorPath() {
779 void setActor(ActorRef actor) {
781 this.actorPath = actor.path();
784 ShardIdentifier getShardId() {
788 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
789 this.localShardDataTree = localShardDataTree;
792 Optional<DataTree> getLocalShardDataTree() {
793 return localShardDataTree;
796 Map<String, String> getPeerAddresses() {
797 return peerAddresses;
800 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
801 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
803 if(peerAddresses.containsKey(peerId)){
804 peerAddresses.put(peerId, peerAddress);
807 if(LOG.isDebugEnabled()) {
808 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
809 peerId, peerAddress, actor.path());
812 actor.tell(new PeerAddressResolved(peerId.toString(), peerAddress), sender);
815 notifyOnShardInitializedCallbacks();
819 boolean isShardReady() {
820 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
823 boolean isShardReadyWithLeaderId() {
824 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
825 (isLeader() || peerAddresses.get(leaderId) != null);
828 boolean isShardInitialized() {
829 return getActor() != null && actorInitialized;
833 return Objects.equal(leaderId, shardId.toString());
836 String getSerializedLeaderActor() {
838 return Serialization.serializedActorPath(getActor());
840 return peerAddresses.get(leaderId);
844 void setActorInitialized() {
845 LOG.debug("Shard {} is initialized", shardId);
847 this.actorInitialized = true;
849 notifyOnShardInitializedCallbacks();
852 private void notifyOnShardInitializedCallbacks() {
853 if(onShardInitializedSet.isEmpty()) {
857 boolean ready = isShardReadyWithLeaderId();
859 if(LOG.isDebugEnabled()) {
860 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
861 ready ? "ready" : "initialized", onShardInitializedSet.size());
864 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
865 while(iter.hasNext()) {
866 OnShardInitialized onShardInitialized = iter.next();
867 if(!(onShardInitialized instanceof OnShardReady) || ready) {
869 onShardInitialized.getTimeoutSchedule().cancel();
870 onShardInitialized.getReplyRunnable().run();
875 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
876 onShardInitializedSet.add(onShardInitialized);
879 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
880 onShardInitializedSet.remove(onShardInitialized);
883 void setRole(String newRole) {
886 notifyOnShardInitializedCallbacks();
889 void setFollowerSyncStatus(boolean syncStatus){
890 this.followerSyncStatus = syncStatus;
894 if(RaftState.Follower.name().equals(this.role)){
895 return followerSyncStatus;
896 } else if(RaftState.Leader.name().equals(this.role)){
903 boolean setLeaderId(String leaderId) {
904 boolean changed = !Objects.equal(this.leaderId, leaderId);
905 this.leaderId = leaderId;
906 if(leaderId != null) {
907 this.leaderAvailable = true;
909 notifyOnShardInitializedCallbacks();
914 String getLeaderId() {
918 void setLeaderAvailable(boolean leaderAvailable) {
919 this.leaderAvailable = leaderAvailable;
922 short getLeaderVersion() {
923 return leaderVersion;
926 void setLeaderVersion(short leaderVersion) {
927 this.leaderVersion = leaderVersion;
931 private static class ShardManagerCreator implements Creator<ShardManager> {
932 private static final long serialVersionUID = 1L;
934 final ClusterWrapper cluster;
935 final Configuration configuration;
936 final DatastoreContext datastoreContext;
937 private final CountDownLatch waitTillReadyCountdownLatch;
938 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
940 ShardManagerCreator(ClusterWrapper cluster, Configuration configuration, DatastoreContext datastoreContext,
941 CountDownLatch waitTillReadyCountdownLatch, PrimaryShardInfoFutureCache primaryShardInfoCache) {
942 this.cluster = cluster;
943 this.configuration = configuration;
944 this.datastoreContext = datastoreContext;
945 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
946 this.primaryShardInfoCache = primaryShardInfoCache;
950 public ShardManager create() throws Exception {
951 return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch,
952 primaryShardInfoCache);
956 private static class OnShardInitialized {
957 private final Runnable replyRunnable;
958 private Cancellable timeoutSchedule;
960 OnShardInitialized(Runnable replyRunnable) {
961 this.replyRunnable = replyRunnable;
964 Runnable getReplyRunnable() {
965 return replyRunnable;
968 Cancellable getTimeoutSchedule() {
969 return timeoutSchedule;
972 void setTimeoutSchedule(Cancellable timeoutSchedule) {
973 this.timeoutSchedule = timeoutSchedule;
977 private static class OnShardReady extends OnShardInitialized {
978 OnShardReady(Runnable replyRunnable) {
979 super(replyRunnable);
983 private static class ShardNotInitializedTimeout {
984 private final ActorRef sender;
985 private final ShardInformation shardInfo;
986 private final OnShardInitialized onShardInitialized;
988 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
989 this.sender = sender;
990 this.shardInfo = shardInfo;
991 this.onShardInitialized = onShardInitialized;
994 ActorRef getSender() {
998 ShardInformation getShardInfo() {
1002 OnShardInitialized getOnShardInitialized() {
1003 return onShardInitialized;
1008 * We no longer persist SchemaContextModules but keep this class around for now for backwards
1009 * compatibility so we don't get de-serialization failures on upgrade from Helium.
1012 static class SchemaContextModules implements Serializable {
1013 private static final long serialVersionUID = -8884620101025936590L;
1015 private final Set<String> modules;
1017 SchemaContextModules(Set<String> modules){
1018 this.modules = modules;
1021 public Set<String> getModules() {