2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.datastore.shardmanager;
11 import static akka.pattern.Patterns.ask;
13 import akka.actor.ActorRef;
14 import akka.actor.Address;
15 import akka.actor.Cancellable;
16 import akka.actor.OneForOneStrategy;
17 import akka.actor.PoisonPill;
18 import akka.actor.Status;
19 import akka.actor.SupervisorStrategy;
20 import akka.actor.SupervisorStrategy.Directive;
21 import akka.cluster.ClusterEvent;
22 import akka.cluster.ClusterEvent.MemberWeaklyUp;
23 import akka.cluster.Member;
24 import akka.dispatch.Futures;
25 import akka.dispatch.OnComplete;
26 import akka.japi.Function;
27 import akka.pattern.Patterns;
28 import akka.persistence.DeleteSnapshotsFailure;
29 import akka.persistence.DeleteSnapshotsSuccess;
30 import akka.persistence.RecoveryCompleted;
31 import akka.persistence.SaveSnapshotFailure;
32 import akka.persistence.SaveSnapshotSuccess;
33 import akka.persistence.SnapshotOffer;
34 import akka.persistence.SnapshotSelectionCriteria;
35 import akka.util.Timeout;
36 import com.google.common.annotations.VisibleForTesting;
37 import com.google.common.base.Preconditions;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
45 import java.util.Map.Entry;
47 import java.util.concurrent.CountDownLatch;
48 import java.util.concurrent.TimeUnit;
49 import java.util.concurrent.TimeoutException;
50 import java.util.function.Consumer;
51 import java.util.function.Supplier;
52 import org.opendaylight.controller.cluster.access.concepts.MemberName;
53 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
54 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
55 import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
56 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
57 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
58 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
59 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
60 import org.opendaylight.controller.cluster.datastore.Shard;
61 import org.opendaylight.controller.cluster.datastore.config.Configuration;
62 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
63 import org.opendaylight.controller.cluster.datastore.config.PrefixShardConfiguration;
64 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
65 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
66 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
67 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
68 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
69 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
70 import org.opendaylight.controller.cluster.datastore.messages.AddPrefixShardReplica;
71 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
72 import org.opendaylight.controller.cluster.datastore.messages.ChangeShardMembersVotingStatus;
73 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
74 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
75 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
76 import org.opendaylight.controller.cluster.datastore.messages.FlipShardMembersVotingStatus;
77 import org.opendaylight.controller.cluster.datastore.messages.GetShardRole;
78 import org.opendaylight.controller.cluster.datastore.messages.GetShardRoleReply;
79 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
80 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
81 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
82 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
83 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
84 import org.opendaylight.controller.cluster.datastore.messages.RemovePrefixShardReplica;
85 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
86 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
87 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
88 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
89 import org.opendaylight.controller.cluster.datastore.persisted.ShardManagerSnapshot;
90 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
91 import org.opendaylight.controller.cluster.datastore.utils.CompositeOnComplete;
92 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
93 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
94 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListenerReply;
95 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
96 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
97 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
98 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
99 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
100 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
101 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
102 import org.opendaylight.controller.cluster.raft.messages.AddServer;
103 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
104 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
105 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
106 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
107 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
108 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
109 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
110 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
111 import org.opendaylight.controller.cluster.sharding.PrefixedShardConfigUpdateHandler;
112 import org.opendaylight.controller.cluster.sharding.messages.InitConfigListener;
113 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardCreated;
114 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardRemoved;
115 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
116 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
117 import org.opendaylight.yangtools.concepts.ListenerRegistration;
118 import org.opendaylight.yangtools.concepts.Registration;
119 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
120 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
121 import org.slf4j.Logger;
122 import org.slf4j.LoggerFactory;
123 import scala.concurrent.ExecutionContext;
124 import scala.concurrent.Future;
125 import scala.concurrent.duration.Duration;
126 import scala.concurrent.duration.FiniteDuration;
129 * Manages the shards for a data store. The ShardManager has the following jobs:
131 * <li> Create all the local shard replicas that belong on this cluster member
132 * <li> Find the address of the local shard
133 * <li> Find the primary replica for any given shard
134 * <li> Monitor the cluster members and store their addresses
137 class ShardManager extends AbstractUntypedPersistentActorWithMetering {
138 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
140 // Stores a mapping between a shard name and it's corresponding information
141 // Shard names look like inventory, topology etc and are as specified in
143 private final Map<String, ShardInformation> localShards = new HashMap<>();
145 // The type of a ShardManager reflects the type of the datastore itself
146 // A data store could be of type config/operational
147 private final String type;
149 private final ClusterWrapper cluster;
151 private final Configuration configuration;
153 private final String shardDispatcherPath;
155 private final ShardManagerInfo shardManagerMBean;
157 private DatastoreContextFactory datastoreContextFactory;
159 private final CountDownLatch waitTillReadyCountdownLatch;
161 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
163 private final ShardPeerAddressResolver peerAddressResolver;
165 private SchemaContext schemaContext;
167 private DatastoreSnapshot restoreFromSnapshot;
169 private ShardManagerSnapshot currentSnapshot;
171 private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
173 private final Map<String, CompositeOnComplete<Boolean>> shardActorsStopping = new HashMap<>();
175 private final Set<Consumer<String>> shardAvailabilityCallbacks = new HashSet<>();
177 private final String persistenceId;
178 private final AbstractDataStore dataStore;
180 private ListenerRegistration<DOMDataTreeChangeListener> configListenerReg = null;
181 private PrefixedShardConfigUpdateHandler configUpdateHandler;
183 ShardManager(final AbstractShardManagerCreator<?> builder) {
184 this.cluster = builder.getCluster();
185 this.configuration = builder.getConfiguration();
186 this.datastoreContextFactory = builder.getDatastoreContextFactory();
187 this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
188 this.shardDispatcherPath =
189 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
190 this.waitTillReadyCountdownLatch = builder.getWaitTillReadyCountDownLatch();
191 this.primaryShardInfoCache = builder.getPrimaryShardInfoCache();
192 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
194 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
195 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
197 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
199 // Subscribe this actor to cluster member events
200 cluster.subscribeToMemberEvents(getSelf());
202 shardManagerMBean = new ShardManagerInfo(getSelf(), cluster.getCurrentMemberName(),
203 "shard-manager-" + this.type,
204 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
205 shardManagerMBean.registerMBean();
207 dataStore = builder.getDistributedDataStore();
211 public void preStart() {
212 LOG.info("Starting ShardManager {}", persistenceId);
216 public void postStop() {
217 LOG.info("Stopping ShardManager {}", persistenceId());
219 shardManagerMBean.unregisterMBean();
221 if (configListenerReg != null) {
222 configListenerReg.close();
223 configListenerReg = null;
228 public void handleCommand(final Object message) throws Exception {
229 if (message instanceof FindPrimary) {
230 findPrimary((FindPrimary)message);
231 } else if (message instanceof FindLocalShard) {
232 findLocalShard((FindLocalShard) message);
233 } else if (message instanceof UpdateSchemaContext) {
234 updateSchemaContext(message);
235 } else if (message instanceof ActorInitialized) {
236 onActorInitialized(message);
237 } else if (message instanceof ClusterEvent.MemberUp) {
238 memberUp((ClusterEvent.MemberUp) message);
239 } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
240 memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
241 } else if (message instanceof ClusterEvent.MemberExited) {
242 memberExited((ClusterEvent.MemberExited) message);
243 } else if (message instanceof ClusterEvent.MemberRemoved) {
244 memberRemoved((ClusterEvent.MemberRemoved) message);
245 } else if (message instanceof ClusterEvent.UnreachableMember) {
246 memberUnreachable((ClusterEvent.UnreachableMember) message);
247 } else if (message instanceof ClusterEvent.ReachableMember) {
248 memberReachable((ClusterEvent.ReachableMember) message);
249 } else if (message instanceof DatastoreContextFactory) {
250 onDatastoreContextFactory((DatastoreContextFactory) message);
251 } else if (message instanceof RoleChangeNotification) {
252 onRoleChangeNotification((RoleChangeNotification) message);
253 } else if (message instanceof FollowerInitialSyncUpStatus) {
254 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
255 } else if (message instanceof ShardNotInitializedTimeout) {
256 onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
257 } else if (message instanceof ShardLeaderStateChanged) {
258 onLeaderStateChanged((ShardLeaderStateChanged) message);
259 } else if (message instanceof SwitchShardBehavior) {
260 onSwitchShardBehavior((SwitchShardBehavior) message);
261 } else if (message instanceof CreateShard) {
262 onCreateShard((CreateShard)message);
263 } else if (message instanceof AddShardReplica) {
264 onAddShardReplica((AddShardReplica) message);
265 } else if (message instanceof AddPrefixShardReplica) {
266 onAddPrefixShardReplica((AddPrefixShardReplica) message);
267 } else if (message instanceof PrefixShardCreated) {
268 onPrefixShardCreated((PrefixShardCreated) message);
269 } else if (message instanceof PrefixShardRemoved) {
270 onPrefixShardRemoved((PrefixShardRemoved) message);
271 } else if (message instanceof InitConfigListener) {
272 onInitConfigListener();
273 } else if (message instanceof ForwardedAddServerReply) {
274 ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
275 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
276 msg.removeShardOnFailure);
277 } else if (message instanceof ForwardedAddServerFailure) {
278 ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
279 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
280 } else if (message instanceof RemoveShardReplica) {
281 onRemoveShardReplica((RemoveShardReplica) message);
282 } else if (message instanceof RemovePrefixShardReplica) {
283 onRemovePrefixShardReplica((RemovePrefixShardReplica) message);
284 } else if (message instanceof WrappedShardResponse) {
285 onWrappedShardResponse((WrappedShardResponse) message);
286 } else if (message instanceof GetSnapshot) {
288 } else if (message instanceof ServerRemoved) {
289 onShardReplicaRemoved((ServerRemoved) message);
290 } else if (message instanceof ChangeShardMembersVotingStatus) {
291 onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
292 } else if (message instanceof FlipShardMembersVotingStatus) {
293 onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
294 } else if (message instanceof SaveSnapshotSuccess) {
295 onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
296 } else if (message instanceof SaveSnapshotFailure) {
297 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
298 ((SaveSnapshotFailure) message).cause());
299 } else if (message instanceof Shutdown) {
301 } else if (message instanceof GetLocalShardIds) {
302 onGetLocalShardIds();
303 } else if (message instanceof GetShardRole) {
304 onGetShardRole((GetShardRole) message);
305 } else if (message instanceof RunnableMessage) {
306 ((RunnableMessage)message).run();
307 } else if (message instanceof RegisterForShardAvailabilityChanges) {
308 onRegisterForShardAvailabilityChanges((RegisterForShardAvailabilityChanges)message);
309 } else if (message instanceof DeleteSnapshotsFailure) {
310 LOG.warn("{}: Failed to delete prior snapshots", persistenceId(),
311 ((DeleteSnapshotsFailure) message).cause());
312 } else if (message instanceof DeleteSnapshotsSuccess) {
313 LOG.debug("{}: Successfully deleted prior snapshots", persistenceId(), message);
314 } else if (message instanceof RegisterRoleChangeListenerReply) {
315 LOG.trace("{}: Received RegisterRoleChangeListenerReply", persistenceId());
316 } else if (message instanceof ClusterEvent.MemberEvent) {
317 LOG.trace("{}: Received other ClusterEvent.MemberEvent: {}", persistenceId(), message);
319 unknownMessage(message);
323 private void onRegisterForShardAvailabilityChanges(RegisterForShardAvailabilityChanges message) {
324 LOG.debug("{}: onRegisterForShardAvailabilityChanges: {}", persistenceId(), message);
326 final Consumer<String> callback = message.getCallback();
327 shardAvailabilityCallbacks.add(callback);
329 getSender().tell(new Status.Success((Registration)
330 () -> executeInSelf(() -> shardAvailabilityCallbacks.remove(callback))), self());
333 private void onGetShardRole(final GetShardRole message) {
334 LOG.debug("{}: onGetShardRole for shard: {}", persistenceId(), message.getName());
336 final String name = message.getName();
338 final ShardInformation shardInformation = localShards.get(name);
340 if (shardInformation == null) {
341 LOG.info("{}: no shard information for {} found", persistenceId(), name);
342 getSender().tell(new Status.Failure(
343 new IllegalArgumentException("Shard with name " + name + " not present.")), ActorRef.noSender());
347 getSender().tell(new GetShardRoleReply(shardInformation.getRole()), ActorRef.noSender());
350 private void onInitConfigListener() {
351 LOG.debug("{}: Initializing config listener on {}", persistenceId(), cluster.getCurrentMemberName());
353 final org.opendaylight.mdsal.common.api.LogicalDatastoreType datastoreType =
354 org.opendaylight.mdsal.common.api.LogicalDatastoreType
355 .valueOf(datastoreContextFactory.getBaseDatastoreContext().getLogicalStoreType().name());
357 if (configUpdateHandler != null) {
358 configUpdateHandler.close();
361 configUpdateHandler = new PrefixedShardConfigUpdateHandler(self(), cluster.getCurrentMemberName());
362 configUpdateHandler.initListener(dataStore, datastoreType);
365 private void onShutDown() {
366 List<Future<Boolean>> stopFutures = new ArrayList<>(localShards.size());
367 for (ShardInformation info : localShards.values()) {
368 if (info.getActor() != null) {
369 LOG.debug("{}: Issuing gracefulStop to shard {}", persistenceId(), info.getShardId());
371 FiniteDuration duration = info.getDatastoreContext().getShardRaftConfig()
372 .getElectionTimeOutInterval().$times(2);
373 stopFutures.add(Patterns.gracefulStop(info.getActor(), duration, Shutdown.INSTANCE));
377 LOG.info("Shutting down ShardManager {} - waiting on {} shards", persistenceId(), stopFutures.size());
379 ExecutionContext dispatcher = new Dispatchers(context().system().dispatchers())
380 .getDispatcher(Dispatchers.DispatcherType.Client);
381 Future<Iterable<Boolean>> combinedFutures = Futures.sequence(stopFutures, dispatcher);
383 combinedFutures.onComplete(new OnComplete<Iterable<Boolean>>() {
385 public void onComplete(final Throwable failure, final Iterable<Boolean> results) {
386 LOG.debug("{}: All shards shutdown - sending PoisonPill to self", persistenceId());
388 self().tell(PoisonPill.getInstance(), self());
390 if (failure != null) {
391 LOG.warn("{}: An error occurred attempting to shut down the shards", persistenceId(), failure);
394 for (Boolean result : results) {
401 LOG.warn("{}: {} shards did not shut down gracefully", persistenceId(), nfailed);
408 private void onWrappedShardResponse(final WrappedShardResponse message) {
409 if (message.getResponse() instanceof RemoveServerReply) {
410 onRemoveServerReply(getSender(), message.getShardId(), (RemoveServerReply) message.getResponse(),
411 message.getLeaderPath());
415 private void onRemoveServerReply(final ActorRef originalSender, final ShardIdentifier shardId,
416 final RemoveServerReply replyMsg, final String leaderPath) {
417 shardReplicaOperationsInProgress.remove(shardId.getShardName());
419 LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
421 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
422 LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
423 shardId.getShardName());
424 originalSender.tell(new Status.Success(null), getSelf());
426 LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
427 persistenceId(), shardId, replyMsg.getStatus());
429 Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
430 originalSender.tell(new Status.Failure(failure), getSelf());
434 private void removePrefixShardReplica(final RemovePrefixShardReplica contextMessage, final String shardName,
435 final String primaryPath, final ActorRef sender) {
436 if (isShardReplicaOperationInProgress(shardName, sender)) {
440 shardReplicaOperationsInProgress.add(shardName);
442 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
444 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
446 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
447 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
448 primaryPath, shardId);
450 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
451 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
452 new RemoveServer(shardId.toString()), removeServerTimeout);
454 futureObj.onComplete(new OnComplete<Object>() {
456 public void onComplete(final Throwable failure, final Object response) {
457 if (failure != null) {
458 shardReplicaOperationsInProgress.remove(shardName);
459 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
460 primaryPath, shardName);
462 LOG.debug("{}: {}", persistenceId(), msg, failure);
465 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
468 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
471 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
474 private void removeShardReplica(final RemoveShardReplica contextMessage, final String shardName,
475 final String primaryPath, final ActorRef sender) {
476 if (isShardReplicaOperationInProgress(shardName, sender)) {
480 shardReplicaOperationsInProgress.add(shardName);
482 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
484 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
486 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
487 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
488 primaryPath, shardId);
490 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
491 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
492 new RemoveServer(shardId.toString()), removeServerTimeout);
494 futureObj.onComplete(new OnComplete<Object>() {
496 public void onComplete(final Throwable failure, final Object response) {
497 if (failure != null) {
498 shardReplicaOperationsInProgress.remove(shardName);
499 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
500 primaryPath, shardName);
502 LOG.debug("{}: {}", persistenceId(), msg, failure);
505 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
508 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
511 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
514 private void onShardReplicaRemoved(final ServerRemoved message) {
515 removeShard(new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build());
518 @SuppressWarnings("checkstyle:IllegalCatch")
519 private void removeShard(final ShardIdentifier shardId) {
520 final String shardName = shardId.getShardName();
521 final ShardInformation shardInformation = localShards.remove(shardName);
522 if (shardInformation == null) {
523 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
527 final ActorRef shardActor = shardInformation.getActor();
528 if (shardActor != null) {
529 long timeoutInMS = Math.max(shardInformation.getDatastoreContext().getShardRaftConfig()
530 .getElectionTimeOutInterval().$times(3).toMillis(), 10000);
532 LOG.debug("{} : Sending Shutdown to Shard actor {} with {} ms timeout", persistenceId(), shardActor,
535 final Future<Boolean> stopFuture = Patterns.gracefulStop(shardActor,
536 FiniteDuration.apply(timeoutInMS, TimeUnit.MILLISECONDS), Shutdown.INSTANCE);
538 final CompositeOnComplete<Boolean> onComplete = new CompositeOnComplete<Boolean>() {
540 public void onComplete(final Throwable failure, final Boolean result) {
541 if (failure == null) {
542 LOG.debug("{} : Successfully shut down Shard actor {}", persistenceId(), shardActor);
544 LOG.warn("{}: Failed to shut down Shard actor {}", persistenceId(), shardActor, failure);
547 self().tell((RunnableMessage) () -> {
548 // At any rate, invalidate primaryShardInfo cache
549 primaryShardInfoCache.remove(shardName);
551 shardActorsStopping.remove(shardName);
552 notifyOnCompleteTasks(failure, result);
553 }, ActorRef.noSender());
557 shardActorsStopping.put(shardName, onComplete);
558 stopFuture.onComplete(onComplete, new Dispatchers(context().system().dispatchers())
559 .getDispatcher(Dispatchers.DispatcherType.Client));
562 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardName);
566 private void onGetSnapshot() {
567 LOG.debug("{}: onGetSnapshot", persistenceId());
569 List<String> notInitialized = null;
570 for (ShardInformation shardInfo : localShards.values()) {
571 if (!shardInfo.isShardInitialized()) {
572 if (notInitialized == null) {
573 notInitialized = new ArrayList<>();
576 notInitialized.add(shardInfo.getShardName());
580 if (notInitialized != null) {
581 getSender().tell(new Status.Failure(new IllegalStateException(String.format(
582 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
586 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
587 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
588 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
590 for (ShardInformation shardInfo: localShards.values()) {
591 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
595 @SuppressWarnings("checkstyle:IllegalCatch")
596 private void onCreateShard(final CreateShard createShard) {
597 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
601 String shardName = createShard.getModuleShardConfig().getShardName();
602 if (localShards.containsKey(shardName)) {
603 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
604 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
606 doCreateShard(createShard);
607 reply = new Status.Success(null);
609 } catch (Exception e) {
610 LOG.error("{}: onCreateShard failed", persistenceId(), e);
611 reply = new Status.Failure(e);
614 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
615 getSender().tell(reply, getSelf());
619 private void onPrefixShardCreated(final PrefixShardCreated message) {
620 LOG.debug("{}: onPrefixShardCreated: {}", persistenceId(), message);
622 final PrefixShardConfiguration config = message.getConfiguration();
623 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
624 ClusterUtils.getCleanShardName(config.getPrefix().getRootIdentifier()));
625 final String shardName = shardId.getShardName();
627 if (isPreviousShardActorStopInProgress(shardName, message)) {
631 if (localShards.containsKey(shardName)) {
632 LOG.debug("{}: Received create for an already existing shard {}", persistenceId(), shardName);
633 final PrefixShardConfiguration existing =
634 configuration.getAllPrefixShardConfigurations().get(config.getPrefix());
636 if (existing != null && existing.equals(config)) {
637 // we don't have to do nothing here
642 doCreatePrefixShard(config, shardId, shardName);
645 private boolean isPreviousShardActorStopInProgress(final String shardName, final Object messageToDefer) {
646 final CompositeOnComplete<Boolean> stopOnComplete = shardActorsStopping.get(shardName);
647 if (stopOnComplete == null) {
651 LOG.debug("{} : Stop is in progress for shard {} - adding OnComplete callback to defer {}", persistenceId(),
652 shardName, messageToDefer);
653 final ActorRef sender = getSender();
654 stopOnComplete.addOnComplete(new OnComplete<Boolean>() {
656 public void onComplete(final Throwable failure, final Boolean result) {
657 LOG.debug("{} : Stop complete for shard {} - re-queing {}", persistenceId(), shardName, messageToDefer);
658 self().tell(messageToDefer, sender);
665 private void doCreatePrefixShard(final PrefixShardConfiguration config, final ShardIdentifier shardId,
666 final String shardName) {
667 configuration.addPrefixShardConfiguration(config);
669 final Builder builder = newShardDatastoreContextBuilder(shardName);
670 builder.logicalStoreType(config.getPrefix().getDatastoreType())
671 .storeRoot(config.getPrefix().getRootIdentifier());
672 DatastoreContext shardDatastoreContext = builder.build();
674 final Map<String, String> peerAddresses = getPeerAddresses(shardName);
675 final boolean isActiveMember = true;
677 LOG.debug("{} doCreatePrefixShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
678 persistenceId(), shardId, config.getShardMemberNames(), peerAddresses, isActiveMember);
680 final ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
681 shardDatastoreContext, Shard.builder(), peerAddressResolver);
682 info.setActiveMember(isActiveMember);
683 localShards.put(info.getShardName(), info);
685 if (schemaContext != null) {
686 info.setSchemaContext(schemaContext);
687 info.setActor(newShardActor(info));
691 private void onPrefixShardRemoved(final PrefixShardRemoved message) {
692 LOG.debug("{}: onPrefixShardRemoved : {}", persistenceId(), message);
694 final DOMDataTreeIdentifier prefix = message.getPrefix();
695 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
696 ClusterUtils.getCleanShardName(prefix.getRootIdentifier()));
698 configuration.removePrefixShardConfiguration(prefix);
699 removeShard(shardId);
702 private void doCreateShard(final CreateShard createShard) {
703 final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
704 final String shardName = moduleShardConfig.getShardName();
706 configuration.addModuleShardConfiguration(moduleShardConfig);
708 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
709 if (shardDatastoreContext == null) {
710 shardDatastoreContext = newShardDatastoreContext(shardName);
712 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
713 peerAddressResolver).build();
716 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
718 boolean shardWasInRecoveredSnapshot = currentSnapshot != null
719 && currentSnapshot.getShardList().contains(shardName);
721 Map<String, String> peerAddresses;
722 boolean isActiveMember;
723 if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
724 .contains(cluster.getCurrentMemberName())) {
725 peerAddresses = getPeerAddresses(shardName);
726 isActiveMember = true;
728 // The local member is not in the static shard member configuration and the shard did not
729 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
730 // the shard with no peers and with elections disabled so it stays as follower. A
731 // subsequent AddServer request will be needed to make it an active member.
732 isActiveMember = false;
733 peerAddresses = Collections.emptyMap();
734 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
735 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
738 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
739 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
742 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
743 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
744 info.setActiveMember(isActiveMember);
745 localShards.put(info.getShardName(), info);
747 if (schemaContext != null) {
748 info.setSchemaContext(schemaContext);
749 info.setActor(newShardActor(info));
753 private DatastoreContext.Builder newShardDatastoreContextBuilder(final String shardName) {
754 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
755 .shardPeerAddressResolver(peerAddressResolver);
758 private DatastoreContext newShardDatastoreContext(final String shardName) {
759 return newShardDatastoreContextBuilder(shardName).build();
762 private void checkReady() {
763 if (isReadyWithLeaderId()) {
764 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
765 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
767 waitTillReadyCountdownLatch.countDown();
771 private void onLeaderStateChanged(final ShardLeaderStateChanged leaderStateChanged) {
772 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
774 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
775 if (shardInformation != null) {
776 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
777 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
778 if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
779 primaryShardInfoCache.remove(shardInformation.getShardName());
781 notifyShardAvailabilityCallbacks(shardInformation);
786 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
790 private void notifyShardAvailabilityCallbacks(ShardInformation shardInformation) {
791 shardAvailabilityCallbacks.forEach(callback -> callback.accept(shardInformation.getShardName()));
794 private void onShardNotInitializedTimeout(final ShardNotInitializedTimeout message) {
795 ShardInformation shardInfo = message.getShardInfo();
797 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
798 shardInfo.getShardName());
800 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
802 if (!shardInfo.isShardInitialized()) {
803 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
804 message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
806 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
807 message.getSender().tell(createNoShardLeaderException(shardInfo.getShardId()), getSelf());
811 private void onFollowerInitialSyncStatus(final FollowerInitialSyncUpStatus status) {
812 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
813 status.getName(), status.isInitialSyncDone());
815 ShardInformation shardInformation = findShardInformation(status.getName());
817 if (shardInformation != null) {
818 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
820 shardManagerMBean.setSyncStatus(isInSync());
825 private void onRoleChangeNotification(final RoleChangeNotification roleChanged) {
826 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
827 roleChanged.getOldRole(), roleChanged.getNewRole());
829 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
830 if (shardInformation != null) {
831 shardInformation.setRole(roleChanged.getNewRole());
833 shardManagerMBean.setSyncStatus(isInSync());
838 private ShardInformation findShardInformation(final String memberId) {
839 for (ShardInformation info : localShards.values()) {
840 if (info.getShardId().toString().equals(memberId)) {
848 private boolean isReadyWithLeaderId() {
849 boolean isReady = true;
850 for (ShardInformation info : localShards.values()) {
851 if (!info.isShardReadyWithLeaderId()) {
859 private boolean isInSync() {
860 for (ShardInformation info : localShards.values()) {
861 if (!info.isInSync()) {
868 private void onActorInitialized(final Object message) {
869 final ActorRef sender = getSender();
871 if (sender == null) {
872 // why is a non-actor sending this message? Just ignore.
876 String actorName = sender.path().name();
877 //find shard name from actor name; actor name is stringified shardId
879 final ShardIdentifier shardId;
881 shardId = ShardIdentifier.fromShardIdString(actorName);
882 } catch (IllegalArgumentException e) {
883 LOG.debug("{}: ignoring actor {}", actorName, e);
887 markShardAsInitialized(shardId.getShardName());
890 private void markShardAsInitialized(final String shardName) {
891 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
893 ShardInformation shardInformation = localShards.get(shardName);
894 if (shardInformation != null) {
895 shardInformation.setActorInitialized();
897 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
902 protected void handleRecover(final Object message) throws Exception {
903 if (message instanceof RecoveryCompleted) {
904 onRecoveryCompleted();
905 } else if (message instanceof SnapshotOffer) {
906 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
910 @SuppressWarnings("checkstyle:IllegalCatch")
911 private void onRecoveryCompleted() {
912 LOG.info("Recovery complete : {}", persistenceId());
914 if (currentSnapshot == null && restoreFromSnapshot != null
915 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
916 ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
918 LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
920 applyShardManagerSnapshot(snapshot);
926 private void sendResponse(final ShardInformation shardInformation, final boolean doWait,
927 final boolean wantShardReady, final Supplier<Object> messageSupplier) {
928 if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
930 final ActorRef sender = getSender();
931 final ActorRef self = self();
933 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
935 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
936 new OnShardInitialized(replyRunnable);
938 shardInformation.addOnShardInitialized(onShardInitialized);
940 FiniteDuration timeout = shardInformation.getDatastoreContext()
941 .getShardInitializationTimeout().duration();
942 if (shardInformation.isShardInitialized()) {
943 // If the shard is already initialized then we'll wait enough time for the shard to
944 // elect a leader, ie 2 times the election timeout.
945 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
946 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
949 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
952 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
954 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
955 getContext().dispatcher(), getSelf());
957 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
959 } else if (!shardInformation.isShardInitialized()) {
960 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
961 shardInformation.getShardName());
962 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
964 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
965 shardInformation.getShardName());
966 getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
972 getSender().tell(messageSupplier.get(), getSelf());
975 private static NoShardLeaderException createNoShardLeaderException(final ShardIdentifier shardId) {
976 return new NoShardLeaderException(null, shardId.toString());
979 private static NotInitializedException createNotInitializedException(final ShardIdentifier shardId) {
980 return new NotInitializedException(String.format(
981 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
985 static MemberName memberToName(final Member member) {
986 return MemberName.forName(member.roles().iterator().next());
989 private void memberRemoved(final ClusterEvent.MemberRemoved message) {
990 MemberName memberName = memberToName(message.member());
992 LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
993 message.member().address());
995 peerAddressResolver.removePeerAddress(memberName);
997 for (ShardInformation info : localShards.values()) {
998 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1002 private void memberExited(final ClusterEvent.MemberExited message) {
1003 MemberName memberName = memberToName(message.member());
1005 LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
1006 message.member().address());
1008 peerAddressResolver.removePeerAddress(memberName);
1010 for (ShardInformation info : localShards.values()) {
1011 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1015 private void memberUp(final ClusterEvent.MemberUp message) {
1016 MemberName memberName = memberToName(message.member());
1018 LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
1019 message.member().address());
1021 memberUp(memberName, message.member().address());
1024 private void memberUp(final MemberName memberName, final Address address) {
1025 addPeerAddress(memberName, address);
1029 private void memberWeaklyUp(final MemberWeaklyUp message) {
1030 MemberName memberName = memberToName(message.member());
1032 LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
1033 message.member().address());
1035 memberUp(memberName, message.member().address());
1038 private void addPeerAddress(final MemberName memberName, final Address address) {
1039 peerAddressResolver.addPeerAddress(memberName, address);
1041 for (ShardInformation info : localShards.values()) {
1042 String shardName = info.getShardName();
1043 String peerId = getShardIdentifier(memberName, shardName).toString();
1044 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
1046 info.peerUp(memberName, peerId, getSelf());
1050 private void memberReachable(final ClusterEvent.ReachableMember message) {
1051 MemberName memberName = memberToName(message.member());
1052 LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
1054 addPeerAddress(memberName, message.member().address());
1056 markMemberAvailable(memberName);
1059 private void memberUnreachable(final ClusterEvent.UnreachableMember message) {
1060 MemberName memberName = memberToName(message.member());
1061 LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
1063 markMemberUnavailable(memberName);
1066 private void markMemberUnavailable(final MemberName memberName) {
1067 for (ShardInformation info : localShards.values()) {
1068 String leaderId = info.getLeaderId();
1069 if (leaderId != null && ShardIdentifier.fromShardIdString(leaderId).getMemberName().equals(memberName)) {
1070 LOG.debug("Marking Leader {} as unavailable.", leaderId);
1071 info.setLeaderAvailable(false);
1073 primaryShardInfoCache.remove(info.getShardName());
1075 notifyShardAvailabilityCallbacks(info);
1078 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1082 private void markMemberAvailable(final MemberName memberName) {
1083 for (ShardInformation info : localShards.values()) {
1084 String leaderId = info.getLeaderId();
1085 if (leaderId != null && ShardIdentifier.fromShardIdString(leaderId).getMemberName().equals(memberName)) {
1086 LOG.debug("Marking Leader {} as available.", leaderId);
1087 info.setLeaderAvailable(true);
1090 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1094 private void onDatastoreContextFactory(final DatastoreContextFactory factory) {
1095 datastoreContextFactory = factory;
1096 for (ShardInformation info : localShards.values()) {
1097 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
1101 private void onGetLocalShardIds() {
1102 final List<String> response = new ArrayList<>(localShards.size());
1104 for (ShardInformation info : localShards.values()) {
1105 response.add(info.getShardId().toString());
1108 getSender().tell(new Status.Success(response), getSelf());
1111 private void onSwitchShardBehavior(final SwitchShardBehavior message) {
1112 final ShardIdentifier identifier = message.getShardId();
1114 if (identifier != null) {
1115 final ShardInformation info = localShards.get(identifier.getShardName());
1117 getSender().tell(new Status.Failure(
1118 new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
1122 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1124 for (ShardInformation info : localShards.values()) {
1125 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1129 getSender().tell(new Status.Success(null), getSelf());
1132 private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
1133 final ActorRef actor = info.getActor();
1134 if (actor != null) {
1135 actor.tell(switchBehavior, getSelf());
1137 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
1138 info.getShardName(), switchBehavior.getNewState());
1143 * Notifies all the local shards of a change in the schema context.
1145 * @param message the message to send
1147 private void updateSchemaContext(final Object message) {
1148 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
1150 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getModules().size());
1152 for (ShardInformation info : localShards.values()) {
1153 info.setSchemaContext(schemaContext);
1155 if (info.getActor() == null) {
1156 LOG.debug("Creating Shard {}", info.getShardId());
1157 info.setActor(newShardActor(info));
1158 // Update peer address for every existing peer memeber to avoid missing sending
1159 // PeerAddressResolved and PeerUp to this shard while UpdateSchemaContext comes after MemberUp.
1160 String shardName = info.getShardName();
1161 for (MemberName memberName : peerAddressResolver.getPeerMembers()) {
1162 String peerId = getShardIdentifier(memberName, shardName).toString() ;
1163 String peerAddress = peerAddressResolver.getShardActorAddress(shardName, memberName);
1164 info.updatePeerAddress(peerId, peerAddress, getSelf());
1165 info.peerUp(memberName, peerId, getSelf());
1166 LOG.debug("{}: updated peer {} on member {} with address {} on shard {} whose actor address is {}",
1167 persistenceId(), peerId, memberName, peerAddress, info.getShardId(), info.getActor());
1170 info.getActor().tell(message, getSelf());
1176 protected ClusterWrapper getCluster() {
1181 protected ActorRef newShardActor(final ShardInformation info) {
1182 return getContext().actorOf(info.newProps().withDispatcher(shardDispatcherPath),
1183 info.getShardId().toString());
1186 private void findPrimary(final FindPrimary message) {
1187 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1189 final String shardName = message.getShardName();
1190 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1192 // First see if the there is a local replica for the shard
1193 final ShardInformation info = localShards.get(shardName);
1194 if (info != null && info.isActiveMember()) {
1195 sendResponse(info, message.isWaitUntilReady(), true, () -> {
1196 String primaryPath = info.getSerializedLeaderActor();
1197 Object found = canReturnLocalShardState && info.isLeader()
1198 ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1199 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1201 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1208 final Collection<String> visitedAddresses;
1209 if (message instanceof RemoteFindPrimary) {
1210 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1212 visitedAddresses = new ArrayList<>(1);
1215 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1217 for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1218 if (visitedAddresses.contains(address)) {
1222 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1223 persistenceId(), shardName, address, visitedAddresses);
1225 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1226 message.isWaitUntilReady(), visitedAddresses), getContext());
1230 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1232 getSender().tell(new PrimaryNotFoundException(
1233 String.format("No primary shard found for %s.", shardName)), getSelf());
1236 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1237 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1238 .getShardInitializationTimeout().duration().$times(2));
1240 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1241 futureObj.onComplete(new OnComplete<Object>() {
1243 public void onComplete(final Throwable failure, final Object response) {
1244 if (failure != null) {
1245 handler.onFailure(failure);
1247 if (response instanceof RemotePrimaryShardFound) {
1248 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1249 } else if (response instanceof LocalPrimaryShardFound) {
1250 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1252 handler.onUnknownResponse(response);
1256 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1260 * Construct the name of the shard actor given the name of the member on
1261 * which the shard resides and the name of the shard.
1263 * @param memberName the member name
1264 * @param shardName the shard name
1267 private ShardIdentifier getShardIdentifier(final MemberName memberName, final String shardName) {
1268 return peerAddressResolver.getShardIdentifier(memberName, shardName);
1272 * Create shards that are local to the member on which the ShardManager runs.
1274 private void createLocalShards() {
1275 MemberName memberName = this.cluster.getCurrentMemberName();
1276 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1278 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1279 if (restoreFromSnapshot != null) {
1280 for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1281 shardSnapshots.put(snapshot.getName(), snapshot);
1286 restoreFromSnapshot = null;
1288 for (String shardName : memberShardNames) {
1289 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1291 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1293 Map<String, String> peerAddresses = getPeerAddresses(shardName);
1294 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
1295 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
1296 shardSnapshots.get(shardName)), peerAddressResolver));
1301 * Given the name of the shard find the addresses of all it's peers.
1303 * @param shardName the shard name
1305 private Map<String, String> getPeerAddresses(final String shardName) {
1306 final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1307 return getPeerAddresses(shardName, members);
1310 private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1311 Map<String, String> peerAddresses = new HashMap<>();
1312 MemberName currentMemberName = this.cluster.getCurrentMemberName();
1314 for (MemberName memberName : members) {
1315 if (!currentMemberName.equals(memberName)) {
1316 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1317 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1318 peerAddresses.put(shardId.toString(), address);
1321 return peerAddresses;
1325 public SupervisorStrategy supervisorStrategy() {
1327 return new OneForOneStrategy(10, Duration.create("1 minute"),
1328 (Function<Throwable, Directive>) t -> {
1329 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1330 return SupervisorStrategy.resume();
1335 public String persistenceId() {
1336 return persistenceId;
1340 ShardManagerInfoMBean getMBean() {
1341 return shardManagerMBean;
1344 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1345 if (shardReplicaOperationsInProgress.contains(shardName)) {
1346 String msg = String.format("A shard replica operation for %s is already in progress", shardName);
1347 LOG.debug("{}: {}", persistenceId(), msg);
1348 sender.tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1355 private void onAddPrefixShardReplica(final AddPrefixShardReplica message) {
1356 LOG.debug("{}: onAddPrefixShardReplica: {}", persistenceId(), message);
1358 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1359 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1360 final String shardName = shardId.getShardName();
1362 // Create the localShard
1363 if (schemaContext == null) {
1364 String msg = String.format(
1365 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1366 LOG.debug("{}: {}", persistenceId(), msg);
1367 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1371 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1374 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1375 final RunnableMessage runnable = (RunnableMessage) () -> addPrefixShard(getShardName(),
1376 message.getShardPrefix(), response, getSender());
1377 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1378 getSelf().tell(runnable, getTargetActor());
1383 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1384 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1389 private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1390 final String shardName = shardReplicaMsg.getShardName();
1392 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1394 // verify the shard with the specified name is present in the cluster configuration
1395 if (!this.configuration.isShardConfigured(shardName)) {
1396 String msg = String.format("No module configuration exists for shard %s", shardName);
1397 LOG.debug("{}: {}", persistenceId(), msg);
1398 getSender().tell(new Status.Failure(new IllegalArgumentException(msg)), getSelf());
1402 // Create the localShard
1403 if (schemaContext == null) {
1404 String msg = String.format(
1405 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1406 LOG.debug("{}: {}", persistenceId(), msg);
1407 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1411 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1414 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1415 final RunnableMessage runnable = (RunnableMessage) () ->
1416 addShard(getShardName(), response, getSender());
1417 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1418 getSelf().tell(runnable, getTargetActor());
1423 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1424 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1429 private void sendLocalReplicaAlreadyExistsReply(final String shardName, final ActorRef sender) {
1430 String msg = String.format("Local shard %s already exists", shardName);
1431 LOG.debug("{}: {}", persistenceId(), msg);
1432 sender.tell(new Status.Failure(new AlreadyExistsException(msg)), getSelf());
1435 private void addPrefixShard(final String shardName, final YangInstanceIdentifier shardPrefix,
1436 final RemotePrimaryShardFound response, final ActorRef sender) {
1437 if (isShardReplicaOperationInProgress(shardName, sender)) {
1441 shardReplicaOperationsInProgress.add(shardName);
1443 final ShardInformation shardInfo;
1444 final boolean removeShardOnFailure;
1445 ShardInformation existingShardInfo = localShards.get(shardName);
1446 if (existingShardInfo == null) {
1447 removeShardOnFailure = true;
1448 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1450 final Builder builder = newShardDatastoreContextBuilder(shardName);
1451 builder.storeRoot(shardPrefix).customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1453 DatastoreContext datastoreContext = builder.build();
1455 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1456 Shard.builder(), peerAddressResolver);
1457 shardInfo.setActiveMember(false);
1458 shardInfo.setSchemaContext(schemaContext);
1459 localShards.put(shardName, shardInfo);
1460 shardInfo.setActor(newShardActor(shardInfo));
1462 removeShardOnFailure = false;
1463 shardInfo = existingShardInfo;
1466 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1469 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1470 if (isShardReplicaOperationInProgress(shardName, sender)) {
1474 shardReplicaOperationsInProgress.add(shardName);
1476 final ShardInformation shardInfo;
1477 final boolean removeShardOnFailure;
1478 ShardInformation existingShardInfo = localShards.get(shardName);
1479 if (existingShardInfo == null) {
1480 removeShardOnFailure = true;
1481 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1483 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1484 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1486 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1487 Shard.builder(), peerAddressResolver);
1488 shardInfo.setActiveMember(false);
1489 shardInfo.setSchemaContext(schemaContext);
1490 localShards.put(shardName, shardInfo);
1491 shardInfo.setActor(newShardActor(shardInfo));
1493 removeShardOnFailure = false;
1494 shardInfo = existingShardInfo;
1497 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1500 private void execAddShard(final String shardName,
1501 final ShardInformation shardInfo,
1502 final RemotePrimaryShardFound response,
1503 final boolean removeShardOnFailure,
1504 final ActorRef sender) {
1506 final String localShardAddress =
1507 peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1509 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1510 LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1511 response.getPrimaryPath(), shardInfo.getShardId());
1513 final Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1514 .getShardLeaderElectionTimeout().duration());
1515 final Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1516 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1518 futureObj.onComplete(new OnComplete<Object>() {
1520 public void onComplete(final Throwable failure, final Object addServerResponse) {
1521 if (failure != null) {
1522 LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1523 response.getPrimaryPath(), shardName, failure);
1525 final String msg = String.format("AddServer request to leader %s for shard %s failed",
1526 response.getPrimaryPath(), shardName);
1527 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1529 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1530 response.getPrimaryPath(), removeShardOnFailure), sender);
1533 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1536 private void onAddServerFailure(final String shardName, final String message, final Throwable failure,
1537 final ActorRef sender, final boolean removeShardOnFailure) {
1538 shardReplicaOperationsInProgress.remove(shardName);
1540 if (removeShardOnFailure) {
1541 ShardInformation shardInfo = localShards.remove(shardName);
1542 if (shardInfo.getActor() != null) {
1543 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1547 sender.tell(new Status.Failure(message == null ? failure :
1548 new RuntimeException(message, failure)), getSelf());
1551 private void onAddServerReply(final ShardInformation shardInfo, final AddServerReply replyMsg,
1552 final ActorRef sender, final String leaderPath, final boolean removeShardOnFailure) {
1553 String shardName = shardInfo.getShardName();
1554 shardReplicaOperationsInProgress.remove(shardName);
1556 LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1558 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1559 LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1561 // Make the local shard voting capable
1562 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1563 shardInfo.setActiveMember(true);
1566 sender.tell(new Status.Success(null), getSelf());
1567 } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1568 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1570 LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1571 persistenceId(), shardName, replyMsg.getStatus());
1573 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1574 shardInfo.getShardId());
1576 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1580 private static Exception getServerChangeException(final Class<?> serverChange,
1581 final ServerChangeStatus serverChangeStatus, final String leaderPath, final ShardIdentifier shardId) {
1582 switch (serverChangeStatus) {
1584 return new TimeoutException(String.format(
1585 "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1586 + "Possible causes - there was a problem replicating the data or shard leadership changed "
1587 + "while replicating the shard data", leaderPath, shardId.getShardName()));
1589 return createNoShardLeaderException(shardId);
1591 return new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1592 serverChange.getSimpleName(), shardId.getShardName()));
1594 return new RuntimeException(String.format("%s request to leader %s for shard %s failed with status %s",
1595 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1599 private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1600 LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1602 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1603 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1605 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1606 doRemoveShardReplicaAsync(response.getPrimaryPath());
1610 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1611 doRemoveShardReplicaAsync(response.getPrimaryPath());
1614 private void doRemoveShardReplicaAsync(final String primaryPath) {
1615 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1616 primaryPath, getSender()), getTargetActor());
1621 private void onRemovePrefixShardReplica(final RemovePrefixShardReplica message) {
1622 LOG.debug("{}: onRemovePrefixShardReplica: {}", persistenceId(), message);
1624 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1625 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1626 final String shardName = shardId.getShardName();
1628 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(),
1629 shardName, persistenceId(), getSelf()) {
1631 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1632 doRemoveShardReplicaAsync(response.getPrimaryPath());
1636 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1637 doRemoveShardReplicaAsync(response.getPrimaryPath());
1640 private void doRemoveShardReplicaAsync(final String primaryPath) {
1641 getSelf().tell((RunnableMessage) () -> removePrefixShardReplica(message, getShardName(),
1642 primaryPath, getSender()), getTargetActor());
1647 private void persistShardList() {
1648 List<String> shardList = new ArrayList<>(localShards.keySet());
1649 for (ShardInformation shardInfo : localShards.values()) {
1650 if (!shardInfo.isActiveMember()) {
1651 shardList.remove(shardInfo.getShardName());
1654 LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1655 saveSnapshot(updateShardManagerSnapshot(shardList, configuration.getAllPrefixShardConfigurations()));
1658 private ShardManagerSnapshot updateShardManagerSnapshot(
1659 final List<String> shardList,
1660 final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> allPrefixShardConfigurations) {
1661 currentSnapshot = new ShardManagerSnapshot(shardList, allPrefixShardConfigurations);
1662 return currentSnapshot;
1665 private void applyShardManagerSnapshot(final ShardManagerSnapshot snapshot) {
1666 currentSnapshot = snapshot;
1668 LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1670 final MemberName currentMember = cluster.getCurrentMemberName();
1671 Set<String> configuredShardList =
1672 new HashSet<>(configuration.getMemberShardNames(currentMember));
1673 for (String shard : currentSnapshot.getShardList()) {
1674 if (!configuredShardList.contains(shard)) {
1675 // add the current member as a replica for the shard
1676 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1677 configuration.addMemberReplicaForShard(shard, currentMember);
1679 configuredShardList.remove(shard);
1682 for (String shard : configuredShardList) {
1683 // remove the member as a replica for the shard
1684 LOG.debug("{}: removing shard {}", persistenceId(), shard);
1685 configuration.removeMemberReplicaForShard(shard, currentMember);
1689 private void onSaveSnapshotSuccess(final SaveSnapshotSuccess successMessage) {
1690 LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1692 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1696 private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1697 LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1699 String shardName = changeMembersVotingStatus.getShardName();
1700 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1701 for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1702 serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1706 ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1708 findLocalShard(shardName, getSender(),
1709 localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1710 localShardFound.getPath(), getSender()));
1713 private void onFlipShardMembersVotingStatus(final FlipShardMembersVotingStatus flipMembersVotingStatus) {
1714 LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1716 ActorRef sender = getSender();
1717 final String shardName = flipMembersVotingStatus.getShardName();
1718 findLocalShard(shardName, sender, localShardFound -> {
1719 Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1720 Timeout.apply(30, TimeUnit.SECONDS));
1722 future.onComplete(new OnComplete<Object>() {
1724 public void onComplete(final Throwable failure, final Object response) {
1725 if (failure != null) {
1726 sender.tell(new Status.Failure(new RuntimeException(
1727 String.format("Failed to access local shard %s", shardName), failure)), self());
1731 OnDemandRaftState raftState = (OnDemandRaftState) response;
1732 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1733 for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1734 serverVotingStatusMap.put(e.getKey(), !e.getValue());
1737 serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1738 .toString(), !raftState.isVoting());
1740 changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1741 shardName, localShardFound.getPath(), sender);
1743 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1748 private void findLocalShard(final FindLocalShard message) {
1749 LOG.debug("{}: findLocalShard : {}", persistenceId(), message.getShardName());
1751 final ShardInformation shardInformation = localShards.get(message.getShardName());
1753 if (shardInformation == null) {
1754 LOG.debug("{}: Local shard {} not found - shards present: {}",
1755 persistenceId(), message.getShardName(), localShards.keySet());
1757 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1761 sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1762 () -> new LocalShardFound(shardInformation.getActor()));
1765 private void findLocalShard(final String shardName, final ActorRef sender,
1766 final Consumer<LocalShardFound> onLocalShardFound) {
1767 Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1768 .getShardInitializationTimeout().duration().$times(2));
1770 Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1771 futureObj.onComplete(new OnComplete<Object>() {
1773 public void onComplete(final Throwable failure, final Object response) {
1774 if (failure != null) {
1775 LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1777 sender.tell(new Status.Failure(new RuntimeException(
1778 String.format("Failed to find local shard %s", shardName), failure)), self());
1780 if (response instanceof LocalShardFound) {
1781 getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1783 } else if (response instanceof LocalShardNotFound) {
1784 String msg = String.format("Local shard %s does not exist", shardName);
1785 LOG.debug("{}: {}", persistenceId, msg);
1786 sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
1788 String msg = String.format("Failed to find local shard %s: received response: %s",
1789 shardName, response);
1790 LOG.debug("{}: {}", persistenceId, msg);
1791 sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1792 new RuntimeException(msg)), self());
1796 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1799 private void changeShardMembersVotingStatus(final ChangeServersVotingStatus changeServersVotingStatus,
1800 final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1801 if (isShardReplicaOperationInProgress(shardName, sender)) {
1805 shardReplicaOperationsInProgress.add(shardName);
1807 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1808 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1810 LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1811 changeServersVotingStatus, shardActorRef.path());
1813 Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1814 Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1816 futureObj.onComplete(new OnComplete<Object>() {
1818 public void onComplete(final Throwable failure, final Object response) {
1819 shardReplicaOperationsInProgress.remove(shardName);
1820 if (failure != null) {
1821 String msg = String.format("ChangeServersVotingStatus request to local shard %s failed",
1822 shardActorRef.path());
1823 LOG.debug("{}: {}", persistenceId(), msg, failure);
1824 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
1826 LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1828 ServerChangeReply replyMsg = (ServerChangeReply) response;
1829 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1830 LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1831 sender.tell(new Status.Success(null), getSelf());
1832 } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1833 sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1834 "The requested voting state change for shard %s is invalid. At least one member "
1835 + "must be voting", shardId.getShardName()))), getSelf());
1837 LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1838 persistenceId(), shardName, replyMsg.getStatus());
1840 Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1841 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1842 sender.tell(new Status.Failure(error), getSelf());
1846 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1849 private static final class ForwardedAddServerReply {
1850 ShardInformation shardInfo;
1851 AddServerReply addServerReply;
1853 boolean removeShardOnFailure;
1855 ForwardedAddServerReply(final ShardInformation shardInfo, final AddServerReply addServerReply,
1856 final String leaderPath, final boolean removeShardOnFailure) {
1857 this.shardInfo = shardInfo;
1858 this.addServerReply = addServerReply;
1859 this.leaderPath = leaderPath;
1860 this.removeShardOnFailure = removeShardOnFailure;
1864 private static final class ForwardedAddServerFailure {
1866 String failureMessage;
1868 boolean removeShardOnFailure;
1870 ForwardedAddServerFailure(final String shardName, final String failureMessage, final Throwable failure,
1871 final boolean removeShardOnFailure) {
1872 this.shardName = shardName;
1873 this.failureMessage = failureMessage;
1874 this.failure = failure;
1875 this.removeShardOnFailure = removeShardOnFailure;
1879 static class OnShardInitialized {
1880 private final Runnable replyRunnable;
1881 private Cancellable timeoutSchedule;
1883 OnShardInitialized(final Runnable replyRunnable) {
1884 this.replyRunnable = replyRunnable;
1887 Runnable getReplyRunnable() {
1888 return replyRunnable;
1891 Cancellable getTimeoutSchedule() {
1892 return timeoutSchedule;
1895 void setTimeoutSchedule(final Cancellable timeoutSchedule) {
1896 this.timeoutSchedule = timeoutSchedule;
1900 static class OnShardReady extends OnShardInitialized {
1901 OnShardReady(final Runnable replyRunnable) {
1902 super(replyRunnable);
1906 private interface RunnableMessage extends Runnable {
1910 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1911 * a remote or local find primary message is processed.
1913 private interface FindPrimaryResponseHandler {
1915 * Invoked when a Failure message is received as a response.
1917 * @param failure the failure exception
1919 void onFailure(Throwable failure);
1922 * Invoked when a RemotePrimaryShardFound response is received.
1924 * @param response the response
1926 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1929 * Invoked when a LocalPrimaryShardFound response is received.
1931 * @param response the response
1933 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1936 * Invoked when an unknown response is received. This is another type of failure.
1938 * @param response the response
1940 void onUnknownResponse(Object response);
1944 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1945 * replica and sends a wrapped Failure response to some targetActor.
1947 private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1948 private final ActorRef targetActor;
1949 private final String shardName;
1950 private final String persistenceId;
1951 private final ActorRef shardManagerActor;
1954 * Constructs an instance.
1956 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1957 * @param shardName The name of the shard for which the primary replica had to be found
1958 * @param persistenceId The persistenceId for the ShardManager
1959 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1961 protected AutoFindPrimaryFailureResponseHandler(final ActorRef targetActor, final String shardName,
1962 final String persistenceId, final ActorRef shardManagerActor) {
1963 this.targetActor = Preconditions.checkNotNull(targetActor);
1964 this.shardName = Preconditions.checkNotNull(shardName);
1965 this.persistenceId = Preconditions.checkNotNull(persistenceId);
1966 this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1969 public ActorRef getTargetActor() {
1973 public String getShardName() {
1978 public void onFailure(final Throwable failure) {
1979 LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1980 targetActor.tell(new Status.Failure(new RuntimeException(
1981 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1985 public void onUnknownResponse(final Object response) {
1986 String msg = String.format("Failed to find leader for shard %s: received response: %s",
1987 shardName, response);
1988 LOG.debug("{}: {}", persistenceId, msg);
1989 targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1990 new RuntimeException(msg)), shardManagerActor);
1995 * The WrappedShardResponse class wraps a response from a Shard.
1997 private static final class WrappedShardResponse {
1998 private final ShardIdentifier shardId;
1999 private final Object response;
2000 private final String leaderPath;
2002 WrappedShardResponse(final ShardIdentifier shardId, final Object response, final String leaderPath) {
2003 this.shardId = shardId;
2004 this.response = response;
2005 this.leaderPath = leaderPath;
2008 ShardIdentifier getShardId() {
2012 Object getResponse() {
2016 String getLeaderPath() {
2021 private static final class ShardNotInitializedTimeout {
2022 private final ActorRef sender;
2023 private final ShardInformation shardInfo;
2024 private final OnShardInitialized onShardInitialized;
2026 ShardNotInitializedTimeout(final ShardInformation shardInfo, final OnShardInitialized onShardInitialized,
2027 final ActorRef sender) {
2028 this.sender = sender;
2029 this.shardInfo = shardInfo;
2030 this.onShardInitialized = onShardInitialized;
2033 ActorRef getSender() {
2037 ShardInformation getShardInfo() {
2041 OnShardInitialized getOnShardInitialized() {
2042 return onShardInitialized;