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.actor.ActorRef.noSender;
12 import static akka.pattern.Patterns.ask;
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.cluster.ddata.DistributedData;
26 import akka.cluster.ddata.ORMap;
27 import akka.cluster.ddata.Replicator.Changed;
28 import akka.cluster.ddata.Replicator.Subscribe;
29 import akka.dispatch.Futures;
30 import akka.dispatch.OnComplete;
31 import akka.japi.Function;
32 import akka.pattern.Patterns;
33 import akka.persistence.RecoveryCompleted;
34 import akka.persistence.SaveSnapshotFailure;
35 import akka.persistence.SaveSnapshotSuccess;
36 import akka.persistence.SnapshotOffer;
37 import akka.persistence.SnapshotSelectionCriteria;
38 import akka.util.Timeout;
39 import com.google.common.annotations.VisibleForTesting;
40 import com.google.common.base.Preconditions;
41 import com.google.common.collect.Sets;
42 import com.google.common.collect.Sets.SetView;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.Collections;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.List;
50 import java.util.Map.Entry;
52 import java.util.concurrent.CountDownLatch;
53 import java.util.concurrent.TimeUnit;
54 import java.util.concurrent.TimeoutException;
55 import java.util.function.Consumer;
56 import java.util.function.Supplier;
57 import java.util.stream.Collectors;
58 import org.opendaylight.controller.cluster.access.concepts.MemberName;
59 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
60 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
61 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
62 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
63 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
64 import org.opendaylight.controller.cluster.datastore.Shard;
65 import org.opendaylight.controller.cluster.datastore.config.Configuration;
66 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
67 import org.opendaylight.controller.cluster.datastore.config.PrefixShardConfiguration;
68 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
69 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
70 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
71 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
72 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
73 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
74 import org.opendaylight.controller.cluster.datastore.messages.AddPrefixShardReplica;
75 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
76 import org.opendaylight.controller.cluster.datastore.messages.ChangeShardMembersVotingStatus;
77 import org.opendaylight.controller.cluster.datastore.messages.CreatePrefixedShard;
78 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
79 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
80 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
81 import org.opendaylight.controller.cluster.datastore.messages.FlipShardMembersVotingStatus;
82 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
83 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
84 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
85 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
86 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
87 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
88 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
89 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
90 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
91 import org.opendaylight.controller.cluster.datastore.persisted.ShardManagerSnapshot;
92 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
93 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
94 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
95 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
96 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
97 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
98 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
99 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
100 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
101 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
102 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
103 import org.opendaylight.controller.cluster.raft.messages.AddServer;
104 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
105 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
106 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
107 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
108 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
109 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
110 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
111 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
112 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
113 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
114 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
115 import org.slf4j.Logger;
116 import org.slf4j.LoggerFactory;
117 import scala.concurrent.ExecutionContext;
118 import scala.concurrent.Future;
119 import scala.concurrent.duration.Duration;
120 import scala.concurrent.duration.FiniteDuration;
123 * Manages the shards for a data store. The ShardManager has the following jobs:
125 * <li> Create all the local shard replicas that belong on this cluster member
126 * <li> Find the address of the local shard
127 * <li> Find the primary replica for any given shard
128 * <li> Monitor the cluster members and store their addresses
131 class ShardManager extends AbstractUntypedPersistentActorWithMetering {
132 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
134 // Stores a mapping between a shard name and it's corresponding information
135 // Shard names look like inventory, topology etc and are as specified in
137 private final Map<String, ShardInformation> localShards = new HashMap<>();
139 // The type of a ShardManager reflects the type of the datastore itself
140 // A data store could be of type config/operational
141 private final String type;
143 private final ClusterWrapper cluster;
145 private final Configuration configuration;
147 private final String shardDispatcherPath;
149 private final ShardManagerInfo shardManagerMBean;
151 private DatastoreContextFactory datastoreContextFactory;
153 private final CountDownLatch waitTillReadyCountdownLatch;
155 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
157 private final ShardPeerAddressResolver peerAddressResolver;
159 private SchemaContext schemaContext;
161 private DatastoreSnapshot restoreFromSnapshot;
163 private ShardManagerSnapshot currentSnapshot;
165 private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
167 private final String persistenceId;
169 private final ActorRef replicator;
171 ShardManager(AbstractShardManagerCreator<?> builder) {
172 this.cluster = builder.getCluster();
173 this.configuration = builder.getConfiguration();
174 this.datastoreContextFactory = builder.getDatastoreContextFactory();
175 this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
176 this.shardDispatcherPath =
177 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
178 this.waitTillReadyCountdownLatch = builder.getWaitTillReadyCountDownLatch();
179 this.primaryShardInfoCache = builder.getPrimaryShardInfoCache();
180 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
182 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
183 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
185 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
187 // Subscribe this actor to cluster member events
188 cluster.subscribeToMemberEvents(getSelf());
190 shardManagerMBean = new ShardManagerInfo(getSelf(), cluster.getCurrentMemberName(),
191 "shard-manager-" + this.type,
192 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
193 shardManagerMBean.registerMBean();
195 replicator = DistributedData.get(context().system()).replicator();
199 public void preStart() {
200 LOG.info("Starting Shardmanager {}", persistenceId);
202 final Subscribe<ORMap<PrefixShardConfiguration>> subscribe =
203 new Subscribe<>(ClusterUtils.CONFIGURATION_KEY, self());
204 replicator.tell(subscribe, noSender());
208 public void postStop() {
209 LOG.info("Stopping ShardManager {}", persistenceId());
211 shardManagerMBean.unregisterMBean();
215 public void handleCommand(Object message) throws Exception {
216 if (message instanceof FindPrimary) {
217 findPrimary((FindPrimary)message);
218 } else if (message instanceof FindLocalShard) {
219 findLocalShard((FindLocalShard) message);
220 } else if (message instanceof UpdateSchemaContext) {
221 updateSchemaContext(message);
222 } else if (message instanceof ActorInitialized) {
223 onActorInitialized(message);
224 } else if (message instanceof ClusterEvent.MemberUp) {
225 memberUp((ClusterEvent.MemberUp) message);
226 } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
227 memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
228 } else if (message instanceof ClusterEvent.MemberExited) {
229 memberExited((ClusterEvent.MemberExited) message);
230 } else if (message instanceof ClusterEvent.MemberRemoved) {
231 memberRemoved((ClusterEvent.MemberRemoved) message);
232 } else if (message instanceof ClusterEvent.UnreachableMember) {
233 memberUnreachable((ClusterEvent.UnreachableMember) message);
234 } else if (message instanceof ClusterEvent.ReachableMember) {
235 memberReachable((ClusterEvent.ReachableMember) message);
236 } else if (message instanceof DatastoreContextFactory) {
237 onDatastoreContextFactory((DatastoreContextFactory) message);
238 } else if (message instanceof RoleChangeNotification) {
239 onRoleChangeNotification((RoleChangeNotification) message);
240 } else if (message instanceof FollowerInitialSyncUpStatus) {
241 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
242 } else if (message instanceof ShardNotInitializedTimeout) {
243 onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
244 } else if (message instanceof ShardLeaderStateChanged) {
245 onLeaderStateChanged((ShardLeaderStateChanged) message);
246 } else if (message instanceof SwitchShardBehavior) {
247 onSwitchShardBehavior((SwitchShardBehavior) message);
248 } else if (message instanceof CreateShard) {
249 onCreateShard((CreateShard)message);
250 } else if (message instanceof AddShardReplica) {
251 onAddShardReplica((AddShardReplica) message);
252 } else if (message instanceof CreatePrefixedShard) {
253 onCreatePrefixedShard((CreatePrefixedShard) message);
254 } else if (message instanceof AddPrefixShardReplica) {
255 onAddPrefixShardReplica((AddPrefixShardReplica) message);
256 } else if (message instanceof ForwardedAddServerReply) {
257 ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
258 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
259 msg.removeShardOnFailure);
260 } else if (message instanceof ForwardedAddServerFailure) {
261 ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
262 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
263 } else if (message instanceof RemoveShardReplica) {
264 onRemoveShardReplica((RemoveShardReplica) message);
265 } else if (message instanceof WrappedShardResponse) {
266 onWrappedShardResponse((WrappedShardResponse) message);
267 } else if (message instanceof GetSnapshot) {
269 } else if (message instanceof ServerRemoved) {
270 onShardReplicaRemoved((ServerRemoved) message);
271 } else if (message instanceof ChangeShardMembersVotingStatus) {
272 onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
273 } else if (message instanceof FlipShardMembersVotingStatus) {
274 onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
275 } else if (message instanceof SaveSnapshotSuccess) {
276 onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
277 } else if (message instanceof SaveSnapshotFailure) {
278 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
279 ((SaveSnapshotFailure) message).cause());
280 } else if (message instanceof Shutdown) {
282 } else if (message instanceof GetLocalShardIds) {
283 onGetLocalShardIds();
284 } else if (message instanceof RunnableMessage) {
285 ((RunnableMessage)message).run();
286 } else if (message instanceof Changed) {
287 onConfigChanged((Changed) message);
289 unknownMessage(message);
293 private void onShutDown() {
294 List<Future<Boolean>> stopFutures = new ArrayList<>(localShards.size());
295 for (ShardInformation info : localShards.values()) {
296 if (info.getActor() != null) {
297 LOG.debug("{}: Issuing gracefulStop to shard {}", persistenceId(), info.getShardId());
299 FiniteDuration duration = info.getDatastoreContext().getShardRaftConfig()
300 .getElectionTimeOutInterval().$times(2);
301 stopFutures.add(Patterns.gracefulStop(info.getActor(), duration, Shutdown.INSTANCE));
305 LOG.info("Shutting down ShardManager {} - waiting on {} shards", persistenceId(), stopFutures.size());
307 ExecutionContext dispatcher = new Dispatchers(context().system().dispatchers())
308 .getDispatcher(Dispatchers.DispatcherType.Client);
309 Future<Iterable<Boolean>> combinedFutures = Futures.sequence(stopFutures, dispatcher);
311 combinedFutures.onComplete(new OnComplete<Iterable<Boolean>>() {
313 public void onComplete(Throwable failure, Iterable<Boolean> results) {
314 LOG.debug("{}: All shards shutdown - sending PoisonPill to self", persistenceId());
316 self().tell(PoisonPill.getInstance(), self());
318 if (failure != null) {
319 LOG.warn("{}: An error occurred attempting to shut down the shards", persistenceId(), failure);
322 for (Boolean result : results) {
329 LOG.warn("{}: {} shards did not shut down gracefully", persistenceId(), nfailed);
336 private void onWrappedShardResponse(WrappedShardResponse message) {
337 if (message.getResponse() instanceof RemoveServerReply) {
338 onRemoveServerReply(getSender(), message.getShardId(), (RemoveServerReply) message.getResponse(),
339 message.getLeaderPath());
343 private void onConfigChanged(final Changed<ORMap<PrefixShardConfiguration>> change) {
344 LOG.debug("{}, ShardManager {} received config changed {}",
345 cluster.getCurrentMemberName(), persistenceId, change.dataValue().getEntries());
347 final Map<String, PrefixShardConfiguration> changedConfig = change.dataValue().getEntries();
349 final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> newConfig =
350 changedConfig.values().stream().collect(
351 Collectors.toMap(PrefixShardConfiguration::getPrefix, java.util.function.Function.identity()));
353 resolveConfig(newConfig);
356 private void resolveConfig(final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> newConfig) {
357 LOG.debug("{} ShardManager : {}, resolving new shard configuration : {}",
358 cluster.getCurrentMemberName(), persistenceId, newConfig);
360 newConfig.forEach((prefix, config) ->
361 LOG.debug("{} ShardManager : {}, received shard config "
362 + "for prefix {}, config {}", cluster.getCurrentMemberName(), persistenceId, prefix, config));
364 final SetView<DOMDataTreeIdentifier> removedConfigs =
365 Sets.difference(configuration.getAllPrefixShardConfigurations().keySet(), newConfig.keySet());
369 resolveRemovals(removedConfigs);
371 final SetView<DOMDataTreeIdentifier> addedConfigs =
372 Sets.difference(newConfig.keySet(), configuration.getAllPrefixShardConfigurations().keySet());
375 resolveAdditions(addedConfigs, newConfig);
376 // iter through to update existing shards, either start/stop replicas or update the shard
377 // to check for more peers
378 resolveUpdates(Collections.emptySet());
381 private void resolveRemovals(final Set<DOMDataTreeIdentifier> removedConfigs) {
382 LOG.debug("{} ShardManager : {}, resolving removed configs : {}",
383 cluster.getCurrentMemberName(), persistenceId, removedConfigs);
385 removedConfigs.forEach(id -> doRemovePrefixedShard(id));
388 private void resolveAdditions(final Set<DOMDataTreeIdentifier> addedConfigs,
389 final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> configs) {
390 LOG.debug("{} ShardManager : {}, resolving added configs : {}", addedConfigs);
392 addedConfigs.stream().filter(identifier
394 .getDatastoreType().equals(
395 ClusterUtils.toMDSalApi(datastoreContextFactory.getBaseDatastoreContext().getLogicalStoreType())))
396 .forEach(id -> doCreatePrefixedShard(configs.get(id)));
399 private void resolveUpdates(Set<DOMDataTreeIdentifier> maybeUpdatedConfigs) {
400 LOG.debug("{} ShardManager : {}, resolving potentially updated configs : {}", maybeUpdatedConfigs);
403 private void doRemovePrefixedShard(final DOMDataTreeIdentifier prefix) {
404 LOG.debug("{} ShardManager : {}, removing prefix shard: {}",
405 cluster.getCurrentMemberName(), persistenceId, prefix);
406 final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(), prefix);
407 final ShardInformation shard = localShards.remove(shardId.getShardName());
409 configuration.removePrefixShardConfiguration(prefix);
412 LOG.warn("Received removal for unconfigured shard: {} , ignoring.. ", prefix);
416 if (shard.getActor() != null) {
417 LOG.debug("{} : Sending Shutdown to Shard actor {}", persistenceId(), shard.getActor());
418 shard.getActor().tell(Shutdown.INSTANCE, self());
420 LOG.debug("{} : {} : Local Shard replica for shard {} has been removed", cluster.getCurrentMemberName(),
421 persistenceId(), shardId.getShardName());
425 private void onRemoveServerReply(ActorRef originalSender, ShardIdentifier shardId, RemoveServerReply replyMsg,
427 shardReplicaOperationsInProgress.remove(shardId.getShardName());
429 LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
431 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
432 LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
433 shardId.getShardName());
434 originalSender.tell(new Status.Success(null), getSelf());
436 LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
437 persistenceId(), shardId, replyMsg.getStatus());
439 Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
440 originalSender.tell(new Status.Failure(failure), getSelf());
444 private void removeShardReplica(RemoveShardReplica contextMessage, final String shardName, final String primaryPath,
445 final ActorRef sender) {
446 if (isShardReplicaOperationInProgress(shardName, sender)) {
450 shardReplicaOperationsInProgress.add(shardName);
452 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
454 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
456 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
457 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
458 primaryPath, shardId);
460 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
461 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
462 new RemoveServer(shardId.toString()), removeServerTimeout);
464 futureObj.onComplete(new OnComplete<Object>() {
466 public void onComplete(Throwable failure, Object response) {
467 if (failure != null) {
468 shardReplicaOperationsInProgress.remove(shardName);
469 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
470 primaryPath, shardName);
472 LOG.debug("{}: {}", persistenceId(), msg, failure);
475 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
478 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
481 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
484 private void onShardReplicaRemoved(ServerRemoved message) {
485 final ShardIdentifier shardId = new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build();
486 final ShardInformation shardInformation = localShards.remove(shardId.getShardName());
487 if (shardInformation == null) {
488 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
490 } else if (shardInformation.getActor() != null) {
491 LOG.debug("{} : Sending Shutdown to Shard actor {}", persistenceId(), shardInformation.getActor());
492 shardInformation.getActor().tell(Shutdown.INSTANCE, self());
494 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardId.getShardName());
498 private void onGetSnapshot() {
499 LOG.debug("{}: onGetSnapshot", persistenceId());
501 List<String> notInitialized = null;
502 for (ShardInformation shardInfo : localShards.values()) {
503 if (!shardInfo.isShardInitialized()) {
504 if (notInitialized == null) {
505 notInitialized = new ArrayList<>();
508 notInitialized.add(shardInfo.getShardName());
512 if (notInitialized != null) {
513 getSender().tell(new Status.Failure(new IllegalStateException(String.format(
514 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
518 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
519 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
520 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
522 for (ShardInformation shardInfo: localShards.values()) {
523 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
527 @SuppressWarnings("checkstyle:IllegalCatch")
528 private void onCreatePrefixedShard(final CreatePrefixedShard createPrefixedShard) {
529 LOG.debug("{}: onCreatePrefixedShard: {}", persistenceId(), createPrefixedShard);
533 final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(),
534 createPrefixedShard.getConfig().getPrefix());
535 if (localShards.containsKey(shardId.getShardName())) {
536 LOG.debug("{}: Shard {} already exists", persistenceId(), shardId);
537 reply = new Status.Success(String.format("Shard with name %s already exists", shardId));
539 doCreatePrefixedShard(createPrefixedShard);
540 reply = new Status.Success(null);
542 } catch (final Exception e) {
543 LOG.error("{}: onCreateShard failed", persistenceId(), e);
544 reply = new Status.Failure(e);
547 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
548 getSender().tell(reply, getSelf());
552 @SuppressWarnings("checkstyle:IllegalCatch")
553 private void onCreateShard(CreateShard createShard) {
554 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
558 String shardName = createShard.getModuleShardConfig().getShardName();
559 if (localShards.containsKey(shardName)) {
560 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
561 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
563 doCreateShard(createShard);
564 reply = new Status.Success(null);
566 } catch (Exception e) {
567 LOG.error("{}: onCreateShard failed", persistenceId(), e);
568 reply = new Status.Failure(e);
571 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
572 getSender().tell(reply, getSelf());
576 private void doCreatePrefixedShard(final CreatePrefixedShard createPrefixedShard) {
577 doCreatePrefixedShard(createPrefixedShard.getConfig());
578 // do not replicate on this level
581 private void doCreatePrefixedShard(final PrefixShardConfiguration config) {
582 LOG.debug("doCreatePrefixShard : {}", config.getPrefix());
584 final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(),
586 final String shardName = shardId.getShardName();
588 if (localShards.containsKey(shardName)) {
589 LOG.debug("{}: Received create for an already existing shard {}", persistenceId(), shardName);
590 final PrefixShardConfiguration existing =
591 configuration.getAllPrefixShardConfigurations().get(config.getPrefix());
593 if (existing != null && existing.equals(config)) {
594 // we don't have to do nothing here
599 configuration.addPrefixShardConfiguration(config);
601 final Builder builder = newShardDatastoreContextBuilder(shardName);
602 builder.logicalStoreType(LogicalDatastoreType.valueOf(config.getPrefix().getDatastoreType().name()))
603 .storeRoot(config.getPrefix().getRootIdentifier());
604 DatastoreContext shardDatastoreContext = builder.build();
606 final Map<String, String> peerAddresses = Collections.emptyMap();
607 final boolean isActiveMember = true;
608 LOG.debug("{} doCreatePrefixedShard: persistenceId(): {}, memberNames: "
609 + "{}, peerAddresses: {}, isActiveMember: {}",
610 shardId, persistenceId(), config.getShardMemberNames(),
611 peerAddresses, isActiveMember);
613 final ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
614 shardDatastoreContext, Shard.builder(), peerAddressResolver);
615 info.setActiveMember(isActiveMember);
616 localShards.put(info.getShardName(), info);
618 if (schemaContext != null) {
619 info.setActor(newShardActor(schemaContext, info));
625 private void doCreateShard(final CreateShard createShard) {
626 final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
627 final String shardName = moduleShardConfig.getShardName();
629 configuration.addModuleShardConfiguration(moduleShardConfig);
631 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
632 if (shardDatastoreContext == null) {
633 shardDatastoreContext = newShardDatastoreContext(shardName);
635 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
636 peerAddressResolver).build();
639 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
641 boolean shardWasInRecoveredSnapshot = currentSnapshot != null
642 && currentSnapshot.getShardList().contains(shardName);
644 Map<String, String> peerAddresses;
645 boolean isActiveMember;
646 if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
647 .contains(cluster.getCurrentMemberName())) {
648 peerAddresses = getPeerAddresses(shardName);
649 isActiveMember = true;
651 // The local member is not in the static shard member configuration and the shard did not
652 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
653 // the shard with no peers and with elections disabled so it stays as follower. A
654 // subsequent AddServer request will be needed to make it an active member.
655 isActiveMember = false;
656 peerAddresses = Collections.emptyMap();
657 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
658 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
661 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
662 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
665 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
666 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
667 info.setActiveMember(isActiveMember);
668 localShards.put(info.getShardName(), info);
670 if (schemaContext != null) {
671 info.setActor(newShardActor(schemaContext, info));
675 private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
676 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
677 .shardPeerAddressResolver(peerAddressResolver);
680 private DatastoreContext newShardDatastoreContext(String shardName) {
681 return newShardDatastoreContextBuilder(shardName).build();
684 private void checkReady() {
685 if (isReadyWithLeaderId()) {
686 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
687 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
689 waitTillReadyCountdownLatch.countDown();
693 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
694 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
696 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
697 if (shardInformation != null) {
698 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
699 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
700 if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
701 primaryShardInfoCache.remove(shardInformation.getShardName());
706 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
710 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
711 ShardInformation shardInfo = message.getShardInfo();
713 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
714 shardInfo.getShardName());
716 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
718 if (!shardInfo.isShardInitialized()) {
719 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
720 message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
722 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
723 message.getSender().tell(createNoShardLeaderException(shardInfo.getShardId()), getSelf());
727 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
728 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
729 status.getName(), status.isInitialSyncDone());
731 ShardInformation shardInformation = findShardInformation(status.getName());
733 if (shardInformation != null) {
734 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
736 shardManagerMBean.setSyncStatus(isInSync());
741 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
742 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
743 roleChanged.getOldRole(), roleChanged.getNewRole());
745 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
746 if (shardInformation != null) {
747 shardInformation.setRole(roleChanged.getNewRole());
749 shardManagerMBean.setSyncStatus(isInSync());
754 private ShardInformation findShardInformation(String memberId) {
755 for (ShardInformation info : localShards.values()) {
756 if (info.getShardId().toString().equals(memberId)) {
764 private boolean isReadyWithLeaderId() {
765 boolean isReady = true;
766 for (ShardInformation info : localShards.values()) {
767 if (!info.isShardReadyWithLeaderId()) {
775 private boolean isInSync() {
776 for (ShardInformation info : localShards.values()) {
777 if (!info.isInSync()) {
784 private void onActorInitialized(Object message) {
785 final ActorRef sender = getSender();
787 if (sender == null) {
788 return; //why is a non-actor sending this message? Just ignore.
791 String actorName = sender.path().name();
792 //find shard name from actor name; actor name is stringified shardId
794 final ShardIdentifier shardId;
796 shardId = ShardIdentifier.fromShardIdString(actorName);
797 } catch (IllegalArgumentException e) {
798 LOG.debug("{}: ignoring actor {}", actorName, e);
802 markShardAsInitialized(shardId.getShardName());
805 private void markShardAsInitialized(String shardName) {
806 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
808 ShardInformation shardInformation = localShards.get(shardName);
809 if (shardInformation != null) {
810 shardInformation.setActorInitialized();
812 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
817 protected void handleRecover(Object message) throws Exception {
818 if (message instanceof RecoveryCompleted) {
819 onRecoveryCompleted();
820 } else if (message instanceof SnapshotOffer) {
821 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
825 @SuppressWarnings("checkstyle:IllegalCatch")
826 private void onRecoveryCompleted() {
827 LOG.info("Recovery complete : {}", persistenceId());
829 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
830 // journal on upgrade from Helium.
831 deleteMessages(lastSequenceNr());
833 if (currentSnapshot == null && restoreFromSnapshot != null
834 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
835 ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
837 LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
839 applyShardManagerSnapshot(snapshot);
845 private void sendResponse(ShardInformation shardInformation, boolean doWait,
846 boolean wantShardReady, final Supplier<Object> messageSupplier) {
847 if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
849 final ActorRef sender = getSender();
850 final ActorRef self = self();
852 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
854 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
855 new OnShardInitialized(replyRunnable);
857 shardInformation.addOnShardInitialized(onShardInitialized);
859 FiniteDuration timeout = shardInformation.getDatastoreContext()
860 .getShardInitializationTimeout().duration();
861 if (shardInformation.isShardInitialized()) {
862 // If the shard is already initialized then we'll wait enough time for the shard to
863 // elect a leader, ie 2 times the election timeout.
864 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
865 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
868 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
869 shardInformation.getShardName());
871 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
873 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
874 getContext().dispatcher(), getSelf());
876 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
878 } else if (!shardInformation.isShardInitialized()) {
879 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
880 shardInformation.getShardName());
881 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
883 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
884 shardInformation.getShardName());
885 getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
891 getSender().tell(messageSupplier.get(), getSelf());
894 private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
895 return new NoShardLeaderException(null, shardId.toString());
898 private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
899 return new NotInitializedException(String.format(
900 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
904 static MemberName memberToName(final Member member) {
905 return MemberName.forName(member.roles().iterator().next());
908 private void memberRemoved(ClusterEvent.MemberRemoved message) {
909 MemberName memberName = memberToName(message.member());
911 LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
912 message.member().address());
914 peerAddressResolver.removePeerAddress(memberName);
916 for (ShardInformation info : localShards.values()) {
917 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
921 private void memberExited(ClusterEvent.MemberExited message) {
922 MemberName memberName = memberToName(message.member());
924 LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
925 message.member().address());
927 peerAddressResolver.removePeerAddress(memberName);
929 for (ShardInformation info : localShards.values()) {
930 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
934 private void memberUp(ClusterEvent.MemberUp message) {
935 MemberName memberName = memberToName(message.member());
937 LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
938 message.member().address());
940 memberUp(memberName, message.member().address());
943 private void memberUp(MemberName memberName, Address address) {
944 addPeerAddress(memberName, address);
948 private void memberWeaklyUp(MemberWeaklyUp message) {
949 MemberName memberName = memberToName(message.member());
951 LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
952 message.member().address());
954 memberUp(memberName, message.member().address());
957 private void addPeerAddress(MemberName memberName, Address address) {
958 peerAddressResolver.addPeerAddress(memberName, address);
960 for (ShardInformation info : localShards.values()) {
961 String shardName = info.getShardName();
962 String peerId = getShardIdentifier(memberName, shardName).toString();
963 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
965 info.peerUp(memberName, peerId, getSelf());
969 private void memberReachable(ClusterEvent.ReachableMember message) {
970 MemberName memberName = memberToName(message.member());
971 LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
973 addPeerAddress(memberName, message.member().address());
975 markMemberAvailable(memberName);
978 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
979 MemberName memberName = memberToName(message.member());
980 LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
982 markMemberUnavailable(memberName);
985 private void markMemberUnavailable(final MemberName memberName) {
986 final String memberStr = memberName.getName();
987 for (ShardInformation info : localShards.values()) {
988 String leaderId = info.getLeaderId();
989 // XXX: why are we using String#contains() here?
990 if (leaderId != null && leaderId.contains(memberStr)) {
991 LOG.debug("Marking Leader {} as unavailable.", leaderId);
992 info.setLeaderAvailable(false);
994 primaryShardInfoCache.remove(info.getShardName());
997 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1001 private void markMemberAvailable(final MemberName memberName) {
1002 final String memberStr = memberName.getName();
1003 for (ShardInformation info : localShards.values()) {
1004 String leaderId = info.getLeaderId();
1005 // XXX: why are we using String#contains() here?
1006 if (leaderId != null && leaderId.contains(memberStr)) {
1007 LOG.debug("Marking Leader {} as available.", leaderId);
1008 info.setLeaderAvailable(true);
1011 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1015 private void onDatastoreContextFactory(DatastoreContextFactory factory) {
1016 datastoreContextFactory = factory;
1017 for (ShardInformation info : localShards.values()) {
1018 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
1022 private void onGetLocalShardIds() {
1023 final List<String> response = new ArrayList<>(localShards.size());
1025 for (ShardInformation info : localShards.values()) {
1026 response.add(info.getShardId().toString());
1029 getSender().tell(new Status.Success(response), getSelf());
1032 private void onSwitchShardBehavior(final SwitchShardBehavior message) {
1033 final ShardIdentifier identifier = message.getShardId();
1035 if (identifier != null) {
1036 final ShardInformation info = localShards.get(identifier.getShardName());
1038 getSender().tell(new Status.Failure(
1039 new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
1043 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1045 for (ShardInformation info : localShards.values()) {
1046 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1050 getSender().tell(new Status.Success(null), getSelf());
1053 private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
1054 final ActorRef actor = info.getActor();
1055 if (actor != null) {
1056 actor.tell(switchBehavior, getSelf());
1058 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
1059 info.getShardName(), switchBehavior.getNewState());
1064 * Notifies all the local shards of a change in the schema context.
1066 * @param message the message to send
1068 private void updateSchemaContext(final Object message) {
1069 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
1071 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
1073 for (ShardInformation info : localShards.values()) {
1074 if (info.getActor() == null) {
1075 LOG.debug("Creating Shard {}", info.getShardId());
1076 info.setActor(newShardActor(schemaContext, info));
1078 info.getActor().tell(message, getSelf());
1084 protected ClusterWrapper getCluster() {
1089 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
1090 return getContext().actorOf(info.newProps(schemaContext)
1091 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
1094 private void findPrimary(FindPrimary message) {
1095 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1097 final String shardName = message.getShardName();
1098 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1100 // First see if the there is a local replica for the shard
1101 final ShardInformation info = localShards.get(shardName);
1102 if (info != null && info.isActiveMember()) {
1103 sendResponse(info, message.isWaitUntilReady(), true, () -> {
1104 String primaryPath = info.getSerializedLeaderActor();
1105 Object found = canReturnLocalShardState && info.isLeader()
1106 ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1107 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1109 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1116 final Collection<String> visitedAddresses;
1117 if (message instanceof RemoteFindPrimary) {
1118 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1120 visitedAddresses = new ArrayList<>(1);
1123 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1125 for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1126 if (visitedAddresses.contains(address)) {
1130 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1131 persistenceId(), shardName, address, visitedAddresses);
1133 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1134 message.isWaitUntilReady(), visitedAddresses), getContext());
1138 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1140 getSender().tell(new PrimaryNotFoundException(
1141 String.format("No primary shard found for %s.", shardName)), getSelf());
1144 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1145 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1146 .getShardInitializationTimeout().duration().$times(2));
1148 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1149 futureObj.onComplete(new OnComplete<Object>() {
1151 public void onComplete(Throwable failure, Object response) {
1152 if (failure != null) {
1153 handler.onFailure(failure);
1155 if (response instanceof RemotePrimaryShardFound) {
1156 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1157 } else if (response instanceof LocalPrimaryShardFound) {
1158 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1160 handler.onUnknownResponse(response);
1164 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1168 * Construct the name of the shard actor given the name of the member on
1169 * which the shard resides and the name of the shard.
1171 * @param memberName the member name
1172 * @param shardName the shard name
1175 private ShardIdentifier getShardIdentifier(MemberName memberName, String shardName) {
1176 return peerAddressResolver.getShardIdentifier(memberName, shardName);
1180 * Create shards that are local to the member on which the ShardManager runs.
1182 private void createLocalShards() {
1183 MemberName memberName = this.cluster.getCurrentMemberName();
1184 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1186 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1187 if (restoreFromSnapshot != null) {
1188 for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1189 shardSnapshots.put(snapshot.getName(), snapshot);
1193 restoreFromSnapshot = null; // null out to GC
1195 for (String shardName : memberShardNames) {
1196 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1198 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1200 Map<String, String> peerAddresses = getPeerAddresses(shardName);
1201 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
1202 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
1203 shardSnapshots.get(shardName)), peerAddressResolver));
1208 * Given the name of the shard find the addresses of all it's peers.
1210 * @param shardName the shard name
1212 private Map<String, String> getPeerAddresses(String shardName) {
1213 final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1214 return getPeerAddresses(shardName, members);
1217 private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1218 Map<String, String> peerAddresses = new HashMap<>();
1219 MemberName currentMemberName = this.cluster.getCurrentMemberName();
1221 for (MemberName memberName : members) {
1222 if (!currentMemberName.equals(memberName)) {
1223 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1224 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1225 peerAddresses.put(shardId.toString(), address);
1228 return peerAddresses;
1232 public SupervisorStrategy supervisorStrategy() {
1234 return new OneForOneStrategy(10, Duration.create("1 minute"),
1235 (Function<Throwable, Directive>) t -> {
1236 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1237 return SupervisorStrategy.resume();
1242 public String persistenceId() {
1243 return persistenceId;
1247 ShardManagerInfoMBean getMBean() {
1248 return shardManagerMBean;
1251 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1252 if (shardReplicaOperationsInProgress.contains(shardName)) {
1253 String msg = String.format("A shard replica operation for %s is already in progress", shardName);
1254 LOG.debug("{}: {}", persistenceId(), msg);
1255 sender.tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1263 // With this message the shard does NOT have to be preconfigured
1264 // do a dynamic lookup if the shard exists somewhere and replicate
1265 private void onAddPrefixShardReplica(final AddPrefixShardReplica shardReplicaMsg) {
1266 final String shardName = ClusterUtils.getCleanShardName(shardReplicaMsg.getPrefix());
1268 LOG.debug("{}: onAddPrefixShardReplica: {}", persistenceId(), shardReplicaMsg);
1270 if (schemaContext == null) {
1271 final String msg = String.format(
1272 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1273 LOG.debug("{}: {}", persistenceId(), msg);
1274 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1278 findPrimary(shardName,
1279 new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(), getSelf()) {
1281 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1282 getSelf().tell((RunnableMessage) () -> addShard(getShardName(), response, getSender()),
1287 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1288 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1294 private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1295 final String shardName = shardReplicaMsg.getShardName();
1297 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1299 // verify the shard with the specified name is present in the cluster configuration
1300 if (!this.configuration.isShardConfigured(shardName)) {
1301 String msg = String.format("No module configuration exists for shard %s", shardName);
1302 LOG.debug("{}: {}", persistenceId(), msg);
1303 getSender().tell(new Status.Failure(new IllegalArgumentException(msg)), getSelf());
1307 // Create the localShard
1308 if (schemaContext == null) {
1309 String msg = String.format(
1310 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1311 LOG.debug("{}: {}", persistenceId(), msg);
1312 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1316 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1319 public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1320 getSelf().tell((RunnableMessage) () -> addShard(getShardName(), response, getSender()),
1325 public void onLocalPrimaryFound(LocalPrimaryShardFound message) {
1326 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1332 private void sendLocalReplicaAlreadyExistsReply(String shardName, ActorRef sender) {
1333 String msg = String.format("Local shard %s already exists", shardName);
1334 LOG.debug("{}: {}", persistenceId(), msg);
1335 sender.tell(new Status.Failure(new AlreadyExistsException(msg)), getSelf());
1338 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1339 if (isShardReplicaOperationInProgress(shardName, sender)) {
1343 shardReplicaOperationsInProgress.add(shardName);
1345 final ShardInformation shardInfo;
1346 final boolean removeShardOnFailure;
1347 ShardInformation existingShardInfo = localShards.get(shardName);
1348 if (existingShardInfo == null) {
1349 removeShardOnFailure = true;
1350 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1352 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1353 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1355 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1356 Shard.builder(), peerAddressResolver);
1357 shardInfo.setActiveMember(false);
1358 localShards.put(shardName, shardInfo);
1359 shardInfo.setActor(newShardActor(schemaContext, shardInfo));
1361 removeShardOnFailure = false;
1362 shardInfo = existingShardInfo;
1365 String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1367 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1368 LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1369 response.getPrimaryPath(), shardInfo.getShardId());
1371 Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1372 .getShardLeaderElectionTimeout().duration());
1373 Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1374 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1376 futureObj.onComplete(new OnComplete<Object>() {
1378 public void onComplete(Throwable failure, Object addServerResponse) {
1379 if (failure != null) {
1380 LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1381 response.getPrimaryPath(), shardName, failure);
1383 String msg = String.format("AddServer request to leader %s for shard %s failed",
1384 response.getPrimaryPath(), shardName);
1385 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1387 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1388 response.getPrimaryPath(), removeShardOnFailure), sender);
1391 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1394 private void onAddServerFailure(String shardName, String message, Throwable failure, ActorRef sender,
1395 boolean removeShardOnFailure) {
1396 shardReplicaOperationsInProgress.remove(shardName);
1398 if (removeShardOnFailure) {
1399 ShardInformation shardInfo = localShards.remove(shardName);
1400 if (shardInfo.getActor() != null) {
1401 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1405 sender.tell(new Status.Failure(message == null ? failure :
1406 new RuntimeException(message, failure)), getSelf());
1409 private void onAddServerReply(ShardInformation shardInfo, AddServerReply replyMsg, ActorRef sender,
1410 String leaderPath, boolean removeShardOnFailure) {
1411 String shardName = shardInfo.getShardName();
1412 shardReplicaOperationsInProgress.remove(shardName);
1414 LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1416 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1417 LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1419 // Make the local shard voting capable
1420 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1421 shardInfo.setActiveMember(true);
1424 sender.tell(new Status.Success(null), getSelf());
1425 } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1426 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1428 LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1429 persistenceId(), shardName, replyMsg.getStatus());
1431 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1432 shardInfo.getShardId());
1434 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1438 private static Exception getServerChangeException(Class<?> serverChange, ServerChangeStatus serverChangeStatus,
1439 String leaderPath, ShardIdentifier shardId) {
1441 switch (serverChangeStatus) {
1443 failure = new TimeoutException(String.format(
1444 "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1445 + "Possible causes - there was a problem replicating the data or shard leadership changed "
1446 + "while replicating the shard data", leaderPath, shardId.getShardName()));
1449 failure = createNoShardLeaderException(shardId);
1452 failure = new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1453 serverChange.getSimpleName(), shardId.getShardName()));
1456 failure = new RuntimeException(String.format(
1457 "%s request to leader %s for shard %s failed with status %s",
1458 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1463 private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1464 LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1466 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1467 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1469 public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1470 doRemoveShardReplicaAsync(response.getPrimaryPath());
1474 public void onLocalPrimaryFound(LocalPrimaryShardFound response) {
1475 doRemoveShardReplicaAsync(response.getPrimaryPath());
1478 private void doRemoveShardReplicaAsync(final String primaryPath) {
1479 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1480 primaryPath, getSender()), getTargetActor());
1485 private void persistShardList() {
1486 List<String> shardList = new ArrayList<>(localShards.keySet());
1487 for (ShardInformation shardInfo : localShards.values()) {
1488 if (!shardInfo.isActiveMember()) {
1489 shardList.remove(shardInfo.getShardName());
1492 LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1493 saveSnapshot(updateShardManagerSnapshot(shardList, configuration.getAllPrefixShardConfigurations()));
1496 private ShardManagerSnapshot updateShardManagerSnapshot(
1497 final List<String> shardList,
1498 final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> allPrefixShardConfigurations) {
1499 currentSnapshot = new ShardManagerSnapshot(shardList, allPrefixShardConfigurations);
1500 return currentSnapshot;
1503 private void applyShardManagerSnapshot(ShardManagerSnapshot snapshot) {
1504 currentSnapshot = snapshot;
1506 LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1508 final MemberName currentMember = cluster.getCurrentMemberName();
1509 Set<String> configuredShardList =
1510 new HashSet<>(configuration.getMemberShardNames(currentMember));
1511 for (String shard : currentSnapshot.getShardList()) {
1512 if (!configuredShardList.contains(shard)) {
1513 // add the current member as a replica for the shard
1514 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1515 configuration.addMemberReplicaForShard(shard, currentMember);
1517 configuredShardList.remove(shard);
1520 for (String shard : configuredShardList) {
1521 // remove the member as a replica for the shard
1522 LOG.debug("{}: removing shard {}", persistenceId(), shard);
1523 configuration.removeMemberReplicaForShard(shard, currentMember);
1527 private void onSaveSnapshotSuccess(SaveSnapshotSuccess successMessage) {
1528 LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1530 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1534 private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1535 LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1537 String shardName = changeMembersVotingStatus.getShardName();
1538 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1539 for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1540 serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1544 ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1546 findLocalShard(shardName, getSender(),
1547 localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1548 localShardFound.getPath(), getSender()));
1551 private void onFlipShardMembersVotingStatus(FlipShardMembersVotingStatus flipMembersVotingStatus) {
1552 LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1554 ActorRef sender = getSender();
1555 final String shardName = flipMembersVotingStatus.getShardName();
1556 findLocalShard(shardName, sender, localShardFound -> {
1557 Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1558 Timeout.apply(30, TimeUnit.SECONDS));
1560 future.onComplete(new OnComplete<Object>() {
1562 public void onComplete(Throwable failure, Object response) {
1563 if (failure != null) {
1564 sender.tell(new Status.Failure(new RuntimeException(
1565 String.format("Failed to access local shard %s", shardName), failure)), self());
1569 OnDemandRaftState raftState = (OnDemandRaftState) response;
1570 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1571 for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1572 serverVotingStatusMap.put(e.getKey(), !e.getValue());
1575 serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1576 .toString(), !raftState.isVoting());
1578 changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1579 shardName, localShardFound.getPath(), sender);
1581 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1586 private void findLocalShard(FindLocalShard message) {
1587 final ShardInformation shardInformation = localShards.get(message.getShardName());
1589 if (shardInformation == null) {
1590 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1594 sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1595 () -> new LocalShardFound(shardInformation.getActor()));
1598 private void findLocalShard(final String shardName, final ActorRef sender,
1599 final Consumer<LocalShardFound> onLocalShardFound) {
1600 Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1601 .getShardInitializationTimeout().duration().$times(2));
1603 Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1604 futureObj.onComplete(new OnComplete<Object>() {
1606 public void onComplete(Throwable failure, Object response) {
1607 if (failure != null) {
1608 LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1610 sender.tell(new Status.Failure(new RuntimeException(
1611 String.format("Failed to find local shard %s", shardName), failure)), self());
1613 if (response instanceof LocalShardFound) {
1614 getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1616 } else if (response instanceof LocalShardNotFound) {
1617 String msg = String.format("Local shard %s does not exist", shardName);
1618 LOG.debug("{}: {}", persistenceId, msg);
1619 sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
1621 String msg = String.format("Failed to find local shard %s: received response: %s",
1622 shardName, response);
1623 LOG.debug("{}: {}", persistenceId, msg);
1624 sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1625 new RuntimeException(msg)), self());
1629 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1632 private void changeShardMembersVotingStatus(ChangeServersVotingStatus changeServersVotingStatus,
1633 final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1634 if (isShardReplicaOperationInProgress(shardName, sender)) {
1638 shardReplicaOperationsInProgress.add(shardName);
1640 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1641 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1643 LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1644 changeServersVotingStatus, shardActorRef.path());
1646 Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1647 Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1649 futureObj.onComplete(new OnComplete<Object>() {
1651 public void onComplete(Throwable failure, Object response) {
1652 shardReplicaOperationsInProgress.remove(shardName);
1653 if (failure != null) {
1654 String msg = String.format("ChangeServersVotingStatus request to local shard %s failed",
1655 shardActorRef.path());
1656 LOG.debug("{}: {}", persistenceId(), msg, failure);
1657 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
1659 LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1661 ServerChangeReply replyMsg = (ServerChangeReply) response;
1662 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1663 LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1664 sender.tell(new Status.Success(null), getSelf());
1665 } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1666 sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1667 "The requested voting state change for shard %s is invalid. At least one member "
1668 + "must be voting", shardId.getShardName()))), getSelf());
1670 LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1671 persistenceId(), shardName, replyMsg.getStatus());
1673 Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1674 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1675 sender.tell(new Status.Failure(error), getSelf());
1679 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1682 private static final class ForwardedAddServerReply {
1683 ShardInformation shardInfo;
1684 AddServerReply addServerReply;
1686 boolean removeShardOnFailure;
1688 ForwardedAddServerReply(ShardInformation shardInfo, AddServerReply addServerReply, String leaderPath,
1689 boolean removeShardOnFailure) {
1690 this.shardInfo = shardInfo;
1691 this.addServerReply = addServerReply;
1692 this.leaderPath = leaderPath;
1693 this.removeShardOnFailure = removeShardOnFailure;
1697 private static final class ForwardedAddServerFailure {
1699 String failureMessage;
1701 boolean removeShardOnFailure;
1703 ForwardedAddServerFailure(String shardName, String failureMessage, Throwable failure,
1704 boolean removeShardOnFailure) {
1705 this.shardName = shardName;
1706 this.failureMessage = failureMessage;
1707 this.failure = failure;
1708 this.removeShardOnFailure = removeShardOnFailure;
1712 static class OnShardInitialized {
1713 private final Runnable replyRunnable;
1714 private Cancellable timeoutSchedule;
1716 OnShardInitialized(Runnable replyRunnable) {
1717 this.replyRunnable = replyRunnable;
1720 Runnable getReplyRunnable() {
1721 return replyRunnable;
1724 Cancellable getTimeoutSchedule() {
1725 return timeoutSchedule;
1728 void setTimeoutSchedule(Cancellable timeoutSchedule) {
1729 this.timeoutSchedule = timeoutSchedule;
1733 static class OnShardReady extends OnShardInitialized {
1734 OnShardReady(Runnable replyRunnable) {
1735 super(replyRunnable);
1739 private interface RunnableMessage extends Runnable {
1743 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1744 * a remote or local find primary message is processed.
1746 private interface FindPrimaryResponseHandler {
1748 * Invoked when a Failure message is received as a response.
1750 * @param failure the failure exception
1752 void onFailure(Throwable failure);
1755 * Invoked when a RemotePrimaryShardFound response is received.
1757 * @param response the response
1759 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1762 * Invoked when a LocalPrimaryShardFound response is received.
1764 * @param response the response
1766 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1769 * Invoked when an unknown response is received. This is another type of failure.
1771 * @param response the response
1773 void onUnknownResponse(Object response);
1777 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1778 * replica and sends a wrapped Failure response to some targetActor.
1780 private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1781 private final ActorRef targetActor;
1782 private final String shardName;
1783 private final String persistenceId;
1784 private final ActorRef shardManagerActor;
1787 * Constructs an instance.
1789 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1790 * @param shardName The name of the shard for which the primary replica had to be found
1791 * @param persistenceId The persistenceId for the ShardManager
1792 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1794 protected AutoFindPrimaryFailureResponseHandler(ActorRef targetActor, String shardName, String persistenceId,
1795 ActorRef shardManagerActor) {
1796 this.targetActor = Preconditions.checkNotNull(targetActor);
1797 this.shardName = Preconditions.checkNotNull(shardName);
1798 this.persistenceId = Preconditions.checkNotNull(persistenceId);
1799 this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1802 public ActorRef getTargetActor() {
1806 public String getShardName() {
1811 public void onFailure(Throwable failure) {
1812 LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1813 targetActor.tell(new Status.Failure(new RuntimeException(
1814 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1818 public void onUnknownResponse(Object response) {
1819 String msg = String.format("Failed to find leader for shard %s: received response: %s",
1820 shardName, response);
1821 LOG.debug("{}: {}", persistenceId, msg);
1822 targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1823 new RuntimeException(msg)), shardManagerActor);
1828 * The WrappedShardResponse class wraps a response from a Shard.
1830 private static final class WrappedShardResponse {
1831 private final ShardIdentifier shardId;
1832 private final Object response;
1833 private final String leaderPath;
1835 WrappedShardResponse(ShardIdentifier shardId, Object response, String leaderPath) {
1836 this.shardId = shardId;
1837 this.response = response;
1838 this.leaderPath = leaderPath;
1841 ShardIdentifier getShardId() {
1845 Object getResponse() {
1849 String getLeaderPath() {
1854 private static final class ShardNotInitializedTimeout {
1855 private final ActorRef sender;
1856 private final ShardInformation shardInfo;
1857 private final OnShardInitialized onShardInitialized;
1859 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1860 this.sender = sender;
1861 this.shardInfo = shardInfo;
1862 this.onShardInitialized = onShardInitialized;
1865 ActorRef getSender() {
1869 ShardInformation getShardInfo() {
1873 OnShardInitialized getOnShardInitialized() {
1874 return onShardInitialized;