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.config.ModuleShardConfiguration;
43 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
44 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
45 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
46 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
47 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
48 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
49 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
50 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
51 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateShardReply;
53 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
54 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
55 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
56 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
57 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
58 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
59 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
60 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
61 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
62 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
63 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
64 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
65 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
66 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
67 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
68 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
69 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
70 import org.opendaylight.controller.cluster.raft.RaftState;
71 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
72 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import scala.concurrent.duration.Duration;
78 import scala.concurrent.duration.FiniteDuration;
81 * The ShardManager has the following jobs,
83 * <li> Create all the local shard replicas that belong on this cluster member
84 * <li> Find the address of the local shard
85 * <li> Find the primary replica for any given shard
86 * <li> Monitor the cluster members and store their addresses
89 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
91 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
93 // Stores a mapping between a member name and the address of the member
94 // Member names look like "member-1", "member-2" etc and are as specified
96 private final Map<String, Address> memberNameToAddress = new HashMap<>();
98 // Stores a mapping between a shard name and it's corresponding information
99 // Shard names look like inventory, topology etc and are as specified in
101 private final Map<String, ShardInformation> localShards = new HashMap<>();
103 // The type of a ShardManager reflects the type of the datastore itself
104 // A data store could be of type config/operational
105 private final String type;
107 private final String shardManagerIdentifierString;
109 private final ClusterWrapper cluster;
111 private final Configuration configuration;
113 private final String shardDispatcherPath;
115 private ShardManagerInfo mBean;
117 private DatastoreContext datastoreContext;
119 private final CountDownLatch waitTillReadyCountdownLatch;
121 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
123 private SchemaContext schemaContext;
127 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
128 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
129 PrimaryShardInfoFutureCache primaryShardInfoCache) {
131 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
132 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
133 this.datastoreContext = datastoreContext;
134 this.type = datastoreContext.getDataStoreType();
135 this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
136 this.shardDispatcherPath =
137 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
138 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
139 this.primaryShardInfoCache = primaryShardInfoCache;
141 // Subscribe this actor to cluster member events
142 cluster.subscribeToMemberEvents(getSelf());
147 public static Props props(
148 final ClusterWrapper cluster,
149 final Configuration configuration,
150 final DatastoreContext datastoreContext,
151 final CountDownLatch waitTillReadyCountdownLatch,
152 final PrimaryShardInfoFutureCache primaryShardInfoCache) {
154 Preconditions.checkNotNull(cluster, "cluster should not be null");
155 Preconditions.checkNotNull(configuration, "configuration should not be null");
156 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
157 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
159 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext,
160 waitTillReadyCountdownLatch, primaryShardInfoCache));
164 public void postStop() {
165 LOG.info("Stopping ShardManager");
167 mBean.unregisterMBean();
171 public void handleCommand(Object message) throws Exception {
172 if (message instanceof FindPrimary) {
173 findPrimary((FindPrimary)message);
174 } else if(message instanceof FindLocalShard){
175 findLocalShard((FindLocalShard) message);
176 } else if (message instanceof UpdateSchemaContext) {
177 updateSchemaContext(message);
178 } else if(message instanceof ActorInitialized) {
179 onActorInitialized(message);
180 } else if (message instanceof ClusterEvent.MemberUp){
181 memberUp((ClusterEvent.MemberUp) message);
182 } else if (message instanceof ClusterEvent.MemberExited){
183 memberExited((ClusterEvent.MemberExited) message);
184 } else if(message instanceof ClusterEvent.MemberRemoved) {
185 memberRemoved((ClusterEvent.MemberRemoved) message);
186 } else if(message instanceof ClusterEvent.UnreachableMember) {
187 memberUnreachable((ClusterEvent.UnreachableMember)message);
188 } else if(message instanceof ClusterEvent.ReachableMember) {
189 memberReachable((ClusterEvent.ReachableMember) message);
190 } else if(message instanceof DatastoreContext) {
191 onDatastoreContext((DatastoreContext)message);
192 } else if(message instanceof RoleChangeNotification) {
193 onRoleChangeNotification((RoleChangeNotification) message);
194 } else if(message instanceof FollowerInitialSyncUpStatus){
195 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
196 } else if(message instanceof ShardNotInitializedTimeout) {
197 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
198 } else if(message instanceof ShardLeaderStateChanged) {
199 onLeaderStateChanged((ShardLeaderStateChanged) message);
200 } else if(message instanceof SwitchShardBehavior){
201 onSwitchShardBehavior((SwitchShardBehavior) message);
202 } else if(message instanceof CreateShard) {
203 onCreateShard((CreateShard)message);
205 unknownMessage(message);
210 private void onCreateShard(CreateShard createShard) {
213 ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
214 if(localShards.containsKey(moduleShardConfig.getShardName())) {
215 throw new IllegalStateException(String.format("Shard with name %s already exists",
216 moduleShardConfig.getShardName()));
219 configuration.addModuleShardConfiguration(moduleShardConfig);
221 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), moduleShardConfig.getShardName());
222 Map<String, String> peerAddresses = getPeerAddresses(moduleShardConfig.getShardName()/*,
223 moduleShardConfig.getShardMemberNames()*/);
225 LOG.debug("onCreateShard: shardId: {}, memberNames: {}. peerAddresses: {}", shardId,
226 moduleShardConfig.getShardMemberNames(), peerAddresses);
228 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
229 if(shardDatastoreContext == null) {
230 shardDatastoreContext = datastoreContext;
233 ShardInformation info = new ShardInformation(moduleShardConfig.getShardName(), shardId, peerAddresses,
234 shardDatastoreContext, createShard.getShardPropsCreator());
235 localShards.put(info.getShardName(), info);
237 mBean.addLocalShard(shardId.toString());
239 if(schemaContext != null) {
240 info.setActor(newShardActor(schemaContext, info));
243 reply = new CreateShardReply();
244 } catch (Exception e) {
245 LOG.error("onCreateShard failed", e);
246 reply = new akka.actor.Status.Failure(e);
249 if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
250 getSender().tell(reply, getSelf());
254 private void checkReady(){
255 if (isReadyWithLeaderId()) {
256 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
257 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
259 waitTillReadyCountdownLatch.countDown();
263 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
264 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
266 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
267 if(shardInformation != null) {
268 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
269 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
270 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
271 primaryShardInfoCache.remove(shardInformation.getShardName());
276 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
280 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
281 ShardInformation shardInfo = message.getShardInfo();
283 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
284 shardInfo.getShardName());
286 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
288 if(!shardInfo.isShardInitialized()) {
289 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
290 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
292 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
293 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
297 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
298 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
299 status.getName(), status.isInitialSyncDone());
301 ShardInformation shardInformation = findShardInformation(status.getName());
303 if(shardInformation != null) {
304 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
306 mBean.setSyncStatus(isInSync());
311 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
312 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
313 roleChanged.getOldRole(), roleChanged.getNewRole());
315 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
316 if(shardInformation != null) {
317 shardInformation.setRole(roleChanged.getNewRole());
319 mBean.setSyncStatus(isInSync());
324 private ShardInformation findShardInformation(String memberId) {
325 for(ShardInformation info : localShards.values()){
326 if(info.getShardId().toString().equals(memberId)){
334 private boolean isReadyWithLeaderId() {
335 boolean isReady = true;
336 for (ShardInformation info : localShards.values()) {
337 if(!info.isShardReadyWithLeaderId()){
345 private boolean isInSync(){
346 for (ShardInformation info : localShards.values()) {
347 if(!info.isInSync()){
354 private void onActorInitialized(Object message) {
355 final ActorRef sender = getSender();
357 if (sender == null) {
358 return; //why is a non-actor sending this message? Just ignore.
361 String actorName = sender.path().name();
362 //find shard name from actor name; actor name is stringified shardId
363 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
365 if (shardId.getShardName() == null) {
369 markShardAsInitialized(shardId.getShardName());
372 private void markShardAsInitialized(String shardName) {
373 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
375 ShardInformation shardInformation = localShards.get(shardName);
376 if (shardInformation != null) {
377 shardInformation.setActorInitialized();
379 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
384 protected void handleRecover(Object message) throws Exception {
385 if (message instanceof RecoveryCompleted) {
386 LOG.info("Recovery complete : {}", persistenceId());
388 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
389 // journal on upgrade from Helium.
390 deleteMessages(lastSequenceNr());
394 private void findLocalShard(FindLocalShard message) {
395 final ShardInformation shardInformation = localShards.get(message.getShardName());
397 if(shardInformation == null){
398 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
402 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
404 public Object get() {
405 return new LocalShardFound(shardInformation.getActor());
410 private void sendResponse(ShardInformation shardInformation, boolean doWait,
411 boolean wantShardReady, final Supplier<Object> messageSupplier) {
412 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
414 final ActorRef sender = getSender();
415 final ActorRef self = self();
417 Runnable replyRunnable = new Runnable() {
420 sender.tell(messageSupplier.get(), self);
424 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
425 new OnShardInitialized(replyRunnable);
427 shardInformation.addOnShardInitialized(onShardInitialized);
429 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
431 FiniteDuration timeout = datastoreContext.getShardInitializationTimeout().duration();
432 if(shardInformation.isShardInitialized()) {
433 // If the shard is already initialized then we'll wait enough time for the shard to
434 // elect a leader, ie 2 times the election timeout.
435 timeout = FiniteDuration.create(datastoreContext.getShardRaftConfig()
436 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
439 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
441 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
442 getContext().dispatcher(), getSelf());
444 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
446 } else if (!shardInformation.isShardInitialized()) {
447 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
448 shardInformation.getShardName());
449 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
451 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
452 shardInformation.getShardName());
453 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
459 getSender().tell(messageSupplier.get(), getSelf());
462 private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
463 return new NoShardLeaderException(null, shardId.toString());
466 private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
467 return new NotInitializedException(String.format(
468 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
471 private void memberRemoved(ClusterEvent.MemberRemoved message) {
472 String memberName = message.member().roles().head();
474 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
475 message.member().address());
477 memberNameToAddress.remove(memberName);
479 for(ShardInformation info : localShards.values()){
480 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
484 private void memberExited(ClusterEvent.MemberExited message) {
485 String memberName = message.member().roles().head();
487 LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
488 message.member().address());
490 memberNameToAddress.remove(memberName);
492 for(ShardInformation info : localShards.values()){
493 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
497 private void memberUp(ClusterEvent.MemberUp message) {
498 String memberName = message.member().roles().head();
500 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
501 message.member().address());
503 memberNameToAddress.put(memberName, message.member().address());
505 for(ShardInformation info : localShards.values()){
506 String shardName = info.getShardName();
507 String peerId = getShardIdentifier(memberName, shardName).toString();
508 info.updatePeerAddress(peerId, getShardActorPath(shardName, memberName), getSelf());
510 info.peerUp(memberName, peerId, getSelf());
516 private void memberReachable(ClusterEvent.ReachableMember message) {
517 String memberName = message.member().roles().head();
518 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
520 markMemberAvailable(memberName);
523 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
524 String memberName = message.member().roles().head();
525 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
527 markMemberUnavailable(memberName);
530 private void markMemberUnavailable(final String memberName) {
531 for(ShardInformation info : localShards.values()){
532 String leaderId = info.getLeaderId();
533 if(leaderId != null && leaderId.contains(memberName)) {
534 LOG.debug("Marking Leader {} as unavailable.", leaderId);
535 info.setLeaderAvailable(false);
537 primaryShardInfoCache.remove(info.getShardName());
540 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
544 private void markMemberAvailable(final String memberName) {
545 for(ShardInformation info : localShards.values()){
546 String leaderId = info.getLeaderId();
547 if(leaderId != null && leaderId.contains(memberName)) {
548 LOG.debug("Marking Leader {} as available.", leaderId);
549 info.setLeaderAvailable(true);
552 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
556 private void onDatastoreContext(DatastoreContext context) {
557 datastoreContext = context;
558 for (ShardInformation info : localShards.values()) {
559 if (info.getActor() != null) {
560 info.getActor().tell(datastoreContext, getSelf());
565 private void onSwitchShardBehavior(SwitchShardBehavior message) {
566 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
568 ShardInformation shardInformation = localShards.get(identifier.getShardName());
570 if(shardInformation != null && shardInformation.getActor() != null) {
571 shardInformation.getActor().tell(
572 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
574 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
575 message.getShardName(), message.getNewState());
580 * Notifies all the local shards of a change in the schema context
584 private void updateSchemaContext(final Object message) {
585 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
587 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
589 for (ShardInformation info : localShards.values()) {
590 if (info.getActor() == null) {
591 LOG.debug("Creating Shard {}", info.getShardId());
592 info.setActor(newShardActor(schemaContext, info));
594 info.getActor().tell(message, getSelf());
600 protected ClusterWrapper getCluster() {
605 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
606 return getContext().actorOf(info.newProps(schemaContext)
607 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
610 private void findPrimary(FindPrimary message) {
611 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
613 final String shardName = message.getShardName();
614 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
616 // First see if the there is a local replica for the shard
617 final ShardInformation info = localShards.get(shardName);
619 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
621 public Object get() {
622 String primaryPath = info.getSerializedLeaderActor();
623 Object found = canReturnLocalShardState && info.isLeader() ?
624 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
625 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
627 if(LOG.isDebugEnabled()) {
628 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
638 for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
639 if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
640 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
642 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
645 getContext().actorSelection(path).forward(new RemoteFindPrimary(shardName,
646 message.isWaitUntilReady()), getContext());
651 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
653 getSender().tell(new PrimaryNotFoundException(
654 String.format("No primary shard found for %s.", shardName)), getSelf());
657 private StringBuilder getShardManagerActorPathBuilder(Address address) {
658 StringBuilder builder = new StringBuilder();
659 builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
663 private String getShardActorPath(String shardName, String memberName) {
664 Address address = memberNameToAddress.get(memberName);
665 if(address != null) {
666 StringBuilder builder = getShardManagerActorPathBuilder(address);
668 .append(getShardIdentifier(memberName, shardName));
669 return builder.toString();
675 * Construct the name of the shard actor given the name of the member on
676 * which the shard resides and the name of the shard
682 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
683 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
687 * Create shards that are local to the member on which the ShardManager
691 private void createLocalShards() {
692 String memberName = this.cluster.getCurrentMemberName();
693 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
695 ShardPropsCreator shardPropsCreator = new DefaultShardPropsCreator();
696 List<String> localShardActorNames = new ArrayList<>();
697 for(String shardName : memberShardNames){
698 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
699 Map<String, String> peerAddresses = getPeerAddresses(shardName);
700 localShardActorNames.add(shardId.toString());
701 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses, datastoreContext,
705 mBean = ShardManagerInfo.createShardManagerMBean(memberName, "shard-manager-" + this.type,
706 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
708 mBean.setShardManager(this);
712 * Given the name of the shard find the addresses of all it's peers
716 private Map<String, String> getPeerAddresses(String shardName) {
717 Collection<String> members = configuration.getMembersFromShardName(shardName);
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() {