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.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 shard name and it's corresponding information
93 // Shard names look like inventory, topology etc and are as specified in
95 private final Map<String, ShardInformation> localShards = new HashMap<>();
97 // The type of a ShardManager reflects the type of the datastore itself
98 // A data store could be of type config/operational
99 private final String type;
101 private final ClusterWrapper cluster;
103 private final Configuration configuration;
105 private final String shardDispatcherPath;
107 private ShardManagerInfo mBean;
109 private DatastoreContext datastoreContext;
111 private final CountDownLatch waitTillReadyCountdownLatch;
113 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
115 private final ShardPeerAddressResolver peerAddressResolver;
117 private SchemaContext schemaContext;
121 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
122 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
123 PrimaryShardInfoFutureCache primaryShardInfoCache) {
125 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
126 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
127 this.datastoreContext = datastoreContext;
128 this.type = datastoreContext.getDataStoreType();
129 this.shardDispatcherPath =
130 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
131 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
132 this.primaryShardInfoCache = primaryShardInfoCache;
134 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
135 this.datastoreContext = DatastoreContext.newBuilderFrom(datastoreContext).shardPeerAddressResolver(
136 peerAddressResolver).build();
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.MemberExited){
180 memberExited((ClusterEvent.MemberExited) message);
181 } else if(message instanceof ClusterEvent.MemberRemoved) {
182 memberRemoved((ClusterEvent.MemberRemoved) message);
183 } else if(message instanceof ClusterEvent.UnreachableMember) {
184 memberUnreachable((ClusterEvent.UnreachableMember)message);
185 } else if(message instanceof ClusterEvent.ReachableMember) {
186 memberReachable((ClusterEvent.ReachableMember) message);
187 } else if(message instanceof DatastoreContext) {
188 onDatastoreContext((DatastoreContext)message);
189 } else if(message instanceof RoleChangeNotification) {
190 onRoleChangeNotification((RoleChangeNotification) message);
191 } else if(message instanceof FollowerInitialSyncUpStatus){
192 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
193 } else if(message instanceof ShardNotInitializedTimeout) {
194 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
195 } else if(message instanceof ShardLeaderStateChanged) {
196 onLeaderStateChanged((ShardLeaderStateChanged) message);
197 } else if(message instanceof SwitchShardBehavior){
198 onSwitchShardBehavior((SwitchShardBehavior) message);
199 } else if(message instanceof CreateShard) {
200 onCreateShard((CreateShard)message);
202 unknownMessage(message);
207 private void onCreateShard(CreateShard createShard) {
210 ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
211 if(localShards.containsKey(moduleShardConfig.getShardName())) {
212 throw new IllegalStateException(String.format("Shard with name %s already exists",
213 moduleShardConfig.getShardName()));
216 configuration.addModuleShardConfiguration(moduleShardConfig);
218 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), moduleShardConfig.getShardName());
219 Map<String, String> peerAddresses = getPeerAddresses(moduleShardConfig.getShardName()/*,
220 moduleShardConfig.getShardMemberNames()*/);
222 LOG.debug("onCreateShard: shardId: {}, memberNames: {}. peerAddresses: {}", shardId,
223 moduleShardConfig.getShardMemberNames(), peerAddresses);
225 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
226 if(shardDatastoreContext == null) {
227 shardDatastoreContext = datastoreContext;
229 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
230 peerAddressResolver).build();
233 ShardInformation info = new ShardInformation(moduleShardConfig.getShardName(), shardId, peerAddresses,
234 shardDatastoreContext, createShard.getShardPropsCreator(), peerAddressResolver);
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 peerAddressResolver.removePeerAddress(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 peerAddressResolver.removePeerAddress(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 addPeerAddress(memberName, message.member().address());
508 private void addPeerAddress(String memberName, Address address) {
509 peerAddressResolver.addPeerAddress(memberName, address);
511 for(ShardInformation info : localShards.values()){
512 String shardName = info.getShardName();
513 String peerId = getShardIdentifier(memberName, shardName).toString();
514 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
516 info.peerUp(memberName, peerId, getSelf());
520 private void memberReachable(ClusterEvent.ReachableMember message) {
521 String memberName = message.member().roles().head();
522 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
524 addPeerAddress(memberName, message.member().address());
526 markMemberAvailable(memberName);
529 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
530 String memberName = message.member().roles().head();
531 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
533 markMemberUnavailable(memberName);
536 private void markMemberUnavailable(final String memberName) {
537 for(ShardInformation info : localShards.values()){
538 String leaderId = info.getLeaderId();
539 if(leaderId != null && leaderId.contains(memberName)) {
540 LOG.debug("Marking Leader {} as unavailable.", leaderId);
541 info.setLeaderAvailable(false);
543 primaryShardInfoCache.remove(info.getShardName());
546 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
550 private void markMemberAvailable(final String memberName) {
551 for(ShardInformation info : localShards.values()){
552 String leaderId = info.getLeaderId();
553 if(leaderId != null && leaderId.contains(memberName)) {
554 LOG.debug("Marking Leader {} as available.", leaderId);
555 info.setLeaderAvailable(true);
558 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
562 private void onDatastoreContext(DatastoreContext context) {
563 datastoreContext = DatastoreContext.newBuilderFrom(context).shardPeerAddressResolver(
564 peerAddressResolver).build();
565 for (ShardInformation info : localShards.values()) {
566 if (info.getActor() != null) {
567 info.getActor().tell(datastoreContext, getSelf());
572 private void onSwitchShardBehavior(SwitchShardBehavior message) {
573 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
575 ShardInformation shardInformation = localShards.get(identifier.getShardName());
577 if(shardInformation != null && shardInformation.getActor() != null) {
578 shardInformation.getActor().tell(
579 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
581 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
582 message.getShardName(), message.getNewState());
587 * Notifies all the local shards of a change in the schema context
591 private void updateSchemaContext(final Object message) {
592 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
594 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
596 for (ShardInformation info : localShards.values()) {
597 if (info.getActor() == null) {
598 LOG.debug("Creating Shard {}", info.getShardId());
599 info.setActor(newShardActor(schemaContext, info));
601 info.getActor().tell(message, getSelf());
607 protected ClusterWrapper getCluster() {
612 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
613 return getContext().actorOf(info.newProps(schemaContext)
614 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
617 private void findPrimary(FindPrimary message) {
618 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
620 final String shardName = message.getShardName();
621 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
623 // First see if the there is a local replica for the shard
624 final ShardInformation info = localShards.get(shardName);
626 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
628 public Object get() {
629 String primaryPath = info.getSerializedLeaderActor();
630 Object found = canReturnLocalShardState && info.isLeader() ?
631 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
632 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
634 if(LOG.isDebugEnabled()) {
635 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
645 for(String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
646 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
649 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
650 message.isWaitUntilReady()), getContext());
654 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
656 getSender().tell(new PrimaryNotFoundException(
657 String.format("No primary shard found for %s.", shardName)), getSelf());
661 * Construct the name of the shard actor given the name of the member on
662 * which the shard resides and the name of the shard
668 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
669 return peerAddressResolver.getShardIdentifier(memberName, shardName);
673 * Create shards that are local to the member on which the ShardManager
677 private void createLocalShards() {
678 String memberName = this.cluster.getCurrentMemberName();
679 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
681 ShardPropsCreator shardPropsCreator = new DefaultShardPropsCreator();
682 List<String> localShardActorNames = new ArrayList<>();
683 for(String shardName : memberShardNames){
684 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
685 Map<String, String> peerAddresses = getPeerAddresses(shardName);
686 localShardActorNames.add(shardId.toString());
687 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses, datastoreContext,
688 shardPropsCreator, peerAddressResolver));
691 mBean = ShardManagerInfo.createShardManagerMBean(memberName, "shard-manager-" + this.type,
692 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
694 mBean.setShardManager(this);
698 * Given the name of the shard find the addresses of all it's peers
702 private Map<String, String> getPeerAddresses(String shardName) {
703 Collection<String> members = configuration.getMembersFromShardName(shardName);
704 Map<String, String> peerAddresses = new HashMap<>();
706 String currentMemberName = this.cluster.getCurrentMemberName();
708 for(String memberName : members) {
709 if(!currentMemberName.equals(memberName)) {
710 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
711 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
712 peerAddresses.put(shardId.toString(), address);
715 return peerAddresses;
719 public SupervisorStrategy supervisorStrategy() {
721 return new OneForOneStrategy(10, Duration.create("1 minute"),
722 new Function<Throwable, SupervisorStrategy.Directive>() {
724 public SupervisorStrategy.Directive apply(Throwable t) {
725 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
726 return SupervisorStrategy.resume();
734 public String persistenceId() {
735 return "shard-manager-" + type;
739 ShardManagerInfoMBean getMBean(){
744 protected static class ShardInformation {
745 private final ShardIdentifier shardId;
746 private final String shardName;
747 private ActorRef actor;
748 private ActorPath actorPath;
749 private final Map<String, String> initialPeerAddresses;
750 private Optional<DataTree> localShardDataTree;
751 private boolean leaderAvailable = false;
753 // flag that determines if the actor is ready for business
754 private boolean actorInitialized = false;
756 private boolean followerSyncStatus = false;
758 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
759 private String role ;
760 private String leaderId;
761 private short leaderVersion;
763 private final DatastoreContext datastoreContext;
764 private final ShardPropsCreator shardPropsCreator;
765 private final ShardPeerAddressResolver addressResolver;
767 private ShardInformation(String shardName, ShardIdentifier shardId,
768 Map<String, String> initialPeerAddresses, DatastoreContext datastoreContext,
769 ShardPropsCreator shardPropsCreator, ShardPeerAddressResolver addressResolver) {
770 this.shardName = shardName;
771 this.shardId = shardId;
772 this.initialPeerAddresses = initialPeerAddresses;
773 this.datastoreContext = datastoreContext;
774 this.shardPropsCreator = shardPropsCreator;
775 this.addressResolver = addressResolver;
778 Props newProps(SchemaContext schemaContext) {
779 return shardPropsCreator.newProps(shardId, initialPeerAddresses, datastoreContext, schemaContext);
782 String getShardName() {
790 ActorPath getActorPath() {
794 void setActor(ActorRef actor) {
796 this.actorPath = actor.path();
799 ShardIdentifier getShardId() {
803 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
804 this.localShardDataTree = localShardDataTree;
807 Optional<DataTree> getLocalShardDataTree() {
808 return localShardDataTree;
811 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
812 LOG.info("updatePeerAddress for peer {} with address {}", peerId, peerAddress);
815 if(LOG.isDebugEnabled()) {
816 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
817 peerId, peerAddress, actor.path());
820 actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
823 notifyOnShardInitializedCallbacks();
826 void peerDown(String memberName, String peerId, ActorRef sender) {
828 actor.tell(new PeerDown(memberName, peerId), sender);
832 void peerUp(String memberName, String peerId, ActorRef sender) {
834 actor.tell(new PeerUp(memberName, peerId), sender);
838 boolean isShardReady() {
839 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
842 boolean isShardReadyWithLeaderId() {
843 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
844 (isLeader() || addressResolver.resolve(leaderId) != null);
847 boolean isShardInitialized() {
848 return getActor() != null && actorInitialized;
852 return Objects.equal(leaderId, shardId.toString());
855 String getSerializedLeaderActor() {
857 return Serialization.serializedActorPath(getActor());
859 return addressResolver.resolve(leaderId);
863 void setActorInitialized() {
864 LOG.debug("Shard {} is initialized", shardId);
866 this.actorInitialized = true;
868 notifyOnShardInitializedCallbacks();
871 private void notifyOnShardInitializedCallbacks() {
872 if(onShardInitializedSet.isEmpty()) {
876 boolean ready = isShardReadyWithLeaderId();
878 if(LOG.isDebugEnabled()) {
879 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
880 ready ? "ready" : "initialized", onShardInitializedSet.size());
883 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
884 while(iter.hasNext()) {
885 OnShardInitialized onShardInitialized = iter.next();
886 if(!(onShardInitialized instanceof OnShardReady) || ready) {
888 onShardInitialized.getTimeoutSchedule().cancel();
889 onShardInitialized.getReplyRunnable().run();
894 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
895 onShardInitializedSet.add(onShardInitialized);
898 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
899 onShardInitializedSet.remove(onShardInitialized);
902 void setRole(String newRole) {
905 notifyOnShardInitializedCallbacks();
908 void setFollowerSyncStatus(boolean syncStatus){
909 this.followerSyncStatus = syncStatus;
913 if(RaftState.Follower.name().equals(this.role)){
914 return followerSyncStatus;
915 } else if(RaftState.Leader.name().equals(this.role)){
922 boolean setLeaderId(String leaderId) {
923 boolean changed = !Objects.equal(this.leaderId, leaderId);
924 this.leaderId = leaderId;
925 if(leaderId != null) {
926 this.leaderAvailable = true;
928 notifyOnShardInitializedCallbacks();
933 String getLeaderId() {
937 void setLeaderAvailable(boolean leaderAvailable) {
938 this.leaderAvailable = leaderAvailable;
941 short getLeaderVersion() {
942 return leaderVersion;
945 void setLeaderVersion(short leaderVersion) {
946 this.leaderVersion = leaderVersion;
950 private static class ShardManagerCreator implements Creator<ShardManager> {
951 private static final long serialVersionUID = 1L;
953 final ClusterWrapper cluster;
954 final Configuration configuration;
955 final DatastoreContext datastoreContext;
956 private final CountDownLatch waitTillReadyCountdownLatch;
957 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
959 ShardManagerCreator(ClusterWrapper cluster, Configuration configuration, DatastoreContext datastoreContext,
960 CountDownLatch waitTillReadyCountdownLatch, PrimaryShardInfoFutureCache primaryShardInfoCache) {
961 this.cluster = cluster;
962 this.configuration = configuration;
963 this.datastoreContext = datastoreContext;
964 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
965 this.primaryShardInfoCache = primaryShardInfoCache;
969 public ShardManager create() throws Exception {
970 return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch,
971 primaryShardInfoCache);
975 private static class OnShardInitialized {
976 private final Runnable replyRunnable;
977 private Cancellable timeoutSchedule;
979 OnShardInitialized(Runnable replyRunnable) {
980 this.replyRunnable = replyRunnable;
983 Runnable getReplyRunnable() {
984 return replyRunnable;
987 Cancellable getTimeoutSchedule() {
988 return timeoutSchedule;
991 void setTimeoutSchedule(Cancellable timeoutSchedule) {
992 this.timeoutSchedule = timeoutSchedule;
996 private static class OnShardReady extends OnShardInitialized {
997 OnShardReady(Runnable replyRunnable) {
998 super(replyRunnable);
1002 private static class ShardNotInitializedTimeout {
1003 private final ActorRef sender;
1004 private final ShardInformation shardInfo;
1005 private final OnShardInitialized onShardInitialized;
1007 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1008 this.sender = sender;
1009 this.shardInfo = shardInfo;
1010 this.onShardInitialized = onShardInitialized;
1013 ActorRef getSender() {
1017 ShardInformation getShardInfo() {
1021 OnShardInitialized getOnShardInitialized() {
1022 return onShardInitialized;
1027 * We no longer persist SchemaContextModules but keep this class around for now for backwards
1028 * compatibility so we don't get de-serialization failures on upgrade from Helium.
1031 static class SchemaContextModules implements Serializable {
1032 private static final long serialVersionUID = -8884620101025936590L;
1034 private final Set<String> modules;
1036 SchemaContextModules(Set<String> modules){
1037 this.modules = modules;
1040 public Set<String> getModules() {