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
8 package org.opendaylight.controller.cluster.datastore.shardmanager;
10 import static java.util.Objects.requireNonNull;
12 import akka.actor.ActorRef;
13 import akka.actor.Address;
14 import akka.actor.Cancellable;
15 import akka.actor.OneForOneStrategy;
16 import akka.actor.PoisonPill;
17 import akka.actor.Status;
18 import akka.actor.SupervisorStrategy;
19 import akka.actor.SupervisorStrategy.Directive;
20 import akka.cluster.ClusterEvent;
21 import akka.cluster.ClusterEvent.MemberWeaklyUp;
22 import akka.cluster.Member;
23 import akka.dispatch.Futures;
24 import akka.dispatch.OnComplete;
25 import akka.japi.Function;
26 import akka.pattern.Patterns;
27 import akka.persistence.DeleteSnapshotsFailure;
28 import akka.persistence.DeleteSnapshotsSuccess;
29 import akka.persistence.RecoveryCompleted;
30 import akka.persistence.SaveSnapshotFailure;
31 import akka.persistence.SaveSnapshotSuccess;
32 import akka.persistence.SnapshotOffer;
33 import akka.persistence.SnapshotSelectionCriteria;
34 import akka.util.Timeout;
35 import com.google.common.annotations.VisibleForTesting;
36 import com.google.common.util.concurrent.SettableFuture;
37 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
44 import java.util.Map.Entry;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.TimeoutException;
48 import java.util.function.Consumer;
49 import java.util.function.Supplier;
50 import org.opendaylight.controller.cluster.access.concepts.MemberName;
51 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
52 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
53 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
54 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
55 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
56 import org.opendaylight.controller.cluster.datastore.Shard;
57 import org.opendaylight.controller.cluster.datastore.config.Configuration;
58 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
59 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
60 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
61 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
62 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
63 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
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.ChangeShardMembersVotingStatus;
67 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
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.FlipShardMembersVotingStatus;
71 import org.opendaylight.controller.cluster.datastore.messages.GetShardRole;
72 import org.opendaylight.controller.cluster.datastore.messages.GetShardRoleReply;
73 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
74 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
75 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
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.UpdateSchemaContext;
81 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
82 import org.opendaylight.controller.cluster.datastore.persisted.ShardManagerSnapshot;
83 import org.opendaylight.controller.cluster.datastore.utils.CompositeOnComplete;
84 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
85 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
86 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
87 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
88 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
89 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
90 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
91 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
92 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
93 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
94 import org.opendaylight.controller.cluster.raft.messages.AddServer;
95 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
96 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
97 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
98 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
99 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
100 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
101 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
102 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
103 import org.opendaylight.yangtools.concepts.Registration;
104 import org.opendaylight.yangtools.yang.common.Empty;
105 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
106 import org.slf4j.Logger;
107 import org.slf4j.LoggerFactory;
108 import scala.concurrent.ExecutionContext;
109 import scala.concurrent.Future;
110 import scala.concurrent.duration.FiniteDuration;
113 * Manages the shards for a data store. The ShardManager has the following jobs:
115 * <li> Create all the local shard replicas that belong on this cluster member
116 * <li> Find the address of the local shard
117 * <li> Find the primary replica for any given shard
118 * <li> Monitor the cluster members and store their addresses
121 class ShardManager extends AbstractUntypedPersistentActorWithMetering {
122 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
124 // Stores a mapping between a shard name and it's corresponding information
125 // Shard names look like inventory, topology etc and are as specified in
128 final Map<String, ShardInformation> localShards = new HashMap<>();
130 // The type of a ShardManager reflects the type of the datastore itself
131 // A data store could be of type config/operational
132 private final String type;
134 private final ClusterWrapper cluster;
136 private final Configuration configuration;
139 final String shardDispatcherPath;
141 private final ShardManagerInfo shardManagerMBean;
143 private DatastoreContextFactory datastoreContextFactory;
145 private final SettableFuture<Empty> readinessFuture;
147 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
150 final ShardPeerAddressResolver peerAddressResolver;
152 private EffectiveModelContext schemaContext;
154 private DatastoreSnapshot restoreFromSnapshot;
156 private ShardManagerSnapshot currentSnapshot;
158 private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
160 private final Map<String, CompositeOnComplete<Boolean>> shardActorsStopping = new HashMap<>();
162 private final Set<Consumer<String>> shardAvailabilityCallbacks = new HashSet<>();
164 private final String persistenceId;
166 @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Akka class design")
167 ShardManager(final AbstractShardManagerCreator<?> builder) {
168 cluster = builder.getCluster();
169 configuration = builder.getConfiguration();
170 datastoreContextFactory = builder.getDatastoreContextFactory();
171 type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
172 shardDispatcherPath = new Dispatchers(context().system().dispatchers())
173 .getDispatcherPath(Dispatchers.DispatcherType.Shard);
174 readinessFuture = builder.getReadinessFuture();
175 primaryShardInfoCache = builder.getPrimaryShardInfoCache();
176 restoreFromSnapshot = builder.getRestoreFromSnapshot();
178 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
179 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
181 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
183 // Subscribe this actor to cluster member events
184 cluster.subscribeToMemberEvents(getSelf());
186 shardManagerMBean = new ShardManagerInfo(getSelf(), cluster.getCurrentMemberName(),
187 "shard-manager-" + type,
188 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
189 shardManagerMBean.registerMBean();
193 public void preStart() {
194 LOG.info("Starting ShardManager {}", persistenceId);
198 public void postStop() {
199 LOG.info("Stopping ShardManager {}", persistenceId());
201 shardManagerMBean.unregisterMBean();
205 public void handleCommand(final Object message) throws Exception {
206 if (message instanceof FindPrimary) {
207 findPrimary((FindPrimary)message);
208 } else if (message instanceof FindLocalShard) {
209 findLocalShard((FindLocalShard) message);
210 } else if (message instanceof UpdateSchemaContext) {
211 updateSchemaContext(message);
212 } else if (message instanceof ActorInitialized) {
213 onActorInitialized(message);
214 } else if (message instanceof ClusterEvent.MemberUp) {
215 memberUp((ClusterEvent.MemberUp) message);
216 } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
217 memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
218 } else if (message instanceof ClusterEvent.MemberExited) {
219 memberExited((ClusterEvent.MemberExited) message);
220 } else if (message instanceof ClusterEvent.MemberRemoved) {
221 memberRemoved((ClusterEvent.MemberRemoved) message);
222 } else if (message instanceof ClusterEvent.UnreachableMember) {
223 memberUnreachable((ClusterEvent.UnreachableMember) message);
224 } else if (message instanceof ClusterEvent.ReachableMember) {
225 memberReachable((ClusterEvent.ReachableMember) message);
226 } else if (message instanceof DatastoreContextFactory) {
227 onDatastoreContextFactory((DatastoreContextFactory) message);
228 } else if (message instanceof RoleChangeNotification) {
229 onRoleChangeNotification((RoleChangeNotification) message);
230 } else if (message instanceof FollowerInitialSyncUpStatus) {
231 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
232 } else if (message instanceof ShardNotInitializedTimeout) {
233 onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
234 } else if (message instanceof ShardLeaderStateChanged) {
235 onLeaderStateChanged((ShardLeaderStateChanged) message);
236 } else if (message instanceof SwitchShardBehavior) {
237 onSwitchShardBehavior((SwitchShardBehavior) message);
238 } else if (message instanceof CreateShard) {
239 onCreateShard((CreateShard)message);
240 } else if (message instanceof AddShardReplica) {
241 onAddShardReplica((AddShardReplica) message);
242 } else if (message instanceof ForwardedAddServerReply msg) {
243 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
244 msg.removeShardOnFailure);
245 } else if (message instanceof ForwardedAddServerFailure msg) {
246 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
247 } else if (message instanceof RemoveShardReplica) {
248 onRemoveShardReplica((RemoveShardReplica) message);
249 } else if (message instanceof WrappedShardResponse) {
250 onWrappedShardResponse((WrappedShardResponse) message);
251 } else if (message instanceof GetSnapshot) {
252 onGetSnapshot((GetSnapshot) message);
253 } else if (message instanceof ServerRemoved) {
254 onShardReplicaRemoved((ServerRemoved) message);
255 } else if (message instanceof ChangeShardMembersVotingStatus) {
256 onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
257 } else if (message instanceof FlipShardMembersVotingStatus) {
258 onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
259 } else if (message instanceof SaveSnapshotSuccess) {
260 onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
261 } else if (message instanceof SaveSnapshotFailure) {
262 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
263 ((SaveSnapshotFailure) message).cause());
264 } else if (message instanceof Shutdown) {
266 } else if (message instanceof GetLocalShardIds) {
267 onGetLocalShardIds();
268 } else if (message instanceof GetShardRole) {
269 onGetShardRole((GetShardRole) message);
270 } else if (message instanceof RunnableMessage) {
271 ((RunnableMessage)message).run();
272 } else if (message instanceof RegisterForShardAvailabilityChanges) {
273 onRegisterForShardAvailabilityChanges((RegisterForShardAvailabilityChanges)message);
274 } else if (message instanceof DeleteSnapshotsFailure) {
275 LOG.warn("{}: Failed to delete prior snapshots", persistenceId(),
276 ((DeleteSnapshotsFailure) message).cause());
277 } else if (message instanceof DeleteSnapshotsSuccess) {
278 LOG.debug("{}: Successfully deleted prior snapshots", persistenceId());
279 } else if (message instanceof RegisterRoleChangeListenerReply) {
280 LOG.trace("{}: Received RegisterRoleChangeListenerReply", persistenceId());
281 } else if (message instanceof ClusterEvent.MemberEvent) {
282 LOG.trace("{}: Received other ClusterEvent.MemberEvent: {}", persistenceId(), message);
284 unknownMessage(message);
288 private void onRegisterForShardAvailabilityChanges(final RegisterForShardAvailabilityChanges message) {
289 LOG.debug("{}: onRegisterForShardAvailabilityChanges: {}", persistenceId(), message);
291 final Consumer<String> callback = message.getCallback();
292 shardAvailabilityCallbacks.add(callback);
294 getSender().tell(new Status.Success((Registration)
295 () -> executeInSelf(() -> shardAvailabilityCallbacks.remove(callback))), self());
298 private void onGetShardRole(final GetShardRole message) {
299 LOG.debug("{}: onGetShardRole for shard: {}", persistenceId(), message.getName());
301 final String name = message.getName();
303 final ShardInformation shardInformation = localShards.get(name);
305 if (shardInformation == null) {
306 LOG.info("{}: no shard information for {} found", persistenceId(), name);
307 getSender().tell(new Status.Failure(
308 new IllegalArgumentException("Shard with name " + name + " not present.")), ActorRef.noSender());
312 getSender().tell(new GetShardRoleReply(shardInformation.getRole()), ActorRef.noSender());
316 List<Future<Boolean>> stopFutures = new ArrayList<>(localShards.size());
317 for (ShardInformation info : localShards.values()) {
318 if (info.getActor() != null) {
319 LOG.debug("{}: Issuing gracefulStop to shard {}", persistenceId(), info.getShardId());
321 FiniteDuration duration = info.getDatastoreContext().getShardRaftConfig()
322 .getElectionTimeOutInterval().$times(2);
323 stopFutures.add(Patterns.gracefulStop(info.getActor(), duration, Shutdown.INSTANCE));
327 LOG.info("Shutting down ShardManager {} - waiting on {} shards", persistenceId(), stopFutures.size());
329 ExecutionContext dispatcher = new Dispatchers(context().system().dispatchers())
330 .getDispatcher(Dispatchers.DispatcherType.Client);
331 Future<Iterable<Boolean>> combinedFutures = Futures.sequence(stopFutures, dispatcher);
333 combinedFutures.onComplete(new OnComplete<Iterable<Boolean>>() {
335 public void onComplete(final Throwable failure, final Iterable<Boolean> results) {
336 LOG.debug("{}: All shards shutdown - sending PoisonPill to self", persistenceId());
338 self().tell(PoisonPill.getInstance(), self());
340 if (failure != null) {
341 LOG.warn("{}: An error occurred attempting to shut down the shards", persistenceId(), failure);
344 for (Boolean result : results) {
351 LOG.warn("{}: {} shards did not shut down gracefully", persistenceId(), nfailed);
358 private void onWrappedShardResponse(final WrappedShardResponse message) {
359 if (message.getResponse() instanceof RemoveServerReply) {
360 onRemoveServerReply(getSender(), message.getShardId(), (RemoveServerReply) message.getResponse(),
361 message.getLeaderPath());
365 private void onRemoveServerReply(final ActorRef originalSender, final ShardIdentifier shardId,
366 final RemoveServerReply replyMsg, final String leaderPath) {
367 shardReplicaOperationsInProgress.remove(shardId.getShardName());
369 LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
371 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
372 LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
373 shardId.getShardName());
374 originalSender.tell(new Status.Success(null), getSelf());
376 LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
377 persistenceId(), shardId, replyMsg.getStatus());
379 Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
380 originalSender.tell(new Status.Failure(failure), getSelf());
384 private void removeShardReplica(final RemoveShardReplica contextMessage, final String shardName,
385 final String primaryPath, final ActorRef sender) {
386 if (isShardReplicaOperationInProgress(shardName, sender)) {
390 shardReplicaOperationsInProgress.add(shardName);
392 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
394 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
396 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
397 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
398 primaryPath, shardId);
400 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
401 Future<Object> futureObj = Patterns.ask(getContext().actorSelection(primaryPath),
402 new RemoveServer(shardId.toString()), removeServerTimeout);
404 futureObj.onComplete(new OnComplete<>() {
406 public void onComplete(final Throwable failure, final Object response) {
407 if (failure != null) {
408 shardReplicaOperationsInProgress.remove(shardName);
409 LOG.debug("{}: RemoveServer request to leader {} for shard {} failed", persistenceId(), primaryPath,
413 sender.tell(new Status.Failure(new RuntimeException(
414 String.format("RemoveServer request to leader %s for shard %s failed", primaryPath, shardName),
418 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
421 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
424 private void onShardReplicaRemoved(final ServerRemoved message) {
425 removeShard(new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build());
428 @SuppressWarnings("checkstyle:IllegalCatch")
429 private void removeShard(final ShardIdentifier shardId) {
430 final String shardName = shardId.getShardName();
431 final ShardInformation shardInformation = localShards.remove(shardName);
432 if (shardInformation == null) {
433 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
437 final ActorRef shardActor = shardInformation.getActor();
438 if (shardActor != null) {
439 long timeoutInMS = Math.max(shardInformation.getDatastoreContext().getShardRaftConfig()
440 .getElectionTimeOutInterval().$times(3).toMillis(), 10000);
442 LOG.debug("{} : Sending Shutdown to Shard actor {} with {} ms timeout", persistenceId(), shardActor,
445 final Future<Boolean> stopFuture = Patterns.gracefulStop(shardActor,
446 FiniteDuration.apply(timeoutInMS, TimeUnit.MILLISECONDS), Shutdown.INSTANCE);
448 final CompositeOnComplete<Boolean> onComplete = new CompositeOnComplete<>() {
450 public void onComplete(final Throwable failure, final Boolean result) {
451 if (failure == null) {
452 LOG.debug("{} : Successfully shut down Shard actor {}", persistenceId(), shardActor);
454 LOG.warn("{}: Failed to shut down Shard actor {}", persistenceId(), shardActor, failure);
457 self().tell((RunnableMessage) () -> {
458 // At any rate, invalidate primaryShardInfo cache
459 primaryShardInfoCache.remove(shardName);
461 shardActorsStopping.remove(shardName);
462 notifyOnCompleteTasks(failure, result);
463 }, ActorRef.noSender());
467 shardActorsStopping.put(shardName, onComplete);
468 stopFuture.onComplete(onComplete, new Dispatchers(context().system().dispatchers())
469 .getDispatcher(Dispatchers.DispatcherType.Client));
472 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardName);
476 private void onGetSnapshot(final GetSnapshot getSnapshot) {
477 LOG.debug("{}: onGetSnapshot", persistenceId());
479 List<String> notInitialized = null;
480 for (ShardInformation shardInfo : localShards.values()) {
481 if (!shardInfo.isShardInitialized()) {
482 if (notInitialized == null) {
483 notInitialized = new ArrayList<>();
486 notInitialized.add(shardInfo.getShardName());
490 if (notInitialized != null) {
491 getSender().tell(new Status.Failure(new IllegalStateException(String.format(
492 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
496 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
497 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
498 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
500 for (ShardInformation shardInfo: localShards.values()) {
501 shardInfo.getActor().tell(getSnapshot, replyActor);
505 @SuppressWarnings("checkstyle:IllegalCatch")
506 private void onCreateShard(final CreateShard createShard) {
507 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
511 String shardName = createShard.getModuleShardConfig().getShardName();
512 if (localShards.containsKey(shardName)) {
513 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
514 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
516 doCreateShard(createShard);
517 reply = new Status.Success(null);
519 } catch (Exception e) {
520 LOG.error("{}: onCreateShard failed", persistenceId(), e);
521 reply = new Status.Failure(e);
524 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
525 getSender().tell(reply, getSelf());
529 private boolean isPreviousShardActorStopInProgress(final String shardName, final Object messageToDefer) {
530 final CompositeOnComplete<Boolean> stopOnComplete = shardActorsStopping.get(shardName);
531 if (stopOnComplete == null) {
535 LOG.debug("{} : Stop is in progress for shard {} - adding OnComplete callback to defer {}", persistenceId(),
536 shardName, messageToDefer);
537 final ActorRef sender = getSender();
538 stopOnComplete.addOnComplete(new OnComplete<Boolean>() {
540 public void onComplete(final Throwable failure, final Boolean result) {
541 LOG.debug("{} : Stop complete for shard {} - re-queing {}", persistenceId(), shardName, messageToDefer);
542 self().tell(messageToDefer, sender);
549 private void doCreateShard(final CreateShard createShard) {
550 final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
551 final String shardName = moduleShardConfig.getShardName();
553 configuration.addModuleShardConfiguration(moduleShardConfig);
555 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
556 if (shardDatastoreContext == null) {
557 shardDatastoreContext = newShardDatastoreContext(shardName);
559 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
560 peerAddressResolver).build();
563 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
565 boolean shardWasInRecoveredSnapshot = currentSnapshot != null
566 && currentSnapshot.getShardList().contains(shardName);
568 Map<String, String> peerAddresses;
569 boolean isActiveMember;
570 if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
571 .contains(cluster.getCurrentMemberName())) {
572 peerAddresses = getPeerAddresses(shardName);
573 isActiveMember = true;
575 // The local member is not in the static shard member configuration and the shard did not
576 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
577 // the shard with no peers and with elections disabled so it stays as follower. A
578 // subsequent AddServer request will be needed to make it an active member.
579 isActiveMember = false;
580 peerAddresses = Map.of();
581 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
582 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
585 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
586 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
589 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
590 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
591 info.setActiveMember(isActiveMember);
592 localShards.put(info.getShardName(), info);
594 if (schemaContext != null) {
595 info.setSchemaContext(schemaContext);
596 info.setActor(newShardActor(info));
600 private DatastoreContext.Builder newShardDatastoreContextBuilder(final String shardName) {
601 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
602 .shardPeerAddressResolver(peerAddressResolver);
605 private DatastoreContext newShardDatastoreContext(final String shardName) {
606 return newShardDatastoreContextBuilder(shardName).build();
609 private void checkReady() {
610 if (isReadyWithLeaderId()) {
611 LOG.info("{}: All Shards are ready - data store {} is ready", persistenceId(), type);
612 readinessFuture.set(Empty.value());
616 private void onLeaderStateChanged(final ShardLeaderStateChanged leaderStateChanged) {
617 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
619 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
620 if (shardInformation != null) {
621 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
622 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
623 if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
624 primaryShardInfoCache.remove(shardInformation.getShardName());
626 notifyShardAvailabilityCallbacks(shardInformation);
631 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
635 private void notifyShardAvailabilityCallbacks(final ShardInformation shardInformation) {
636 shardAvailabilityCallbacks.forEach(callback -> callback.accept(shardInformation.getShardName()));
639 private void onShardNotInitializedTimeout(final ShardNotInitializedTimeout message) {
640 ShardInformation shardInfo = message.getShardInfo();
642 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
643 shardInfo.getShardName());
645 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
647 if (!shardInfo.isShardInitialized()) {
648 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
649 message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
651 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
652 message.getSender().tell(new NoShardLeaderException(shardInfo.getShardId()), getSelf());
656 private void onFollowerInitialSyncStatus(final FollowerInitialSyncUpStatus status) {
657 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
658 status.getName(), status.isInitialSyncDone());
660 ShardInformation shardInformation = findShardInformation(status.getName());
662 if (shardInformation != null) {
663 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
665 shardManagerMBean.setSyncStatus(isInSync());
670 private void onRoleChangeNotification(final RoleChangeNotification roleChanged) {
671 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
672 roleChanged.getOldRole(), roleChanged.getNewRole());
674 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
675 if (shardInformation != null) {
676 shardInformation.setRole(roleChanged.getNewRole());
678 shardManagerMBean.setSyncStatus(isInSync());
683 private ShardInformation findShardInformation(final String memberId) {
684 for (ShardInformation info : localShards.values()) {
685 if (info.getShardId().toString().equals(memberId)) {
693 private boolean isReadyWithLeaderId() {
694 boolean isReady = true;
695 for (ShardInformation info : localShards.values()) {
696 if (!info.isShardReadyWithLeaderId()) {
704 private boolean isInSync() {
705 for (ShardInformation info : localShards.values()) {
706 if (!info.isInSync()) {
713 private void onActorInitialized(final Object message) {
714 final ActorRef sender = getSender();
716 if (sender == null) {
717 // why is a non-actor sending this message? Just ignore.
721 String actorName = sender.path().name();
722 //find shard name from actor name; actor name is stringified shardId
724 final ShardIdentifier shardId;
726 shardId = ShardIdentifier.fromShardIdString(actorName);
727 } catch (IllegalArgumentException e) {
728 LOG.debug("{}: ignoring actor {}", persistenceId, actorName, e);
732 markShardAsInitialized(shardId.getShardName());
735 private void markShardAsInitialized(final String shardName) {
736 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
738 ShardInformation shardInformation = localShards.get(shardName);
739 if (shardInformation != null) {
740 shardInformation.setActorInitialized();
742 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
747 protected void handleRecover(final Object message) throws Exception {
748 if (message instanceof RecoveryCompleted) {
749 onRecoveryCompleted();
750 } else if (message instanceof SnapshotOffer) {
751 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
755 @SuppressWarnings("checkstyle:IllegalCatch")
756 private void onRecoveryCompleted() {
757 LOG.info("Recovery complete : {}", persistenceId());
759 if (currentSnapshot == null && restoreFromSnapshot != null
760 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
761 ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
763 LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
765 applyShardManagerSnapshot(snapshot);
771 private void sendResponse(final ShardInformation shardInformation, final boolean doWait,
772 final boolean wantShardReady, final Supplier<Object> messageSupplier) {
773 if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
775 final ActorRef sender = getSender();
776 final ActorRef self = self();
778 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
780 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
781 new OnShardInitialized(replyRunnable);
783 shardInformation.addOnShardInitialized(onShardInitialized);
785 FiniteDuration timeout = shardInformation.getDatastoreContext()
786 .getShardInitializationTimeout().duration();
787 if (shardInformation.isShardInitialized()) {
788 // If the shard is already initialized then we'll wait enough time for the shard to
789 // elect a leader, ie 2 times the election timeout.
790 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
791 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
794 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
797 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
799 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
800 getContext().dispatcher(), getSelf());
802 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
804 } else if (!shardInformation.isShardInitialized()) {
805 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
806 shardInformation.getShardName());
807 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
809 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
810 shardInformation.getShardName());
811 getSender().tell(new NoShardLeaderException(shardInformation.getShardId()), getSelf());
817 getSender().tell(messageSupplier.get(), getSelf());
820 private static NotInitializedException createNotInitializedException(final ShardIdentifier shardId) {
821 return new NotInitializedException(String.format(
822 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
826 static MemberName memberToName(final Member member) {
827 return MemberName.forName(member.roles().iterator().next());
830 private void memberRemoved(final ClusterEvent.MemberRemoved message) {
831 MemberName memberName = memberToName(message.member());
833 LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
834 message.member().address());
836 peerAddressResolver.removePeerAddress(memberName);
839 private void memberExited(final ClusterEvent.MemberExited message) {
840 MemberName memberName = memberToName(message.member());
842 LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
843 message.member().address());
845 peerAddressResolver.removePeerAddress(memberName);
848 private void memberUp(final ClusterEvent.MemberUp message) {
849 MemberName memberName = memberToName(message.member());
851 LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
852 message.member().address());
854 memberUp(memberName, message.member().address());
857 private void memberUp(final MemberName memberName, final Address address) {
858 addPeerAddress(memberName, address);
862 private void memberWeaklyUp(final MemberWeaklyUp message) {
863 MemberName memberName = memberToName(message.member());
865 LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
866 message.member().address());
868 memberUp(memberName, message.member().address());
871 private void addPeerAddress(final MemberName memberName, final Address address) {
872 peerAddressResolver.addPeerAddress(memberName, address);
874 for (ShardInformation info : localShards.values()) {
875 String shardName = info.getShardName();
876 String peerId = getShardIdentifier(memberName, shardName).toString();
877 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
881 private void memberReachable(final ClusterEvent.ReachableMember message) {
882 MemberName memberName = memberToName(message.member());
883 LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
885 addPeerAddress(memberName, message.member().address());
887 markMemberAvailable(memberName);
890 private void memberUnreachable(final ClusterEvent.UnreachableMember message) {
891 MemberName memberName = memberToName(message.member());
892 LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
894 markMemberUnavailable(memberName);
897 private void markMemberUnavailable(final MemberName memberName) {
898 for (ShardInformation info : localShards.values()) {
899 String leaderId = info.getLeaderId();
900 if (leaderId != null && ShardIdentifier.fromShardIdString(leaderId).getMemberName().equals(memberName)) {
901 LOG.debug("Marking Leader {} as unavailable.", leaderId);
902 info.setLeaderAvailable(false);
904 primaryShardInfoCache.remove(info.getShardName());
906 notifyShardAvailabilityCallbacks(info);
911 private void markMemberAvailable(final MemberName memberName) {
912 for (ShardInformation info : localShards.values()) {
913 String leaderId = info.getLeaderId();
914 if (leaderId != null && ShardIdentifier.fromShardIdString(leaderId).getMemberName().equals(memberName)) {
915 LOG.debug("Marking Leader {} as available.", leaderId);
916 info.setLeaderAvailable(true);
921 private void onDatastoreContextFactory(final DatastoreContextFactory factory) {
922 datastoreContextFactory = factory;
923 for (ShardInformation info : localShards.values()) {
924 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
928 private void onGetLocalShardIds() {
929 final List<String> response = new ArrayList<>(localShards.size());
931 for (ShardInformation info : localShards.values()) {
932 response.add(info.getShardId().toString());
935 getSender().tell(new Status.Success(response), getSelf());
938 private void onSwitchShardBehavior(final SwitchShardBehavior message) {
939 final ShardIdentifier identifier = message.getShardId();
941 if (identifier != null) {
942 final ShardInformation info = localShards.get(identifier.getShardName());
944 getSender().tell(new Status.Failure(
945 new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
949 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
951 for (ShardInformation info : localShards.values()) {
952 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
956 getSender().tell(new Status.Success(null), getSelf());
959 private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
960 final ActorRef actor = info.getActor();
962 actor.tell(switchBehavior, getSelf());
964 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
965 info.getShardName(), switchBehavior.getNewState());
970 * Notifies all the local shards of a change in the schema context.
972 * @param message the message to send
974 private void updateSchemaContext(final Object message) {
975 schemaContext = ((UpdateSchemaContext) message).getEffectiveModelContext();
977 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getModules().size());
979 for (ShardInformation info : localShards.values()) {
980 info.setSchemaContext(schemaContext);
982 if (info.getActor() == null) {
983 LOG.debug("Creating Shard {}", info.getShardId());
984 info.setActor(newShardActor(info));
985 // Update peer address for every existing peer memeber to avoid missing sending
986 // PeerAddressResolved and PeerUp to this shard while UpdateSchemaContext comes after MemberUp.
987 String shardName = info.getShardName();
988 for (MemberName memberName : peerAddressResolver.getPeerMembers()) {
989 String peerId = getShardIdentifier(memberName, shardName).toString() ;
990 String peerAddress = peerAddressResolver.getShardActorAddress(shardName, memberName);
991 info.updatePeerAddress(peerId, peerAddress, getSelf());
992 LOG.debug("{}: updated peer {} on member {} with address {} on shard {} whose actor address is {}",
993 persistenceId(), peerId, memberName, peerAddress, info.getShardId(), info.getActor());
996 info.getActor().tell(message, getSelf());
1002 protected ClusterWrapper getCluster() {
1007 protected ActorRef newShardActor(final ShardInformation info) {
1008 return getContext().actorOf(info.newProps().withDispatcher(shardDispatcherPath),
1009 info.getShardId().toString());
1012 private void findPrimary(final FindPrimary message) {
1013 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1015 final String shardName = message.getShardName();
1016 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1018 // First see if the there is a local replica for the shard
1019 final ShardInformation info = localShards.get(shardName);
1020 if (info != null && info.isActiveMember()) {
1021 sendResponse(info, message.isWaitUntilReady(), true, () -> {
1022 String primaryPath = info.getSerializedLeaderActor();
1023 Object found = canReturnLocalShardState && info.isLeader()
1024 ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().orElseThrow()) :
1025 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1027 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1034 final Collection<String> visitedAddresses;
1035 if (message instanceof RemoteFindPrimary) {
1036 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1038 visitedAddresses = new ArrayList<>(1);
1041 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1043 for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1044 if (visitedAddresses.contains(address)) {
1048 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1049 persistenceId(), shardName, address, visitedAddresses);
1051 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1052 message.isWaitUntilReady(), visitedAddresses), getContext());
1056 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1058 getSender().tell(new PrimaryNotFoundException(
1059 String.format("No primary shard found for %s.", shardName)), getSelf());
1062 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1063 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1064 .getShardInitializationTimeout().duration().$times(2));
1066 Future<Object> futureObj = Patterns.ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1067 futureObj.onComplete(new OnComplete<>() {
1069 public void onComplete(final Throwable failure, final Object response) {
1070 if (failure != null) {
1071 handler.onFailure(failure);
1073 if (response instanceof RemotePrimaryShardFound) {
1074 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1075 } else if (response instanceof LocalPrimaryShardFound) {
1076 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1078 handler.onUnknownResponse(response);
1082 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1086 * Construct the name of the shard actor given the name of the member on
1087 * which the shard resides and the name of the shard.
1089 * @param memberName the member name
1090 * @param shardName the shard name
1093 private ShardIdentifier getShardIdentifier(final MemberName memberName, final String shardName) {
1094 return peerAddressResolver.getShardIdentifier(memberName, shardName);
1098 * Create shards that are local to the member on which the ShardManager runs.
1100 private void createLocalShards() {
1101 MemberName memberName = cluster.getCurrentMemberName();
1102 Collection<String> memberShardNames = configuration.getMemberShardNames(memberName);
1104 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1105 if (restoreFromSnapshot != null) {
1106 for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1107 shardSnapshots.put(snapshot.getName(), snapshot);
1112 restoreFromSnapshot = null;
1114 for (String shardName : memberShardNames) {
1115 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1117 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1119 Map<String, String> peerAddresses = getPeerAddresses(shardName);
1120 localShards.put(shardName, createShardInfoFor(shardName, shardId, peerAddresses,
1121 newShardDatastoreContext(shardName), shardSnapshots));
1126 ShardInformation createShardInfoFor(final String shardName, final ShardIdentifier shardId,
1127 final Map<String, String> peerAddresses,
1128 final DatastoreContext datastoreContext,
1129 final Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots) {
1130 return new ShardInformation(shardName, shardId, peerAddresses,
1131 datastoreContext, Shard.builder().restoreFromSnapshot(shardSnapshots.get(shardName)),
1132 peerAddressResolver);
1136 * Given the name of the shard find the addresses of all it's peers.
1138 * @param shardName the shard name
1140 Map<String, String> getPeerAddresses(final String shardName) {
1141 final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1142 return getPeerAddresses(shardName, members);
1145 private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1146 Map<String, String> peerAddresses = new HashMap<>();
1147 MemberName currentMemberName = cluster.getCurrentMemberName();
1149 for (MemberName memberName : members) {
1150 if (!currentMemberName.equals(memberName)) {
1151 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1152 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1153 peerAddresses.put(shardId.toString(), address);
1156 return peerAddresses;
1160 public SupervisorStrategy supervisorStrategy() {
1162 return new OneForOneStrategy(10, FiniteDuration.create(1, TimeUnit.MINUTES),
1163 (Function<Throwable, Directive>) t -> {
1164 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1165 return SupervisorStrategy.resume();
1170 public String persistenceId() {
1171 return persistenceId;
1175 ShardManagerInfoMBean getMBean() {
1176 return shardManagerMBean;
1179 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1180 if (shardReplicaOperationsInProgress.contains(shardName)) {
1181 LOG.debug("{}: A shard replica operation for {} is already in progress", persistenceId(), shardName);
1182 sender.tell(new Status.Failure(new IllegalStateException(
1183 String.format("A shard replica operation for %s is already in progress", shardName))), getSelf());
1190 private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1191 final String shardName = shardReplicaMsg.getShardName();
1193 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1195 // verify the shard with the specified name is present in the cluster configuration
1196 if (!configuration.isShardConfigured(shardName)) {
1197 LOG.debug("{}: No module configuration exists for shard {}", persistenceId(), shardName);
1198 getSender().tell(new Status.Failure(new IllegalArgumentException(
1199 "No module configuration exists for shard " + shardName)), getSelf());
1203 // Create the localShard
1204 if (schemaContext == null) {
1205 LOG.debug("{}: No SchemaContext is available in order to create a local shard instance for {}",
1206 persistenceId(), shardName);
1207 getSender().tell(new Status.Failure(new IllegalStateException(
1208 "No SchemaContext is available in order to create a local shard instance for " + shardName)),
1213 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1216 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1217 final RunnableMessage runnable = (RunnableMessage) () ->
1218 addShard(getShardName(), response, getSender());
1219 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1220 getSelf().tell(runnable, getTargetActor());
1225 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1226 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1231 private void sendLocalReplicaAlreadyExistsReply(final String shardName, final ActorRef sender) {
1232 LOG.debug("{}: Local shard {} already exists", persistenceId(), shardName);
1233 sender.tell(new Status.Failure(new AlreadyExistsException(
1234 String.format("Local shard %s already exists", shardName))), getSelf());
1237 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1238 if (isShardReplicaOperationInProgress(shardName, sender)) {
1242 shardReplicaOperationsInProgress.add(shardName);
1244 final ShardInformation shardInfo;
1245 final boolean removeShardOnFailure;
1246 ShardInformation existingShardInfo = localShards.get(shardName);
1247 if (existingShardInfo == null) {
1248 removeShardOnFailure = true;
1249 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1251 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1252 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1254 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1255 Shard.builder(), peerAddressResolver);
1256 shardInfo.setActiveMember(false);
1257 shardInfo.setSchemaContext(schemaContext);
1258 localShards.put(shardName, shardInfo);
1259 shardInfo.setActor(newShardActor(shardInfo));
1261 removeShardOnFailure = false;
1262 shardInfo = existingShardInfo;
1265 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1268 private void execAddShard(final String shardName,
1269 final ShardInformation shardInfo,
1270 final RemotePrimaryShardFound response,
1271 final boolean removeShardOnFailure,
1272 final ActorRef sender) {
1274 final String localShardAddress =
1275 peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1277 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1278 LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1279 response.getPrimaryPath(), shardInfo.getShardId());
1281 final Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1282 .getShardLeaderElectionTimeout().duration());
1283 final Future<Object> futureObj = Patterns.ask(getContext().actorSelection(response.getPrimaryPath()),
1284 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1286 futureObj.onComplete(new OnComplete<>() {
1288 public void onComplete(final Throwable failure, final Object addServerResponse) {
1289 if (failure != null) {
1290 LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1291 response.getPrimaryPath(), shardName, failure);
1293 final String msg = String.format("AddServer request to leader %s for shard %s failed",
1294 response.getPrimaryPath(), shardName);
1295 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1297 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1298 response.getPrimaryPath(), removeShardOnFailure), sender);
1301 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1304 private void onAddServerFailure(final String shardName, final String message, final Throwable failure,
1305 final ActorRef sender, final boolean removeShardOnFailure) {
1306 shardReplicaOperationsInProgress.remove(shardName);
1308 if (removeShardOnFailure) {
1309 ShardInformation shardInfo = localShards.remove(shardName);
1310 if (shardInfo.getActor() != null) {
1311 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1315 sender.tell(new Status.Failure(message == null ? failure :
1316 new RuntimeException(message, failure)), getSelf());
1319 private void onAddServerReply(final ShardInformation shardInfo, final AddServerReply replyMsg,
1320 final ActorRef sender, final String leaderPath, final boolean removeShardOnFailure) {
1321 String shardName = shardInfo.getShardName();
1322 shardReplicaOperationsInProgress.remove(shardName);
1324 LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1326 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1327 LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1329 // Make the local shard voting capable
1330 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1331 shardInfo.setActiveMember(true);
1334 sender.tell(new Status.Success(null), getSelf());
1335 } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1336 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1338 LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1339 persistenceId(), shardName, replyMsg.getStatus());
1341 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1342 shardInfo.getShardId());
1344 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1348 private static Exception getServerChangeException(final Class<?> serverChange,
1349 final ServerChangeStatus serverChangeStatus, final String leaderPath, final ShardIdentifier shardId) {
1350 return switch (serverChangeStatus) {
1351 case TIMEOUT -> new TimeoutException("""
1352 The shard leader %s timed out trying to replicate the initial data to the new shard %s. Possible \
1353 causes - there was a problem replicating the data or shard leadership changed while replicating the \
1354 shard data""".formatted(leaderPath, shardId.getShardName()));
1355 case NO_LEADER -> new NoShardLeaderException(shardId);
1356 case NOT_SUPPORTED -> new UnsupportedOperationException(
1357 "%s request is not supported for shard %s".formatted(
1358 serverChange.getSimpleName(), shardId.getShardName()));
1359 default -> new RuntimeException("%s request to leader %s for shard %s failed with status %s".formatted(
1360 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1364 private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1365 LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1367 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1368 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1370 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1371 doRemoveShardReplicaAsync(response.getPrimaryPath());
1375 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1376 doRemoveShardReplicaAsync(response.getPrimaryPath());
1379 private void doRemoveShardReplicaAsync(final String primaryPath) {
1380 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1381 primaryPath, getSender()), getTargetActor());
1386 private void persistShardList() {
1387 List<String> shardList = new ArrayList<>(localShards.keySet());
1388 for (ShardInformation shardInfo : localShards.values()) {
1389 if (!shardInfo.isActiveMember()) {
1390 shardList.remove(shardInfo.getShardName());
1393 LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1394 saveSnapshot(updateShardManagerSnapshot(shardList));
1397 private ShardManagerSnapshot updateShardManagerSnapshot(final List<String> shardList) {
1398 currentSnapshot = new ShardManagerSnapshot(shardList);
1399 return currentSnapshot;
1402 private void applyShardManagerSnapshot(final ShardManagerSnapshot snapshot) {
1403 currentSnapshot = snapshot;
1405 LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1407 final MemberName currentMember = cluster.getCurrentMemberName();
1408 Set<String> configuredShardList =
1409 new HashSet<>(configuration.getMemberShardNames(currentMember));
1410 for (String shard : currentSnapshot.getShardList()) {
1411 if (!configuredShardList.contains(shard)) {
1412 // add the current member as a replica for the shard
1413 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1414 configuration.addMemberReplicaForShard(shard, currentMember);
1416 configuredShardList.remove(shard);
1419 for (String shard : configuredShardList) {
1420 // remove the member as a replica for the shard
1421 LOG.debug("{}: removing shard {}", persistenceId(), shard);
1422 configuration.removeMemberReplicaForShard(shard, currentMember);
1426 private void onSaveSnapshotSuccess(final SaveSnapshotSuccess successMessage) {
1427 LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1429 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1433 private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1434 LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1436 String shardName = changeMembersVotingStatus.getShardName();
1437 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1438 for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1439 serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1443 ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1445 findLocalShard(shardName, getSender(),
1446 localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1447 localShardFound.getPath(), getSender()));
1450 private void onFlipShardMembersVotingStatus(final FlipShardMembersVotingStatus flipMembersVotingStatus) {
1451 LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1453 ActorRef sender = getSender();
1454 final String shardName = flipMembersVotingStatus.getShardName();
1455 findLocalShard(shardName, sender, localShardFound -> {
1456 Future<Object> future = Patterns.ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1457 Timeout.apply(30, TimeUnit.SECONDS));
1459 future.onComplete(new OnComplete<>() {
1461 public void onComplete(final Throwable failure, final Object response) {
1462 if (failure != null) {
1463 sender.tell(new Status.Failure(new RuntimeException(
1464 String.format("Failed to access local shard %s", shardName), failure)), self());
1468 OnDemandRaftState raftState = (OnDemandRaftState) response;
1469 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1470 for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1471 serverVotingStatusMap.put(e.getKey(), !e.getValue());
1474 serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1475 .toString(), !raftState.isVoting());
1477 changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1478 shardName, localShardFound.getPath(), sender);
1480 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1485 private void findLocalShard(final FindLocalShard message) {
1486 LOG.debug("{}: findLocalShard : {}", persistenceId(), message.getShardName());
1488 final ShardInformation shardInformation = localShards.get(message.getShardName());
1490 if (shardInformation == null) {
1491 LOG.debug("{}: Local shard {} not found - shards present: {}",
1492 persistenceId(), message.getShardName(), localShards.keySet());
1494 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1498 sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1499 () -> new LocalShardFound(shardInformation.getActor()));
1502 private void findLocalShard(final String shardName, final ActorRef sender,
1503 final Consumer<LocalShardFound> onLocalShardFound) {
1504 Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1505 .getShardInitializationTimeout().duration().$times(2));
1507 Future<Object> futureObj = Patterns.ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1508 futureObj.onComplete(new OnComplete<>() {
1510 public void onComplete(final Throwable failure, final Object response) {
1511 if (failure != null) {
1512 LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1514 sender.tell(new Status.Failure(new RuntimeException(
1515 String.format("Failed to find local shard %s", shardName), failure)), self());
1517 if (response instanceof LocalShardFound) {
1518 getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1520 } else if (response instanceof LocalShardNotFound) {
1521 LOG.debug("{}: Local shard {} does not exist", persistenceId, shardName);
1522 sender.tell(new Status.Failure(new IllegalArgumentException(
1523 String.format("Local shard %s does not exist", shardName))), self());
1525 LOG.debug("{}: Failed to find local shard {}: received response: {}", persistenceId, shardName,
1527 sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response
1528 : new RuntimeException(
1529 String.format("Failed to find local shard %s: received response: %s", shardName,
1530 response))), self());
1534 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1537 private void changeShardMembersVotingStatus(final ChangeServersVotingStatus changeServersVotingStatus,
1538 final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1539 if (isShardReplicaOperationInProgress(shardName, sender)) {
1543 shardReplicaOperationsInProgress.add(shardName);
1545 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1546 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1548 LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1549 changeServersVotingStatus, shardActorRef.path());
1551 Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1552 Future<Object> futureObj = Patterns.ask(shardActorRef, changeServersVotingStatus, timeout);
1554 futureObj.onComplete(new OnComplete<>() {
1556 public void onComplete(final Throwable failure, final Object response) {
1557 shardReplicaOperationsInProgress.remove(shardName);
1558 if (failure != null) {
1559 LOG.debug("{}: ChangeServersVotingStatus request to local shard {} failed", persistenceId(),
1560 shardActorRef.path(), failure);
1561 sender.tell(new Status.Failure(new RuntimeException(
1562 String.format("ChangeServersVotingStatus request to local shard %s failed",
1563 shardActorRef.path()), failure)), self());
1565 LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1567 ServerChangeReply replyMsg = (ServerChangeReply) response;
1568 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1569 LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1570 sender.tell(new Status.Success(null), getSelf());
1571 } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1572 sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1573 "The requested voting state change for shard %s is invalid. At least one member "
1574 + "must be voting", shardId.getShardName()))), getSelf());
1576 LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1577 persistenceId(), shardName, replyMsg.getStatus());
1579 Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1580 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1581 sender.tell(new Status.Failure(error), getSelf());
1585 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1588 private static final class ForwardedAddServerReply {
1589 ShardInformation shardInfo;
1590 AddServerReply addServerReply;
1592 boolean removeShardOnFailure;
1594 ForwardedAddServerReply(final ShardInformation shardInfo, final AddServerReply addServerReply,
1595 final String leaderPath, final boolean removeShardOnFailure) {
1596 this.shardInfo = shardInfo;
1597 this.addServerReply = addServerReply;
1598 this.leaderPath = leaderPath;
1599 this.removeShardOnFailure = removeShardOnFailure;
1603 private static final class ForwardedAddServerFailure {
1605 String failureMessage;
1607 boolean removeShardOnFailure;
1609 ForwardedAddServerFailure(final String shardName, final String failureMessage, final Throwable failure,
1610 final boolean removeShardOnFailure) {
1611 this.shardName = shardName;
1612 this.failureMessage = failureMessage;
1613 this.failure = failure;
1614 this.removeShardOnFailure = removeShardOnFailure;
1618 static class OnShardInitialized {
1619 private final Runnable replyRunnable;
1620 private Cancellable timeoutSchedule;
1622 OnShardInitialized(final Runnable replyRunnable) {
1623 this.replyRunnable = replyRunnable;
1626 Runnable getReplyRunnable() {
1627 return replyRunnable;
1630 Cancellable getTimeoutSchedule() {
1631 return timeoutSchedule;
1634 void setTimeoutSchedule(final Cancellable timeoutSchedule) {
1635 this.timeoutSchedule = timeoutSchedule;
1639 static class OnShardReady extends OnShardInitialized {
1640 OnShardReady(final Runnable replyRunnable) {
1641 super(replyRunnable);
1645 private interface RunnableMessage extends Runnable {
1649 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1650 * a remote or local find primary message is processed.
1652 private interface FindPrimaryResponseHandler {
1654 * Invoked when a Failure message is received as a response.
1656 * @param failure the failure exception
1658 void onFailure(Throwable failure);
1661 * Invoked when a RemotePrimaryShardFound response is received.
1663 * @param response the response
1665 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1668 * Invoked when a LocalPrimaryShardFound response is received.
1670 * @param response the response
1672 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1675 * Invoked when an unknown response is received. This is another type of failure.
1677 * @param response the response
1679 void onUnknownResponse(Object response);
1683 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1684 * replica and sends a wrapped Failure response to some targetActor.
1686 private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1687 private final ActorRef targetActor;
1688 private final String shardName;
1689 private final String persistenceId;
1690 private final ActorRef shardManagerActor;
1693 * Constructs an instance.
1695 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1696 * @param shardName The name of the shard for which the primary replica had to be found
1697 * @param persistenceId The persistenceId for the ShardManager
1698 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1700 protected AutoFindPrimaryFailureResponseHandler(final ActorRef targetActor, final String shardName,
1701 final String persistenceId, final ActorRef shardManagerActor) {
1702 this.targetActor = requireNonNull(targetActor);
1703 this.shardName = requireNonNull(shardName);
1704 this.persistenceId = requireNonNull(persistenceId);
1705 this.shardManagerActor = requireNonNull(shardManagerActor);
1708 public ActorRef getTargetActor() {
1712 public String getShardName() {
1717 public void onFailure(final Throwable failure) {
1718 LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1719 targetActor.tell(new Status.Failure(new RuntimeException(
1720 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1724 public void onUnknownResponse(final Object response) {
1725 LOG.debug("{}: Failed to find leader for shard {}: received response: {}", persistenceId, shardName,
1727 targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response
1728 : new RuntimeException(String.format("Failed to find leader for shard %s: received response: %s",
1729 shardName, response))), shardManagerActor);
1734 * The WrappedShardResponse class wraps a response from a Shard.
1736 private static final class WrappedShardResponse {
1737 private final ShardIdentifier shardId;
1738 private final Object response;
1739 private final String leaderPath;
1741 WrappedShardResponse(final ShardIdentifier shardId, final Object response, final String leaderPath) {
1742 this.shardId = shardId;
1743 this.response = response;
1744 this.leaderPath = leaderPath;
1747 ShardIdentifier getShardId() {
1751 Object getResponse() {
1755 String getLeaderPath() {
1760 private static final class ShardNotInitializedTimeout {
1761 private final ActorRef sender;
1762 private final ShardInformation shardInfo;
1763 private final OnShardInitialized onShardInitialized;
1765 ShardNotInitializedTimeout(final ShardInformation shardInfo, final OnShardInitialized onShardInitialized,
1766 final ActorRef sender) {
1767 this.sender = sender;
1768 this.shardInfo = shardInfo;
1769 this.onShardInitialized = onShardInitialized;
1772 ActorRef getSender() {
1776 ShardInformation getShardInfo() {
1780 OnShardInitialized getOnShardInitialized() {
1781 return onShardInitialized;