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.forEach(id -> doCreatePrefixedShard(configs.get(id)));
395 private void resolveUpdates(Set<DOMDataTreeIdentifier> maybeUpdatedConfigs) {
396 LOG.debug("{} ShardManager : {}, resolving potentially updated configs : {}", maybeUpdatedConfigs);
399 private void doRemovePrefixedShard(final DOMDataTreeIdentifier prefix) {
400 LOG.debug("{} ShardManager : {}, removing prefix shard: {}",
401 cluster.getCurrentMemberName(), persistenceId, prefix);
402 final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(), prefix);
403 final ShardInformation shard = localShards.remove(shardId.getShardName());
405 configuration.removePrefixShardConfiguration(prefix);
408 LOG.warn("Received removal for unconfigured shard: {} , ignoring.. ", prefix);
412 if (shard.getActor() != null) {
413 LOG.debug("{} : Sending Shutdown to Shard actor {}", persistenceId(), shard.getActor());
414 shard.getActor().tell(Shutdown.INSTANCE, self());
416 LOG.debug("{} : {} : Local Shard replica for shard {} has been removed", cluster.getCurrentMemberName(),
417 persistenceId(), shardId.getShardName());
421 private void onRemoveServerReply(ActorRef originalSender, ShardIdentifier shardId, RemoveServerReply replyMsg,
423 shardReplicaOperationsInProgress.remove(shardId.getShardName());
425 LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
427 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
428 LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
429 shardId.getShardName());
430 originalSender.tell(new Status.Success(null), getSelf());
432 LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
433 persistenceId(), shardId, replyMsg.getStatus());
435 Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
436 originalSender.tell(new Status.Failure(failure), getSelf());
440 private void removeShardReplica(RemoveShardReplica contextMessage, final String shardName, final String primaryPath,
441 final ActorRef sender) {
442 if (isShardReplicaOperationInProgress(shardName, sender)) {
446 shardReplicaOperationsInProgress.add(shardName);
448 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
450 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
452 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
453 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
454 primaryPath, shardId);
456 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
457 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
458 new RemoveServer(shardId.toString()), removeServerTimeout);
460 futureObj.onComplete(new OnComplete<Object>() {
462 public void onComplete(Throwable failure, Object response) {
463 if (failure != null) {
464 shardReplicaOperationsInProgress.remove(shardName);
465 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
466 primaryPath, shardName);
468 LOG.debug("{}: {}", persistenceId(), msg, failure);
471 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
474 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
477 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
480 private void onShardReplicaRemoved(ServerRemoved message) {
481 final ShardIdentifier shardId = new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build();
482 final ShardInformation shardInformation = localShards.remove(shardId.getShardName());
483 if (shardInformation == null) {
484 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
486 } else if (shardInformation.getActor() != null) {
487 LOG.debug("{} : Sending Shutdown to Shard actor {}", persistenceId(), shardInformation.getActor());
488 shardInformation.getActor().tell(Shutdown.INSTANCE, self());
490 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardId.getShardName());
494 private void onGetSnapshot() {
495 LOG.debug("{}: onGetSnapshot", persistenceId());
497 List<String> notInitialized = null;
498 for (ShardInformation shardInfo : localShards.values()) {
499 if (!shardInfo.isShardInitialized()) {
500 if (notInitialized == null) {
501 notInitialized = new ArrayList<>();
504 notInitialized.add(shardInfo.getShardName());
508 if (notInitialized != null) {
509 getSender().tell(new Status.Failure(new IllegalStateException(String.format(
510 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
514 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
515 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
516 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
518 for (ShardInformation shardInfo: localShards.values()) {
519 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
523 @SuppressWarnings("checkstyle:IllegalCatch")
524 private void onCreatePrefixedShard(final CreatePrefixedShard createPrefixedShard) {
525 LOG.debug("{}: onCreatePrefixedShard: {}", persistenceId(), createPrefixedShard);
529 final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(),
530 createPrefixedShard.getConfig().getPrefix());
531 if (localShards.containsKey(shardId.getShardName())) {
532 LOG.debug("{}: Shard {} already exists", persistenceId(), shardId);
533 reply = new Status.Success(String.format("Shard with name %s already exists", shardId));
535 doCreatePrefixedShard(createPrefixedShard);
536 reply = new Status.Success(null);
538 } catch (final Exception e) {
539 LOG.error("{}: onCreateShard failed", persistenceId(), e);
540 reply = new Status.Failure(e);
543 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
544 getSender().tell(reply, getSelf());
548 @SuppressWarnings("checkstyle:IllegalCatch")
549 private void onCreateShard(CreateShard createShard) {
550 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
554 String shardName = createShard.getModuleShardConfig().getShardName();
555 if (localShards.containsKey(shardName)) {
556 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
557 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
559 doCreateShard(createShard);
560 reply = new Status.Success(null);
562 } catch (Exception e) {
563 LOG.error("{}: onCreateShard failed", persistenceId(), e);
564 reply = new Status.Failure(e);
567 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
568 getSender().tell(reply, getSelf());
572 private void doCreatePrefixedShard(final CreatePrefixedShard createPrefixedShard) {
573 doCreatePrefixedShard(createPrefixedShard.getConfig());
574 // do not replicate on this level
577 private void doCreatePrefixedShard(final PrefixShardConfiguration config) {
578 LOG.debug("doCreatePrefixShard : {}", config.getPrefix());
580 final ShardIdentifier shardId = ClusterUtils.getShardIdentifier(cluster.getCurrentMemberName(),
582 final String shardName = shardId.getShardName();
584 configuration.addPrefixShardConfiguration(config);
586 final Builder builder = newShardDatastoreContextBuilder(shardName);
587 builder.logicalStoreType(LogicalDatastoreType.valueOf(config.getPrefix().getDatastoreType().name()))
588 .storeRoot(config.getPrefix().getRootIdentifier());
589 DatastoreContext shardDatastoreContext = builder.build();
591 final Map<String, String> peerAddresses = Collections.emptyMap();
592 final boolean isActiveMember = true;
593 LOG.debug("{} doCreatePrefixedShard: persistenceId(): {}, memberNames: "
594 + "{}, peerAddresses: {}, isActiveMember: {}",
595 shardId, persistenceId(), config.getShardMemberNames(),
596 peerAddresses, isActiveMember);
598 final ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
599 shardDatastoreContext, Shard.builder(), peerAddressResolver);
600 info.setActiveMember(isActiveMember);
601 localShards.put(info.getShardName(), info);
603 if (schemaContext != null) {
604 info.setActor(newShardActor(schemaContext, info));
610 private void doCreateShard(final CreateShard createShard) {
611 final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
612 final String shardName = moduleShardConfig.getShardName();
614 configuration.addModuleShardConfiguration(moduleShardConfig);
616 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
617 if (shardDatastoreContext == null) {
618 shardDatastoreContext = newShardDatastoreContext(shardName);
620 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
621 peerAddressResolver).build();
624 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
626 boolean shardWasInRecoveredSnapshot = currentSnapshot != null
627 && currentSnapshot.getShardList().contains(shardName);
629 Map<String, String> peerAddresses;
630 boolean isActiveMember;
631 if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
632 .contains(cluster.getCurrentMemberName())) {
633 peerAddresses = getPeerAddresses(shardName);
634 isActiveMember = true;
636 // The local member is not in the static shard member configuration and the shard did not
637 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
638 // the shard with no peers and with elections disabled so it stays as follower. A
639 // subsequent AddServer request will be needed to make it an active member.
640 isActiveMember = false;
641 peerAddresses = Collections.emptyMap();
642 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
643 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
646 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
647 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
650 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
651 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
652 info.setActiveMember(isActiveMember);
653 localShards.put(info.getShardName(), info);
655 if (schemaContext != null) {
656 info.setActor(newShardActor(schemaContext, info));
660 private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
661 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
662 .shardPeerAddressResolver(peerAddressResolver);
665 private DatastoreContext newShardDatastoreContext(String shardName) {
666 return newShardDatastoreContextBuilder(shardName).build();
669 private void checkReady() {
670 if (isReadyWithLeaderId()) {
671 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
672 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
674 waitTillReadyCountdownLatch.countDown();
678 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
679 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
681 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
682 if (shardInformation != null) {
683 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
684 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
685 if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
686 primaryShardInfoCache.remove(shardInformation.getShardName());
691 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
695 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
696 ShardInformation shardInfo = message.getShardInfo();
698 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
699 shardInfo.getShardName());
701 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
703 if (!shardInfo.isShardInitialized()) {
704 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
705 message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
707 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
708 message.getSender().tell(createNoShardLeaderException(shardInfo.getShardId()), getSelf());
712 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
713 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
714 status.getName(), status.isInitialSyncDone());
716 ShardInformation shardInformation = findShardInformation(status.getName());
718 if (shardInformation != null) {
719 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
721 shardManagerMBean.setSyncStatus(isInSync());
726 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
727 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
728 roleChanged.getOldRole(), roleChanged.getNewRole());
730 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
731 if (shardInformation != null) {
732 shardInformation.setRole(roleChanged.getNewRole());
734 shardManagerMBean.setSyncStatus(isInSync());
739 private ShardInformation findShardInformation(String memberId) {
740 for (ShardInformation info : localShards.values()) {
741 if (info.getShardId().toString().equals(memberId)) {
749 private boolean isReadyWithLeaderId() {
750 boolean isReady = true;
751 for (ShardInformation info : localShards.values()) {
752 if (!info.isShardReadyWithLeaderId()) {
760 private boolean isInSync() {
761 for (ShardInformation info : localShards.values()) {
762 if (!info.isInSync()) {
769 private void onActorInitialized(Object message) {
770 final ActorRef sender = getSender();
772 if (sender == null) {
773 return; //why is a non-actor sending this message? Just ignore.
776 String actorName = sender.path().name();
777 //find shard name from actor name; actor name is stringified shardId
779 final ShardIdentifier shardId;
781 shardId = ShardIdentifier.fromShardIdString(actorName);
782 } catch (IllegalArgumentException e) {
783 LOG.debug("{}: ignoring actor {}", actorName, e);
787 markShardAsInitialized(shardId.getShardName());
790 private void markShardAsInitialized(String shardName) {
791 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
793 ShardInformation shardInformation = localShards.get(shardName);
794 if (shardInformation != null) {
795 shardInformation.setActorInitialized();
797 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
802 protected void handleRecover(Object message) throws Exception {
803 if (message instanceof RecoveryCompleted) {
804 onRecoveryCompleted();
805 } else if (message instanceof SnapshotOffer) {
806 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
810 @SuppressWarnings("checkstyle:IllegalCatch")
811 private void onRecoveryCompleted() {
812 LOG.info("Recovery complete : {}", persistenceId());
814 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
815 // journal on upgrade from Helium.
816 deleteMessages(lastSequenceNr());
818 if (currentSnapshot == null && restoreFromSnapshot != null
819 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
820 ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
822 LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
824 applyShardManagerSnapshot(snapshot);
830 private void sendResponse(ShardInformation shardInformation, boolean doWait,
831 boolean wantShardReady, final Supplier<Object> messageSupplier) {
832 if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
834 final ActorRef sender = getSender();
835 final ActorRef self = self();
837 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
839 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
840 new OnShardInitialized(replyRunnable);
842 shardInformation.addOnShardInitialized(onShardInitialized);
844 FiniteDuration timeout = shardInformation.getDatastoreContext()
845 .getShardInitializationTimeout().duration();
846 if (shardInformation.isShardInitialized()) {
847 // If the shard is already initialized then we'll wait enough time for the shard to
848 // elect a leader, ie 2 times the election timeout.
849 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
850 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
853 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
854 shardInformation.getShardName());
856 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
858 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
859 getContext().dispatcher(), getSelf());
861 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
863 } else if (!shardInformation.isShardInitialized()) {
864 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
865 shardInformation.getShardName());
866 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
868 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
869 shardInformation.getShardName());
870 getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
876 getSender().tell(messageSupplier.get(), getSelf());
879 private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
880 return new NoShardLeaderException(null, shardId.toString());
883 private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
884 return new NotInitializedException(String.format(
885 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
889 static MemberName memberToName(final Member member) {
890 return MemberName.forName(member.roles().iterator().next());
893 private void memberRemoved(ClusterEvent.MemberRemoved message) {
894 MemberName memberName = memberToName(message.member());
896 LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
897 message.member().address());
899 peerAddressResolver.removePeerAddress(memberName);
901 for (ShardInformation info : localShards.values()) {
902 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
906 private void memberExited(ClusterEvent.MemberExited message) {
907 MemberName memberName = memberToName(message.member());
909 LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
910 message.member().address());
912 peerAddressResolver.removePeerAddress(memberName);
914 for (ShardInformation info : localShards.values()) {
915 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
919 private void memberUp(ClusterEvent.MemberUp message) {
920 MemberName memberName = memberToName(message.member());
922 LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
923 message.member().address());
925 memberUp(memberName, message.member().address());
928 private void memberUp(MemberName memberName, Address address) {
929 addPeerAddress(memberName, address);
933 private void memberWeaklyUp(MemberWeaklyUp message) {
934 MemberName memberName = memberToName(message.member());
936 LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
937 message.member().address());
939 memberUp(memberName, message.member().address());
942 private void addPeerAddress(MemberName memberName, Address address) {
943 peerAddressResolver.addPeerAddress(memberName, address);
945 for (ShardInformation info : localShards.values()) {
946 String shardName = info.getShardName();
947 String peerId = getShardIdentifier(memberName, shardName).toString();
948 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
950 info.peerUp(memberName, peerId, getSelf());
954 private void memberReachable(ClusterEvent.ReachableMember message) {
955 MemberName memberName = memberToName(message.member());
956 LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
958 addPeerAddress(memberName, message.member().address());
960 markMemberAvailable(memberName);
963 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
964 MemberName memberName = memberToName(message.member());
965 LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
967 markMemberUnavailable(memberName);
970 private void markMemberUnavailable(final MemberName memberName) {
971 final String memberStr = memberName.getName();
972 for (ShardInformation info : localShards.values()) {
973 String leaderId = info.getLeaderId();
974 // XXX: why are we using String#contains() here?
975 if (leaderId != null && leaderId.contains(memberStr)) {
976 LOG.debug("Marking Leader {} as unavailable.", leaderId);
977 info.setLeaderAvailable(false);
979 primaryShardInfoCache.remove(info.getShardName());
982 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
986 private void markMemberAvailable(final MemberName memberName) {
987 final String memberStr = memberName.getName();
988 for (ShardInformation info : localShards.values()) {
989 String leaderId = info.getLeaderId();
990 // XXX: why are we using String#contains() here?
991 if (leaderId != null && leaderId.contains(memberStr)) {
992 LOG.debug("Marking Leader {} as available.", leaderId);
993 info.setLeaderAvailable(true);
996 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1000 private void onDatastoreContextFactory(DatastoreContextFactory factory) {
1001 datastoreContextFactory = factory;
1002 for (ShardInformation info : localShards.values()) {
1003 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
1007 private void onGetLocalShardIds() {
1008 final List<String> response = new ArrayList<>(localShards.size());
1010 for (ShardInformation info : localShards.values()) {
1011 response.add(info.getShardId().toString());
1014 getSender().tell(new Status.Success(response), getSelf());
1017 private void onSwitchShardBehavior(final SwitchShardBehavior message) {
1018 final ShardIdentifier identifier = message.getShardId();
1020 if (identifier != null) {
1021 final ShardInformation info = localShards.get(identifier.getShardName());
1023 getSender().tell(new Status.Failure(
1024 new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
1028 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1030 for (ShardInformation info : localShards.values()) {
1031 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1035 getSender().tell(new Status.Success(null), getSelf());
1038 private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
1039 final ActorRef actor = info.getActor();
1040 if (actor != null) {
1041 actor.tell(switchBehavior, getSelf());
1043 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
1044 info.getShardName(), switchBehavior.getNewState());
1049 * Notifies all the local shards of a change in the schema context.
1051 * @param message the message to send
1053 private void updateSchemaContext(final Object message) {
1054 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
1056 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
1058 for (ShardInformation info : localShards.values()) {
1059 if (info.getActor() == null) {
1060 LOG.debug("Creating Shard {}", info.getShardId());
1061 info.setActor(newShardActor(schemaContext, info));
1063 info.getActor().tell(message, getSelf());
1069 protected ClusterWrapper getCluster() {
1074 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
1075 return getContext().actorOf(info.newProps(schemaContext)
1076 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
1079 private void findPrimary(FindPrimary message) {
1080 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1082 final String shardName = message.getShardName();
1083 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1085 // First see if the there is a local replica for the shard
1086 final ShardInformation info = localShards.get(shardName);
1087 if (info != null && info.isActiveMember()) {
1088 sendResponse(info, message.isWaitUntilReady(), true, () -> {
1089 String primaryPath = info.getSerializedLeaderActor();
1090 Object found = canReturnLocalShardState && info.isLeader()
1091 ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1092 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1094 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1101 final Collection<String> visitedAddresses;
1102 if (message instanceof RemoteFindPrimary) {
1103 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1105 visitedAddresses = new ArrayList<>(1);
1108 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1110 for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1111 if (visitedAddresses.contains(address)) {
1115 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1116 persistenceId(), shardName, address, visitedAddresses);
1118 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1119 message.isWaitUntilReady(), visitedAddresses), getContext());
1123 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1125 getSender().tell(new PrimaryNotFoundException(
1126 String.format("No primary shard found for %s.", shardName)), getSelf());
1129 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1130 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1131 .getShardInitializationTimeout().duration().$times(2));
1133 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1134 futureObj.onComplete(new OnComplete<Object>() {
1136 public void onComplete(Throwable failure, Object response) {
1137 if (failure != null) {
1138 handler.onFailure(failure);
1140 if (response instanceof RemotePrimaryShardFound) {
1141 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1142 } else if (response instanceof LocalPrimaryShardFound) {
1143 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1145 handler.onUnknownResponse(response);
1149 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1153 * Construct the name of the shard actor given the name of the member on
1154 * which the shard resides and the name of the shard.
1156 * @param memberName the member name
1157 * @param shardName the shard name
1160 private ShardIdentifier getShardIdentifier(MemberName memberName, String shardName) {
1161 return peerAddressResolver.getShardIdentifier(memberName, shardName);
1165 * Create shards that are local to the member on which the ShardManager runs.
1167 private void createLocalShards() {
1168 MemberName memberName = this.cluster.getCurrentMemberName();
1169 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1171 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1172 if (restoreFromSnapshot != null) {
1173 for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1174 shardSnapshots.put(snapshot.getName(), snapshot);
1178 restoreFromSnapshot = null; // null out to GC
1180 for (String shardName : memberShardNames) {
1181 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1183 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1185 Map<String, String> peerAddresses = getPeerAddresses(shardName);
1186 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
1187 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
1188 shardSnapshots.get(shardName)), peerAddressResolver));
1193 * Given the name of the shard find the addresses of all it's peers.
1195 * @param shardName the shard name
1197 private Map<String, String> getPeerAddresses(String shardName) {
1198 final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1199 return getPeerAddresses(shardName, members);
1202 private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1203 Map<String, String> peerAddresses = new HashMap<>();
1204 MemberName currentMemberName = this.cluster.getCurrentMemberName();
1206 for (MemberName memberName : members) {
1207 if (!currentMemberName.equals(memberName)) {
1208 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1209 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1210 peerAddresses.put(shardId.toString(), address);
1213 return peerAddresses;
1217 public SupervisorStrategy supervisorStrategy() {
1219 return new OneForOneStrategy(10, Duration.create("1 minute"),
1220 (Function<Throwable, Directive>) t -> {
1221 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1222 return SupervisorStrategy.resume();
1227 public String persistenceId() {
1228 return persistenceId;
1232 ShardManagerInfoMBean getMBean() {
1233 return shardManagerMBean;
1236 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1237 if (shardReplicaOperationsInProgress.contains(shardName)) {
1238 String msg = String.format("A shard replica operation for %s is already in progress", shardName);
1239 LOG.debug("{}: {}", persistenceId(), msg);
1240 sender.tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1248 // With this message the shard does NOT have to be preconfigured
1249 // do a dynamic lookup if the shard exists somewhere and replicate
1250 private void onAddPrefixShardReplica(final AddPrefixShardReplica shardReplicaMsg) {
1251 final String shardName = ClusterUtils.getCleanShardName(shardReplicaMsg.getPrefix());
1253 LOG.debug("{}: onAddPrefixShardReplica: {}", persistenceId(), shardReplicaMsg);
1255 if (schemaContext == null) {
1256 final String msg = String.format(
1257 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1258 LOG.debug("{}: {}", persistenceId(), msg);
1259 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1263 findPrimary(shardName,
1264 new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(), getSelf()) {
1266 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1267 getSelf().tell((RunnableMessage) () -> addShard(getShardName(), response, getSender()),
1272 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1273 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1279 private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1280 final String shardName = shardReplicaMsg.getShardName();
1282 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1284 // verify the shard with the specified name is present in the cluster configuration
1285 if (!this.configuration.isShardConfigured(shardName)) {
1286 String msg = String.format("No module configuration exists for shard %s", shardName);
1287 LOG.debug("{}: {}", persistenceId(), msg);
1288 getSender().tell(new Status.Failure(new IllegalArgumentException(msg)), getSelf());
1292 // Create the localShard
1293 if (schemaContext == null) {
1294 String msg = String.format(
1295 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1296 LOG.debug("{}: {}", persistenceId(), msg);
1297 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1301 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1304 public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1305 getSelf().tell((RunnableMessage) () -> addShard(getShardName(), response, getSender()),
1310 public void onLocalPrimaryFound(LocalPrimaryShardFound message) {
1311 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1317 private void sendLocalReplicaAlreadyExistsReply(String shardName, ActorRef sender) {
1318 String msg = String.format("Local shard %s already exists", shardName);
1319 LOG.debug("{}: {}", persistenceId(), msg);
1320 sender.tell(new Status.Failure(new AlreadyExistsException(msg)), getSelf());
1323 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1324 if (isShardReplicaOperationInProgress(shardName, sender)) {
1328 shardReplicaOperationsInProgress.add(shardName);
1330 final ShardInformation shardInfo;
1331 final boolean removeShardOnFailure;
1332 ShardInformation existingShardInfo = localShards.get(shardName);
1333 if (existingShardInfo == null) {
1334 removeShardOnFailure = true;
1335 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1337 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1338 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1340 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1341 Shard.builder(), peerAddressResolver);
1342 shardInfo.setActiveMember(false);
1343 localShards.put(shardName, shardInfo);
1344 shardInfo.setActor(newShardActor(schemaContext, shardInfo));
1346 removeShardOnFailure = false;
1347 shardInfo = existingShardInfo;
1350 String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1352 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1353 LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1354 response.getPrimaryPath(), shardInfo.getShardId());
1356 Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1357 .getShardLeaderElectionTimeout().duration());
1358 Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1359 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1361 futureObj.onComplete(new OnComplete<Object>() {
1363 public void onComplete(Throwable failure, Object addServerResponse) {
1364 if (failure != null) {
1365 LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1366 response.getPrimaryPath(), shardName, failure);
1368 String msg = String.format("AddServer request to leader %s for shard %s failed",
1369 response.getPrimaryPath(), shardName);
1370 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1372 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1373 response.getPrimaryPath(), removeShardOnFailure), sender);
1376 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1379 private void onAddServerFailure(String shardName, String message, Throwable failure, ActorRef sender,
1380 boolean removeShardOnFailure) {
1381 shardReplicaOperationsInProgress.remove(shardName);
1383 if (removeShardOnFailure) {
1384 ShardInformation shardInfo = localShards.remove(shardName);
1385 if (shardInfo.getActor() != null) {
1386 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1390 sender.tell(new Status.Failure(message == null ? failure :
1391 new RuntimeException(message, failure)), getSelf());
1394 private void onAddServerReply(ShardInformation shardInfo, AddServerReply replyMsg, ActorRef sender,
1395 String leaderPath, boolean removeShardOnFailure) {
1396 String shardName = shardInfo.getShardName();
1397 shardReplicaOperationsInProgress.remove(shardName);
1399 LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1401 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1402 LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1404 // Make the local shard voting capable
1405 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1406 shardInfo.setActiveMember(true);
1409 sender.tell(new Status.Success(null), getSelf());
1410 } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1411 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1413 LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1414 persistenceId(), shardName, replyMsg.getStatus());
1416 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1417 shardInfo.getShardId());
1419 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1423 private static Exception getServerChangeException(Class<?> serverChange, ServerChangeStatus serverChangeStatus,
1424 String leaderPath, ShardIdentifier shardId) {
1426 switch (serverChangeStatus) {
1428 failure = new TimeoutException(String.format(
1429 "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1430 + "Possible causes - there was a problem replicating the data or shard leadership changed "
1431 + "while replicating the shard data", leaderPath, shardId.getShardName()));
1434 failure = createNoShardLeaderException(shardId);
1437 failure = new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1438 serverChange.getSimpleName(), shardId.getShardName()));
1441 failure = new RuntimeException(String.format(
1442 "%s request to leader %s for shard %s failed with status %s",
1443 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1448 private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1449 LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1451 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1452 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1454 public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1455 doRemoveShardReplicaAsync(response.getPrimaryPath());
1459 public void onLocalPrimaryFound(LocalPrimaryShardFound response) {
1460 doRemoveShardReplicaAsync(response.getPrimaryPath());
1463 private void doRemoveShardReplicaAsync(final String primaryPath) {
1464 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1465 primaryPath, getSender()), getTargetActor());
1470 private void persistShardList() {
1471 List<String> shardList = new ArrayList<>(localShards.keySet());
1472 for (ShardInformation shardInfo : localShards.values()) {
1473 if (!shardInfo.isActiveMember()) {
1474 shardList.remove(shardInfo.getShardName());
1477 LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1478 saveSnapshot(updateShardManagerSnapshot(shardList, configuration.getAllPrefixShardConfigurations()));
1481 private ShardManagerSnapshot updateShardManagerSnapshot(
1482 final List<String> shardList,
1483 final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> allPrefixShardConfigurations) {
1484 currentSnapshot = new ShardManagerSnapshot(shardList, allPrefixShardConfigurations);
1485 return currentSnapshot;
1488 private void applyShardManagerSnapshot(ShardManagerSnapshot snapshot) {
1489 currentSnapshot = snapshot;
1491 LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1493 final MemberName currentMember = cluster.getCurrentMemberName();
1494 Set<String> configuredShardList =
1495 new HashSet<>(configuration.getMemberShardNames(currentMember));
1496 for (String shard : currentSnapshot.getShardList()) {
1497 if (!configuredShardList.contains(shard)) {
1498 // add the current member as a replica for the shard
1499 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1500 configuration.addMemberReplicaForShard(shard, currentMember);
1502 configuredShardList.remove(shard);
1505 for (String shard : configuredShardList) {
1506 // remove the member as a replica for the shard
1507 LOG.debug("{}: removing shard {}", persistenceId(), shard);
1508 configuration.removeMemberReplicaForShard(shard, currentMember);
1512 private void onSaveSnapshotSuccess(SaveSnapshotSuccess successMessage) {
1513 LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1515 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1519 private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1520 LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1522 String shardName = changeMembersVotingStatus.getShardName();
1523 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1524 for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1525 serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1529 ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1531 findLocalShard(shardName, getSender(),
1532 localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1533 localShardFound.getPath(), getSender()));
1536 private void onFlipShardMembersVotingStatus(FlipShardMembersVotingStatus flipMembersVotingStatus) {
1537 LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1539 ActorRef sender = getSender();
1540 final String shardName = flipMembersVotingStatus.getShardName();
1541 findLocalShard(shardName, sender, localShardFound -> {
1542 Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1543 Timeout.apply(30, TimeUnit.SECONDS));
1545 future.onComplete(new OnComplete<Object>() {
1547 public void onComplete(Throwable failure, Object response) {
1548 if (failure != null) {
1549 sender.tell(new Status.Failure(new RuntimeException(
1550 String.format("Failed to access local shard %s", shardName), failure)), self());
1554 OnDemandRaftState raftState = (OnDemandRaftState) response;
1555 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1556 for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1557 serverVotingStatusMap.put(e.getKey(), !e.getValue());
1560 serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1561 .toString(), !raftState.isVoting());
1563 changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1564 shardName, localShardFound.getPath(), sender);
1566 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1571 private void findLocalShard(FindLocalShard message) {
1572 final ShardInformation shardInformation = localShards.get(message.getShardName());
1574 if (shardInformation == null) {
1575 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1579 sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1580 () -> new LocalShardFound(shardInformation.getActor()));
1583 private void findLocalShard(final String shardName, final ActorRef sender,
1584 final Consumer<LocalShardFound> onLocalShardFound) {
1585 Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1586 .getShardInitializationTimeout().duration().$times(2));
1588 Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1589 futureObj.onComplete(new OnComplete<Object>() {
1591 public void onComplete(Throwable failure, Object response) {
1592 if (failure != null) {
1593 LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1595 sender.tell(new Status.Failure(new RuntimeException(
1596 String.format("Failed to find local shard %s", shardName), failure)), self());
1598 if (response instanceof LocalShardFound) {
1599 getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1601 } else if (response instanceof LocalShardNotFound) {
1602 String msg = String.format("Local shard %s does not exist", shardName);
1603 LOG.debug("{}: {}", persistenceId, msg);
1604 sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
1606 String msg = String.format("Failed to find local shard %s: received response: %s",
1607 shardName, response);
1608 LOG.debug("{}: {}", persistenceId, msg);
1609 sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1610 new RuntimeException(msg)), self());
1614 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1617 private void changeShardMembersVotingStatus(ChangeServersVotingStatus changeServersVotingStatus,
1618 final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1619 if (isShardReplicaOperationInProgress(shardName, sender)) {
1623 shardReplicaOperationsInProgress.add(shardName);
1625 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1626 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1628 LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1629 changeServersVotingStatus, shardActorRef.path());
1631 Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1632 Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1634 futureObj.onComplete(new OnComplete<Object>() {
1636 public void onComplete(Throwable failure, Object response) {
1637 shardReplicaOperationsInProgress.remove(shardName);
1638 if (failure != null) {
1639 String msg = String.format("ChangeServersVotingStatus request to local shard %s failed",
1640 shardActorRef.path());
1641 LOG.debug("{}: {}", persistenceId(), msg, failure);
1642 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
1644 LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1646 ServerChangeReply replyMsg = (ServerChangeReply) response;
1647 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1648 LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1649 sender.tell(new Status.Success(null), getSelf());
1650 } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1651 sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1652 "The requested voting state change for shard %s is invalid. At least one member "
1653 + "must be voting", shardId.getShardName()))), getSelf());
1655 LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1656 persistenceId(), shardName, replyMsg.getStatus());
1658 Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1659 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1660 sender.tell(new Status.Failure(error), getSelf());
1664 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1667 private static final class ForwardedAddServerReply {
1668 ShardInformation shardInfo;
1669 AddServerReply addServerReply;
1671 boolean removeShardOnFailure;
1673 ForwardedAddServerReply(ShardInformation shardInfo, AddServerReply addServerReply, String leaderPath,
1674 boolean removeShardOnFailure) {
1675 this.shardInfo = shardInfo;
1676 this.addServerReply = addServerReply;
1677 this.leaderPath = leaderPath;
1678 this.removeShardOnFailure = removeShardOnFailure;
1682 private static final class ForwardedAddServerFailure {
1684 String failureMessage;
1686 boolean removeShardOnFailure;
1688 ForwardedAddServerFailure(String shardName, String failureMessage, Throwable failure,
1689 boolean removeShardOnFailure) {
1690 this.shardName = shardName;
1691 this.failureMessage = failureMessage;
1692 this.failure = failure;
1693 this.removeShardOnFailure = removeShardOnFailure;
1697 static class OnShardInitialized {
1698 private final Runnable replyRunnable;
1699 private Cancellable timeoutSchedule;
1701 OnShardInitialized(Runnable replyRunnable) {
1702 this.replyRunnable = replyRunnable;
1705 Runnable getReplyRunnable() {
1706 return replyRunnable;
1709 Cancellable getTimeoutSchedule() {
1710 return timeoutSchedule;
1713 void setTimeoutSchedule(Cancellable timeoutSchedule) {
1714 this.timeoutSchedule = timeoutSchedule;
1718 static class OnShardReady extends OnShardInitialized {
1719 OnShardReady(Runnable replyRunnable) {
1720 super(replyRunnable);
1724 private interface RunnableMessage extends Runnable {
1728 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1729 * a remote or local find primary message is processed.
1731 private interface FindPrimaryResponseHandler {
1733 * Invoked when a Failure message is received as a response.
1735 * @param failure the failure exception
1737 void onFailure(Throwable failure);
1740 * Invoked when a RemotePrimaryShardFound response is received.
1742 * @param response the response
1744 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1747 * Invoked when a LocalPrimaryShardFound response is received.
1749 * @param response the response
1751 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1754 * Invoked when an unknown response is received. This is another type of failure.
1756 * @param response the response
1758 void onUnknownResponse(Object response);
1762 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1763 * replica and sends a wrapped Failure response to some targetActor.
1765 private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1766 private final ActorRef targetActor;
1767 private final String shardName;
1768 private final String persistenceId;
1769 private final ActorRef shardManagerActor;
1772 * Constructs an instance.
1774 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1775 * @param shardName The name of the shard for which the primary replica had to be found
1776 * @param persistenceId The persistenceId for the ShardManager
1777 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1779 protected AutoFindPrimaryFailureResponseHandler(ActorRef targetActor, String shardName, String persistenceId,
1780 ActorRef shardManagerActor) {
1781 this.targetActor = Preconditions.checkNotNull(targetActor);
1782 this.shardName = Preconditions.checkNotNull(shardName);
1783 this.persistenceId = Preconditions.checkNotNull(persistenceId);
1784 this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1787 public ActorRef getTargetActor() {
1791 public String getShardName() {
1796 public void onFailure(Throwable failure) {
1797 LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1798 targetActor.tell(new Status.Failure(new RuntimeException(
1799 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1803 public void onUnknownResponse(Object response) {
1804 String msg = String.format("Failed to find leader for shard %s: received response: %s",
1805 shardName, response);
1806 LOG.debug("{}: {}", persistenceId, msg);
1807 targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1808 new RuntimeException(msg)), shardManagerActor);
1813 * The WrappedShardResponse class wraps a response from a Shard.
1815 private static final class WrappedShardResponse {
1816 private final ShardIdentifier shardId;
1817 private final Object response;
1818 private final String leaderPath;
1820 WrappedShardResponse(ShardIdentifier shardId, Object response, String leaderPath) {
1821 this.shardId = shardId;
1822 this.response = response;
1823 this.leaderPath = leaderPath;
1826 ShardIdentifier getShardId() {
1830 Object getResponse() {
1834 String getLeaderPath() {
1839 private static final class ShardNotInitializedTimeout {
1840 private final ActorRef sender;
1841 private final ShardInformation shardInfo;
1842 private final OnShardInitialized onShardInitialized;
1844 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1845 this.sender = sender;
1846 this.shardInfo = shardInfo;
1847 this.onShardInitialized = onShardInitialized;
1850 ActorRef getSender() {
1854 ShardInformation getShardInfo() {
1858 OnShardInitialized getOnShardInitialized() {
1859 return onShardInitialized;