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 static akka.pattern.Patterns.ask;
12 import akka.actor.ActorPath;
13 import akka.actor.ActorRef;
14 import akka.actor.Address;
15 import akka.actor.Cancellable;
16 import akka.actor.OneForOneStrategy;
17 import akka.actor.PoisonPill;
18 import akka.actor.Props;
19 import akka.actor.SupervisorStrategy;
20 import akka.cluster.ClusterEvent;
21 import akka.dispatch.OnComplete;
22 import akka.japi.Function;
23 import akka.persistence.RecoveryCompleted;
24 import akka.persistence.SaveSnapshotFailure;
25 import akka.persistence.SaveSnapshotSuccess;
26 import akka.persistence.SnapshotOffer;
27 import akka.serialization.Serialization;
28 import akka.util.Timeout;
29 import com.google.common.annotations.VisibleForTesting;
30 import com.google.common.base.Objects;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33 import com.google.common.base.Strings;
34 import com.google.common.base.Supplier;
35 import com.google.common.collect.Sets;
36 import java.io.ByteArrayInputStream;
37 import java.io.ObjectInputStream;
38 import java.io.Serializable;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.Collections;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Iterator;
45 import java.util.List;
48 import java.util.concurrent.CountDownLatch;
49 import java.util.concurrent.TimeUnit;
50 import java.util.concurrent.TimeoutException;
51 import javax.annotation.Nonnull;
52 import javax.annotation.Nullable;
53 import org.apache.commons.lang3.SerializationUtils;
54 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
55 import org.opendaylight.controller.cluster.datastore.config.Configuration;
56 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
57 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
58 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
59 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
60 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
61 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
62 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
63 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
64 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
65 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
67 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
68 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
69 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
70 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
71 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
72 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
73 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
74 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
75 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
76 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
77 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
78 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
79 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
80 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
81 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
82 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
83 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
84 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
85 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
86 import org.opendaylight.controller.cluster.raft.RaftState;
87 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
88 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
89 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
90 import org.opendaylight.controller.cluster.raft.messages.AddServer;
91 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
92 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
93 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
94 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
95 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
99 import scala.concurrent.Future;
100 import scala.concurrent.duration.Duration;
101 import scala.concurrent.duration.FiniteDuration;
104 * The ShardManager has the following jobs,
106 * <li> Create all the local shard replicas that belong on this cluster member
107 * <li> Find the address of the local shard
108 * <li> Find the primary replica for any given shard
109 * <li> Monitor the cluster members and store their addresses
112 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
114 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
116 // Stores a mapping between a shard name and it's corresponding information
117 // Shard names look like inventory, topology etc and are as specified in
119 private final Map<String, ShardInformation> localShards = new HashMap<>();
121 // The type of a ShardManager reflects the type of the datastore itself
122 // A data store could be of type config/operational
123 private final String type;
125 private final ClusterWrapper cluster;
127 private final Configuration configuration;
129 private final String shardDispatcherPath;
131 private final ShardManagerInfo mBean;
133 private DatastoreContextFactory datastoreContextFactory;
135 private final CountDownLatch waitTillReadyCountdownLatch;
137 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
139 private final ShardPeerAddressResolver peerAddressResolver;
141 private SchemaContext schemaContext;
143 private DatastoreSnapshot restoreFromSnapshot;
145 private ShardManagerSnapshot currentSnapshot;
147 private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
149 private final String persistenceId;
153 protected ShardManager(AbstractBuilder<?> builder) {
155 this.cluster = builder.cluster;
156 this.configuration = builder.configuration;
157 this.datastoreContextFactory = builder.datastoreContextFactory;
158 this.type = builder.datastoreContextFactory.getBaseDatastoreContext().getDataStoreType();
159 this.shardDispatcherPath =
160 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
161 this.waitTillReadyCountdownLatch = builder.waitTillReadyCountdownLatch;
162 this.primaryShardInfoCache = builder.primaryShardInfoCache;
163 this.restoreFromSnapshot = builder.restoreFromSnapshot;
165 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
166 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
168 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
170 // Subscribe this actor to cluster member events
171 cluster.subscribeToMemberEvents(getSelf());
173 List<String> localShardActorNames = new ArrayList<>();
174 mBean = ShardManagerInfo.createShardManagerMBean(cluster.getCurrentMemberName(),
175 "shard-manager-" + this.type,
176 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType(),
177 localShardActorNames);
178 mBean.setShardManager(this);
182 public void postStop() {
183 LOG.info("Stopping ShardManager");
185 mBean.unregisterMBean();
189 public void handleCommand(Object message) throws Exception {
190 if (message instanceof FindPrimary) {
191 findPrimary((FindPrimary)message);
192 } else if(message instanceof FindLocalShard){
193 findLocalShard((FindLocalShard) message);
194 } else if (message instanceof UpdateSchemaContext) {
195 updateSchemaContext(message);
196 } else if(message instanceof ActorInitialized) {
197 onActorInitialized(message);
198 } else if (message instanceof ClusterEvent.MemberUp){
199 memberUp((ClusterEvent.MemberUp) message);
200 } else if (message instanceof ClusterEvent.MemberExited){
201 memberExited((ClusterEvent.MemberExited) message);
202 } else if(message instanceof ClusterEvent.MemberRemoved) {
203 memberRemoved((ClusterEvent.MemberRemoved) message);
204 } else if(message instanceof ClusterEvent.UnreachableMember) {
205 memberUnreachable((ClusterEvent.UnreachableMember)message);
206 } else if(message instanceof ClusterEvent.ReachableMember) {
207 memberReachable((ClusterEvent.ReachableMember) message);
208 } else if(message instanceof DatastoreContextFactory) {
209 onDatastoreContextFactory((DatastoreContextFactory)message);
210 } else if(message instanceof RoleChangeNotification) {
211 onRoleChangeNotification((RoleChangeNotification) message);
212 } else if(message instanceof FollowerInitialSyncUpStatus){
213 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
214 } else if(message instanceof ShardNotInitializedTimeout) {
215 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
216 } else if(message instanceof ShardLeaderStateChanged) {
217 onLeaderStateChanged((ShardLeaderStateChanged) message);
218 } else if(message instanceof SwitchShardBehavior){
219 onSwitchShardBehavior((SwitchShardBehavior) message);
220 } else if(message instanceof CreateShard) {
221 onCreateShard((CreateShard)message);
222 } else if(message instanceof AddShardReplica){
223 onAddShardReplica((AddShardReplica)message);
224 } else if(message instanceof ForwardedAddServerReply) {
225 ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
226 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
227 msg.removeShardOnFailure);
228 } else if(message instanceof ForwardedAddServerFailure) {
229 ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
230 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
231 } else if(message instanceof PrimaryShardFoundForContext) {
232 PrimaryShardFoundForContext primaryShardFoundContext = (PrimaryShardFoundForContext)message;
233 onPrimaryShardFoundContext(primaryShardFoundContext);
234 } else if(message instanceof RemoveShardReplica){
235 onRemoveShardReplica((RemoveShardReplica)message);
236 } else if(message instanceof GetSnapshot) {
238 } else if(message instanceof ServerRemoved){
239 onShardReplicaRemoved((ServerRemoved) message);
240 } else if (message instanceof SaveSnapshotSuccess) {
241 LOG.debug("{} saved ShardManager snapshot successfully", persistenceId());
242 } else if (message instanceof SaveSnapshotFailure) {
243 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards",
244 persistenceId(), ((SaveSnapshotFailure) message).cause());
246 unknownMessage(message);
250 private void onPrimaryShardFoundContext(PrimaryShardFoundForContext primaryShardFoundContext) {
251 if(primaryShardFoundContext.getContextMessage() instanceof AddShardReplica) {
252 addShard(primaryShardFoundContext.shardName, primaryShardFoundContext.getRemotePrimaryShardFound(), getSender());
256 private void onShardReplicaRemoved(ServerRemoved message) {
257 final ShardIdentifier shardId = new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build();
258 final ShardInformation shardInformation = localShards.remove(shardId.getShardName());
259 if(shardInformation == null) {
260 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
262 } else if(shardInformation.getActor() != null) {
263 LOG.debug("{} : Sending PoisonPill to Shard actor {}", persistenceId(), shardInformation.getActor());
264 shardInformation.getActor().tell(PoisonPill.getInstance(), self());
266 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardId.getShardName());
270 private void onGetSnapshot() {
271 LOG.debug("{}: onGetSnapshot", persistenceId());
273 List<String> notInitialized = null;
274 for(ShardInformation shardInfo: localShards.values()) {
275 if(!shardInfo.isShardInitialized()) {
276 if(notInitialized == null) {
277 notInitialized = new ArrayList<>();
280 notInitialized.add(shardInfo.getShardName());
284 if(notInitialized != null) {
285 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(String.format(
286 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
290 byte[] shardManagerSnapshot = null;
291 if(currentSnapshot != null) {
292 shardManagerSnapshot = SerializationUtils.serialize(currentSnapshot);
295 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
296 new ArrayList<>(localShards.keySet()), type, shardManagerSnapshot , getSender(), persistenceId(),
297 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
299 for(ShardInformation shardInfo: localShards.values()) {
300 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
304 private void onCreateShard(CreateShard createShard) {
305 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
309 String shardName = createShard.getModuleShardConfig().getShardName();
310 if(localShards.containsKey(shardName)) {
311 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
312 reply = new akka.actor.Status.Success(String.format("Shard with name %s already exists", shardName));
314 doCreateShard(createShard);
315 reply = new akka.actor.Status.Success(null);
317 } catch (Exception e) {
318 LOG.error("{}: onCreateShard failed", persistenceId(), e);
319 reply = new akka.actor.Status.Failure(e);
322 if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
323 getSender().tell(reply, getSelf());
327 private void doCreateShard(CreateShard createShard) {
328 ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
329 String shardName = moduleShardConfig.getShardName();
331 configuration.addModuleShardConfiguration(moduleShardConfig);
333 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
334 if(shardDatastoreContext == null) {
335 shardDatastoreContext = newShardDatastoreContext(shardName);
337 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
338 peerAddressResolver).build();
341 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
343 boolean shardWasInRecoveredSnapshot = currentSnapshot != null &&
344 currentSnapshot.getShardList().contains(shardName);
346 Map<String, String> peerAddresses;
347 boolean isActiveMember;
348 if(shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName).
349 contains(cluster.getCurrentMemberName())) {
350 peerAddresses = getPeerAddresses(shardName);
351 isActiveMember = true;
353 // The local member is not in the static shard member configuration and the shard did not
354 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
355 // the shard with no peers and with elections disabled so it stays as follower. A
356 // subsequent AddServer request will be needed to make it an active member.
357 isActiveMember = false;
358 peerAddresses = Collections.emptyMap();
359 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).
360 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
363 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
364 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
367 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
368 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
369 info.setActiveMember(isActiveMember);
370 localShards.put(info.getShardName(), info);
372 mBean.addLocalShard(shardId.toString());
374 if(schemaContext != null) {
375 info.setActor(newShardActor(schemaContext, info));
379 private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
380 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName)).
381 shardPeerAddressResolver(peerAddressResolver);
384 private DatastoreContext newShardDatastoreContext(String shardName) {
385 return newShardDatastoreContextBuilder(shardName).build();
388 private void checkReady(){
389 if (isReadyWithLeaderId()) {
390 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
391 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
393 waitTillReadyCountdownLatch.countDown();
397 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
398 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
400 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
401 if(shardInformation != null) {
402 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
403 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
404 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
405 primaryShardInfoCache.remove(shardInformation.getShardName());
410 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
414 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
415 ShardInformation shardInfo = message.getShardInfo();
417 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
418 shardInfo.getShardName());
420 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
422 if(!shardInfo.isShardInitialized()) {
423 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
424 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
426 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
427 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
431 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
432 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
433 status.getName(), status.isInitialSyncDone());
435 ShardInformation shardInformation = findShardInformation(status.getName());
437 if(shardInformation != null) {
438 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
440 mBean.setSyncStatus(isInSync());
445 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
446 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
447 roleChanged.getOldRole(), roleChanged.getNewRole());
449 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
450 if(shardInformation != null) {
451 shardInformation.setRole(roleChanged.getNewRole());
453 mBean.setSyncStatus(isInSync());
458 private ShardInformation findShardInformation(String memberId) {
459 for(ShardInformation info : localShards.values()){
460 if(info.getShardId().toString().equals(memberId)){
468 private boolean isReadyWithLeaderId() {
469 boolean isReady = true;
470 for (ShardInformation info : localShards.values()) {
471 if(!info.isShardReadyWithLeaderId()){
479 private boolean isInSync(){
480 for (ShardInformation info : localShards.values()) {
481 if(!info.isInSync()){
488 private void onActorInitialized(Object message) {
489 final ActorRef sender = getSender();
491 if (sender == null) {
492 return; //why is a non-actor sending this message? Just ignore.
495 String actorName = sender.path().name();
496 //find shard name from actor name; actor name is stringified shardId
497 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
499 if (shardId.getShardName() == null) {
503 markShardAsInitialized(shardId.getShardName());
506 private void markShardAsInitialized(String shardName) {
507 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
509 ShardInformation shardInformation = localShards.get(shardName);
510 if (shardInformation != null) {
511 shardInformation.setActorInitialized();
513 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
518 protected void handleRecover(Object message) throws Exception {
519 if (message instanceof RecoveryCompleted) {
520 onRecoveryCompleted();
521 } else if (message instanceof SnapshotOffer) {
522 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
526 private void onRecoveryCompleted() {
527 LOG.info("Recovery complete : {}", persistenceId());
529 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
530 // journal on upgrade from Helium.
531 deleteMessages(lastSequenceNr());
533 if(currentSnapshot == null && restoreFromSnapshot != null &&
534 restoreFromSnapshot.getShardManagerSnapshot() != null) {
535 try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
536 restoreFromSnapshot.getShardManagerSnapshot()))) {
537 ShardManagerSnapshot snapshot = (ShardManagerSnapshot) ois.readObject();
539 LOG.debug("{}: Deserialized restored ShardManagerSnapshot: {}", persistenceId(), snapshot);
541 applyShardManagerSnapshot(snapshot);
542 } catch(Exception e) {
543 LOG.error("{}: Error deserializing restored ShardManagerSnapshot", persistenceId(), e);
550 private void findLocalShard(FindLocalShard message) {
551 final ShardInformation shardInformation = localShards.get(message.getShardName());
553 if(shardInformation == null){
554 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
558 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
560 public Object get() {
561 return new LocalShardFound(shardInformation.getActor());
566 private void sendResponse(ShardInformation shardInformation, boolean doWait,
567 boolean wantShardReady, final Supplier<Object> messageSupplier) {
568 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
570 final ActorRef sender = getSender();
571 final ActorRef self = self();
573 Runnable replyRunnable = new Runnable() {
576 sender.tell(messageSupplier.get(), self);
580 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
581 new OnShardInitialized(replyRunnable);
583 shardInformation.addOnShardInitialized(onShardInitialized);
585 FiniteDuration timeout = shardInformation.getDatastoreContext().getShardInitializationTimeout().duration();
586 if(shardInformation.isShardInitialized()) {
587 // If the shard is already initialized then we'll wait enough time for the shard to
588 // elect a leader, ie 2 times the election timeout.
589 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
590 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
593 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
594 shardInformation.getShardName());
596 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
598 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
599 getContext().dispatcher(), getSelf());
601 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
603 } else if (!shardInformation.isShardInitialized()) {
604 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
605 shardInformation.getShardName());
606 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
608 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
609 shardInformation.getShardName());
610 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
616 getSender().tell(messageSupplier.get(), getSelf());
619 private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
620 return new NoShardLeaderException(null, shardId.toString());
623 private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
624 return new NotInitializedException(String.format(
625 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
628 private void memberRemoved(ClusterEvent.MemberRemoved message) {
629 String memberName = message.member().roles().head();
631 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
632 message.member().address());
634 peerAddressResolver.removePeerAddress(memberName);
636 for(ShardInformation info : localShards.values()){
637 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
641 private void memberExited(ClusterEvent.MemberExited message) {
642 String memberName = message.member().roles().head();
644 LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
645 message.member().address());
647 peerAddressResolver.removePeerAddress(memberName);
649 for(ShardInformation info : localShards.values()){
650 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
654 private void memberUp(ClusterEvent.MemberUp message) {
655 String memberName = message.member().roles().head();
657 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
658 message.member().address());
660 addPeerAddress(memberName, message.member().address());
665 private void addPeerAddress(String memberName, Address address) {
666 peerAddressResolver.addPeerAddress(memberName, address);
668 for(ShardInformation info : localShards.values()){
669 String shardName = info.getShardName();
670 String peerId = getShardIdentifier(memberName, shardName).toString();
671 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
673 info.peerUp(memberName, peerId, getSelf());
677 private void memberReachable(ClusterEvent.ReachableMember message) {
678 String memberName = message.member().roles().head();
679 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
681 addPeerAddress(memberName, message.member().address());
683 markMemberAvailable(memberName);
686 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
687 String memberName = message.member().roles().head();
688 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
690 markMemberUnavailable(memberName);
693 private void markMemberUnavailable(final String memberName) {
694 for(ShardInformation info : localShards.values()){
695 String leaderId = info.getLeaderId();
696 if(leaderId != null && leaderId.contains(memberName)) {
697 LOG.debug("Marking Leader {} as unavailable.", leaderId);
698 info.setLeaderAvailable(false);
700 primaryShardInfoCache.remove(info.getShardName());
703 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
707 private void markMemberAvailable(final String memberName) {
708 for(ShardInformation info : localShards.values()){
709 String leaderId = info.getLeaderId();
710 if(leaderId != null && leaderId.contains(memberName)) {
711 LOG.debug("Marking Leader {} as available.", leaderId);
712 info.setLeaderAvailable(true);
715 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
719 private void onDatastoreContextFactory(DatastoreContextFactory factory) {
720 datastoreContextFactory = factory;
721 for (ShardInformation info : localShards.values()) {
722 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
726 private void onSwitchShardBehavior(SwitchShardBehavior message) {
727 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
729 ShardInformation shardInformation = localShards.get(identifier.getShardName());
731 if(shardInformation != null && shardInformation.getActor() != null) {
732 shardInformation.getActor().tell(
733 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
735 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
736 message.getShardName(), message.getNewState());
741 * Notifies all the local shards of a change in the schema context
745 private void updateSchemaContext(final Object message) {
746 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
748 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
750 for (ShardInformation info : localShards.values()) {
751 if (info.getActor() == null) {
752 LOG.debug("Creating Shard {}", info.getShardId());
753 info.setActor(newShardActor(schemaContext, info));
755 info.getActor().tell(message, getSelf());
761 protected ClusterWrapper getCluster() {
766 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
767 return getContext().actorOf(info.newProps(schemaContext)
768 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
771 private void findPrimary(FindPrimary message) {
772 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
774 final String shardName = message.getShardName();
775 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
777 // First see if the there is a local replica for the shard
778 final ShardInformation info = localShards.get(shardName);
779 if (info != null && info.isActiveMember()) {
780 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
782 public Object get() {
783 String primaryPath = info.getSerializedLeaderActor();
784 Object found = canReturnLocalShardState && info.isLeader() ?
785 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
786 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
788 if(LOG.isDebugEnabled()) {
789 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
799 for(String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
800 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
803 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
804 message.isWaitUntilReady()), getContext());
808 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
810 getSender().tell(new PrimaryNotFoundException(
811 String.format("No primary shard found for %s.", shardName)), getSelf());
815 * Construct the name of the shard actor given the name of the member on
816 * which the shard resides and the name of the shard
822 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
823 return peerAddressResolver.getShardIdentifier(memberName, shardName);
827 * Create shards that are local to the member on which the ShardManager
831 private void createLocalShards() {
832 String memberName = this.cluster.getCurrentMemberName();
833 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
835 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
836 if(restoreFromSnapshot != null)
838 for(DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
839 shardSnapshots.put(snapshot.getName(), snapshot);
843 restoreFromSnapshot = null; // null out to GC
845 for(String shardName : memberShardNames){
846 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
848 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
850 Map<String, String> peerAddresses = getPeerAddresses(shardName);
851 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
852 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
853 shardSnapshots.get(shardName)), peerAddressResolver));
854 mBean.addLocalShard(shardId.toString());
859 * Given the name of the shard find the addresses of all it's peers
863 private Map<String, String> getPeerAddresses(String shardName) {
864 Collection<String> members = configuration.getMembersFromShardName(shardName);
865 Map<String, String> peerAddresses = new HashMap<>();
867 String currentMemberName = this.cluster.getCurrentMemberName();
869 for(String memberName : members) {
870 if(!currentMemberName.equals(memberName)) {
871 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
872 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
873 peerAddresses.put(shardId.toString(), address);
876 return peerAddresses;
880 public SupervisorStrategy supervisorStrategy() {
882 return new OneForOneStrategy(10, Duration.create("1 minute"),
883 new Function<Throwable, SupervisorStrategy.Directive>() {
885 public SupervisorStrategy.Directive apply(Throwable t) {
886 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
887 return SupervisorStrategy.resume();
895 public String persistenceId() {
896 return persistenceId;
900 ShardManagerInfoMBean getMBean(){
904 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
905 if (shardReplicaOperationsInProgress.contains(shardName)) {
906 String msg = String.format("A shard replica operation for %s is already in progress", shardName);
907 LOG.debug ("{}: {}", persistenceId(), msg);
908 sender.tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
915 private void onAddShardReplica (final AddShardReplica shardReplicaMsg) {
916 final String shardName = shardReplicaMsg.getShardName();
918 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
920 // verify the shard with the specified name is present in the cluster configuration
921 if (!(this.configuration.isShardConfigured(shardName))) {
922 String msg = String.format("No module configuration exists for shard %s", shardName);
923 LOG.debug ("{}: {}", persistenceId(), msg);
924 getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
928 // Create the localShard
929 if (schemaContext == null) {
930 String msg = String.format(
931 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
932 LOG.debug ("{}: {}", persistenceId(), msg);
933 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
937 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(), getSelf()) {
939 public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
940 getSelf().tell(new PrimaryShardFoundForContext(getShardName(), shardReplicaMsg, response), getTargetActor());
945 public void onLocalPrimaryFound(LocalPrimaryShardFound message) {
946 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
952 private void sendLocalReplicaAlreadyExistsReply(String shardName, ActorRef sender) {
953 String msg = String.format("Local shard %s already exists", shardName);
954 LOG.debug ("{}: {}", persistenceId(), msg);
955 sender.tell(new akka.actor.Status.Failure(new AlreadyExistsException(msg)), getSelf());
958 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
959 if(isShardReplicaOperationInProgress(shardName, sender)) {
963 shardReplicaOperationsInProgress.add(shardName);
965 final ShardInformation shardInfo;
966 final boolean removeShardOnFailure;
967 ShardInformation existingShardInfo = localShards.get(shardName);
968 if(existingShardInfo == null) {
969 removeShardOnFailure = true;
970 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
972 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).customRaftPolicyImplementation(
973 DisableElectionsRaftPolicy.class.getName()).build();
975 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
976 Shard.builder(), peerAddressResolver);
977 shardInfo.setActiveMember(false);
978 localShards.put(shardName, shardInfo);
979 shardInfo.setActor(newShardActor(schemaContext, shardInfo));
981 removeShardOnFailure = false;
982 shardInfo = existingShardInfo;
985 String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
987 //inform ShardLeader to add this shard as a replica by sending an AddServer message
988 LOG.debug ("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
989 response.getPrimaryPath(), shardInfo.getShardId());
991 Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext().getShardLeaderElectionTimeout().
993 Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
994 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
996 futureObj.onComplete(new OnComplete<Object>() {
998 public void onComplete(Throwable failure, Object addServerResponse) {
999 if (failure != null) {
1000 LOG.debug ("{}: AddServer request to {} for {} failed", persistenceId(),
1001 response.getPrimaryPath(), shardName, failure);
1003 String msg = String.format("AddServer request to leader %s for shard %s failed",
1004 response.getPrimaryPath(), shardName);
1005 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1007 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1008 response.getPrimaryPath(), removeShardOnFailure), sender);
1011 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1014 private void onAddServerFailure(String shardName, String message, Throwable failure, ActorRef sender,
1015 boolean removeShardOnFailure) {
1016 shardReplicaOperationsInProgress.remove(shardName);
1018 if(removeShardOnFailure) {
1019 ShardInformation shardInfo = localShards.remove(shardName);
1020 if (shardInfo.getActor() != null) {
1021 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1025 sender.tell(new akka.actor.Status.Failure(message == null ? failure :
1026 new RuntimeException(message, failure)), getSelf());
1029 private void onAddServerReply(ShardInformation shardInfo, AddServerReply replyMsg, ActorRef sender,
1030 String leaderPath, boolean removeShardOnFailure) {
1031 String shardName = shardInfo.getShardName();
1032 shardReplicaOperationsInProgress.remove(shardName);
1034 LOG.debug ("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1036 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1037 LOG.debug ("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1039 // Make the local shard voting capable
1040 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1041 shardInfo.setActiveMember(true);
1044 mBean.addLocalShard(shardInfo.getShardId().toString());
1045 sender.tell(new akka.actor.Status.Success(null), getSelf());
1046 } else if(replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1047 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1049 LOG.warn ("{}: Leader failed to add shard replica {} with status {}",
1050 persistenceId(), shardName, replyMsg.getStatus());
1053 switch (replyMsg.getStatus()) {
1055 failure = new TimeoutException(String.format(
1056 "The shard leader %s timed out trying to replicate the initial data to the new shard %s." +
1057 "Possible causes - there was a problem replicating the data or shard leadership changed while replicating the shard data",
1058 leaderPath, shardName));
1061 failure = createNoShardLeaderException(shardInfo.getShardId());
1064 failure = new RuntimeException(String.format(
1065 "AddServer request to leader %s for shard %s failed with status %s",
1066 leaderPath, shardName, replyMsg.getStatus()));
1069 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1073 private void onRemoveShardReplica (RemoveShardReplica shardReplicaMsg) {
1074 String shardName = shardReplicaMsg.getShardName();
1076 // verify the local shard replica is available in the controller node
1077 if (!localShards.containsKey(shardName)) {
1078 String msg = String.format("Local shard %s does not", shardName);
1079 LOG.debug ("{}: {}", persistenceId(), msg);
1080 getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
1083 // call RemoveShard for the shardName
1084 getSender().tell(new akka.actor.Status.Success(true), getSelf());
1088 private void persistShardList() {
1089 List<String> shardList = new ArrayList<>(localShards.keySet());
1090 for (ShardInformation shardInfo : localShards.values()) {
1091 if (!shardInfo.isActiveMember()) {
1092 shardList.remove(shardInfo.getShardName());
1095 LOG.debug ("{}: persisting the shard list {}", persistenceId(), shardList);
1096 saveSnapshot(updateShardManagerSnapshot(shardList));
1099 private ShardManagerSnapshot updateShardManagerSnapshot(List<String> shardList) {
1100 currentSnapshot = new ShardManagerSnapshot(shardList);
1101 return currentSnapshot;
1104 private void applyShardManagerSnapshot(ShardManagerSnapshot snapshot) {
1105 currentSnapshot = snapshot;
1107 LOG.debug ("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1109 String currentMember = cluster.getCurrentMemberName();
1110 Set<String> configuredShardList =
1111 new HashSet<>(configuration.getMemberShardNames(currentMember));
1112 for (String shard : currentSnapshot.getShardList()) {
1113 if (!configuredShardList.contains(shard)) {
1114 // add the current member as a replica for the shard
1115 LOG.debug ("{}: adding shard {}", persistenceId(), shard);
1116 configuration.addMemberReplicaForShard(shard, currentMember);
1118 configuredShardList.remove(shard);
1121 for (String shard : configuredShardList) {
1122 // remove the member as a replica for the shard
1123 LOG.debug ("{}: removing shard {}", persistenceId(), shard);
1124 configuration.removeMemberReplicaForShard(shard, currentMember);
1128 private static class ForwardedAddServerReply {
1129 ShardInformation shardInfo;
1130 AddServerReply addServerReply;
1132 boolean removeShardOnFailure;
1134 ForwardedAddServerReply(ShardInformation shardInfo, AddServerReply addServerReply, String leaderPath,
1135 boolean removeShardOnFailure) {
1136 this.shardInfo = shardInfo;
1137 this.addServerReply = addServerReply;
1138 this.leaderPath = leaderPath;
1139 this.removeShardOnFailure = removeShardOnFailure;
1143 private static class ForwardedAddServerFailure {
1145 String failureMessage;
1147 boolean removeShardOnFailure;
1149 ForwardedAddServerFailure(String shardName, String failureMessage, Throwable failure,
1150 boolean removeShardOnFailure) {
1151 this.shardName = shardName;
1152 this.failureMessage = failureMessage;
1153 this.failure = failure;
1154 this.removeShardOnFailure = removeShardOnFailure;
1159 protected static class ShardInformation {
1160 private final ShardIdentifier shardId;
1161 private final String shardName;
1162 private ActorRef actor;
1163 private ActorPath actorPath;
1164 private final Map<String, String> initialPeerAddresses;
1165 private Optional<DataTree> localShardDataTree;
1166 private boolean leaderAvailable = false;
1168 // flag that determines if the actor is ready for business
1169 private boolean actorInitialized = false;
1171 private boolean followerSyncStatus = false;
1173 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
1174 private String role ;
1175 private String leaderId;
1176 private short leaderVersion;
1178 private DatastoreContext datastoreContext;
1179 private Shard.AbstractBuilder<?, ?> builder;
1180 private final ShardPeerAddressResolver addressResolver;
1181 private boolean isActiveMember = true;
1183 private ShardInformation(String shardName, ShardIdentifier shardId,
1184 Map<String, String> initialPeerAddresses, DatastoreContext datastoreContext,
1185 Shard.AbstractBuilder<?, ?> builder, ShardPeerAddressResolver addressResolver) {
1186 this.shardName = shardName;
1187 this.shardId = shardId;
1188 this.initialPeerAddresses = initialPeerAddresses;
1189 this.datastoreContext = datastoreContext;
1190 this.builder = builder;
1191 this.addressResolver = addressResolver;
1194 Props newProps(SchemaContext schemaContext) {
1195 Preconditions.checkNotNull(builder);
1196 Props props = builder.id(shardId).peerAddresses(initialPeerAddresses).datastoreContext(datastoreContext).
1197 schemaContext(schemaContext).props();
1202 String getShardName() {
1207 ActorRef getActor(){
1211 ActorPath getActorPath() {
1215 void setActor(ActorRef actor) {
1217 this.actorPath = actor.path();
1220 ShardIdentifier getShardId() {
1224 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
1225 this.localShardDataTree = localShardDataTree;
1228 Optional<DataTree> getLocalShardDataTree() {
1229 return localShardDataTree;
1232 DatastoreContext getDatastoreContext() {
1233 return datastoreContext;
1236 void setDatastoreContext(DatastoreContext datastoreContext, ActorRef sender) {
1237 this.datastoreContext = datastoreContext;
1238 if (actor != null) {
1239 LOG.debug ("Sending new DatastoreContext to {}", shardId);
1240 actor.tell(this.datastoreContext, sender);
1244 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
1245 LOG.info("updatePeerAddress for peer {} with address {}", peerId, peerAddress);
1248 if(LOG.isDebugEnabled()) {
1249 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
1250 peerId, peerAddress, actor.path());
1253 actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
1256 notifyOnShardInitializedCallbacks();
1259 void peerDown(String memberName, String peerId, ActorRef sender) {
1261 actor.tell(new PeerDown(memberName, peerId), sender);
1265 void peerUp(String memberName, String peerId, ActorRef sender) {
1267 actor.tell(new PeerUp(memberName, peerId), sender);
1271 boolean isShardReady() {
1272 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
1275 boolean isShardReadyWithLeaderId() {
1276 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
1277 (isLeader() || addressResolver.resolve(leaderId) != null);
1280 boolean isShardInitialized() {
1281 return getActor() != null && actorInitialized;
1284 boolean isLeader() {
1285 return Objects.equal(leaderId, shardId.toString());
1288 String getSerializedLeaderActor() {
1290 return Serialization.serializedActorPath(getActor());
1292 return addressResolver.resolve(leaderId);
1296 void setActorInitialized() {
1297 LOG.debug("Shard {} is initialized", shardId);
1299 this.actorInitialized = true;
1301 notifyOnShardInitializedCallbacks();
1304 private void notifyOnShardInitializedCallbacks() {
1305 if(onShardInitializedSet.isEmpty()) {
1309 boolean ready = isShardReadyWithLeaderId();
1311 if(LOG.isDebugEnabled()) {
1312 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
1313 ready ? "ready" : "initialized", onShardInitializedSet.size());
1316 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
1317 while(iter.hasNext()) {
1318 OnShardInitialized onShardInitialized = iter.next();
1319 if(!(onShardInitialized instanceof OnShardReady) || ready) {
1321 onShardInitialized.getTimeoutSchedule().cancel();
1322 onShardInitialized.getReplyRunnable().run();
1327 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
1328 onShardInitializedSet.add(onShardInitialized);
1331 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
1332 onShardInitializedSet.remove(onShardInitialized);
1335 void setRole(String newRole) {
1336 this.role = newRole;
1338 notifyOnShardInitializedCallbacks();
1341 void setFollowerSyncStatus(boolean syncStatus){
1342 this.followerSyncStatus = syncStatus;
1346 if(RaftState.Follower.name().equals(this.role)){
1347 return followerSyncStatus;
1348 } else if(RaftState.Leader.name().equals(this.role)){
1355 boolean setLeaderId(String leaderId) {
1356 boolean changed = !Objects.equal(this.leaderId, leaderId);
1357 this.leaderId = leaderId;
1358 if(leaderId != null) {
1359 this.leaderAvailable = true;
1361 notifyOnShardInitializedCallbacks();
1366 String getLeaderId() {
1370 void setLeaderAvailable(boolean leaderAvailable) {
1371 this.leaderAvailable = leaderAvailable;
1374 short getLeaderVersion() {
1375 return leaderVersion;
1378 void setLeaderVersion(short leaderVersion) {
1379 this.leaderVersion = leaderVersion;
1382 boolean isActiveMember() {
1383 return isActiveMember;
1386 void setActiveMember(boolean isActiveMember) {
1387 this.isActiveMember = isActiveMember;
1391 private static class OnShardInitialized {
1392 private final Runnable replyRunnable;
1393 private Cancellable timeoutSchedule;
1395 OnShardInitialized(Runnable replyRunnable) {
1396 this.replyRunnable = replyRunnable;
1399 Runnable getReplyRunnable() {
1400 return replyRunnable;
1403 Cancellable getTimeoutSchedule() {
1404 return timeoutSchedule;
1407 void setTimeoutSchedule(Cancellable timeoutSchedule) {
1408 this.timeoutSchedule = timeoutSchedule;
1412 private static class OnShardReady extends OnShardInitialized {
1413 OnShardReady(Runnable replyRunnable) {
1414 super(replyRunnable);
1418 private static class ShardNotInitializedTimeout {
1419 private final ActorRef sender;
1420 private final ShardInformation shardInfo;
1421 private final OnShardInitialized onShardInitialized;
1423 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1424 this.sender = sender;
1425 this.shardInfo = shardInfo;
1426 this.onShardInitialized = onShardInitialized;
1429 ActorRef getSender() {
1433 ShardInformation getShardInfo() {
1437 OnShardInitialized getOnShardInitialized() {
1438 return onShardInitialized;
1443 * We no longer persist SchemaContextModules but keep this class around for now for backwards
1444 * compatibility so we don't get de-serialization failures on upgrade from Helium.
1447 static class SchemaContextModules implements Serializable {
1448 private static final long serialVersionUID = -8884620101025936590L;
1450 private final Set<String> modules;
1452 SchemaContextModules(Set<String> modules){
1453 this.modules = modules;
1456 public Set<String> getModules() {
1461 public static Builder builder() {
1462 return new Builder();
1465 public static abstract class AbstractBuilder<T extends AbstractBuilder<T>> {
1466 private ClusterWrapper cluster;
1467 private Configuration configuration;
1468 private DatastoreContextFactory datastoreContextFactory;
1469 private CountDownLatch waitTillReadyCountdownLatch;
1470 private PrimaryShardInfoFutureCache primaryShardInfoCache;
1471 private DatastoreSnapshot restoreFromSnapshot;
1472 private volatile boolean sealed;
1474 @SuppressWarnings("unchecked")
1479 protected void checkSealed() {
1480 Preconditions.checkState(!sealed, "Builder is already sealed - further modifications are not allowed");
1483 public T cluster(ClusterWrapper cluster) {
1485 this.cluster = cluster;
1489 public T configuration(Configuration configuration) {
1491 this.configuration = configuration;
1495 public T datastoreContextFactory(DatastoreContextFactory datastoreContextFactory) {
1497 this.datastoreContextFactory = datastoreContextFactory;
1501 public T waitTillReadyCountdownLatch(CountDownLatch waitTillReadyCountdownLatch) {
1503 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
1507 public T primaryShardInfoCache(PrimaryShardInfoFutureCache primaryShardInfoCache) {
1509 this.primaryShardInfoCache = primaryShardInfoCache;
1513 public T restoreFromSnapshot(DatastoreSnapshot restoreFromSnapshot) {
1515 this.restoreFromSnapshot = restoreFromSnapshot;
1519 protected void verify() {
1521 Preconditions.checkNotNull(cluster, "cluster should not be null");
1522 Preconditions.checkNotNull(configuration, "configuration should not be null");
1523 Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
1524 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
1525 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
1528 public Props props() {
1530 return Props.create(ShardManager.class, this);
1534 public static class Builder extends AbstractBuilder<Builder> {
1537 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1538 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext().
1539 getShardInitializationTimeout().duration().$times(2));
1542 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1543 futureObj.onComplete(new OnComplete<Object>() {
1545 public void onComplete(Throwable failure, Object response) {
1546 if (failure != null) {
1547 handler.onFailure(failure);
1549 if(response instanceof RemotePrimaryShardFound) {
1550 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1551 } else if(response instanceof LocalPrimaryShardFound) {
1552 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1554 handler.onUnknownResponse(response);
1558 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1562 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1563 * a remote or local find primary message is processed
1565 private static interface FindPrimaryResponseHandler {
1567 * Invoked when a Failure message is received as a response
1571 void onFailure(Throwable failure);
1574 * Invoked when a RemotePrimaryShardFound response is received
1578 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1581 * Invoked when a LocalPrimaryShardFound response is received
1584 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1587 * Invoked when an unknown response is received. This is another type of failure.
1591 void onUnknownResponse(Object response);
1595 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1596 * replica and sends a wrapped Failure response to some targetActor
1598 private static abstract class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1599 private final ActorRef targetActor;
1600 private final String shardName;
1601 private final String persistenceId;
1602 private final ActorRef shardManagerActor;
1605 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1606 * @param shardName The name of the shard for which the primary replica had to be found
1607 * @param persistenceId The persistenceId for the ShardManager
1608 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1610 protected AutoFindPrimaryFailureResponseHandler(ActorRef targetActor, String shardName, String persistenceId, ActorRef shardManagerActor){
1611 this.targetActor = Preconditions.checkNotNull(targetActor);
1612 this.shardName = Preconditions.checkNotNull(shardName);
1613 this.persistenceId = Preconditions.checkNotNull(persistenceId);
1614 this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1617 public ActorRef getTargetActor() {
1621 public String getShardName() {
1625 public ActorRef getShardManagerActor() {
1626 return shardManagerActor;
1630 public void onFailure(Throwable failure) {
1631 LOG.debug ("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1632 targetActor.tell(new akka.actor.Status.Failure(new RuntimeException(
1633 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1637 public void onUnknownResponse(Object response) {
1638 String msg = String.format("Failed to find leader for shard %s: received response: %s",
1639 shardName, response);
1640 LOG.debug ("{}: {}", persistenceId, msg);
1641 targetActor.tell(new akka.actor.Status.Failure(response instanceof Throwable ? (Throwable) response :
1642 new RuntimeException(msg)), shardManagerActor);
1648 * The PrimaryShardFoundForContext is a DTO which puts together a message (aka 'Context' message) which needs to be
1649 * forwarded to the primary replica of a shard and the message (aka 'PrimaryShardFound' message) that is received
1650 * as a successful response to find primary.
1652 private static class PrimaryShardFoundForContext {
1653 private final String shardName;
1654 private final Object contextMessage;
1655 private final RemotePrimaryShardFound remotePrimaryShardFound;
1656 private final LocalPrimaryShardFound localPrimaryShardFound;
1658 public PrimaryShardFoundForContext(@Nonnull String shardName, @Nonnull Object contextMessage, @Nonnull Object primaryFoundMessage) {
1659 this.shardName = Preconditions.checkNotNull(shardName);
1660 this.contextMessage = Preconditions.checkNotNull(contextMessage);
1661 Preconditions.checkNotNull(primaryFoundMessage);
1662 this.remotePrimaryShardFound = (primaryFoundMessage instanceof RemotePrimaryShardFound) ? (RemotePrimaryShardFound) primaryFoundMessage : null;
1663 this.localPrimaryShardFound = (primaryFoundMessage instanceof LocalPrimaryShardFound) ? (LocalPrimaryShardFound) primaryFoundMessage : null;
1667 public String getPrimaryPath(){
1668 if(remotePrimaryShardFound != null){
1669 return remotePrimaryShardFound.getPrimaryPath();
1671 return localPrimaryShardFound.getPrimaryPath();
1675 public Object getContextMessage() {
1676 return contextMessage;
1680 public RemotePrimaryShardFound getRemotePrimaryShardFound(){
1681 return remotePrimaryShardFound;
1685 public LocalPrimaryShardFound getLocalPrimaryShardFound(){
1686 return localPrimaryShardFound;
1689 boolean isPrimaryLocal(){
1690 return (remotePrimaryShardFound == null);
1694 public String getShardName() {