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.Preconditions;
28 import com.google.common.base.Strings;
29 import com.google.common.base.Supplier;
30 import com.google.common.collect.ImmutableSet;
31 import com.google.common.collect.Sets;
32 import java.io.Serializable;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.Iterator;
39 import java.util.List;
42 import java.util.concurrent.CountDownLatch;
43 import org.opendaylight.controller.cluster.DataPersistenceProvider;
44 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
45 import org.opendaylight.controller.cluster.PersistentDataProvider;
46 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
47 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
48 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
49 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
50 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
51 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
52 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
53 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
54 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
55 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
56 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
57 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
58 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
59 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
60 import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
61 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
62 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
63 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
64 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
65 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
66 import org.opendaylight.controller.cluster.raft.RaftState;
67 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
68 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import scala.concurrent.duration.Duration;
75 * The ShardManager has the following jobs,
77 * <li> Create all the local shard replicas that belong on this cluster member
78 * <li> Find the address of the local shard
79 * <li> Find the primary replica for any given shard
80 * <li> Monitor the cluster members and store their addresses
83 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
85 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
87 // Stores a mapping between a member name and the address of the member
88 // Member names look like "member-1", "member-2" etc and are as specified
90 private final Map<String, Address> memberNameToAddress = new HashMap<>();
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 String shardManagerIdentifierString;
103 private final ClusterWrapper cluster;
105 private final Configuration configuration;
107 private final String shardDispatcherPath;
109 private ShardManagerInfo mBean;
111 private DatastoreContext datastoreContext;
113 private Collection<String> knownModules = Collections.emptySet();
115 private final DataPersistenceProvider dataPersistenceProvider;
117 private final CountDownLatch waitTillReadyCountdownLatch;
121 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
122 DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch) {
124 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
125 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
126 this.datastoreContext = datastoreContext;
127 this.dataPersistenceProvider = createDataPersistenceProvider(datastoreContext.isPersistent());
128 this.type = datastoreContext.getDataStoreType();
129 this.shardManagerIdentifierString = ShardManagerIdentifier.builder().type(type).build().toString();
130 this.shardDispatcherPath =
131 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
132 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
134 // Subscribe this actor to cluster member events
135 cluster.subscribeToMemberEvents(getSelf());
140 protected DataPersistenceProvider createDataPersistenceProvider(boolean persistent) {
141 return (persistent) ? new PersistentDataProvider(this) : new NonPersistentDataProvider();
144 public static Props props(
145 final ClusterWrapper cluster,
146 final Configuration configuration,
147 final DatastoreContext datastoreContext,
148 final CountDownLatch waitTillReadyCountdownLatch) {
150 Preconditions.checkNotNull(cluster, "cluster should not be null");
151 Preconditions.checkNotNull(configuration, "configuration should not be null");
152 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
154 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch));
158 public void postStop() {
159 LOG.info("Stopping ShardManager");
161 mBean.unregisterMBean();
165 public void handleCommand(Object message) throws Exception {
166 if (message instanceof FindPrimary) {
167 findPrimary((FindPrimary)message);
168 } else if(message instanceof FindLocalShard){
169 findLocalShard((FindLocalShard) message);
170 } else if (message instanceof UpdateSchemaContext) {
171 updateSchemaContext(message);
172 } else if(message instanceof ActorInitialized) {
173 onActorInitialized(message);
174 } else if (message instanceof ClusterEvent.MemberUp){
175 memberUp((ClusterEvent.MemberUp) message);
176 } else if(message instanceof ClusterEvent.MemberRemoved) {
177 memberRemoved((ClusterEvent.MemberRemoved) message);
178 } else if(message instanceof ClusterEvent.UnreachableMember) {
179 ignoreMessage(message);
180 } else if(message instanceof DatastoreContext) {
181 onDatastoreContext((DatastoreContext)message);
182 } else if(message instanceof RoleChangeNotification) {
183 onRoleChangeNotification((RoleChangeNotification) message);
184 } else if(message instanceof FollowerInitialSyncUpStatus){
185 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
186 } else if(message instanceof ShardNotInitializedTimeout) {
187 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
188 } else if(message instanceof LeaderStateChanged) {
189 onLeaderStateChanged((LeaderStateChanged)message);
191 unknownMessage(message);
196 private void onLeaderStateChanged(LeaderStateChanged leaderStateChanged) {
197 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
199 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
200 if(shardInformation != null) {
201 shardInformation.setLeaderId(leaderStateChanged.getLeaderId());
202 if (isReadyWithLeaderId()) {
203 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
204 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
206 waitTillReadyCountdownLatch.countDown();
210 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
214 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
215 ShardInformation shardInfo = message.getShardInfo();
217 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
218 shardInfo.getShardName());
220 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
222 if(!shardInfo.isShardInitialized()) {
223 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
224 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
226 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
227 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
231 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
232 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
233 status.getName(), status.isInitialSyncDone());
235 ShardInformation shardInformation = findShardInformation(status.getName());
237 if(shardInformation != null) {
238 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
240 mBean.setSyncStatus(isInSync());
245 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
246 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
247 roleChanged.getOldRole(), roleChanged.getNewRole());
249 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
250 if(shardInformation != null) {
251 shardInformation.setRole(roleChanged.getNewRole());
253 if (isReadyWithLeaderId()) {
254 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
255 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
257 waitTillReadyCountdownLatch.countDown();
260 mBean.setSyncStatus(isInSync());
265 private ShardInformation findShardInformation(String memberId) {
266 for(ShardInformation info : localShards.values()){
267 if(info.getShardId().toString().equals(memberId)){
275 private boolean isReadyWithLeaderId() {
276 boolean isReady = true;
277 for (ShardInformation info : localShards.values()) {
278 if(!info.isShardReadyWithLeaderId()){
286 private boolean isInSync(){
287 for (ShardInformation info : localShards.values()) {
288 if(!info.isInSync()){
295 private void onActorInitialized(Object message) {
296 final ActorRef sender = getSender();
298 if (sender == null) {
299 return; //why is a non-actor sending this message? Just ignore.
302 String actorName = sender.path().name();
303 //find shard name from actor name; actor name is stringified shardId
304 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
306 if (shardId.getShardName() == null) {
310 markShardAsInitialized(shardId.getShardName());
313 private void markShardAsInitialized(String shardName) {
314 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
316 ShardInformation shardInformation = localShards.get(shardName);
317 if (shardInformation != null) {
318 shardInformation.setActorInitialized();
320 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
325 protected void handleRecover(Object message) throws Exception {
326 if(dataPersistenceProvider.isRecoveryApplicable()) {
327 if (message instanceof SchemaContextModules) {
328 SchemaContextModules msg = (SchemaContextModules) message;
329 knownModules = ImmutableSet.copyOf(msg.getModules());
330 } else if (message instanceof RecoveryFailure) {
331 RecoveryFailure failure = (RecoveryFailure) message;
332 LOG.error("Recovery failed", failure.cause());
333 } else if (message instanceof RecoveryCompleted) {
334 LOG.info("Recovery complete : {}", persistenceId());
336 // Delete all the messages from the akka journal except the last one
337 deleteMessages(lastSequenceNr() - 1);
340 if (message instanceof RecoveryCompleted) {
341 LOG.info("Recovery complete : {}", persistenceId());
343 // Delete all the messages from the akka journal
344 deleteMessages(lastSequenceNr());
349 private void findLocalShard(FindLocalShard message) {
350 final ShardInformation shardInformation = localShards.get(message.getShardName());
352 if(shardInformation == null){
353 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
357 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
359 public Object get() {
360 return new LocalShardFound(shardInformation.getActor());
365 private void sendResponse(ShardInformation shardInformation, boolean doWait,
366 boolean wantShardReady, final Supplier<Object> messageSupplier) {
367 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
369 final ActorRef sender = getSender();
370 final ActorRef self = self();
372 Runnable replyRunnable = new Runnable() {
375 sender.tell(messageSupplier.get(), self);
379 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
380 new OnShardInitialized(replyRunnable);
382 shardInformation.addOnShardInitialized(onShardInitialized);
384 LOG.debug("{}: Scheduling timer to wait for shard {}", persistenceId(), shardInformation.getShardName());
386 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
387 datastoreContext.getShardInitializationTimeout().duration(), getSelf(),
388 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
389 getContext().dispatcher(), getSelf());
391 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
393 } else if (!shardInformation.isShardInitialized()) {
394 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
395 shardInformation.getShardName());
396 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
398 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
399 shardInformation.getShardName());
400 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
406 getSender().tell(messageSupplier.get(), getSelf());
409 private NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
410 return new NoShardLeaderException(String.format(
411 "Could not find a leader for shard %s. This typically happens when the system is coming up or " +
412 "recovering and a leader is being elected. Try again later.", shardId));
415 private NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
416 return new NotInitializedException(String.format(
417 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
420 private void memberRemoved(ClusterEvent.MemberRemoved message) {
421 String memberName = message.member().roles().head();
423 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
424 message.member().address());
426 memberNameToAddress.remove(message.member().roles().head());
429 private void memberUp(ClusterEvent.MemberUp message) {
430 String memberName = message.member().roles().head();
432 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
433 message.member().address());
435 memberNameToAddress.put(memberName, message.member().address());
437 for(ShardInformation info : localShards.values()){
438 String shardName = info.getShardName();
439 info.updatePeerAddress(getShardIdentifier(memberName, shardName).toString(),
440 getShardActorPath(shardName, memberName), getSelf());
444 private void onDatastoreContext(DatastoreContext context) {
445 datastoreContext = context;
446 for (ShardInformation info : localShards.values()) {
447 if (info.getActor() != null) {
448 info.getActor().tell(datastoreContext, getSelf());
454 * Notifies all the local shards of a change in the schema context
458 private void updateSchemaContext(final Object message) {
459 final SchemaContext schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
461 Set<ModuleIdentifier> allModuleIdentifiers = schemaContext.getAllModuleIdentifiers();
462 Set<String> newModules = new HashSet<>(128);
464 for(ModuleIdentifier moduleIdentifier : allModuleIdentifiers){
465 String s = moduleIdentifier.getNamespace().toString();
469 if(newModules.containsAll(knownModules)) {
471 LOG.debug("New SchemaContext has a super set of current knownModules - persisting info");
473 knownModules = ImmutableSet.copyOf(newModules);
475 dataPersistenceProvider.persist(new SchemaContextModules(newModules), new Procedure<SchemaContextModules>() {
478 public void apply(SchemaContextModules param) throws Exception {
479 LOG.debug("Sending new SchemaContext to Shards");
480 for (ShardInformation info : localShards.values()) {
481 if (info.getActor() == null) {
482 info.setActor(newShardActor(schemaContext, info));
484 info.getActor().tell(message, getSelf());
491 LOG.debug("Rejecting schema context update - not a super set of previously known modules:\nUPDATE: {}\nKNOWN: {}",
492 newModules, knownModules);
498 protected ClusterWrapper getCluster() {
503 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
504 return getContext().actorOf(Shard.props(info.getShardId(),
505 info.getPeerAddresses(), datastoreContext, schemaContext)
506 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
509 private void findPrimary(FindPrimary message) {
510 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
512 final String shardName = message.getShardName();
514 // First see if the there is a local replica for the shard
515 final ShardInformation info = localShards.get(shardName);
517 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
519 public Object get() {
520 Object found = new PrimaryFound(info.getSerializedLeaderActor());
522 if(LOG.isDebugEnabled()) {
523 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
533 for(Map.Entry<String, Address> entry: memberNameToAddress.entrySet()) {
534 if(!cluster.getCurrentMemberName().equals(entry.getKey())) {
535 String path = getShardManagerActorPathBuilder(entry.getValue()).toString();
537 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
540 getContext().actorSelection(path).forward(message, getContext());
545 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
547 getSender().tell(new PrimaryNotFoundException(
548 String.format("No primary shard found for %s.", shardName)), getSelf());
551 private StringBuilder getShardManagerActorPathBuilder(Address address) {
552 StringBuilder builder = new StringBuilder();
553 builder.append(address.toString()).append("/user/").append(shardManagerIdentifierString);
557 private String getShardActorPath(String shardName, String memberName) {
558 Address address = memberNameToAddress.get(memberName);
559 if(address != null) {
560 StringBuilder builder = getShardManagerActorPathBuilder(address);
562 .append(getShardIdentifier(memberName, shardName));
563 return builder.toString();
569 * Construct the name of the shard actor given the name of the member on
570 * which the shard resides and the name of the shard
576 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
577 return ShardIdentifier.builder().memberName(memberName).shardName(shardName).type(type).build();
581 * Create shards that are local to the member on which the ShardManager
585 private void createLocalShards() {
586 String memberName = this.cluster.getCurrentMemberName();
587 List<String> memberShardNames =
588 this.configuration.getMemberShardNames(memberName);
590 List<String> localShardActorNames = new ArrayList<>();
591 for(String shardName : memberShardNames){
592 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
593 Map<String, String> peerAddresses = getPeerAddresses(shardName);
594 localShardActorNames.add(shardId.toString());
595 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses));
598 mBean = ShardManagerInfo.createShardManagerMBean("shard-manager-" + this.type,
599 datastoreContext.getDataStoreMXBeanType(), localShardActorNames);
603 * Given the name of the shard find the addresses of all it's peers
608 private Map<String, String> getPeerAddresses(String shardName){
610 Map<String, String> peerAddresses = new HashMap<>();
612 List<String> members = this.configuration.getMembersFromShardName(shardName);
614 String currentMemberName = this.cluster.getCurrentMemberName();
616 for(String memberName : members){
617 if(!currentMemberName.equals(memberName)){
618 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
619 String path = getShardActorPath(shardName, currentMemberName);
620 peerAddresses.put(shardId.toString(), path);
623 return peerAddresses;
627 public SupervisorStrategy supervisorStrategy() {
629 return new OneForOneStrategy(10, Duration.create("1 minute"),
630 new Function<Throwable, SupervisorStrategy.Directive>() {
632 public SupervisorStrategy.Directive apply(Throwable t) {
633 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
634 return SupervisorStrategy.resume();
642 public String persistenceId() {
643 return "shard-manager-" + type;
647 Collection<String> getKnownModules() {
652 DataPersistenceProvider getDataPersistenceProvider() {
653 return dataPersistenceProvider;
657 ShardManagerInfoMBean getMBean(){
662 protected static class ShardInformation {
663 private final ShardIdentifier shardId;
664 private final String shardName;
665 private ActorRef actor;
666 private ActorPath actorPath;
667 private final Map<String, String> peerAddresses;
669 // flag that determines if the actor is ready for business
670 private boolean actorInitialized = false;
672 private boolean followerSyncStatus = false;
674 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
675 private String role ;
676 private String leaderId;
678 private ShardInformation(String shardName, ShardIdentifier shardId,
679 Map<String, String> peerAddresses) {
680 this.shardName = shardName;
681 this.shardId = shardId;
682 this.peerAddresses = peerAddresses;
685 String getShardName() {
693 ActorPath getActorPath() {
697 void setActor(ActorRef actor) {
699 this.actorPath = actor.path();
702 ShardIdentifier getShardId() {
706 Map<String, String> getPeerAddresses() {
707 return peerAddresses;
710 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
711 LOG.info("updatePeerAddress for peer {} with address {}", peerId,
713 if(peerAddresses.containsKey(peerId)){
714 peerAddresses.put(peerId, peerAddress);
717 if(LOG.isDebugEnabled()) {
718 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
719 peerId, peerAddress, actor.path());
722 actor.tell(new PeerAddressResolved(peerId.toString(), peerAddress), sender);
725 notifyOnShardInitializedCallbacks();
729 boolean isShardReady() {
730 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
733 boolean isShardReadyWithLeaderId() {
734 return isShardReady() && (isLeader() || peerAddresses.containsKey(leaderId));
737 boolean isShardInitialized() {
738 return getActor() != null && actorInitialized;
742 return Objects.equal(leaderId, shardId.toString());
745 String getSerializedLeaderActor() {
747 return Serialization.serializedActorPath(getActor());
749 return peerAddresses.get(leaderId);
753 void setActorInitialized() {
754 LOG.debug("Shard {} is initialized", shardId);
756 this.actorInitialized = true;
758 notifyOnShardInitializedCallbacks();
761 private void notifyOnShardInitializedCallbacks() {
762 if(onShardInitializedSet.isEmpty()) {
766 boolean ready = isShardReadyWithLeaderId();
768 if(LOG.isDebugEnabled()) {
769 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
770 ready ? "ready" : "initialized", onShardInitializedSet.size());
773 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
774 while(iter.hasNext()) {
775 OnShardInitialized onShardInitialized = iter.next();
776 if(!(onShardInitialized instanceof OnShardReady) || ready) {
778 onShardInitialized.getTimeoutSchedule().cancel();
779 onShardInitialized.getReplyRunnable().run();
784 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
785 onShardInitializedSet.add(onShardInitialized);
788 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
789 onShardInitializedSet.remove(onShardInitialized);
792 void setRole(String newRole) {
795 notifyOnShardInitializedCallbacks();
798 void setFollowerSyncStatus(boolean syncStatus){
799 this.followerSyncStatus = syncStatus;
803 if(RaftState.Follower.name().equals(this.role)){
804 return followerSyncStatus;
805 } else if(RaftState.Leader.name().equals(this.role)){
812 void setLeaderId(String leaderId) {
813 this.leaderId = leaderId;
815 notifyOnShardInitializedCallbacks();
819 private static class ShardManagerCreator implements Creator<ShardManager> {
820 private static final long serialVersionUID = 1L;
822 final ClusterWrapper cluster;
823 final Configuration configuration;
824 final DatastoreContext datastoreContext;
825 private final CountDownLatch waitTillReadyCountdownLatch;
827 ShardManagerCreator(ClusterWrapper cluster,
828 Configuration configuration, DatastoreContext datastoreContext, CountDownLatch waitTillReadyCountdownLatch) {
829 this.cluster = cluster;
830 this.configuration = configuration;
831 this.datastoreContext = datastoreContext;
832 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
836 public ShardManager create() throws Exception {
837 return new ShardManager(cluster, configuration, datastoreContext, waitTillReadyCountdownLatch);
841 private static class OnShardInitialized {
842 private final Runnable replyRunnable;
843 private Cancellable timeoutSchedule;
845 OnShardInitialized(Runnable replyRunnable) {
846 this.replyRunnable = replyRunnable;
849 Runnable getReplyRunnable() {
850 return replyRunnable;
853 Cancellable getTimeoutSchedule() {
854 return timeoutSchedule;
857 void setTimeoutSchedule(Cancellable timeoutSchedule) {
858 this.timeoutSchedule = timeoutSchedule;
862 private static class OnShardReady extends OnShardInitialized {
863 OnShardReady(Runnable replyRunnable) {
864 super(replyRunnable);
868 private static class ShardNotInitializedTimeout {
869 private final ActorRef sender;
870 private final ShardInformation shardInfo;
871 private final OnShardInitialized onShardInitialized;
873 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
874 this.sender = sender;
875 this.shardInfo = shardInfo;
876 this.onShardInitialized = onShardInitialized;
879 ActorRef getSender() {
883 ShardInformation getShardInfo() {
887 OnShardInitialized getOnShardInitialized() {
888 return onShardInitialized;
892 static class SchemaContextModules implements Serializable {
893 private static final long serialVersionUID = -8884620101025936590L;
895 private final Set<String> modules;
897 SchemaContextModules(Set<String> modules){
898 this.modules = modules;
901 public Set<String> getModules() {