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.PeerDown;
59 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
60 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
61 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
62 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
63 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
64 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
65 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
66 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
67 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
68 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
69 import org.opendaylight.controller.cluster.raft.RaftState;
70 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
71 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76 import scala.concurrent.duration.Duration;
77 import scala.concurrent.duration.FiniteDuration;
80 * The ShardManager has the following jobs,
82 * <li> Create all the local shard replicas that belong on this cluster member
83 * <li> Find the address of the local shard
84 * <li> Find the primary replica for any given shard
85 * <li> Monitor the cluster members and store their addresses
88 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
90 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
92 // Stores a mapping between a member name and the address of the member
93 // Member names look like "member-1", "member-2" etc and are as specified
95 private final Map<String, Address> memberNameToAddress = new HashMap<>();
97 // Stores a mapping between a shard name and it's corresponding information
98 // Shard names look like inventory, topology etc and are as specified in
100 private final Map<String, ShardInformation> localShards = new HashMap<>();
102 // The type of a ShardManager reflects the type of the datastore itself
103 // A data store could be of type config/operational
104 private final String type;
106 private final String shardManagerIdentifierString;
108 private final ClusterWrapper cluster;
110 private final Configuration configuration;
112 private final String shardDispatcherPath;
114 private ShardManagerInfo mBean;
116 private DatastoreContext datastoreContext;
118 private final CountDownLatch waitTillReadyCountdownLatch;
120 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
122 private SchemaContext schemaContext;
126 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
127 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
128 PrimaryShardInfoFutureCache primaryShardInfoCache) {
130 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
131 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
132 this.datastoreContext = datastoreContext;
133 this.type = datastoreContext.getDataStoreType();
134 this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
135 this.shardDispatcherPath =
136 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
137 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
138 this.primaryShardInfoCache = primaryShardInfoCache;
140 // Subscribe this actor to cluster member events
141 cluster.subscribeToMemberEvents(getSelf());
146 public static Props props(
147 final ClusterWrapper cluster,
148 final Configuration configuration,
149 final DatastoreContext datastoreContext,
150 final CountDownLatch waitTillReadyCountdownLatch,
151 final PrimaryShardInfoFutureCache primaryShardInfoCache) {
153 Preconditions.checkNotNull(cluster, "cluster should not be null");
154 Preconditions.checkNotNull(configuration, "configuration should not be null");
155 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
156 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
158 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext,
159 waitTillReadyCountdownLatch, primaryShardInfoCache));
163 public void postStop() {
164 LOG.info("Stopping ShardManager");
166 mBean.unregisterMBean();
170 public void handleCommand(Object message) throws Exception {
171 if (message instanceof FindPrimary) {
172 findPrimary((FindPrimary)message);
173 } else if(message instanceof FindLocalShard){
174 findLocalShard((FindLocalShard) message);
175 } else if (message instanceof UpdateSchemaContext) {
176 updateSchemaContext(message);
177 } else if(message instanceof ActorInitialized) {
178 onActorInitialized(message);
179 } else if (message instanceof ClusterEvent.MemberUp){
180 memberUp((ClusterEvent.MemberUp) message);
181 } else if (message instanceof ClusterEvent.MemberExited){
182 memberExited((ClusterEvent.MemberExited) message);
183 } else if(message instanceof ClusterEvent.MemberRemoved) {
184 memberRemoved((ClusterEvent.MemberRemoved) message);
185 } else if(message instanceof ClusterEvent.UnreachableMember) {
186 memberUnreachable((ClusterEvent.UnreachableMember)message);
187 } else if(message instanceof ClusterEvent.ReachableMember) {
188 memberReachable((ClusterEvent.ReachableMember) message);
189 } else if(message instanceof DatastoreContext) {
190 onDatastoreContext((DatastoreContext)message);
191 } else if(message instanceof RoleChangeNotification) {
192 onRoleChangeNotification((RoleChangeNotification) message);
193 } else if(message instanceof FollowerInitialSyncUpStatus){
194 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
195 } else if(message instanceof ShardNotInitializedTimeout) {
196 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
197 } else if(message instanceof ShardLeaderStateChanged) {
198 onLeaderStateChanged((ShardLeaderStateChanged) message);
199 } else if(message instanceof SwitchShardBehavior){
200 onSwitchShardBehavior((SwitchShardBehavior) message);
201 } else if(message instanceof CreateShard) {
202 onCreateShard((CreateShard)message);
204 unknownMessage(message);
209 private void onCreateShard(CreateShard createShard) {
212 if(localShards.containsKey(createShard.getShardName())) {
213 throw new IllegalStateException(String.format("Shard with name %s already exists",
214 createShard.getShardName()));
217 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), createShard.getShardName());
218 Map<String, String> peerAddresses = getPeerAddresses(createShard.getShardName(), createShard.getMemberNames());
220 LOG.debug("onCreateShard: shardId: {}, memberNames: {}. peerAddresses: {}", shardId,
221 createShard.getMemberNames(), peerAddresses);
223 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
224 if(shardDatastoreContext == null) {
225 shardDatastoreContext = datastoreContext;
228 ShardInformation info = new ShardInformation(createShard.getShardName(), shardId, peerAddresses,
229 shardDatastoreContext, createShard.getShardPropsCreator());
230 localShards.put(createShard.getShardName(), info);
232 mBean.addLocalShard(shardId.toString());
234 if(schemaContext != null) {
235 info.setActor(newShardActor(schemaContext, info));
238 reply = new CreateShardReply();
239 } catch (Exception e) {
240 LOG.error("onCreateShard failed", e);
241 reply = new akka.actor.Status.Failure(e);
244 if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
245 getSender().tell(reply, getSelf());
249 private void checkReady(){
250 if (isReadyWithLeaderId()) {
251 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
252 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
254 waitTillReadyCountdownLatch.countDown();
258 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
259 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
261 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
262 if(shardInformation != null) {
263 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
264 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
265 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
266 primaryShardInfoCache.remove(shardInformation.getShardName());
271 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
275 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
276 ShardInformation shardInfo = message.getShardInfo();
278 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
279 shardInfo.getShardName());
281 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
283 if(!shardInfo.isShardInitialized()) {
284 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
285 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
287 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
288 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
292 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
293 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
294 status.getName(), status.isInitialSyncDone());
296 ShardInformation shardInformation = findShardInformation(status.getName());
298 if(shardInformation != null) {
299 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
301 mBean.setSyncStatus(isInSync());
306 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
307 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
308 roleChanged.getOldRole(), roleChanged.getNewRole());
310 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
311 if(shardInformation != null) {
312 shardInformation.setRole(roleChanged.getNewRole());
314 mBean.setSyncStatus(isInSync());
319 private ShardInformation findShardInformation(String memberId) {
320 for(ShardInformation info : localShards.values()){
321 if(info.getShardId().toString().equals(memberId)){
329 private boolean isReadyWithLeaderId() {
330 boolean isReady = true;
331 for (ShardInformation info : localShards.values()) {
332 if(!info.isShardReadyWithLeaderId()){
340 private boolean isInSync(){
341 for (ShardInformation info : localShards.values()) {
342 if(!info.isInSync()){
349 private void onActorInitialized(Object message) {
350 final ActorRef sender = getSender();
352 if (sender == null) {
353 return; //why is a non-actor sending this message? Just ignore.
356 String actorName = sender.path().name();
357 //find shard name from actor name; actor name is stringified shardId
358 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
360 if (shardId.getShardName() == null) {
364 markShardAsInitialized(shardId.getShardName());
367 private void markShardAsInitialized(String shardName) {
368 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
370 ShardInformation shardInformation = localShards.get(shardName);
371 if (shardInformation != null) {
372 shardInformation.setActorInitialized();
374 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
379 protected void handleRecover(Object message) throws Exception {
380 if (message instanceof RecoveryCompleted) {
381 LOG.info("Recovery complete : {}", persistenceId());
383 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
384 // journal on upgrade from Helium.
385 deleteMessages(lastSequenceNr());
389 private void findLocalShard(FindLocalShard message) {
390 final ShardInformation shardInformation = localShards.get(message.getShardName());
392 if(shardInformation == null){
393 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
397 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
399 public Object get() {
400 return new LocalShardFound(shardInformation.getActor());
405 private void sendResponse(ShardInformation shardInformation, boolean doWait,
406 boolean wantShardReady, final Supplier<Object> messageSupplier) {
407 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
409 final ActorRef sender = getSender();
410 final ActorRef self = self();
412 Runnable replyRunnable = new Runnable() {
415 sender.tell(messageSupplier.get(), self);
419 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
420 new OnShardInitialized(replyRunnable);
422 shardInformation.addOnShardInitialized(onShardInitialized);
424 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
426 FiniteDuration timeout = datastoreContext.getShardInitializationTimeout().duration();
427 if(shardInformation.isShardInitialized()) {
428 // If the shard is already initialized then we'll wait enough time for the shard to
429 // elect a leader, ie 2 times the election timeout.
430 timeout = FiniteDuration.create(datastoreContext.getShardRaftConfig()
431 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
434 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
436 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
437 getContext().dispatcher(), getSelf());
439 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
441 } else if (!shardInformation.isShardInitialized()) {
442 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
443 shardInformation.getShardName());
444 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
446 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
447 shardInformation.getShardName());
448 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
454 getSender().tell(messageSupplier.get(), getSelf());
457 private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
458 return new NoShardLeaderException(null, shardId.toString());
461 private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
462 return new NotInitializedException(String.format(
463 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
466 private void memberRemoved(ClusterEvent.MemberRemoved message) {
467 String memberName = message.member().roles().head();
469 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
470 message.member().address());
472 memberNameToAddress.remove(memberName);
474 for(ShardInformation info : localShards.values()){
475 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
479 private void memberExited(ClusterEvent.MemberExited message) {
480 String memberName = message.member().roles().head();
482 LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
483 message.member().address());
485 memberNameToAddress.remove(memberName);
487 for(ShardInformation info : localShards.values()){
488 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
492 private void memberUp(ClusterEvent.MemberUp message) {
493 String memberName = message.member().roles().head();
495 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
496 message.member().address());
498 memberNameToAddress.put(memberName, message.member().address());
500 for(ShardInformation info : localShards.values()){
501 String shardName = info.getShardName();
502 String peerId = getShardIdentifier(memberName, shardName).toString();
503 info.updatePeerAddress(peerId, getShardActorPath(shardName, memberName), getSelf());
505 info.peerUp(memberName, peerId, getSelf());
511 private void memberReachable(ClusterEvent.ReachableMember message) {
512 String memberName = message.member().roles().head();
513 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
515 markMemberAvailable(memberName);
518 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
519 String memberName = message.member().roles().head();
520 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
522 markMemberUnavailable(memberName);
525 private void markMemberUnavailable(final String memberName) {
526 for(ShardInformation info : localShards.values()){
527 String leaderId = info.getLeaderId();
528 if(leaderId != null && leaderId.contains(memberName)) {
529 LOG.debug("Marking Leader {} as unavailable.", leaderId);
530 info.setLeaderAvailable(false);
532 primaryShardInfoCache.remove(info.getShardName());
535 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
539 private void markMemberAvailable(final String memberName) {
540 for(ShardInformation info : localShards.values()){
541 String leaderId = info.getLeaderId();
542 if(leaderId != null && leaderId.contains(memberName)) {
543 LOG.debug("Marking Leader {} as available.", leaderId);
544 info.setLeaderAvailable(true);
547 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
551 private void onDatastoreContext(DatastoreContext context) {
552 datastoreContext = context;
553 for (ShardInformation info : localShards.values()) {
554 if (info.getActor() != null) {
555 info.getActor().tell(datastoreContext, getSelf());
560 private void onSwitchShardBehavior(SwitchShardBehavior message) {
561 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
563 ShardInformation shardInformation = localShards.get(identifier.getShardName());
565 if(shardInformation != null && shardInformation.getActor() != null) {
566 shardInformation.getActor().tell(
567 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
569 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
570 message.getShardName(), message.getNewState());
575 * Notifies all the local shards of a change in the schema context
579 private void updateSchemaContext(final Object message) {
580 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
582 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
584 for (ShardInformation info : localShards.values()) {
585 if (info.getActor() == null) {
586 LOG.debug("Creating Shard {}", info.getShardId());
587 info.setActor(newShardActor(schemaContext, info));
589 info.getActor().tell(message, getSelf());
595 protected ClusterWrapper getCluster() {
600 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
601 return getContext().actorOf(info.newProps(schemaContext)
602 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
605 private void findPrimary(FindPrimary message) {
606 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
608 final String shardName = message.getShardName();
609 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
611 // First see if the there is a local replica for the shard
612 final ShardInformation info = localShards.get(shardName);
614 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
616 public Object get() {
617 String primaryPath = info.getSerializedLeaderActor();
618 Object found = canReturnLocalShardState && info.isLeader() ?
619 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
620 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
622 if(LOG.isDebugEnabled()) {
623 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
633 for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
634 if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
635 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
637 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
640 getContext().actorSelection(path).forward(new RemoteFindPrimary(shardName,
641 message.isWaitUntilReady()), getContext());
646 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
648 getSender().tell(new PrimaryNotFoundException(
649 String.format("No primary shard found for %s.", shardName)), getSelf());
652 private StringBuilder getShardManagerActorPathBuilder(Address address) {
653 StringBuilder builder = new StringBuilder();
654 builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
658 private String getShardActorPath(String shardName, String memberName) {
659 Address address = memberNameToAddress.get(memberName);
660 if(address != null) {
661 StringBuilder builder = getShardManagerActorPathBuilder(address);
663 .append(getShardIdentifier(memberName, shardName));
664 return builder.toString();
670 * Construct the name of the shard actor given the name of the member on
671 * which the shard resides and the name of the shard
677 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
678 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
682 * Create shards that are local to the member on which the ShardManager
686 private void createLocalShards() {
687 String memberName = this.cluster.getCurrentMemberName();
688 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
690 ShardPropsCreator shardPropsCreator = new DefaultShardPropsCreator();
691 List<String> localShardActorNames = new ArrayList<>();
692 for(String shardName : memberShardNames){
693 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
694 Map<String, String> peerAddresses = getPeerAddresses(shardName);
695 localShardActorNames.add(shardId.toString());
696 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses, datastoreContext,
700 mBean = ShardManagerInfo.createShardManagerMBean(memberName, "shard-manager-" + this.type,
701 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
703 mBean.setShardManager(this);
707 * Given the name of the shard find the addresses of all it's peers
712 private Map<String, String> getPeerAddresses(String shardName) {
713 return getPeerAddresses(shardName, configuration.getMembersFromShardName(shardName));
716 private Map<String, String> getPeerAddresses(String shardName, Collection<String> members) {
718 Map<String, String> peerAddresses = new HashMap<>();
720 String currentMemberName = this.cluster.getCurrentMemberName();
722 for(String memberName : members) {
723 if(!currentMemberName.equals(memberName)) {
724 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
725 String path = getShardActorPath(shardName, memberName);
726 peerAddresses.put(shardId.toString(), path);
729 return peerAddresses;
733 public SupervisorStrategy supervisorStrategy() {
735 return new OneForOneStrategy(10, Duration.create("1 minute"),
736 new Function<Throwable, SupervisorStrategy.Directive>() {
738 public SupervisorStrategy.Directive apply(Throwable t) {
739 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
740 return SupervisorStrategy.resume();
748 public String persistenceId() {
749 return "shard-manager-" + type;
753 ShardManagerInfoMBean getMBean(){
758 protected static class ShardInformation {
759 private final ShardIdentifier shardId;
760 private final String shardName;
761 private ActorRef actor;
762 private ActorPath actorPath;
763 private final Map<String, String> peerAddresses;
764 private Optional<DataTree> localShardDataTree;
765 private boolean leaderAvailable = false;
767 // flag that determines if the actor is ready for business
768 private boolean actorInitialized = false;
770 private boolean followerSyncStatus = false;
772 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
773 private String role ;
774 private String leaderId;
775 private short leaderVersion;
777 private final DatastoreContext datastoreContext;
778 private final ShardPropsCreator shardPropsCreator;
780 private ShardInformation(String shardName, ShardIdentifier shardId,
781 Map<String, String> peerAddresses, DatastoreContext datastoreContext,
782 ShardPropsCreator shardPropsCreator) {
783 this.shardName = shardName;
784 this.shardId = shardId;
785 this.peerAddresses = peerAddresses;
786 this.datastoreContext = datastoreContext;
787 this.shardPropsCreator = shardPropsCreator;
790 Props newProps(SchemaContext schemaContext) {
791 return shardPropsCreator.newProps(shardId, peerAddresses, datastoreContext, schemaContext);
794 String getShardName() {
802 ActorPath getActorPath() {
806 void setActor(ActorRef actor) {
808 this.actorPath = actor.path();
811 ShardIdentifier getShardId() {
815 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
816 this.localShardDataTree = localShardDataTree;
819 Optional<DataTree> getLocalShardDataTree() {
820 return localShardDataTree;
823 Map<String, String> getPeerAddresses() {
824 return peerAddresses;
827 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
828 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
830 if(peerAddresses.containsKey(peerId)){
831 peerAddresses.put(peerId, peerAddress);
834 if(LOG.isDebugEnabled()) {
835 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
836 peerId, peerAddress, actor.path());
839 actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
842 notifyOnShardInitializedCallbacks();
846 void peerDown(String memberName, String peerId, ActorRef sender) {
847 if(peerAddresses.containsKey(peerId) && actor != null) {
848 actor.tell(new PeerDown(memberName, peerId), sender);
852 void peerUp(String memberName, String peerId, ActorRef sender) {
853 if(peerAddresses.containsKey(peerId) && actor != null) {
854 actor.tell(new PeerUp(memberName, peerId), sender);
858 boolean isShardReady() {
859 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
862 boolean isShardReadyWithLeaderId() {
863 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
864 (isLeader() || peerAddresses.get(leaderId) != null);
867 boolean isShardInitialized() {
868 return getActor() != null && actorInitialized;
872 return Objects.equal(leaderId, shardId.toString());
875 String getSerializedLeaderActor() {
877 return Serialization.serializedActorPath(getActor());
879 return peerAddresses.get(leaderId);
883 void setActorInitialized() {
884 LOG.debug("Shard {} is initialized", shardId);
886 this.actorInitialized = true;
888 notifyOnShardInitializedCallbacks();
891 private void notifyOnShardInitializedCallbacks() {
892 if(onShardInitializedSet.isEmpty()) {
896 boolean ready = isShardReadyWithLeaderId();
898 if(LOG.isDebugEnabled()) {
899 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
900 ready ? "ready" : "initialized", onShardInitializedSet.size());
903 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
904 while(iter.hasNext()) {
905 OnShardInitialized onShardInitialized = iter.next();
906 if(!(onShardInitialized instanceof OnShardReady) || ready) {
908 onShardInitialized.getTimeoutSchedule().cancel();
909 onShardInitialized.getReplyRunnable().run();
914 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
915 onShardInitializedSet.add(onShardInitialized);
918 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
919 onShardInitializedSet.remove(onShardInitialized);
922 void setRole(String newRole) {
925 notifyOnShardInitializedCallbacks();
928 void setFollowerSyncStatus(boolean syncStatus){
929 this.followerSyncStatus = syncStatus;
933 if(RaftState.Follower.name().equals(this.role)){
934 return followerSyncStatus;
935 } else if(RaftState.Leader.name().equals(this.role)){
942 boolean setLeaderId(String leaderId) {
943 boolean changed = !Objects.equal(this.leaderId, leaderId);
944 this.leaderId = leaderId;
945 if(leaderId != null) {
946 this.leaderAvailable = true;
948 notifyOnShardInitializedCallbacks();
953 String getLeaderId() {
957 void setLeaderAvailable(boolean leaderAvailable) {
958 this.leaderAvailable = leaderAvailable;
961 short getLeaderVersion() {
962 return leaderVersion;
965 void setLeaderVersion(short leaderVersion) {
966 this.leaderVersion = leaderVersion;
970 private static class ShardManagerCreator implements Creator<ShardManager> {
971 private static final long serialVersionUID = 1L;
973 final ClusterWrapper cluster;
974 final Configuration configuration;
975 final DatastoreContext datastoreContext;
976 private final CountDownLatch waitTillReadyCountdownLatch;
977 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
979 ShardManagerCreator(ClusterWrapper cluster, Configuration configuration, DatastoreContext datastoreContext,
980 CountDownLatch waitTillReadyCountdownLatch, PrimaryShardInfoFutureCache primaryShardInfoCache) {
981 this.cluster = cluster;
982 this.configuration = configuration;
983 this.datastoreContext = datastoreContext;
984 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
985 this.primaryShardInfoCache = primaryShardInfoCache;
989 public ShardManager create() throws Exception {
990 return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch,
991 primaryShardInfoCache);
995 private static class OnShardInitialized {
996 private final Runnable replyRunnable;
997 private Cancellable timeoutSchedule;
999 OnShardInitialized(Runnable replyRunnable) {
1000 this.replyRunnable = replyRunnable;
1003 Runnable getReplyRunnable() {
1004 return replyRunnable;
1007 Cancellable getTimeoutSchedule() {
1008 return timeoutSchedule;
1011 void setTimeoutSchedule(Cancellable timeoutSchedule) {
1012 this.timeoutSchedule = timeoutSchedule;
1016 private static class OnShardReady extends OnShardInitialized {
1017 OnShardReady(Runnable replyRunnable) {
1018 super(replyRunnable);
1022 private static class ShardNotInitializedTimeout {
1023 private final ActorRef sender;
1024 private final ShardInformation shardInfo;
1025 private final OnShardInitialized onShardInitialized;
1027 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1028 this.sender = sender;
1029 this.shardInfo = shardInfo;
1030 this.onShardInitialized = onShardInitialized;
1033 ActorRef getSender() {
1037 ShardInformation getShardInfo() {
1041 OnShardInitialized getOnShardInitialized() {
1042 return onShardInitialized;
1047 * We no longer persist SchemaContextModules but keep this class around for now for backwards
1048 * compatibility so we don't get de-serialization failures on upgrade from Helium.
1051 static class SchemaContextModules implements Serializable {
1052 private static final long serialVersionUID = -8884620101025936590L;
1054 private final Set<String> modules;
1056 SchemaContextModules(Set<String> modules){
1057 this.modules = modules;
1060 public Set<String> getModules() {