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.shardmanager;
11 import static akka.pattern.Patterns.ask;
12 import static java.util.Objects.requireNonNull;
14 import akka.actor.ActorRef;
15 import akka.actor.Address;
16 import akka.actor.Cancellable;
17 import akka.actor.OneForOneStrategy;
18 import akka.actor.PoisonPill;
19 import akka.actor.Status;
20 import akka.actor.SupervisorStrategy;
21 import akka.actor.SupervisorStrategy.Directive;
22 import akka.cluster.ClusterEvent;
23 import akka.cluster.ClusterEvent.MemberWeaklyUp;
24 import akka.cluster.Member;
25 import akka.dispatch.Futures;
26 import akka.dispatch.OnComplete;
27 import akka.japi.Function;
28 import akka.pattern.Patterns;
29 import akka.persistence.DeleteSnapshotsFailure;
30 import akka.persistence.DeleteSnapshotsSuccess;
31 import akka.persistence.RecoveryCompleted;
32 import akka.persistence.SaveSnapshotFailure;
33 import akka.persistence.SaveSnapshotSuccess;
34 import akka.persistence.SnapshotOffer;
35 import akka.persistence.SnapshotSelectionCriteria;
36 import akka.util.Timeout;
37 import com.google.common.annotations.VisibleForTesting;
38 import com.google.common.util.concurrent.SettableFuture;
39 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.Collections;
43 import java.util.HashMap;
44 import java.util.HashSet;
45 import java.util.List;
47 import java.util.Map.Entry;
49 import java.util.concurrent.TimeUnit;
50 import java.util.concurrent.TimeoutException;
51 import java.util.function.Consumer;
52 import java.util.function.Supplier;
53 import org.opendaylight.controller.cluster.access.concepts.MemberName;
54 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
55 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
56 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
57 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
58 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
59 import org.opendaylight.controller.cluster.datastore.Shard;
60 import org.opendaylight.controller.cluster.datastore.config.Configuration;
61 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
62 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
63 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
64 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
65 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
66 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
67 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
68 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
69 import org.opendaylight.controller.cluster.datastore.messages.ChangeShardMembersVotingStatus;
70 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
71 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
72 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
73 import org.opendaylight.controller.cluster.datastore.messages.FlipShardMembersVotingStatus;
74 import org.opendaylight.controller.cluster.datastore.messages.GetShardRole;
75 import org.opendaylight.controller.cluster.datastore.messages.GetShardRoleReply;
76 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
77 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
78 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
79 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
80 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
81 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
82 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
83 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
84 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
85 import org.opendaylight.controller.cluster.datastore.persisted.ShardManagerSnapshot;
86 import org.opendaylight.controller.cluster.datastore.utils.CompositeOnComplete;
87 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
88 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
89 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
90 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
91 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
92 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
93 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
94 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
95 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
96 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
97 import org.opendaylight.controller.cluster.raft.messages.AddServer;
98 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
99 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
100 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
101 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
102 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
103 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
104 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
105 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
106 import org.opendaylight.yangtools.concepts.Registration;
107 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
110 import scala.concurrent.ExecutionContext;
111 import scala.concurrent.Future;
112 import scala.concurrent.duration.FiniteDuration;
115 * Manages the shards for a data store. The ShardManager has the following jobs:
117 * <li> Create all the local shard replicas that belong on this cluster member
118 * <li> Find the address of the local shard
119 * <li> Find the primary replica for any given shard
120 * <li> Monitor the cluster members and store their addresses
123 class ShardManager extends AbstractUntypedPersistentActorWithMetering {
124 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
126 // Stores a mapping between a shard name and it's corresponding information
127 // Shard names look like inventory, topology etc and are as specified in
130 final Map<String, ShardInformation> localShards = new HashMap<>();
132 // The type of a ShardManager reflects the type of the datastore itself
133 // A data store could be of type config/operational
134 private final String type;
136 private final ClusterWrapper cluster;
138 private final Configuration configuration;
141 final String shardDispatcherPath;
143 private final ShardManagerInfo shardManagerMBean;
145 private DatastoreContextFactory datastoreContextFactory;
147 private final SettableFuture<Void> readinessFuture;
149 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
152 final ShardPeerAddressResolver peerAddressResolver;
154 private EffectiveModelContext schemaContext;
156 private DatastoreSnapshot restoreFromSnapshot;
158 private ShardManagerSnapshot currentSnapshot;
160 private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
162 private final Map<String, CompositeOnComplete<Boolean>> shardActorsStopping = new HashMap<>();
164 private final Set<Consumer<String>> shardAvailabilityCallbacks = new HashSet<>();
166 private final String persistenceId;
168 ShardManager(final AbstractShardManagerCreator<?> builder) {
169 this.cluster = builder.getCluster();
170 this.configuration = builder.getConfiguration();
171 this.datastoreContextFactory = builder.getDatastoreContextFactory();
172 this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
173 this.shardDispatcherPath =
174 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
175 this.readinessFuture = builder.getReadinessFuture();
176 this.primaryShardInfoCache = builder.getPrimaryShardInfoCache();
177 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
179 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
180 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
182 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
184 // Subscribe this actor to cluster member events
185 cluster.subscribeToMemberEvents(getSelf());
187 shardManagerMBean = new ShardManagerInfo(getSelf(), cluster.getCurrentMemberName(),
188 "shard-manager-" + this.type,
189 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
190 shardManagerMBean.registerMBean();
194 public void preStart() {
195 LOG.info("Starting ShardManager {}", persistenceId);
199 public void postStop() {
200 LOG.info("Stopping ShardManager {}", persistenceId());
202 shardManagerMBean.unregisterMBean();
206 public void handleCommand(final Object message) throws Exception {
207 if (message instanceof FindPrimary) {
208 findPrimary((FindPrimary)message);
209 } else if (message instanceof FindLocalShard) {
210 findLocalShard((FindLocalShard) message);
211 } else if (message instanceof UpdateSchemaContext) {
212 updateSchemaContext(message);
213 } else if (message instanceof ActorInitialized) {
214 onActorInitialized(message);
215 } else if (message instanceof ClusterEvent.MemberUp) {
216 memberUp((ClusterEvent.MemberUp) message);
217 } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
218 memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
219 } else if (message instanceof ClusterEvent.MemberExited) {
220 memberExited((ClusterEvent.MemberExited) message);
221 } else if (message instanceof ClusterEvent.MemberRemoved) {
222 memberRemoved((ClusterEvent.MemberRemoved) message);
223 } else if (message instanceof ClusterEvent.UnreachableMember) {
224 memberUnreachable((ClusterEvent.UnreachableMember) message);
225 } else if (message instanceof ClusterEvent.ReachableMember) {
226 memberReachable((ClusterEvent.ReachableMember) message);
227 } else if (message instanceof DatastoreContextFactory) {
228 onDatastoreContextFactory((DatastoreContextFactory) message);
229 } else if (message instanceof RoleChangeNotification) {
230 onRoleChangeNotification((RoleChangeNotification) message);
231 } else if (message instanceof FollowerInitialSyncUpStatus) {
232 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
233 } else if (message instanceof ShardNotInitializedTimeout) {
234 onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
235 } else if (message instanceof ShardLeaderStateChanged) {
236 onLeaderStateChanged((ShardLeaderStateChanged) message);
237 } else if (message instanceof SwitchShardBehavior) {
238 onSwitchShardBehavior((SwitchShardBehavior) message);
239 } else if (message instanceof CreateShard) {
240 onCreateShard((CreateShard)message);
241 } else if (message instanceof AddShardReplica) {
242 onAddShardReplica((AddShardReplica) message);
243 } else if (message instanceof ForwardedAddServerReply) {
244 ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
245 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
246 msg.removeShardOnFailure);
247 } else if (message instanceof ForwardedAddServerFailure) {
248 ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
249 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
250 } else if (message instanceof RemoveShardReplica) {
251 onRemoveShardReplica((RemoveShardReplica) message);
252 } else if (message instanceof WrappedShardResponse) {
253 onWrappedShardResponse((WrappedShardResponse) message);
254 } else if (message instanceof GetSnapshot) {
255 onGetSnapshot((GetSnapshot) message);
256 } else if (message instanceof ServerRemoved) {
257 onShardReplicaRemoved((ServerRemoved) message);
258 } else if (message instanceof ChangeShardMembersVotingStatus) {
259 onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
260 } else if (message instanceof FlipShardMembersVotingStatus) {
261 onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
262 } else if (message instanceof SaveSnapshotSuccess) {
263 onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
264 } else if (message instanceof SaveSnapshotFailure) {
265 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
266 ((SaveSnapshotFailure) message).cause());
267 } else if (message instanceof Shutdown) {
269 } else if (message instanceof GetLocalShardIds) {
270 onGetLocalShardIds();
271 } else if (message instanceof GetShardRole) {
272 onGetShardRole((GetShardRole) message);
273 } else if (message instanceof RunnableMessage) {
274 ((RunnableMessage)message).run();
275 } else if (message instanceof RegisterForShardAvailabilityChanges) {
276 onRegisterForShardAvailabilityChanges((RegisterForShardAvailabilityChanges)message);
277 } else if (message instanceof DeleteSnapshotsFailure) {
278 LOG.warn("{}: Failed to delete prior snapshots", persistenceId(),
279 ((DeleteSnapshotsFailure) message).cause());
280 } else if (message instanceof DeleteSnapshotsSuccess) {
281 LOG.debug("{}: Successfully deleted prior snapshots", persistenceId());
282 } else if (message instanceof RegisterRoleChangeListenerReply) {
283 LOG.trace("{}: Received RegisterRoleChangeListenerReply", persistenceId());
284 } else if (message instanceof ClusterEvent.MemberEvent) {
285 LOG.trace("{}: Received other ClusterEvent.MemberEvent: {}", persistenceId(), message);
287 unknownMessage(message);
291 private void onRegisterForShardAvailabilityChanges(final RegisterForShardAvailabilityChanges message) {
292 LOG.debug("{}: onRegisterForShardAvailabilityChanges: {}", persistenceId(), message);
294 final Consumer<String> callback = message.getCallback();
295 shardAvailabilityCallbacks.add(callback);
297 getSender().tell(new Status.Success((Registration)
298 () -> executeInSelf(() -> shardAvailabilityCallbacks.remove(callback))), self());
301 private void onGetShardRole(final GetShardRole message) {
302 LOG.debug("{}: onGetShardRole for shard: {}", persistenceId(), message.getName());
304 final String name = message.getName();
306 final ShardInformation shardInformation = localShards.get(name);
308 if (shardInformation == null) {
309 LOG.info("{}: no shard information for {} found", persistenceId(), name);
310 getSender().tell(new Status.Failure(
311 new IllegalArgumentException("Shard with name " + name + " not present.")), ActorRef.noSender());
315 getSender().tell(new GetShardRoleReply(shardInformation.getRole()), ActorRef.noSender());
319 List<Future<Boolean>> stopFutures = new ArrayList<>(localShards.size());
320 for (ShardInformation info : localShards.values()) {
321 if (info.getActor() != null) {
322 LOG.debug("{}: Issuing gracefulStop to shard {}", persistenceId(), info.getShardId());
324 FiniteDuration duration = info.getDatastoreContext().getShardRaftConfig()
325 .getElectionTimeOutInterval().$times(2);
326 stopFutures.add(Patterns.gracefulStop(info.getActor(), duration, Shutdown.INSTANCE));
330 LOG.info("Shutting down ShardManager {} - waiting on {} shards", persistenceId(), stopFutures.size());
332 ExecutionContext dispatcher = new Dispatchers(context().system().dispatchers())
333 .getDispatcher(Dispatchers.DispatcherType.Client);
334 Future<Iterable<Boolean>> combinedFutures = Futures.sequence(stopFutures, dispatcher);
336 combinedFutures.onComplete(new OnComplete<Iterable<Boolean>>() {
338 public void onComplete(final Throwable failure, final Iterable<Boolean> results) {
339 LOG.debug("{}: All shards shutdown - sending PoisonPill to self", persistenceId());
341 self().tell(PoisonPill.getInstance(), self());
343 if (failure != null) {
344 LOG.warn("{}: An error occurred attempting to shut down the shards", persistenceId(), failure);
347 for (Boolean result : results) {
354 LOG.warn("{}: {} shards did not shut down gracefully", persistenceId(), nfailed);
361 private void onWrappedShardResponse(final WrappedShardResponse message) {
362 if (message.getResponse() instanceof RemoveServerReply) {
363 onRemoveServerReply(getSender(), message.getShardId(), (RemoveServerReply) message.getResponse(),
364 message.getLeaderPath());
368 private void onRemoveServerReply(final ActorRef originalSender, final ShardIdentifier shardId,
369 final RemoveServerReply replyMsg, final String leaderPath) {
370 shardReplicaOperationsInProgress.remove(shardId.getShardName());
372 LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
374 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
375 LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
376 shardId.getShardName());
377 originalSender.tell(new Status.Success(null), getSelf());
379 LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
380 persistenceId(), shardId, replyMsg.getStatus());
382 Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
383 originalSender.tell(new Status.Failure(failure), getSelf());
387 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
388 justification = "https://github.com/spotbugs/spotbugs/issues/811")
389 private void removeShardReplica(final RemoveShardReplica contextMessage, final String shardName,
390 final String primaryPath, final ActorRef sender) {
391 if (isShardReplicaOperationInProgress(shardName, sender)) {
395 shardReplicaOperationsInProgress.add(shardName);
397 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
399 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
401 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
402 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
403 primaryPath, shardId);
405 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
406 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
407 new RemoveServer(shardId.toString()), removeServerTimeout);
409 futureObj.onComplete(new OnComplete<>() {
411 public void onComplete(final Throwable failure, final Object response) {
412 if (failure != null) {
413 shardReplicaOperationsInProgress.remove(shardName);
414 LOG.debug("{}: RemoveServer request to leader {} for shard {} failed", persistenceId(), primaryPath,
418 sender.tell(new Status.Failure(new RuntimeException(
419 String.format("RemoveServer request to leader %s for shard %s failed", primaryPath, shardName),
423 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
426 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
429 private void onShardReplicaRemoved(final ServerRemoved message) {
430 removeShard(new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build());
433 @SuppressWarnings("checkstyle:IllegalCatch")
434 private void removeShard(final ShardIdentifier shardId) {
435 final String shardName = shardId.getShardName();
436 final ShardInformation shardInformation = localShards.remove(shardName);
437 if (shardInformation == null) {
438 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
442 final ActorRef shardActor = shardInformation.getActor();
443 if (shardActor != null) {
444 long timeoutInMS = Math.max(shardInformation.getDatastoreContext().getShardRaftConfig()
445 .getElectionTimeOutInterval().$times(3).toMillis(), 10000);
447 LOG.debug("{} : Sending Shutdown to Shard actor {} with {} ms timeout", persistenceId(), shardActor,
450 final Future<Boolean> stopFuture = Patterns.gracefulStop(shardActor,
451 FiniteDuration.apply(timeoutInMS, TimeUnit.MILLISECONDS), Shutdown.INSTANCE);
453 final CompositeOnComplete<Boolean> onComplete = new CompositeOnComplete<>() {
455 public void onComplete(final Throwable failure, final Boolean result) {
456 if (failure == null) {
457 LOG.debug("{} : Successfully shut down Shard actor {}", persistenceId(), shardActor);
459 LOG.warn("{}: Failed to shut down Shard actor {}", persistenceId(), shardActor, failure);
462 self().tell((RunnableMessage) () -> {
463 // At any rate, invalidate primaryShardInfo cache
464 primaryShardInfoCache.remove(shardName);
466 shardActorsStopping.remove(shardName);
467 notifyOnCompleteTasks(failure, result);
468 }, ActorRef.noSender());
472 shardActorsStopping.put(shardName, onComplete);
473 stopFuture.onComplete(onComplete, new Dispatchers(context().system().dispatchers())
474 .getDispatcher(Dispatchers.DispatcherType.Client));
477 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardName);
481 private void onGetSnapshot(final GetSnapshot getSnapshot) {
482 LOG.debug("{}: onGetSnapshot", persistenceId());
484 List<String> notInitialized = null;
485 for (ShardInformation shardInfo : localShards.values()) {
486 if (!shardInfo.isShardInitialized()) {
487 if (notInitialized == null) {
488 notInitialized = new ArrayList<>();
491 notInitialized.add(shardInfo.getShardName());
495 if (notInitialized != null) {
496 getSender().tell(new Status.Failure(new IllegalStateException(String.format(
497 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
501 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
502 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
503 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
505 for (ShardInformation shardInfo: localShards.values()) {
506 shardInfo.getActor().tell(getSnapshot, replyActor);
510 @SuppressWarnings("checkstyle:IllegalCatch")
511 private void onCreateShard(final CreateShard createShard) {
512 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
516 String shardName = createShard.getModuleShardConfig().getShardName();
517 if (localShards.containsKey(shardName)) {
518 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
519 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
521 doCreateShard(createShard);
522 reply = new Status.Success(null);
524 } catch (Exception e) {
525 LOG.error("{}: onCreateShard failed", persistenceId(), e);
526 reply = new Status.Failure(e);
529 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
530 getSender().tell(reply, getSelf());
534 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
535 justification = "https://github.com/spotbugs/spotbugs/issues/811")
536 private boolean isPreviousShardActorStopInProgress(final String shardName, final Object messageToDefer) {
537 final CompositeOnComplete<Boolean> stopOnComplete = shardActorsStopping.get(shardName);
538 if (stopOnComplete == null) {
542 LOG.debug("{} : Stop is in progress for shard {} - adding OnComplete callback to defer {}", persistenceId(),
543 shardName, messageToDefer);
544 final ActorRef sender = getSender();
545 stopOnComplete.addOnComplete(new OnComplete<Boolean>() {
547 public void onComplete(final Throwable failure, final Boolean result) {
548 LOG.debug("{} : Stop complete for shard {} - re-queing {}", persistenceId(), shardName, messageToDefer);
549 self().tell(messageToDefer, sender);
556 private void doCreateShard(final CreateShard createShard) {
557 final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
558 final String shardName = moduleShardConfig.getShardName();
560 configuration.addModuleShardConfiguration(moduleShardConfig);
562 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
563 if (shardDatastoreContext == null) {
564 shardDatastoreContext = newShardDatastoreContext(shardName);
566 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
567 peerAddressResolver).build();
570 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
572 boolean shardWasInRecoveredSnapshot = currentSnapshot != null
573 && currentSnapshot.getShardList().contains(shardName);
575 Map<String, String> peerAddresses;
576 boolean isActiveMember;
577 if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
578 .contains(cluster.getCurrentMemberName())) {
579 peerAddresses = getPeerAddresses(shardName);
580 isActiveMember = true;
582 // The local member is not in the static shard member configuration and the shard did not
583 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
584 // the shard with no peers and with elections disabled so it stays as follower. A
585 // subsequent AddServer request will be needed to make it an active member.
586 isActiveMember = false;
587 peerAddresses = Collections.emptyMap();
588 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
589 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
592 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
593 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
596 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
597 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
598 info.setActiveMember(isActiveMember);
599 localShards.put(info.getShardName(), info);
601 if (schemaContext != null) {
602 info.setSchemaContext(schemaContext);
603 info.setActor(newShardActor(info));
607 private DatastoreContext.Builder newShardDatastoreContextBuilder(final String shardName) {
608 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
609 .shardPeerAddressResolver(peerAddressResolver);
612 private DatastoreContext newShardDatastoreContext(final String shardName) {
613 return newShardDatastoreContextBuilder(shardName).build();
616 private void checkReady() {
617 if (isReadyWithLeaderId()) {
618 LOG.info("{}: All Shards are ready - data store {} is ready", persistenceId(), type);
619 readinessFuture.set(null);
623 private void onLeaderStateChanged(final ShardLeaderStateChanged leaderStateChanged) {
624 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
626 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
627 if (shardInformation != null) {
628 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
629 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
630 if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
631 primaryShardInfoCache.remove(shardInformation.getShardName());
633 notifyShardAvailabilityCallbacks(shardInformation);
638 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
642 private void notifyShardAvailabilityCallbacks(final ShardInformation shardInformation) {
643 shardAvailabilityCallbacks.forEach(callback -> callback.accept(shardInformation.getShardName()));
646 private void onShardNotInitializedTimeout(final ShardNotInitializedTimeout message) {
647 ShardInformation shardInfo = message.getShardInfo();
649 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
650 shardInfo.getShardName());
652 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
654 if (!shardInfo.isShardInitialized()) {
655 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
656 message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
658 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
659 message.getSender().tell(new NoShardLeaderException(shardInfo.getShardId()), getSelf());
663 private void onFollowerInitialSyncStatus(final FollowerInitialSyncUpStatus status) {
664 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
665 status.getName(), status.isInitialSyncDone());
667 ShardInformation shardInformation = findShardInformation(status.getName());
669 if (shardInformation != null) {
670 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
672 shardManagerMBean.setSyncStatus(isInSync());
677 private void onRoleChangeNotification(final RoleChangeNotification roleChanged) {
678 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
679 roleChanged.getOldRole(), roleChanged.getNewRole());
681 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
682 if (shardInformation != null) {
683 shardInformation.setRole(roleChanged.getNewRole());
685 shardManagerMBean.setSyncStatus(isInSync());
690 private ShardInformation findShardInformation(final String memberId) {
691 for (ShardInformation info : localShards.values()) {
692 if (info.getShardId().toString().equals(memberId)) {
700 private boolean isReadyWithLeaderId() {
701 boolean isReady = true;
702 for (ShardInformation info : localShards.values()) {
703 if (!info.isShardReadyWithLeaderId()) {
711 private boolean isInSync() {
712 for (ShardInformation info : localShards.values()) {
713 if (!info.isInSync()) {
720 private void onActorInitialized(final Object message) {
721 final ActorRef sender = getSender();
723 if (sender == null) {
724 // why is a non-actor sending this message? Just ignore.
728 String actorName = sender.path().name();
729 //find shard name from actor name; actor name is stringified shardId
731 final ShardIdentifier shardId;
733 shardId = ShardIdentifier.fromShardIdString(actorName);
734 } catch (IllegalArgumentException e) {
735 LOG.debug("{}: ignoring actor {}", persistenceId, actorName, e);
739 markShardAsInitialized(shardId.getShardName());
742 private void markShardAsInitialized(final String shardName) {
743 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
745 ShardInformation shardInformation = localShards.get(shardName);
746 if (shardInformation != null) {
747 shardInformation.setActorInitialized();
749 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
754 protected void handleRecover(final Object message) throws Exception {
755 if (message instanceof RecoveryCompleted) {
756 onRecoveryCompleted();
757 } else if (message instanceof SnapshotOffer) {
758 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
762 @SuppressWarnings("checkstyle:IllegalCatch")
763 private void onRecoveryCompleted() {
764 LOG.info("Recovery complete : {}", persistenceId());
766 if (currentSnapshot == null && restoreFromSnapshot != null
767 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
768 ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
770 LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
772 applyShardManagerSnapshot(snapshot);
778 private void sendResponse(final ShardInformation shardInformation, final boolean doWait,
779 final boolean wantShardReady, final Supplier<Object> messageSupplier) {
780 if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
782 final ActorRef sender = getSender();
783 final ActorRef self = self();
785 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
787 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
788 new OnShardInitialized(replyRunnable);
790 shardInformation.addOnShardInitialized(onShardInitialized);
792 FiniteDuration timeout = shardInformation.getDatastoreContext()
793 .getShardInitializationTimeout().duration();
794 if (shardInformation.isShardInitialized()) {
795 // If the shard is already initialized then we'll wait enough time for the shard to
796 // elect a leader, ie 2 times the election timeout.
797 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
798 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
801 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
804 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
806 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
807 getContext().dispatcher(), getSelf());
809 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
811 } else if (!shardInformation.isShardInitialized()) {
812 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
813 shardInformation.getShardName());
814 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
816 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
817 shardInformation.getShardName());
818 getSender().tell(new NoShardLeaderException(shardInformation.getShardId()), getSelf());
824 getSender().tell(messageSupplier.get(), getSelf());
827 private static NotInitializedException createNotInitializedException(final ShardIdentifier shardId) {
828 return new NotInitializedException(String.format(
829 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
833 static MemberName memberToName(final Member member) {
834 return MemberName.forName(member.roles().iterator().next());
837 private void memberRemoved(final ClusterEvent.MemberRemoved message) {
838 MemberName memberName = memberToName(message.member());
840 LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
841 message.member().address());
843 peerAddressResolver.removePeerAddress(memberName);
846 private void memberExited(final ClusterEvent.MemberExited message) {
847 MemberName memberName = memberToName(message.member());
849 LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
850 message.member().address());
852 peerAddressResolver.removePeerAddress(memberName);
855 private void memberUp(final ClusterEvent.MemberUp message) {
856 MemberName memberName = memberToName(message.member());
858 LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
859 message.member().address());
861 memberUp(memberName, message.member().address());
864 private void memberUp(final MemberName memberName, final Address address) {
865 addPeerAddress(memberName, address);
869 private void memberWeaklyUp(final MemberWeaklyUp message) {
870 MemberName memberName = memberToName(message.member());
872 LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
873 message.member().address());
875 memberUp(memberName, message.member().address());
878 private void addPeerAddress(final MemberName memberName, final Address address) {
879 peerAddressResolver.addPeerAddress(memberName, address);
881 for (ShardInformation info : localShards.values()) {
882 String shardName = info.getShardName();
883 String peerId = getShardIdentifier(memberName, shardName).toString();
884 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
888 private void memberReachable(final ClusterEvent.ReachableMember message) {
889 MemberName memberName = memberToName(message.member());
890 LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
892 addPeerAddress(memberName, message.member().address());
894 markMemberAvailable(memberName);
897 private void memberUnreachable(final ClusterEvent.UnreachableMember message) {
898 MemberName memberName = memberToName(message.member());
899 LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
901 markMemberUnavailable(memberName);
904 private void markMemberUnavailable(final MemberName memberName) {
905 for (ShardInformation info : localShards.values()) {
906 String leaderId = info.getLeaderId();
907 if (leaderId != null && ShardIdentifier.fromShardIdString(leaderId).getMemberName().equals(memberName)) {
908 LOG.debug("Marking Leader {} as unavailable.", leaderId);
909 info.setLeaderAvailable(false);
911 primaryShardInfoCache.remove(info.getShardName());
913 notifyShardAvailabilityCallbacks(info);
918 private void markMemberAvailable(final MemberName memberName) {
919 for (ShardInformation info : localShards.values()) {
920 String leaderId = info.getLeaderId();
921 if (leaderId != null && ShardIdentifier.fromShardIdString(leaderId).getMemberName().equals(memberName)) {
922 LOG.debug("Marking Leader {} as available.", leaderId);
923 info.setLeaderAvailable(true);
928 private void onDatastoreContextFactory(final DatastoreContextFactory factory) {
929 datastoreContextFactory = factory;
930 for (ShardInformation info : localShards.values()) {
931 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
935 private void onGetLocalShardIds() {
936 final List<String> response = new ArrayList<>(localShards.size());
938 for (ShardInformation info : localShards.values()) {
939 response.add(info.getShardId().toString());
942 getSender().tell(new Status.Success(response), getSelf());
945 private void onSwitchShardBehavior(final SwitchShardBehavior message) {
946 final ShardIdentifier identifier = message.getShardId();
948 if (identifier != null) {
949 final ShardInformation info = localShards.get(identifier.getShardName());
951 getSender().tell(new Status.Failure(
952 new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
956 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
958 for (ShardInformation info : localShards.values()) {
959 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
963 getSender().tell(new Status.Success(null), getSelf());
966 private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
967 final ActorRef actor = info.getActor();
969 actor.tell(switchBehavior, getSelf());
971 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
972 info.getShardName(), switchBehavior.getNewState());
977 * Notifies all the local shards of a change in the schema context.
979 * @param message the message to send
981 private void updateSchemaContext(final Object message) {
982 schemaContext = ((UpdateSchemaContext) message).getEffectiveModelContext();
984 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getModules().size());
986 for (ShardInformation info : localShards.values()) {
987 info.setSchemaContext(schemaContext);
989 if (info.getActor() == null) {
990 LOG.debug("Creating Shard {}", info.getShardId());
991 info.setActor(newShardActor(info));
992 // Update peer address for every existing peer memeber to avoid missing sending
993 // PeerAddressResolved and PeerUp to this shard while UpdateSchemaContext comes after MemberUp.
994 String shardName = info.getShardName();
995 for (MemberName memberName : peerAddressResolver.getPeerMembers()) {
996 String peerId = getShardIdentifier(memberName, shardName).toString() ;
997 String peerAddress = peerAddressResolver.getShardActorAddress(shardName, memberName);
998 info.updatePeerAddress(peerId, peerAddress, getSelf());
999 LOG.debug("{}: updated peer {} on member {} with address {} on shard {} whose actor address is {}",
1000 persistenceId(), peerId, memberName, peerAddress, info.getShardId(), info.getActor());
1003 info.getActor().tell(message, getSelf());
1009 protected ClusterWrapper getCluster() {
1014 protected ActorRef newShardActor(final ShardInformation info) {
1015 return getContext().actorOf(info.newProps().withDispatcher(shardDispatcherPath),
1016 info.getShardId().toString());
1019 private void findPrimary(final FindPrimary message) {
1020 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1022 final String shardName = message.getShardName();
1023 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1025 // First see if the there is a local replica for the shard
1026 final ShardInformation info = localShards.get(shardName);
1027 if (info != null && info.isActiveMember()) {
1028 sendResponse(info, message.isWaitUntilReady(), true, () -> {
1029 String primaryPath = info.getSerializedLeaderActor();
1030 Object found = canReturnLocalShardState && info.isLeader()
1031 ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1032 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1034 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1041 final Collection<String> visitedAddresses;
1042 if (message instanceof RemoteFindPrimary) {
1043 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1045 visitedAddresses = new ArrayList<>(1);
1048 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1050 for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1051 if (visitedAddresses.contains(address)) {
1055 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1056 persistenceId(), shardName, address, visitedAddresses);
1058 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1059 message.isWaitUntilReady(), visitedAddresses), getContext());
1063 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1065 getSender().tell(new PrimaryNotFoundException(
1066 String.format("No primary shard found for %s.", shardName)), getSelf());
1069 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1070 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1071 .getShardInitializationTimeout().duration().$times(2));
1073 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1074 futureObj.onComplete(new OnComplete<>() {
1076 public void onComplete(final Throwable failure, final Object response) {
1077 if (failure != null) {
1078 handler.onFailure(failure);
1080 if (response instanceof RemotePrimaryShardFound) {
1081 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1082 } else if (response instanceof LocalPrimaryShardFound) {
1083 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1085 handler.onUnknownResponse(response);
1089 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1093 * Construct the name of the shard actor given the name of the member on
1094 * which the shard resides and the name of the shard.
1096 * @param memberName the member name
1097 * @param shardName the shard name
1100 private ShardIdentifier getShardIdentifier(final MemberName memberName, final String shardName) {
1101 return peerAddressResolver.getShardIdentifier(memberName, shardName);
1105 * Create shards that are local to the member on which the ShardManager runs.
1107 private void createLocalShards() {
1108 MemberName memberName = this.cluster.getCurrentMemberName();
1109 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1111 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1112 if (restoreFromSnapshot != null) {
1113 for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1114 shardSnapshots.put(snapshot.getName(), snapshot);
1119 restoreFromSnapshot = null;
1121 for (String shardName : memberShardNames) {
1122 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1124 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1126 Map<String, String> peerAddresses = getPeerAddresses(shardName);
1127 localShards.put(shardName, createShardInfoFor(shardName, shardId, peerAddresses,
1128 newShardDatastoreContext(shardName), shardSnapshots));
1133 ShardInformation createShardInfoFor(final String shardName, final ShardIdentifier shardId,
1134 final Map<String, String> peerAddresses,
1135 final DatastoreContext datastoreContext,
1136 final Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots) {
1137 return new ShardInformation(shardName, shardId, peerAddresses,
1138 datastoreContext, Shard.builder().restoreFromSnapshot(shardSnapshots.get(shardName)),
1139 peerAddressResolver);
1143 * Given the name of the shard find the addresses of all it's peers.
1145 * @param shardName the shard name
1147 Map<String, String> getPeerAddresses(final String shardName) {
1148 final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1149 return getPeerAddresses(shardName, members);
1152 private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1153 Map<String, String> peerAddresses = new HashMap<>();
1154 MemberName currentMemberName = this.cluster.getCurrentMemberName();
1156 for (MemberName memberName : members) {
1157 if (!currentMemberName.equals(memberName)) {
1158 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1159 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1160 peerAddresses.put(shardId.toString(), address);
1163 return peerAddresses;
1167 public SupervisorStrategy supervisorStrategy() {
1169 return new OneForOneStrategy(10, FiniteDuration.create(1, TimeUnit.MINUTES),
1170 (Function<Throwable, Directive>) t -> {
1171 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1172 return SupervisorStrategy.resume();
1177 public String persistenceId() {
1178 return persistenceId;
1182 ShardManagerInfoMBean getMBean() {
1183 return shardManagerMBean;
1186 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1187 if (shardReplicaOperationsInProgress.contains(shardName)) {
1188 LOG.debug("{}: A shard replica operation for {} is already in progress", persistenceId(), shardName);
1189 sender.tell(new Status.Failure(new IllegalStateException(
1190 String.format("A shard replica operation for %s is already in progress", shardName))), getSelf());
1197 private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1198 final String shardName = shardReplicaMsg.getShardName();
1200 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1202 // verify the shard with the specified name is present in the cluster configuration
1203 if (!this.configuration.isShardConfigured(shardName)) {
1204 LOG.debug("{}: No module configuration exists for shard {}", persistenceId(), shardName);
1205 getSender().tell(new Status.Failure(new IllegalArgumentException(
1206 "No module configuration exists for shard " + shardName)), getSelf());
1210 // Create the localShard
1211 if (schemaContext == null) {
1212 LOG.debug("{}: No SchemaContext is available in order to create a local shard instance for {}",
1213 persistenceId(), shardName);
1214 getSender().tell(new Status.Failure(new IllegalStateException(
1215 "No SchemaContext is available in order to create a local shard instance for " + shardName)),
1220 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1223 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1224 final RunnableMessage runnable = (RunnableMessage) () ->
1225 addShard(getShardName(), response, getSender());
1226 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1227 getSelf().tell(runnable, getTargetActor());
1232 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1233 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1238 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
1239 justification = "https://github.com/spotbugs/spotbugs/issues/811")
1240 private void sendLocalReplicaAlreadyExistsReply(final String shardName, final ActorRef sender) {
1241 LOG.debug("{}: Local shard {} already exists", persistenceId(), shardName);
1242 sender.tell(new Status.Failure(new AlreadyExistsException(
1243 String.format("Local shard %s already exists", shardName))), getSelf());
1246 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
1247 justification = "https://github.com/spotbugs/spotbugs/issues/811")
1248 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1249 if (isShardReplicaOperationInProgress(shardName, sender)) {
1253 shardReplicaOperationsInProgress.add(shardName);
1255 final ShardInformation shardInfo;
1256 final boolean removeShardOnFailure;
1257 ShardInformation existingShardInfo = localShards.get(shardName);
1258 if (existingShardInfo == null) {
1259 removeShardOnFailure = true;
1260 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1262 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1263 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1265 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1266 Shard.builder(), peerAddressResolver);
1267 shardInfo.setActiveMember(false);
1268 shardInfo.setSchemaContext(schemaContext);
1269 localShards.put(shardName, shardInfo);
1270 shardInfo.setActor(newShardActor(shardInfo));
1272 removeShardOnFailure = false;
1273 shardInfo = existingShardInfo;
1276 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1279 private void execAddShard(final String shardName,
1280 final ShardInformation shardInfo,
1281 final RemotePrimaryShardFound response,
1282 final boolean removeShardOnFailure,
1283 final ActorRef sender) {
1285 final String localShardAddress =
1286 peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1288 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1289 LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1290 response.getPrimaryPath(), shardInfo.getShardId());
1292 final Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1293 .getShardLeaderElectionTimeout().duration());
1294 final Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1295 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1297 futureObj.onComplete(new OnComplete<>() {
1299 public void onComplete(final Throwable failure, final Object addServerResponse) {
1300 if (failure != null) {
1301 LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1302 response.getPrimaryPath(), shardName, failure);
1304 final String msg = String.format("AddServer request to leader %s for shard %s failed",
1305 response.getPrimaryPath(), shardName);
1306 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1308 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1309 response.getPrimaryPath(), removeShardOnFailure), sender);
1312 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1315 private void onAddServerFailure(final String shardName, final String message, final Throwable failure,
1316 final ActorRef sender, final boolean removeShardOnFailure) {
1317 shardReplicaOperationsInProgress.remove(shardName);
1319 if (removeShardOnFailure) {
1320 ShardInformation shardInfo = localShards.remove(shardName);
1321 if (shardInfo.getActor() != null) {
1322 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1326 sender.tell(new Status.Failure(message == null ? failure :
1327 new RuntimeException(message, failure)), getSelf());
1330 private void onAddServerReply(final ShardInformation shardInfo, final AddServerReply replyMsg,
1331 final ActorRef sender, final String leaderPath, final boolean removeShardOnFailure) {
1332 String shardName = shardInfo.getShardName();
1333 shardReplicaOperationsInProgress.remove(shardName);
1335 LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1337 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1338 LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1340 // Make the local shard voting capable
1341 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1342 shardInfo.setActiveMember(true);
1345 sender.tell(new Status.Success(null), getSelf());
1346 } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1347 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1349 LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1350 persistenceId(), shardName, replyMsg.getStatus());
1352 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1353 shardInfo.getShardId());
1355 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1359 private static Exception getServerChangeException(final Class<?> serverChange,
1360 final ServerChangeStatus serverChangeStatus, final String leaderPath, final ShardIdentifier shardId) {
1361 switch (serverChangeStatus) {
1363 return new TimeoutException(String.format(
1364 "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1365 + "Possible causes - there was a problem replicating the data or shard leadership changed "
1366 + "while replicating the shard data", leaderPath, shardId.getShardName()));
1368 return new NoShardLeaderException(shardId);
1370 return new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1371 serverChange.getSimpleName(), shardId.getShardName()));
1373 return new RuntimeException(String.format("%s request to leader %s for shard %s failed with status %s",
1374 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1378 private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1379 LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1381 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1382 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1384 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1385 doRemoveShardReplicaAsync(response.getPrimaryPath());
1389 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1390 doRemoveShardReplicaAsync(response.getPrimaryPath());
1393 private void doRemoveShardReplicaAsync(final String primaryPath) {
1394 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1395 primaryPath, getSender()), getTargetActor());
1400 private void persistShardList() {
1401 List<String> shardList = new ArrayList<>(localShards.keySet());
1402 for (ShardInformation shardInfo : localShards.values()) {
1403 if (!shardInfo.isActiveMember()) {
1404 shardList.remove(shardInfo.getShardName());
1407 LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1408 saveSnapshot(updateShardManagerSnapshot(shardList));
1411 private ShardManagerSnapshot updateShardManagerSnapshot(final List<String> shardList) {
1412 currentSnapshot = new ShardManagerSnapshot(shardList);
1413 return currentSnapshot;
1416 private void applyShardManagerSnapshot(final ShardManagerSnapshot snapshot) {
1417 currentSnapshot = snapshot;
1419 LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1421 final MemberName currentMember = cluster.getCurrentMemberName();
1422 Set<String> configuredShardList =
1423 new HashSet<>(configuration.getMemberShardNames(currentMember));
1424 for (String shard : currentSnapshot.getShardList()) {
1425 if (!configuredShardList.contains(shard)) {
1426 // add the current member as a replica for the shard
1427 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1428 configuration.addMemberReplicaForShard(shard, currentMember);
1430 configuredShardList.remove(shard);
1433 for (String shard : configuredShardList) {
1434 // remove the member as a replica for the shard
1435 LOG.debug("{}: removing shard {}", persistenceId(), shard);
1436 configuration.removeMemberReplicaForShard(shard, currentMember);
1440 private void onSaveSnapshotSuccess(final SaveSnapshotSuccess successMessage) {
1441 LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1443 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1447 private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1448 LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1450 String shardName = changeMembersVotingStatus.getShardName();
1451 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1452 for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1453 serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1457 ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1459 findLocalShard(shardName, getSender(),
1460 localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1461 localShardFound.getPath(), getSender()));
1464 private void onFlipShardMembersVotingStatus(final FlipShardMembersVotingStatus flipMembersVotingStatus) {
1465 LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1467 ActorRef sender = getSender();
1468 final String shardName = flipMembersVotingStatus.getShardName();
1469 findLocalShard(shardName, sender, localShardFound -> {
1470 Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1471 Timeout.apply(30, TimeUnit.SECONDS));
1473 future.onComplete(new OnComplete<>() {
1475 public void onComplete(final Throwable failure, final Object response) {
1476 if (failure != null) {
1477 sender.tell(new Status.Failure(new RuntimeException(
1478 String.format("Failed to access local shard %s", shardName), failure)), self());
1482 OnDemandRaftState raftState = (OnDemandRaftState) response;
1483 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1484 for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1485 serverVotingStatusMap.put(e.getKey(), !e.getValue());
1488 serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1489 .toString(), !raftState.isVoting());
1491 changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1492 shardName, localShardFound.getPath(), sender);
1494 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1499 private void findLocalShard(final FindLocalShard message) {
1500 LOG.debug("{}: findLocalShard : {}", persistenceId(), message.getShardName());
1502 final ShardInformation shardInformation = localShards.get(message.getShardName());
1504 if (shardInformation == null) {
1505 LOG.debug("{}: Local shard {} not found - shards present: {}",
1506 persistenceId(), message.getShardName(), localShards.keySet());
1508 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1512 sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1513 () -> new LocalShardFound(shardInformation.getActor()));
1516 private void findLocalShard(final String shardName, final ActorRef sender,
1517 final Consumer<LocalShardFound> onLocalShardFound) {
1518 Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1519 .getShardInitializationTimeout().duration().$times(2));
1521 Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1522 futureObj.onComplete(new OnComplete<>() {
1524 public void onComplete(final Throwable failure, final Object response) {
1525 if (failure != null) {
1526 LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1528 sender.tell(new Status.Failure(new RuntimeException(
1529 String.format("Failed to find local shard %s", shardName), failure)), self());
1531 if (response instanceof LocalShardFound) {
1532 getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1534 } else if (response instanceof LocalShardNotFound) {
1535 LOG.debug("{}: Local shard {} does not exist", persistenceId, shardName);
1536 sender.tell(new Status.Failure(new IllegalArgumentException(
1537 String.format("Local shard %s does not exist", shardName))), self());
1539 LOG.debug("{}: Failed to find local shard {}: received response: {}", persistenceId, shardName,
1541 sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response
1542 : new RuntimeException(
1543 String.format("Failed to find local shard %s: received response: %s", shardName,
1544 response))), self());
1548 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1551 private void changeShardMembersVotingStatus(final ChangeServersVotingStatus changeServersVotingStatus,
1552 final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1553 if (isShardReplicaOperationInProgress(shardName, sender)) {
1557 shardReplicaOperationsInProgress.add(shardName);
1559 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1560 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1562 LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1563 changeServersVotingStatus, shardActorRef.path());
1565 Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1566 Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1568 futureObj.onComplete(new OnComplete<>() {
1570 public void onComplete(final Throwable failure, final Object response) {
1571 shardReplicaOperationsInProgress.remove(shardName);
1572 if (failure != null) {
1573 LOG.debug("{}: ChangeServersVotingStatus request to local shard {} failed", persistenceId(),
1574 shardActorRef.path(), failure);
1575 sender.tell(new Status.Failure(new RuntimeException(
1576 String.format("ChangeServersVotingStatus request to local shard %s failed",
1577 shardActorRef.path()), failure)), self());
1579 LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1581 ServerChangeReply replyMsg = (ServerChangeReply) response;
1582 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1583 LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1584 sender.tell(new Status.Success(null), getSelf());
1585 } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1586 sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1587 "The requested voting state change for shard %s is invalid. At least one member "
1588 + "must be voting", shardId.getShardName()))), getSelf());
1590 LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1591 persistenceId(), shardName, replyMsg.getStatus());
1593 Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1594 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1595 sender.tell(new Status.Failure(error), getSelf());
1599 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1602 private static final class ForwardedAddServerReply {
1603 ShardInformation shardInfo;
1604 AddServerReply addServerReply;
1606 boolean removeShardOnFailure;
1608 ForwardedAddServerReply(final ShardInformation shardInfo, final AddServerReply addServerReply,
1609 final String leaderPath, final boolean removeShardOnFailure) {
1610 this.shardInfo = shardInfo;
1611 this.addServerReply = addServerReply;
1612 this.leaderPath = leaderPath;
1613 this.removeShardOnFailure = removeShardOnFailure;
1617 private static final class ForwardedAddServerFailure {
1619 String failureMessage;
1621 boolean removeShardOnFailure;
1623 ForwardedAddServerFailure(final String shardName, final String failureMessage, final Throwable failure,
1624 final boolean removeShardOnFailure) {
1625 this.shardName = shardName;
1626 this.failureMessage = failureMessage;
1627 this.failure = failure;
1628 this.removeShardOnFailure = removeShardOnFailure;
1632 static class OnShardInitialized {
1633 private final Runnable replyRunnable;
1634 private Cancellable timeoutSchedule;
1636 OnShardInitialized(final Runnable replyRunnable) {
1637 this.replyRunnable = replyRunnable;
1640 Runnable getReplyRunnable() {
1641 return replyRunnable;
1644 Cancellable getTimeoutSchedule() {
1645 return timeoutSchedule;
1648 void setTimeoutSchedule(final Cancellable timeoutSchedule) {
1649 this.timeoutSchedule = timeoutSchedule;
1653 static class OnShardReady extends OnShardInitialized {
1654 OnShardReady(final Runnable replyRunnable) {
1655 super(replyRunnable);
1659 private interface RunnableMessage extends Runnable {
1663 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1664 * a remote or local find primary message is processed.
1666 private interface FindPrimaryResponseHandler {
1668 * Invoked when a Failure message is received as a response.
1670 * @param failure the failure exception
1672 void onFailure(Throwable failure);
1675 * Invoked when a RemotePrimaryShardFound response is received.
1677 * @param response the response
1679 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1682 * Invoked when a LocalPrimaryShardFound response is received.
1684 * @param response the response
1686 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1689 * Invoked when an unknown response is received. This is another type of failure.
1691 * @param response the response
1693 void onUnknownResponse(Object response);
1697 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1698 * replica and sends a wrapped Failure response to some targetActor.
1700 private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1701 private final ActorRef targetActor;
1702 private final String shardName;
1703 private final String persistenceId;
1704 private final ActorRef shardManagerActor;
1707 * Constructs an instance.
1709 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1710 * @param shardName The name of the shard for which the primary replica had to be found
1711 * @param persistenceId The persistenceId for the ShardManager
1712 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1714 protected AutoFindPrimaryFailureResponseHandler(final ActorRef targetActor, final String shardName,
1715 final String persistenceId, final ActorRef shardManagerActor) {
1716 this.targetActor = requireNonNull(targetActor);
1717 this.shardName = requireNonNull(shardName);
1718 this.persistenceId = requireNonNull(persistenceId);
1719 this.shardManagerActor = requireNonNull(shardManagerActor);
1722 public ActorRef getTargetActor() {
1726 public String getShardName() {
1731 public void onFailure(final Throwable failure) {
1732 LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1733 targetActor.tell(new Status.Failure(new RuntimeException(
1734 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1738 public void onUnknownResponse(final Object response) {
1739 LOG.debug("{}: Failed to find leader for shard {}: received response: {}", persistenceId, shardName,
1741 targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response
1742 : new RuntimeException(String.format("Failed to find leader for shard %s: received response: %s",
1743 shardName, response))), shardManagerActor);
1748 * The WrappedShardResponse class wraps a response from a Shard.
1750 private static final class WrappedShardResponse {
1751 private final ShardIdentifier shardId;
1752 private final Object response;
1753 private final String leaderPath;
1755 WrappedShardResponse(final ShardIdentifier shardId, final Object response, final String leaderPath) {
1756 this.shardId = shardId;
1757 this.response = response;
1758 this.leaderPath = leaderPath;
1761 ShardIdentifier getShardId() {
1765 Object getResponse() {
1769 String getLeaderPath() {
1774 private static final class ShardNotInitializedTimeout {
1775 private final ActorRef sender;
1776 private final ShardInformation shardInfo;
1777 private final OnShardInitialized onShardInitialized;
1779 ShardNotInitializedTimeout(final ShardInformation shardInfo, final OnShardInitialized onShardInitialized,
1780 final ActorRef sender) {
1781 this.sender = sender;
1782 this.shardInfo = shardInfo;
1783 this.onShardInitialized = onShardInitialized;
1786 ActorRef getSender() {
1790 ShardInformation getShardInfo() {
1794 OnShardInitialized getOnShardInitialized() {
1795 return onShardInitialized;