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.japi.Procedure;
22 import akka.persistence.RecoveryCompleted;
23 import akka.persistence.RecoveryFailure;
24 import akka.serialization.Serialization;
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.common.base.Objects;
27 import com.google.common.base.Optional;
28 import com.google.common.base.Preconditions;
29 import com.google.common.base.Strings;
30 import com.google.common.base.Supplier;
31 import com.google.common.collect.ImmutableSet;
32 import com.google.common.collect.Sets;
33 import java.io.Serializable;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.List;
43 import java.util.concurrent.CountDownLatch;
44 import org.opendaylight.controller.cluster.DataPersistenceProvider;
45 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
46 import org.opendaylight.controller.cluster.PersistentDataProvider;
47 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
48 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
49 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
50 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
51 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
52 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
53 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
54 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
55 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
56 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
57 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
58 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
59 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
60 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
61 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
62 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
63 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
64 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
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.yangtools.yang.data.api.schema.tree.DataTree;
73 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
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;
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 Collection<String> knownModules = Collections.emptySet();
120 private final DataPersistenceProvider dataPersistenceProvider;
122 private final CountDownLatch waitTillReadyCountdownLatch;
124 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
128 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
129 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch,
130 PrimaryShardInfoFutureCache primaryShardInfoCache) {
132 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
133 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
134 this.datastoreContext = datastoreContext;
135 this.dataPersistenceProvider = createDataPersistenceProvider(datastoreContext.isPersistent());
136 this.type = datastoreContext.getDataStoreType();
137 this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
138 this.shardDispatcherPath =
139 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
140 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
141 this.primaryShardInfoCache = primaryShardInfoCache;
143 // Subscribe this actor to cluster member events
144 cluster.subscribeToMemberEvents(getSelf());
149 protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) {
150 return (persistent) ? new PersistentDataProvider(this) : new NonPersistentDataProvider();
153 public static Props props(
154 final ClusterWrapper cluster,
155 final Configuration configuration,
156 final DatastoreContext datastoreContext,
157 final CountDownLatch waitTillReadyCountdownLatch,
158 final PrimaryShardInfoFutureCache primaryShardInfoCache) {
160 Preconditions.checkNotNull(cluster, "cluster should not be null");
161 Preconditions.checkNotNull(configuration, "configuration should not be null");
162 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
163 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
165 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext,
166 waitTillReadyCountdownLatch, primaryShardInfoCache));
170 public void postStop() {
171 LOG.info("Stopping ShardManager");
173 mBean.unregisterMBean();
177 public void handleCommand(Object message) throws Exception {
178 if (message instanceof FindPrimary) {
179 findPrimary((FindPrimary)message);
180 } else if(message instanceof FindLocalShard){
181 findLocalShard((FindLocalShard) message);
182 } else if (message instanceof UpdateSchemaContext) {
183 updateSchemaContext(message);
184 } else if(message instanceof ActorInitialized) {
185 onActorInitialized(message);
186 } else if (message instanceof ClusterEvent.MemberUp){
187 memberUp((ClusterEvent.MemberUp) message);
188 } else if(message instanceof ClusterEvent.MemberRemoved) {
189 memberRemoved((ClusterEvent.MemberRemoved) message);
190 } else if(message instanceof ClusterEvent.UnreachableMember) {
191 memberUnreachable((ClusterEvent.UnreachableMember)message);
192 } else if(message instanceof ClusterEvent.ReachableMember) {
193 memberReachable((ClusterEvent.ReachableMember) message);
194 } else if(message instanceof DatastoreContext) {
195 onDatastoreContext((DatastoreContext)message);
196 } else if(message instanceof RoleChangeNotification) {
197 onRoleChangeNotification((RoleChangeNotification) message);
198 } else if(message instanceof FollowerInitialSyncUpStatus){
199 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
200 } else if(message instanceof ShardNotInitializedTimeout) {
201 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
202 } else if(message instanceof ShardLeaderStateChanged) {
203 onLeaderStateChanged((ShardLeaderStateChanged)message);
205 unknownMessage(message);
210 private void checkReady(){
211 if (isReadyWithLeaderId()) {
212 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
213 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
215 waitTillReadyCountdownLatch.countDown();
219 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
220 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
222 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
223 if(shardInformation != null) {
224 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
225 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
226 primaryShardInfoCache.remove(shardInformation.getShardName());
231 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
235 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
236 ShardInformation shardInfo = message.getShardInfo();
238 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
239 shardInfo.getShardName());
241 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
243 if(!shardInfo.isShardInitialized()) {
244 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
245 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
247 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
248 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
252 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
253 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
254 status.getName(), status.isInitialSyncDone());
256 ShardInformation shardInformation = findShardInformation(status.getName());
258 if(shardInformation != null) {
259 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
261 mBean.setSyncStatus(isInSync());
266 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
267 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
268 roleChanged.getOldRole(), roleChanged.getNewRole());
270 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
271 if(shardInformation != null) {
272 shardInformation.setRole(roleChanged.getNewRole());
274 mBean.setSyncStatus(isInSync());
279 private ShardInformation findShardInformation(String memberId) {
280 for(ShardInformation info : localShards.values()){
281 if(info.getShardId().toString().equals(memberId)){
289 private boolean isReadyWithLeaderId() {
290 boolean isReady = true;
291 for (ShardInformation info : localShards.values()) {
292 if(!info.isShardReadyWithLeaderId()){
300 private boolean isInSync(){
301 for (ShardInformation info : localShards.values()) {
302 if(!info.isInSync()){
309 private void onActorInitialized(Object message) {
310 final ActorRef sender = getSender();
312 if (sender == null) {
313 return; //why is a non-actor sending this message? Just ignore.
316 String actorName = sender.path().name();
317 //find shard name from actor name; actor name is stringified shardId
318 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
320 if (shardId.getShardName() == null) {
324 markShardAsInitialized(shardId.getShardName());
327 private void markShardAsInitialized(String shardName) {
328 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
330 ShardInformation shardInformation = localShards.get(shardName);
331 if (shardInformation != null) {
332 shardInformation.setActorInitialized();
334 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
339 protected void handleRecover(Object message) throws Exception {
340 if(dataPersistenceProvider.isRecoveryApplicable()) {
341 if (message instanceof SchemaContextModules) {
342 SchemaContextModules msg = (SchemaContextModules) message;
343 knownModules = ImmutableSet.copyOf(msg.getModules());
344 } else if (message instanceof RecoveryFailure) {
345 RecoveryFailure failure = (RecoveryFailure) message;
346 LOG.error("Recovery failed", failure.cause());
347 } else if (message instanceof RecoveryCompleted) {
348 LOG.info("Recovery complete : {}", persistenceId());
350 // Delete all the messages from the akka journal except the last one
351 deleteMessages(lastSequenceNr() - 1);
354 if (message instanceof RecoveryCompleted) {
355 LOG.info("Recovery complete : {}", persistenceId());
357 // Delete all the messages from the akka journal
358 deleteMessages(lastSequenceNr());
363 private void findLocalShard(FindLocalShard message) {
364 final ShardInformation shardInformation = localShards.get(message.getShardName());
366 if(shardInformation == null){
367 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
371 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
373 public Object get() {
374 return new LocalShardFound(shardInformation.getActor());
379 private void sendResponse(ShardInformation shardInformation, boolean doWait,
380 boolean wantShardReady, final Supplier<Object> messageSupplier) {
381 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
383 final ActorRef sender = getSender();
384 final ActorRef self = self();
386 Runnable replyRunnable = new Runnable() {
389 sender.tell(messageSupplier.get(), self);
393 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
394 new OnShardInitialized(replyRunnable);
396 shardInformation.addOnShardInitialized(onShardInitialized);
398 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
400 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
401 datastoreContext.getShardInitializationTimeout().duration(), getSelf(),
402 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
403 getContext().dispatcher(), getSelf());
405 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
407 } else if (!shardInformation.isShardInitialized()) {
408 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
409 shardInformation.getShardName());
410 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
412 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
413 shardInformation.getShardName());
414 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
420 getSender().tell(messageSupplier.get(), getSelf());
423 private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
424 return new NoShardLeaderException(String.format(
425 "Could not find a leader for shard %s. This typically happens when the system is coming up or " +
426 "recovering and a leader is being elected. Try again later.", shardId));
429 private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
430 return new NotInitializedException(String.format(
431 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
434 private void memberRemoved(ClusterEvent.MemberRemoved message) {
435 String memberName = message.member().roles().head();
437 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
438 message.member().address());
440 memberNameToAddress.remove(message.member().roles().head());
443 private void memberUp(ClusterEvent.MemberUp message) {
444 String memberName = message.member().roles().head();
446 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
447 message.member().address());
449 memberNameToAddress.put(memberName, message.member().address());
451 for(ShardInformation info : localShards.values()){
452 String shardName = info.getShardName();
453 info.updatePeerAddress(getShardIdentifier(memberName, shardName).toString(),
454 getShardActorPath(shardName, memberName), getSelf());
460 private void memberReachable(ClusterEvent.ReachableMember message) {
461 String memberName = message.member().roles().head();
462 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
464 markMemberAvailable(memberName);
467 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
468 String memberName = message.member().roles().head();
469 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
471 markMemberUnavailable(memberName);
474 private void markMemberUnavailable(final String memberName) {
475 for(ShardInformation info : localShards.values()){
476 String leaderId = info.getLeaderId();
477 if(leaderId != null && leaderId.contains(memberName)) {
478 LOG.debug("Marking Leader {} as unavailable.", leaderId);
479 info.setLeaderAvailable(false);
484 private void markMemberAvailable(final String memberName) {
485 for(ShardInformation info : localShards.values()){
486 String leaderId = info.getLeaderId();
487 if(leaderId != null && leaderId.contains(memberName)) {
488 LOG.debug("Marking Leader {} as available.", leaderId);
489 info.setLeaderAvailable(true);
494 private void onDatastoreContext(DatastoreContext context) {
495 datastoreContext = context;
496 for (ShardInformation info : localShards.values()) {
497 if (info.getActor() != null) {
498 info.getActor().tell(datastoreContext, getSelf());
504 * Notifies all the local shards of a change in the schema context
508 private void updateSchemaContext(final Object message) {
509 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
511 Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
512 Set<String> newModules = new HashSet<>(128);
514 for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
515 String s = moduleIdentifier.getNamespace().toString();
519 if(newModules.containsAll(knownModules)) {
521 LOG.debug("New SchemaContext has a super set of current knownModules - persisting info");
523 knownModules = ImmutableSet.copyOf(newModules);
525 dataPersistenceProvider.persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
528 public void apply(SchemaContextModules param) throws Exception {
529 LOG.debug("Sending new SchemaContext to Shards");
530 for (ShardInformation info : localShards.values()) {
531 if (info.getActor() == null) {
532 info.setActor(newShardActor(schemaContext, info));
534 info.getActor().tell(message, getSelf());
541 LOG.debug("Rejecting schema context update - not a super set of previously known modules:\nUPDATE: {}\nKNOWN: {}",
542 newModules, knownModules);
548 protected ClusterWrapper getCluster() {
553 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
554 return getContext().actorOf(Shard.props(info.getShardId(),
555 info.getPeerAddresses(), datastoreContext, schemaContext)
556 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
559 private void findPrimary(FindPrimary message) {
560 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
562 final String shardName = message.getShardName();
563 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
565 // First see if the there is a local replica for the shard
566 final ShardInformation info = localShards.get(shardName);
568 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
570 public Object get() {
571 String primaryPath = info.getSerializedLeaderActor();
572 Object found = canReturnLocalShardState && info.isLeader() ?
573 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
574 new RemotePrimaryShardFound(primaryPath);
576 if(LOG.isDebugEnabled()) {
577 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
587 for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
588 if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
589 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
591 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
594 getContext().actorSelection(path).forward(new RemoteFindPrimary(shardName,
595 message.isWaitUntilReady()), getContext());
600 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
602 getSender().tell(new PrimaryNotFoundException(
603 String.format("No primary shard found for %s.", shardName)), getSelf());
606 private StringBuilder getShardManagerActorPathBuilder(Address address) {
607 StringBuilder builder = new StringBuilder();
608 builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
612 private String getShardActorPath(String shardName, String memberName) {
613 Address address = memberNameToAddress.get(memberName);
614 if(address != null) {
615 StringBuilder builder = getShardManagerActorPathBuilder(address);
617 .append(getShardIdentifier(memberName, shardName));
618 return builder.toString();
624 * Construct the name of the shard actor given the name of the member on
625 * which the shard resides and the name of the shard
631 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
632 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
636 * Create shards that are local to the member on which the ShardManager
640 private void createLocalShards() {
641 String memberName = this.cluster.getCurrentMemberName();
642 List<String> memberShardNames =
643 this.configuration.getMemberShardNames(memberName);
645 List<String> localShardActorNames = new ArrayList<>();
646 for(String shardName : memberShardNames){
647 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
648 Map<String, String> peerAddresses = getPeerAddresses(shardName);
649 localShardActorNames.add(shardId.toString());
650 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
653 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
654 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
658 * Given the name of the shard find the addresses of all it's peers
663 private Map<String, String> getPeerAddresses(String shardName){
665 Map<String, String> peerAddresses = new HashMap<>();
667 List<String> members = this.configuration.getMembersFromShardName(shardName);
669 String currentMemberName = this.cluster.getCurrentMemberName();
671 for(String memberName : members){
672 if(!currentMemberName.equals(memberName)){
673 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
674 String path = getShardActorPath(shardName, currentMemberName);
675 peerAddresses.put(shardId.toString(), path);
678 return peerAddresses;
682 public SupervisorStrategy supervisorStrategy() {
684 return new OneForOneStrategy(10, Duration.create("1 minute"),
685 new Function<Throwable, SupervisorStrategy.Directive>() {
687 public SupervisorStrategy.Directive apply(Throwable t) {
688 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
689 return SupervisorStrategy.resume();
697 public String persistenceId() {
698 return "shard-manager-" + type;
702 Collection<String> getKnownModules() {
707 DataPersistenceProvider getDataPersistenceProvider() {
708 return dataPersistenceProvider;
712 ShardManagerInfoMBean getMBean(){
717 protected static class ShardInformation {
718 private final ShardIdentifier shardId;
719 private final String shardName;
720 private ActorRef actor;
721 private ActorPath actorPath;
722 private final Map<String, String> peerAddresses;
723 private Optional<DataTree> localShardDataTree;
724 private boolean leaderAvailable = false;
726 // flag that determines if the actor is ready for business
727 private boolean actorInitialized = false;
729 private boolean followerSyncStatus = false;
731 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
732 private String role ;
733 private String leaderId;
735 private ShardInformation(String shardName, ShardIdentifier shardId,
736 Map<String, String> peerAddresses) {
737 this.shardName = shardName;
738 this.shardId = shardId;
739 this.peerAddresses = peerAddresses;
742 String getShardName() {
750 ActorPath getActorPath() {
754 void setActor(ActorRef actor) {
756 this.actorPath = actor.path();
759 ShardIdentifier getShardId() {
763 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
764 this.localShardDataTree = localShardDataTree;
767 Optional<DataTree> getLocalShardDataTree() {
768 return localShardDataTree;
771 Map<String, String> getPeerAddresses() {
772 return peerAddresses;
775 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
776 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
778 if(peerAddresses.containsKey(peerId)){
779 peerAddresses.put(peerId, peerAddress);
782 if(LOG.isDebugEnabled()) {
783 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
784 peerId, peerAddress, actor.path());
787 actor.tell(new PeerAddressResolved(peerId.toString(), peerAddress), sender);
790 notifyOnShardInitializedCallbacks();
794 boolean isShardReady() {
795 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
798 boolean isShardReadyWithLeaderId() {
799 return leaderAvailable && isShardReady() && (isLeader() || peerAddresses.get(leaderId) != null);
802 boolean isShardInitialized() {
803 return getActor() != null && actorInitialized;
807 return Objects.equal(leaderId, shardId.toString());
810 String getSerializedLeaderActor() {
812 return Serialization.serializedActorPath(getActor());
814 return peerAddresses.get(leaderId);
818 void setActorInitialized() {
819 LOG.debug("Shard {} is initialized", shardId);
821 this.actorInitialized = true;
823 notifyOnShardInitializedCallbacks();
826 private void notifyOnShardInitializedCallbacks() {
827 if(onShardInitializedSet.isEmpty()) {
831 boolean ready = isShardReadyWithLeaderId();
833 if(LOG.isDebugEnabled()) {
834 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
835 ready ? "ready" : "initialized", onShardInitializedSet.size());
838 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
839 while(iter.hasNext()) {
840 OnShardInitialized onShardInitialized = iter.next();
841 if(!(onShardInitialized instanceof OnShardReady) || ready) {
843 onShardInitialized.getTimeoutSchedule().cancel();
844 onShardInitialized.getReplyRunnable().run();
849 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
850 onShardInitializedSet.add(onShardInitialized);
853 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
854 onShardInitializedSet.remove(onShardInitialized);
857 void setRole(String newRole) {
860 notifyOnShardInitializedCallbacks();
863 void setFollowerSyncStatus(boolean syncStatus){
864 this.followerSyncStatus = syncStatus;
868 if(RaftState.Follower.name().equals(this.role)){
869 return followerSyncStatus;
870 } else if(RaftState.Leader.name().equals(this.role)){
877 boolean setLeaderId(String leaderId) {
878 boolean changed = !Objects.equal(this.leaderId, leaderId);
879 this.leaderId = leaderId;
880 if(leaderId != null) {
881 this.leaderAvailable = true;
883 notifyOnShardInitializedCallbacks();
888 public String getLeaderId() {
892 public void setLeaderAvailable(boolean leaderAvailable) {
893 this.leaderAvailable = leaderAvailable;
897 private static class ShardManagerCreator implements Creator<ShardManager> {
898 private static final long serialVersionUID = 1L;
900 final ClusterWrapper cluster;
901 final Configuration configuration;
902 final DatastoreContext datastoreContext;
903 private final CountDownLatch waitTillReadyCountdownLatch;
904 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
906 ShardManagerCreator(ClusterWrapper cluster, Configuration configuration, DatastoreContext datastoreContext,
907 CountDownLatch waitTillReadyCountdownLatch, PrimaryShardInfoFutureCache primaryShardInfoCache) {
908 this.cluster = cluster;
909 this.configuration = configuration;
910 this.datastoreContext = datastoreContext;
911 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
912 this.primaryShardInfoCache = primaryShardInfoCache;
916 public ShardManager create() throws Exception {
917 return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch,
918 primaryShardInfoCache);
922 private static class OnShardInitialized {
923 private final Runnable replyRunnable;
924 private Cancellable timeoutSchedule;
926 OnShardInitialized(Runnable replyRunnable) {
927 this.replyRunnable = replyRunnable;
930 Runnable getReplyRunnable() {
931 return replyRunnable;
934 Cancellable getTimeoutSchedule() {
935 return timeoutSchedule;
938 void setTimeoutSchedule(Cancellable timeoutSchedule) {
939 this.timeoutSchedule = timeoutSchedule;
943 private static class OnShardReady extends OnShardInitialized {
944 OnShardReady(Runnable replyRunnable) {
945 super(replyRunnable);
949 private static class ShardNotInitializedTimeout {
950 private final ActorRef sender;
951 private final ShardInformation shardInfo;
952 private final OnShardInitialized onShardInitialized;
954 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
955 this.sender = sender;
956 this.shardInfo = shardInfo;
957 this.onShardInitialized = onShardInitialized;
960 ActorRef getSender() {
964 ShardInformation getShardInfo() {
968 OnShardInitialized getOnShardInitialized() {
969 return onShardInitialized;
973 static class SchemaContextModules implements Serializable {
974 private static final long serialVersionUID = -8884620101025936590L;
976 private final Set<String> modules;
978 SchemaContextModules(Set<String> modules){
979 this.modules = modules;
982 public Set<String> getModules() {