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.common.api.data.LogicalDatastoreType;
116 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
117 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
118 import org.opendaylight.yangtools.concepts.ListenerRegistration;
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 String persistenceId;
176 private final AbstractDataStore dataStore;
178 private ListenerRegistration<DOMDataTreeChangeListener> configListenerReg = null;
179 private PrefixedShardConfigUpdateHandler configUpdateHandler;
181 ShardManager(final AbstractShardManagerCreator<?> builder) {
182 this.cluster = builder.getCluster();
183 this.configuration = builder.getConfiguration();
184 this.datastoreContextFactory = builder.getDatastoreContextFactory();
185 this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
186 this.shardDispatcherPath =
187 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
188 this.waitTillReadyCountdownLatch = builder.getWaitTillReadyCountDownLatch();
189 this.primaryShardInfoCache = builder.getPrimaryShardInfoCache();
190 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
192 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
193 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
195 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
197 // Subscribe this actor to cluster member events
198 cluster.subscribeToMemberEvents(getSelf());
200 shardManagerMBean = new ShardManagerInfo(getSelf(), cluster.getCurrentMemberName(),
201 "shard-manager-" + this.type,
202 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
203 shardManagerMBean.registerMBean();
205 dataStore = builder.getDistributedDataStore();
209 public void preStart() {
210 LOG.info("Starting ShardManager {}", persistenceId);
214 public void postStop() {
215 LOG.info("Stopping ShardManager {}", persistenceId());
217 shardManagerMBean.unregisterMBean();
219 if (configListenerReg != null) {
220 configListenerReg.close();
221 configListenerReg = null;
226 public void handleCommand(final Object message) throws Exception {
227 if (message instanceof FindPrimary) {
228 findPrimary((FindPrimary)message);
229 } else if (message instanceof FindLocalShard) {
230 findLocalShard((FindLocalShard) message);
231 } else if (message instanceof UpdateSchemaContext) {
232 updateSchemaContext(message);
233 } else if (message instanceof ActorInitialized) {
234 onActorInitialized(message);
235 } else if (message instanceof ClusterEvent.MemberUp) {
236 memberUp((ClusterEvent.MemberUp) message);
237 } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
238 memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
239 } else if (message instanceof ClusterEvent.MemberExited) {
240 memberExited((ClusterEvent.MemberExited) message);
241 } else if (message instanceof ClusterEvent.MemberRemoved) {
242 memberRemoved((ClusterEvent.MemberRemoved) message);
243 } else if (message instanceof ClusterEvent.UnreachableMember) {
244 memberUnreachable((ClusterEvent.UnreachableMember) message);
245 } else if (message instanceof ClusterEvent.ReachableMember) {
246 memberReachable((ClusterEvent.ReachableMember) message);
247 } else if (message instanceof DatastoreContextFactory) {
248 onDatastoreContextFactory((DatastoreContextFactory) message);
249 } else if (message instanceof RoleChangeNotification) {
250 onRoleChangeNotification((RoleChangeNotification) message);
251 } else if (message instanceof FollowerInitialSyncUpStatus) {
252 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
253 } else if (message instanceof ShardNotInitializedTimeout) {
254 onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
255 } else if (message instanceof ShardLeaderStateChanged) {
256 onLeaderStateChanged((ShardLeaderStateChanged) message);
257 } else if (message instanceof SwitchShardBehavior) {
258 onSwitchShardBehavior((SwitchShardBehavior) message);
259 } else if (message instanceof CreateShard) {
260 onCreateShard((CreateShard)message);
261 } else if (message instanceof AddShardReplica) {
262 onAddShardReplica((AddShardReplica) message);
263 } else if (message instanceof AddPrefixShardReplica) {
264 onAddPrefixShardReplica((AddPrefixShardReplica) message);
265 } else if (message instanceof PrefixShardCreated) {
266 onPrefixShardCreated((PrefixShardCreated) message);
267 } else if (message instanceof PrefixShardRemoved) {
268 onPrefixShardRemoved((PrefixShardRemoved) message);
269 } else if (message instanceof InitConfigListener) {
270 onInitConfigListener();
271 } else if (message instanceof ForwardedAddServerReply) {
272 ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
273 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
274 msg.removeShardOnFailure);
275 } else if (message instanceof ForwardedAddServerFailure) {
276 ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
277 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
278 } else if (message instanceof RemoveShardReplica) {
279 onRemoveShardReplica((RemoveShardReplica) message);
280 } else if (message instanceof RemovePrefixShardReplica) {
281 onRemovePrefixShardReplica((RemovePrefixShardReplica) message);
282 } else if (message instanceof WrappedShardResponse) {
283 onWrappedShardResponse((WrappedShardResponse) message);
284 } else if (message instanceof GetSnapshot) {
286 } else if (message instanceof ServerRemoved) {
287 onShardReplicaRemoved((ServerRemoved) message);
288 } else if (message instanceof ChangeShardMembersVotingStatus) {
289 onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
290 } else if (message instanceof FlipShardMembersVotingStatus) {
291 onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
292 } else if (message instanceof SaveSnapshotSuccess) {
293 onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
294 } else if (message instanceof SaveSnapshotFailure) {
295 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
296 ((SaveSnapshotFailure) message).cause());
297 } else if (message instanceof Shutdown) {
299 } else if (message instanceof GetLocalShardIds) {
300 onGetLocalShardIds();
301 } else if (message instanceof GetShardRole) {
302 onGetShardRole((GetShardRole) message);
303 } else if (message instanceof RunnableMessage) {
304 ((RunnableMessage)message).run();
305 } else if (message instanceof DeleteSnapshotsFailure) {
306 LOG.warn("{}: Failed to delete prior snapshots", persistenceId(),
307 ((DeleteSnapshotsFailure) message).cause());
308 } else if (message instanceof DeleteSnapshotsSuccess) {
309 LOG.debug("{}: Successfully deleted prior snapshots", persistenceId(), message);
310 } else if (message instanceof RegisterRoleChangeListenerReply) {
311 LOG.trace("{}: Received RegisterRoleChangeListenerReply", persistenceId());
312 } else if (message instanceof ClusterEvent.MemberEvent) {
313 LOG.trace("{}: Received other ClusterEvent.MemberEvent: {}", persistenceId(), message);
315 unknownMessage(message);
319 private void onGetShardRole(final GetShardRole message) {
320 LOG.debug("{}: onGetShardRole for shard: {}", persistenceId(), message.getName());
322 final String name = message.getName();
324 final ShardInformation shardInformation = localShards.get(name);
326 if (shardInformation == null) {
327 LOG.info("{}: no shard information for {} found", persistenceId(), name);
328 getSender().tell(new Status.Failure(
329 new IllegalArgumentException("Shard with name " + name + " not present.")), ActorRef.noSender());
333 getSender().tell(new GetShardRoleReply(shardInformation.getRole()), ActorRef.noSender());
336 private void onInitConfigListener() {
337 LOG.debug("{}: Initializing config listener on {}", persistenceId(), cluster.getCurrentMemberName());
339 final org.opendaylight.mdsal.common.api.LogicalDatastoreType datastoreType =
340 org.opendaylight.mdsal.common.api.LogicalDatastoreType
341 .valueOf(datastoreContextFactory.getBaseDatastoreContext().getLogicalStoreType().name());
343 if (configUpdateHandler != null) {
344 configUpdateHandler.close();
347 configUpdateHandler = new PrefixedShardConfigUpdateHandler(self(), cluster.getCurrentMemberName());
348 configUpdateHandler.initListener(dataStore, datastoreType);
351 private void onShutDown() {
352 List<Future<Boolean>> stopFutures = new ArrayList<>(localShards.size());
353 for (ShardInformation info : localShards.values()) {
354 if (info.getActor() != null) {
355 LOG.debug("{}: Issuing gracefulStop to shard {}", persistenceId(), info.getShardId());
357 FiniteDuration duration = info.getDatastoreContext().getShardRaftConfig()
358 .getElectionTimeOutInterval().$times(2);
359 stopFutures.add(Patterns.gracefulStop(info.getActor(), duration, Shutdown.INSTANCE));
363 LOG.info("Shutting down ShardManager {} - waiting on {} shards", persistenceId(), stopFutures.size());
365 ExecutionContext dispatcher = new Dispatchers(context().system().dispatchers())
366 .getDispatcher(Dispatchers.DispatcherType.Client);
367 Future<Iterable<Boolean>> combinedFutures = Futures.sequence(stopFutures, dispatcher);
369 combinedFutures.onComplete(new OnComplete<Iterable<Boolean>>() {
371 public void onComplete(final Throwable failure, final Iterable<Boolean> results) {
372 LOG.debug("{}: All shards shutdown - sending PoisonPill to self", persistenceId());
374 self().tell(PoisonPill.getInstance(), self());
376 if (failure != null) {
377 LOG.warn("{}: An error occurred attempting to shut down the shards", persistenceId(), failure);
380 for (Boolean result : results) {
387 LOG.warn("{}: {} shards did not shut down gracefully", persistenceId(), nfailed);
394 private void onWrappedShardResponse(final WrappedShardResponse message) {
395 if (message.getResponse() instanceof RemoveServerReply) {
396 onRemoveServerReply(getSender(), message.getShardId(), (RemoveServerReply) message.getResponse(),
397 message.getLeaderPath());
401 private void onRemoveServerReply(final ActorRef originalSender, final ShardIdentifier shardId,
402 final RemoveServerReply replyMsg, final String leaderPath) {
403 shardReplicaOperationsInProgress.remove(shardId.getShardName());
405 LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
407 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
408 LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
409 shardId.getShardName());
410 originalSender.tell(new Status.Success(null), getSelf());
412 LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
413 persistenceId(), shardId, replyMsg.getStatus());
415 Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
416 originalSender.tell(new Status.Failure(failure), getSelf());
420 private void removePrefixShardReplica(final RemovePrefixShardReplica contextMessage, final String shardName,
421 final String primaryPath, final ActorRef sender) {
422 if (isShardReplicaOperationInProgress(shardName, sender)) {
426 shardReplicaOperationsInProgress.add(shardName);
428 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
430 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
432 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
433 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
434 primaryPath, shardId);
436 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
437 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
438 new RemoveServer(shardId.toString()), removeServerTimeout);
440 futureObj.onComplete(new OnComplete<Object>() {
442 public void onComplete(final Throwable failure, final Object response) {
443 if (failure != null) {
444 shardReplicaOperationsInProgress.remove(shardName);
445 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
446 primaryPath, shardName);
448 LOG.debug("{}: {}", persistenceId(), msg, failure);
451 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
454 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
457 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
460 private void removeShardReplica(final RemoveShardReplica contextMessage, final String shardName,
461 final String primaryPath, final ActorRef sender) {
462 if (isShardReplicaOperationInProgress(shardName, sender)) {
466 shardReplicaOperationsInProgress.add(shardName);
468 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
470 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
472 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
473 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
474 primaryPath, shardId);
476 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
477 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
478 new RemoveServer(shardId.toString()), removeServerTimeout);
480 futureObj.onComplete(new OnComplete<Object>() {
482 public void onComplete(final Throwable failure, final Object response) {
483 if (failure != null) {
484 shardReplicaOperationsInProgress.remove(shardName);
485 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
486 primaryPath, shardName);
488 LOG.debug("{}: {}", persistenceId(), msg, failure);
491 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
494 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
497 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
500 private void onShardReplicaRemoved(final ServerRemoved message) {
501 removeShard(new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build());
504 @SuppressWarnings("checkstyle:IllegalCatch")
505 private void removeShard(final ShardIdentifier shardId) {
506 final String shardName = shardId.getShardName();
507 final ShardInformation shardInformation = localShards.remove(shardName);
508 if (shardInformation == null) {
509 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
513 final ActorRef shardActor = shardInformation.getActor();
514 if (shardActor != null) {
515 long timeoutInMS = Math.max(shardInformation.getDatastoreContext().getShardRaftConfig()
516 .getElectionTimeOutInterval().$times(3).toMillis(), 10000);
518 LOG.debug("{} : Sending Shutdown to Shard actor {} with {} ms timeout", persistenceId(), shardActor,
521 final Future<Boolean> stopFuture = Patterns.gracefulStop(shardActor,
522 FiniteDuration.apply(timeoutInMS, TimeUnit.MILLISECONDS), Shutdown.INSTANCE);
524 final CompositeOnComplete<Boolean> onComplete = new CompositeOnComplete<Boolean>() {
526 public void onComplete(final Throwable failure, final Boolean result) {
527 if (failure == null) {
528 LOG.debug("{} : Successfully shut down Shard actor {}", persistenceId(), shardActor);
530 LOG.warn("{}: Failed to shut down Shard actor {}", persistenceId(), shardActor, failure);
533 self().tell((RunnableMessage) () -> {
534 // At any rate, invalidate primaryShardInfo cache
535 primaryShardInfoCache.remove(shardName);
537 shardActorsStopping.remove(shardName);
538 notifyOnCompleteTasks(failure, result);
539 }, ActorRef.noSender());
543 shardActorsStopping.put(shardName, onComplete);
544 stopFuture.onComplete(onComplete, new Dispatchers(context().system().dispatchers())
545 .getDispatcher(Dispatchers.DispatcherType.Client));
548 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardName);
552 private void onGetSnapshot() {
553 LOG.debug("{}: onGetSnapshot", persistenceId());
555 List<String> notInitialized = null;
556 for (ShardInformation shardInfo : localShards.values()) {
557 if (!shardInfo.isShardInitialized()) {
558 if (notInitialized == null) {
559 notInitialized = new ArrayList<>();
562 notInitialized.add(shardInfo.getShardName());
566 if (notInitialized != null) {
567 getSender().tell(new Status.Failure(new IllegalStateException(String.format(
568 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
572 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
573 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
574 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
576 for (ShardInformation shardInfo: localShards.values()) {
577 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
581 @SuppressWarnings("checkstyle:IllegalCatch")
582 private void onCreateShard(final CreateShard createShard) {
583 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
587 String shardName = createShard.getModuleShardConfig().getShardName();
588 if (localShards.containsKey(shardName)) {
589 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
590 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
592 doCreateShard(createShard);
593 reply = new Status.Success(null);
595 } catch (Exception e) {
596 LOG.error("{}: onCreateShard failed", persistenceId(), e);
597 reply = new Status.Failure(e);
600 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
601 getSender().tell(reply, getSelf());
605 private void onPrefixShardCreated(final PrefixShardCreated message) {
606 LOG.debug("{}: onPrefixShardCreated: {}", persistenceId(), message);
608 final PrefixShardConfiguration config = message.getConfiguration();
609 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
610 ClusterUtils.getCleanShardName(config.getPrefix().getRootIdentifier()));
611 final String shardName = shardId.getShardName();
613 if (isPreviousShardActorStopInProgress(shardName, message)) {
617 if (localShards.containsKey(shardName)) {
618 LOG.debug("{}: Received create for an already existing shard {}", persistenceId(), shardName);
619 final PrefixShardConfiguration existing =
620 configuration.getAllPrefixShardConfigurations().get(config.getPrefix());
622 if (existing != null && existing.equals(config)) {
623 // we don't have to do nothing here
628 doCreatePrefixShard(config, shardId, shardName);
631 private boolean isPreviousShardActorStopInProgress(final String shardName, final Object messageToDefer) {
632 final CompositeOnComplete<Boolean> stopOnComplete = shardActorsStopping.get(shardName);
633 if (stopOnComplete == null) {
637 LOG.debug("{} : Stop is in progress for shard {} - adding OnComplete callback to defer {}", persistenceId(),
638 shardName, messageToDefer);
639 final ActorRef sender = getSender();
640 stopOnComplete.addOnComplete(new OnComplete<Boolean>() {
642 public void onComplete(final Throwable failure, final Boolean result) {
643 LOG.debug("{} : Stop complete for shard {} - re-queing {}", persistenceId(), shardName, messageToDefer);
644 self().tell(messageToDefer, sender);
651 private void doCreatePrefixShard(final PrefixShardConfiguration config, final ShardIdentifier shardId,
652 final String shardName) {
653 configuration.addPrefixShardConfiguration(config);
655 final Builder builder = newShardDatastoreContextBuilder(shardName);
656 builder.logicalStoreType(LogicalDatastoreType.valueOf(config.getPrefix().getDatastoreType().name()))
657 .storeRoot(config.getPrefix().getRootIdentifier());
658 DatastoreContext shardDatastoreContext = builder.build();
660 final Map<String, String> peerAddresses = getPeerAddresses(shardName);
661 final boolean isActiveMember = true;
663 LOG.debug("{} doCreatePrefixShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
664 persistenceId(), shardId, config.getShardMemberNames(), peerAddresses, isActiveMember);
666 final ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
667 shardDatastoreContext, Shard.builder(), peerAddressResolver);
668 info.setActiveMember(isActiveMember);
669 localShards.put(info.getShardName(), info);
671 if (schemaContext != null) {
672 info.setSchemaContext(schemaContext);
673 info.setActor(newShardActor(info));
677 private void onPrefixShardRemoved(final PrefixShardRemoved message) {
678 LOG.debug("{}: onPrefixShardRemoved : {}", persistenceId(), message);
680 final DOMDataTreeIdentifier prefix = message.getPrefix();
681 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
682 ClusterUtils.getCleanShardName(prefix.getRootIdentifier()));
684 configuration.removePrefixShardConfiguration(prefix);
685 removeShard(shardId);
688 private void doCreateShard(final CreateShard createShard) {
689 final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
690 final String shardName = moduleShardConfig.getShardName();
692 configuration.addModuleShardConfiguration(moduleShardConfig);
694 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
695 if (shardDatastoreContext == null) {
696 shardDatastoreContext = newShardDatastoreContext(shardName);
698 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
699 peerAddressResolver).build();
702 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
704 boolean shardWasInRecoveredSnapshot = currentSnapshot != null
705 && currentSnapshot.getShardList().contains(shardName);
707 Map<String, String> peerAddresses;
708 boolean isActiveMember;
709 if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
710 .contains(cluster.getCurrentMemberName())) {
711 peerAddresses = getPeerAddresses(shardName);
712 isActiveMember = true;
714 // The local member is not in the static shard member configuration and the shard did not
715 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
716 // the shard with no peers and with elections disabled so it stays as follower. A
717 // subsequent AddServer request will be needed to make it an active member.
718 isActiveMember = false;
719 peerAddresses = Collections.emptyMap();
720 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
721 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
724 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
725 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
728 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
729 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
730 info.setActiveMember(isActiveMember);
731 localShards.put(info.getShardName(), info);
733 if (schemaContext != null) {
734 info.setSchemaContext(schemaContext);
735 info.setActor(newShardActor(info));
739 private DatastoreContext.Builder newShardDatastoreContextBuilder(final String shardName) {
740 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
741 .shardPeerAddressResolver(peerAddressResolver);
744 private DatastoreContext newShardDatastoreContext(final String shardName) {
745 return newShardDatastoreContextBuilder(shardName).build();
748 private void checkReady() {
749 if (isReadyWithLeaderId()) {
750 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
751 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
753 waitTillReadyCountdownLatch.countDown();
757 private void onLeaderStateChanged(final ShardLeaderStateChanged leaderStateChanged) {
758 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
760 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
761 if (shardInformation != null) {
762 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
763 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
764 if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
765 primaryShardInfoCache.remove(shardInformation.getShardName());
770 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
774 private void onShardNotInitializedTimeout(final ShardNotInitializedTimeout message) {
775 ShardInformation shardInfo = message.getShardInfo();
777 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
778 shardInfo.getShardName());
780 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
782 if (!shardInfo.isShardInitialized()) {
783 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
784 message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
786 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
787 message.getSender().tell(createNoShardLeaderException(shardInfo.getShardId()), getSelf());
791 private void onFollowerInitialSyncStatus(final FollowerInitialSyncUpStatus status) {
792 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
793 status.getName(), status.isInitialSyncDone());
795 ShardInformation shardInformation = findShardInformation(status.getName());
797 if (shardInformation != null) {
798 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
800 shardManagerMBean.setSyncStatus(isInSync());
805 private void onRoleChangeNotification(final RoleChangeNotification roleChanged) {
806 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
807 roleChanged.getOldRole(), roleChanged.getNewRole());
809 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
810 if (shardInformation != null) {
811 shardInformation.setRole(roleChanged.getNewRole());
813 shardManagerMBean.setSyncStatus(isInSync());
818 private ShardInformation findShardInformation(final String memberId) {
819 for (ShardInformation info : localShards.values()) {
820 if (info.getShardId().toString().equals(memberId)) {
828 private boolean isReadyWithLeaderId() {
829 boolean isReady = true;
830 for (ShardInformation info : localShards.values()) {
831 if (!info.isShardReadyWithLeaderId()) {
839 private boolean isInSync() {
840 for (ShardInformation info : localShards.values()) {
841 if (!info.isInSync()) {
848 private void onActorInitialized(final Object message) {
849 final ActorRef sender = getSender();
851 if (sender == null) {
852 // why is a non-actor sending this message? Just ignore.
856 String actorName = sender.path().name();
857 //find shard name from actor name; actor name is stringified shardId
859 final ShardIdentifier shardId;
861 shardId = ShardIdentifier.fromShardIdString(actorName);
862 } catch (IllegalArgumentException e) {
863 LOG.debug("{}: ignoring actor {}", actorName, e);
867 markShardAsInitialized(shardId.getShardName());
870 private void markShardAsInitialized(final String shardName) {
871 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
873 ShardInformation shardInformation = localShards.get(shardName);
874 if (shardInformation != null) {
875 shardInformation.setActorInitialized();
877 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
882 protected void handleRecover(final Object message) throws Exception {
883 if (message instanceof RecoveryCompleted) {
884 onRecoveryCompleted();
885 } else if (message instanceof SnapshotOffer) {
886 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
890 @SuppressWarnings("checkstyle:IllegalCatch")
891 private void onRecoveryCompleted() {
892 LOG.info("Recovery complete : {}", persistenceId());
894 if (currentSnapshot == null && restoreFromSnapshot != null
895 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
896 ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
898 LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
900 applyShardManagerSnapshot(snapshot);
906 private void sendResponse(final ShardInformation shardInformation, final boolean doWait,
907 final boolean wantShardReady, final Supplier<Object> messageSupplier) {
908 if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
910 final ActorRef sender = getSender();
911 final ActorRef self = self();
913 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
915 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
916 new OnShardInitialized(replyRunnable);
918 shardInformation.addOnShardInitialized(onShardInitialized);
920 FiniteDuration timeout = shardInformation.getDatastoreContext()
921 .getShardInitializationTimeout().duration();
922 if (shardInformation.isShardInitialized()) {
923 // If the shard is already initialized then we'll wait enough time for the shard to
924 // elect a leader, ie 2 times the election timeout.
925 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
926 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
929 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
930 shardInformation.getShardName());
932 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
934 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
935 getContext().dispatcher(), getSelf());
937 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
939 } else if (!shardInformation.isShardInitialized()) {
940 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
941 shardInformation.getShardName());
942 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
944 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
945 shardInformation.getShardName());
946 getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
952 getSender().tell(messageSupplier.get(), getSelf());
955 private static NoShardLeaderException createNoShardLeaderException(final ShardIdentifier shardId) {
956 return new NoShardLeaderException(null, shardId.toString());
959 private static NotInitializedException createNotInitializedException(final ShardIdentifier shardId) {
960 return new NotInitializedException(String.format(
961 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
965 static MemberName memberToName(final Member member) {
966 return MemberName.forName(member.roles().iterator().next());
969 private void memberRemoved(final ClusterEvent.MemberRemoved message) {
970 MemberName memberName = memberToName(message.member());
972 LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
973 message.member().address());
975 peerAddressResolver.removePeerAddress(memberName);
977 for (ShardInformation info : localShards.values()) {
978 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
982 private void memberExited(final ClusterEvent.MemberExited message) {
983 MemberName memberName = memberToName(message.member());
985 LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
986 message.member().address());
988 peerAddressResolver.removePeerAddress(memberName);
990 for (ShardInformation info : localShards.values()) {
991 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
995 private void memberUp(final ClusterEvent.MemberUp message) {
996 MemberName memberName = memberToName(message.member());
998 LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
999 message.member().address());
1001 memberUp(memberName, message.member().address());
1004 private void memberUp(final MemberName memberName, final Address address) {
1005 addPeerAddress(memberName, address);
1009 private void memberWeaklyUp(final MemberWeaklyUp message) {
1010 MemberName memberName = memberToName(message.member());
1012 LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
1013 message.member().address());
1015 memberUp(memberName, message.member().address());
1018 private void addPeerAddress(final MemberName memberName, final Address address) {
1019 peerAddressResolver.addPeerAddress(memberName, address);
1021 for (ShardInformation info : localShards.values()) {
1022 String shardName = info.getShardName();
1023 String peerId = getShardIdentifier(memberName, shardName).toString();
1024 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
1026 info.peerUp(memberName, peerId, getSelf());
1030 private void memberReachable(final ClusterEvent.ReachableMember message) {
1031 MemberName memberName = memberToName(message.member());
1032 LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
1034 addPeerAddress(memberName, message.member().address());
1036 markMemberAvailable(memberName);
1039 private void memberUnreachable(final ClusterEvent.UnreachableMember message) {
1040 MemberName memberName = memberToName(message.member());
1041 LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
1043 markMemberUnavailable(memberName);
1046 private void markMemberUnavailable(final MemberName memberName) {
1047 final String memberStr = memberName.getName();
1048 for (ShardInformation info : localShards.values()) {
1049 String leaderId = info.getLeaderId();
1050 // XXX: why are we using String#contains() here?
1051 if (leaderId != null && leaderId.contains(memberStr)) {
1052 LOG.debug("Marking Leader {} as unavailable.", leaderId);
1053 info.setLeaderAvailable(false);
1055 primaryShardInfoCache.remove(info.getShardName());
1058 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1062 private void markMemberAvailable(final MemberName memberName) {
1063 final String memberStr = memberName.getName();
1064 for (ShardInformation info : localShards.values()) {
1065 String leaderId = info.getLeaderId();
1066 // XXX: why are we using String#contains() here?
1067 if (leaderId != null && leaderId.contains(memberStr)) {
1068 LOG.debug("Marking Leader {} as available.", leaderId);
1069 info.setLeaderAvailable(true);
1072 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1076 private void onDatastoreContextFactory(final DatastoreContextFactory factory) {
1077 datastoreContextFactory = factory;
1078 for (ShardInformation info : localShards.values()) {
1079 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
1083 private void onGetLocalShardIds() {
1084 final List<String> response = new ArrayList<>(localShards.size());
1086 for (ShardInformation info : localShards.values()) {
1087 response.add(info.getShardId().toString());
1090 getSender().tell(new Status.Success(response), getSelf());
1093 private void onSwitchShardBehavior(final SwitchShardBehavior message) {
1094 final ShardIdentifier identifier = message.getShardId();
1096 if (identifier != null) {
1097 final ShardInformation info = localShards.get(identifier.getShardName());
1099 getSender().tell(new Status.Failure(
1100 new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
1104 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1106 for (ShardInformation info : localShards.values()) {
1107 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1111 getSender().tell(new Status.Success(null), getSelf());
1114 private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
1115 final ActorRef actor = info.getActor();
1116 if (actor != null) {
1117 actor.tell(switchBehavior, getSelf());
1119 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
1120 info.getShardName(), switchBehavior.getNewState());
1125 * Notifies all the local shards of a change in the schema context.
1127 * @param message the message to send
1129 private void updateSchemaContext(final Object message) {
1130 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
1132 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
1134 for (ShardInformation info : localShards.values()) {
1135 info.setSchemaContext(schemaContext);
1137 if (info.getActor() == null) {
1138 LOG.debug("Creating Shard {}", info.getShardId());
1139 info.setActor(newShardActor(info));
1140 // Update peer address for every existing peer memeber to avoid missing sending
1141 // PeerAddressResolved and PeerUp to this shard while UpdateSchemaContext comes after MemberUp.
1142 String shardName = info.getShardName();
1143 for (MemberName memberName : peerAddressResolver.getPeerMembers()) {
1144 String peerId = getShardIdentifier(memberName, shardName).toString() ;
1145 String peerAddress = peerAddressResolver.getShardActorAddress(shardName, memberName);
1146 info.updatePeerAddress(peerId, peerAddress, getSelf());
1147 info.peerUp(memberName, peerId, getSelf());
1148 LOG.debug("{}: updated peer {} on member {} with address {} on shard {} whose actor address is {}",
1149 persistenceId(), peerId, memberName, peerAddress, info.getShardId(), info.getActor());
1152 info.getActor().tell(message, getSelf());
1158 protected ClusterWrapper getCluster() {
1163 protected ActorRef newShardActor(final ShardInformation info) {
1164 return getContext().actorOf(info.newProps().withDispatcher(shardDispatcherPath),
1165 info.getShardId().toString());
1168 private void findPrimary(final FindPrimary message) {
1169 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1171 final String shardName = message.getShardName();
1172 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1174 // First see if the there is a local replica for the shard
1175 final ShardInformation info = localShards.get(shardName);
1176 if (info != null && info.isActiveMember()) {
1177 sendResponse(info, message.isWaitUntilReady(), true, () -> {
1178 String primaryPath = info.getSerializedLeaderActor();
1179 Object found = canReturnLocalShardState && info.isLeader()
1180 ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1181 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1183 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1190 final Collection<String> visitedAddresses;
1191 if (message instanceof RemoteFindPrimary) {
1192 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1194 visitedAddresses = new ArrayList<>(1);
1197 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1199 for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1200 if (visitedAddresses.contains(address)) {
1204 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1205 persistenceId(), shardName, address, visitedAddresses);
1207 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1208 message.isWaitUntilReady(), visitedAddresses), getContext());
1212 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1214 getSender().tell(new PrimaryNotFoundException(
1215 String.format("No primary shard found for %s.", shardName)), getSelf());
1218 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1219 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1220 .getShardInitializationTimeout().duration().$times(2));
1222 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1223 futureObj.onComplete(new OnComplete<Object>() {
1225 public void onComplete(final Throwable failure, final Object response) {
1226 if (failure != null) {
1227 handler.onFailure(failure);
1229 if (response instanceof RemotePrimaryShardFound) {
1230 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1231 } else if (response instanceof LocalPrimaryShardFound) {
1232 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1234 handler.onUnknownResponse(response);
1238 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1242 * Construct the name of the shard actor given the name of the member on
1243 * which the shard resides and the name of the shard.
1245 * @param memberName the member name
1246 * @param shardName the shard name
1249 private ShardIdentifier getShardIdentifier(final MemberName memberName, final String shardName) {
1250 return peerAddressResolver.getShardIdentifier(memberName, shardName);
1254 * Create shards that are local to the member on which the ShardManager runs.
1256 private void createLocalShards() {
1257 MemberName memberName = this.cluster.getCurrentMemberName();
1258 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1260 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1261 if (restoreFromSnapshot != null) {
1262 for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1263 shardSnapshots.put(snapshot.getName(), snapshot);
1268 restoreFromSnapshot = null;
1270 for (String shardName : memberShardNames) {
1271 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1273 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1275 Map<String, String> peerAddresses = getPeerAddresses(shardName);
1276 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
1277 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
1278 shardSnapshots.get(shardName)), peerAddressResolver));
1283 * Given the name of the shard find the addresses of all it's peers.
1285 * @param shardName the shard name
1287 private Map<String, String> getPeerAddresses(final String shardName) {
1288 final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1289 return getPeerAddresses(shardName, members);
1292 private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1293 Map<String, String> peerAddresses = new HashMap<>();
1294 MemberName currentMemberName = this.cluster.getCurrentMemberName();
1296 for (MemberName memberName : members) {
1297 if (!currentMemberName.equals(memberName)) {
1298 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1299 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1300 peerAddresses.put(shardId.toString(), address);
1303 return peerAddresses;
1307 public SupervisorStrategy supervisorStrategy() {
1309 return new OneForOneStrategy(10, Duration.create("1 minute"),
1310 (Function<Throwable, Directive>) t -> {
1311 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1312 return SupervisorStrategy.resume();
1317 public String persistenceId() {
1318 return persistenceId;
1322 ShardManagerInfoMBean getMBean() {
1323 return shardManagerMBean;
1326 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1327 if (shardReplicaOperationsInProgress.contains(shardName)) {
1328 String msg = String.format("A shard replica operation for %s is already in progress", shardName);
1329 LOG.debug("{}: {}", persistenceId(), msg);
1330 sender.tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1337 private void onAddPrefixShardReplica(final AddPrefixShardReplica message) {
1338 LOG.debug("{}: onAddPrefixShardReplica: {}", persistenceId(), message);
1340 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1341 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1342 final String shardName = shardId.getShardName();
1344 // Create the localShard
1345 if (schemaContext == null) {
1346 String msg = String.format(
1347 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1348 LOG.debug("{}: {}", persistenceId(), msg);
1349 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1353 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1356 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1357 final RunnableMessage runnable = (RunnableMessage) () -> addPrefixShard(getShardName(),
1358 message.getShardPrefix(), response, getSender());
1359 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1360 getSelf().tell(runnable, getTargetActor());
1365 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1366 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1371 private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1372 final String shardName = shardReplicaMsg.getShardName();
1374 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1376 // verify the shard with the specified name is present in the cluster configuration
1377 if (!this.configuration.isShardConfigured(shardName)) {
1378 String msg = String.format("No module configuration exists for shard %s", shardName);
1379 LOG.debug("{}: {}", persistenceId(), msg);
1380 getSender().tell(new Status.Failure(new IllegalArgumentException(msg)), getSelf());
1384 // Create the localShard
1385 if (schemaContext == null) {
1386 String msg = String.format(
1387 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1388 LOG.debug("{}: {}", persistenceId(), msg);
1389 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1393 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1396 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1397 final RunnableMessage runnable = (RunnableMessage) () ->
1398 addShard(getShardName(), response, getSender());
1399 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1400 getSelf().tell(runnable, getTargetActor());
1405 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1406 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1411 private void sendLocalReplicaAlreadyExistsReply(final String shardName, final ActorRef sender) {
1412 String msg = String.format("Local shard %s already exists", shardName);
1413 LOG.debug("{}: {}", persistenceId(), msg);
1414 sender.tell(new Status.Failure(new AlreadyExistsException(msg)), getSelf());
1417 private void addPrefixShard(final String shardName, final YangInstanceIdentifier shardPrefix,
1418 final RemotePrimaryShardFound response, final ActorRef sender) {
1419 if (isShardReplicaOperationInProgress(shardName, sender)) {
1423 shardReplicaOperationsInProgress.add(shardName);
1425 final ShardInformation shardInfo;
1426 final boolean removeShardOnFailure;
1427 ShardInformation existingShardInfo = localShards.get(shardName);
1428 if (existingShardInfo == null) {
1429 removeShardOnFailure = true;
1430 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1432 final Builder builder = newShardDatastoreContextBuilder(shardName);
1433 builder.storeRoot(shardPrefix).customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1435 DatastoreContext datastoreContext = builder.build();
1437 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1438 Shard.builder(), peerAddressResolver);
1439 shardInfo.setActiveMember(false);
1440 shardInfo.setSchemaContext(schemaContext);
1441 localShards.put(shardName, shardInfo);
1442 shardInfo.setActor(newShardActor(shardInfo));
1444 removeShardOnFailure = false;
1445 shardInfo = existingShardInfo;
1448 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1451 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1452 if (isShardReplicaOperationInProgress(shardName, sender)) {
1456 shardReplicaOperationsInProgress.add(shardName);
1458 final ShardInformation shardInfo;
1459 final boolean removeShardOnFailure;
1460 ShardInformation existingShardInfo = localShards.get(shardName);
1461 if (existingShardInfo == null) {
1462 removeShardOnFailure = true;
1463 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1465 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1466 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1468 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1469 Shard.builder(), peerAddressResolver);
1470 shardInfo.setActiveMember(false);
1471 shardInfo.setSchemaContext(schemaContext);
1472 localShards.put(shardName, shardInfo);
1473 shardInfo.setActor(newShardActor(shardInfo));
1475 removeShardOnFailure = false;
1476 shardInfo = existingShardInfo;
1479 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1482 private void execAddShard(final String shardName,
1483 final ShardInformation shardInfo,
1484 final RemotePrimaryShardFound response,
1485 final boolean removeShardOnFailure,
1486 final ActorRef sender) {
1488 final String localShardAddress =
1489 peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1491 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1492 LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1493 response.getPrimaryPath(), shardInfo.getShardId());
1495 final Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1496 .getShardLeaderElectionTimeout().duration());
1497 final Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1498 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1500 futureObj.onComplete(new OnComplete<Object>() {
1502 public void onComplete(final Throwable failure, final Object addServerResponse) {
1503 if (failure != null) {
1504 LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1505 response.getPrimaryPath(), shardName, failure);
1507 final String msg = String.format("AddServer request to leader %s for shard %s failed",
1508 response.getPrimaryPath(), shardName);
1509 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1511 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1512 response.getPrimaryPath(), removeShardOnFailure), sender);
1515 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1518 private void onAddServerFailure(final String shardName, final String message, final Throwable failure,
1519 final ActorRef sender, final boolean removeShardOnFailure) {
1520 shardReplicaOperationsInProgress.remove(shardName);
1522 if (removeShardOnFailure) {
1523 ShardInformation shardInfo = localShards.remove(shardName);
1524 if (shardInfo.getActor() != null) {
1525 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1529 sender.tell(new Status.Failure(message == null ? failure :
1530 new RuntimeException(message, failure)), getSelf());
1533 private void onAddServerReply(final ShardInformation shardInfo, final AddServerReply replyMsg,
1534 final ActorRef sender, final String leaderPath, final boolean removeShardOnFailure) {
1535 String shardName = shardInfo.getShardName();
1536 shardReplicaOperationsInProgress.remove(shardName);
1538 LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1540 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1541 LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1543 // Make the local shard voting capable
1544 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1545 shardInfo.setActiveMember(true);
1548 sender.tell(new Status.Success(null), getSelf());
1549 } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1550 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1552 LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1553 persistenceId(), shardName, replyMsg.getStatus());
1555 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1556 shardInfo.getShardId());
1558 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1562 private static Exception getServerChangeException(final Class<?> serverChange,
1563 final ServerChangeStatus serverChangeStatus, final String leaderPath, final ShardIdentifier shardId) {
1564 switch (serverChangeStatus) {
1566 return new TimeoutException(String.format(
1567 "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1568 + "Possible causes - there was a problem replicating the data or shard leadership changed "
1569 + "while replicating the shard data", leaderPath, shardId.getShardName()));
1571 return createNoShardLeaderException(shardId);
1573 return new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1574 serverChange.getSimpleName(), shardId.getShardName()));
1576 return new RuntimeException(String.format("%s request to leader %s for shard %s failed with status %s",
1577 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1581 private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1582 LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1584 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1585 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1587 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1588 doRemoveShardReplicaAsync(response.getPrimaryPath());
1592 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1593 doRemoveShardReplicaAsync(response.getPrimaryPath());
1596 private void doRemoveShardReplicaAsync(final String primaryPath) {
1597 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1598 primaryPath, getSender()), getTargetActor());
1603 private void onRemovePrefixShardReplica(final RemovePrefixShardReplica message) {
1604 LOG.debug("{}: onRemovePrefixShardReplica: {}", persistenceId(), message);
1606 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1607 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1608 final String shardName = shardId.getShardName();
1610 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(),
1611 shardName, persistenceId(), getSelf()) {
1613 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1614 doRemoveShardReplicaAsync(response.getPrimaryPath());
1618 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1619 doRemoveShardReplicaAsync(response.getPrimaryPath());
1622 private void doRemoveShardReplicaAsync(final String primaryPath) {
1623 getSelf().tell((RunnableMessage) () -> removePrefixShardReplica(message, getShardName(),
1624 primaryPath, getSender()), getTargetActor());
1629 private void persistShardList() {
1630 List<String> shardList = new ArrayList<>(localShards.keySet());
1631 for (ShardInformation shardInfo : localShards.values()) {
1632 if (!shardInfo.isActiveMember()) {
1633 shardList.remove(shardInfo.getShardName());
1636 LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1637 saveSnapshot(updateShardManagerSnapshot(shardList, configuration.getAllPrefixShardConfigurations()));
1640 private ShardManagerSnapshot updateShardManagerSnapshot(
1641 final List<String> shardList,
1642 final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> allPrefixShardConfigurations) {
1643 currentSnapshot = new ShardManagerSnapshot(shardList, allPrefixShardConfigurations);
1644 return currentSnapshot;
1647 private void applyShardManagerSnapshot(final ShardManagerSnapshot snapshot) {
1648 currentSnapshot = snapshot;
1650 LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1652 final MemberName currentMember = cluster.getCurrentMemberName();
1653 Set<String> configuredShardList =
1654 new HashSet<>(configuration.getMemberShardNames(currentMember));
1655 for (String shard : currentSnapshot.getShardList()) {
1656 if (!configuredShardList.contains(shard)) {
1657 // add the current member as a replica for the shard
1658 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1659 configuration.addMemberReplicaForShard(shard, currentMember);
1661 configuredShardList.remove(shard);
1664 for (String shard : configuredShardList) {
1665 // remove the member as a replica for the shard
1666 LOG.debug("{}: removing shard {}", persistenceId(), shard);
1667 configuration.removeMemberReplicaForShard(shard, currentMember);
1671 private void onSaveSnapshotSuccess(final SaveSnapshotSuccess successMessage) {
1672 LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1674 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1678 private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1679 LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1681 String shardName = changeMembersVotingStatus.getShardName();
1682 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1683 for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1684 serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1688 ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1690 findLocalShard(shardName, getSender(),
1691 localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1692 localShardFound.getPath(), getSender()));
1695 private void onFlipShardMembersVotingStatus(final FlipShardMembersVotingStatus flipMembersVotingStatus) {
1696 LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1698 ActorRef sender = getSender();
1699 final String shardName = flipMembersVotingStatus.getShardName();
1700 findLocalShard(shardName, sender, localShardFound -> {
1701 Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1702 Timeout.apply(30, TimeUnit.SECONDS));
1704 future.onComplete(new OnComplete<Object>() {
1706 public void onComplete(final Throwable failure, final Object response) {
1707 if (failure != null) {
1708 sender.tell(new Status.Failure(new RuntimeException(
1709 String.format("Failed to access local shard %s", shardName), failure)), self());
1713 OnDemandRaftState raftState = (OnDemandRaftState) response;
1714 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1715 for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1716 serverVotingStatusMap.put(e.getKey(), !e.getValue());
1719 serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1720 .toString(), !raftState.isVoting());
1722 changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1723 shardName, localShardFound.getPath(), sender);
1725 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1730 private void findLocalShard(final FindLocalShard message) {
1731 LOG.debug("{}: findLocalShard : {}", persistenceId(), message.getShardName());
1733 final ShardInformation shardInformation = localShards.get(message.getShardName());
1735 if (shardInformation == null) {
1736 LOG.debug("{}: Local shard {} not found - shards present: {}",
1737 persistenceId(), message.getShardName(), localShards.keySet());
1739 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1743 sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1744 () -> new LocalShardFound(shardInformation.getActor()));
1747 private void findLocalShard(final String shardName, final ActorRef sender,
1748 final Consumer<LocalShardFound> onLocalShardFound) {
1749 Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1750 .getShardInitializationTimeout().duration().$times(2));
1752 Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1753 futureObj.onComplete(new OnComplete<Object>() {
1755 public void onComplete(final Throwable failure, final Object response) {
1756 if (failure != null) {
1757 LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1759 sender.tell(new Status.Failure(new RuntimeException(
1760 String.format("Failed to find local shard %s", shardName), failure)), self());
1762 if (response instanceof LocalShardFound) {
1763 getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1765 } else if (response instanceof LocalShardNotFound) {
1766 String msg = String.format("Local shard %s does not exist", shardName);
1767 LOG.debug("{}: {}", persistenceId, msg);
1768 sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
1770 String msg = String.format("Failed to find local shard %s: received response: %s",
1771 shardName, response);
1772 LOG.debug("{}: {}", persistenceId, msg);
1773 sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1774 new RuntimeException(msg)), self());
1778 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1781 private void changeShardMembersVotingStatus(final ChangeServersVotingStatus changeServersVotingStatus,
1782 final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1783 if (isShardReplicaOperationInProgress(shardName, sender)) {
1787 shardReplicaOperationsInProgress.add(shardName);
1789 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1790 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1792 LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1793 changeServersVotingStatus, shardActorRef.path());
1795 Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1796 Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1798 futureObj.onComplete(new OnComplete<Object>() {
1800 public void onComplete(final Throwable failure, final Object response) {
1801 shardReplicaOperationsInProgress.remove(shardName);
1802 if (failure != null) {
1803 String msg = String.format("ChangeServersVotingStatus request to local shard %s failed",
1804 shardActorRef.path());
1805 LOG.debug("{}: {}", persistenceId(), msg, failure);
1806 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
1808 LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1810 ServerChangeReply replyMsg = (ServerChangeReply) response;
1811 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1812 LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1813 sender.tell(new Status.Success(null), getSelf());
1814 } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1815 sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1816 "The requested voting state change for shard %s is invalid. At least one member "
1817 + "must be voting", shardId.getShardName()))), getSelf());
1819 LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1820 persistenceId(), shardName, replyMsg.getStatus());
1822 Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1823 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1824 sender.tell(new Status.Failure(error), getSelf());
1828 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1831 private static final class ForwardedAddServerReply {
1832 ShardInformation shardInfo;
1833 AddServerReply addServerReply;
1835 boolean removeShardOnFailure;
1837 ForwardedAddServerReply(final ShardInformation shardInfo, final AddServerReply addServerReply,
1838 final String leaderPath, final boolean removeShardOnFailure) {
1839 this.shardInfo = shardInfo;
1840 this.addServerReply = addServerReply;
1841 this.leaderPath = leaderPath;
1842 this.removeShardOnFailure = removeShardOnFailure;
1846 private static final class ForwardedAddServerFailure {
1848 String failureMessage;
1850 boolean removeShardOnFailure;
1852 ForwardedAddServerFailure(final String shardName, final String failureMessage, final Throwable failure,
1853 final boolean removeShardOnFailure) {
1854 this.shardName = shardName;
1855 this.failureMessage = failureMessage;
1856 this.failure = failure;
1857 this.removeShardOnFailure = removeShardOnFailure;
1861 static class OnShardInitialized {
1862 private final Runnable replyRunnable;
1863 private Cancellable timeoutSchedule;
1865 OnShardInitialized(final Runnable replyRunnable) {
1866 this.replyRunnable = replyRunnable;
1869 Runnable getReplyRunnable() {
1870 return replyRunnable;
1873 Cancellable getTimeoutSchedule() {
1874 return timeoutSchedule;
1877 void setTimeoutSchedule(final Cancellable timeoutSchedule) {
1878 this.timeoutSchedule = timeoutSchedule;
1882 static class OnShardReady extends OnShardInitialized {
1883 OnShardReady(final Runnable replyRunnable) {
1884 super(replyRunnable);
1888 private interface RunnableMessage extends Runnable {
1892 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1893 * a remote or local find primary message is processed.
1895 private interface FindPrimaryResponseHandler {
1897 * Invoked when a Failure message is received as a response.
1899 * @param failure the failure exception
1901 void onFailure(Throwable failure);
1904 * Invoked when a RemotePrimaryShardFound response is received.
1906 * @param response the response
1908 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1911 * Invoked when a LocalPrimaryShardFound response is received.
1913 * @param response the response
1915 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1918 * Invoked when an unknown response is received. This is another type of failure.
1920 * @param response the response
1922 void onUnknownResponse(Object response);
1926 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1927 * replica and sends a wrapped Failure response to some targetActor.
1929 private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1930 private final ActorRef targetActor;
1931 private final String shardName;
1932 private final String persistenceId;
1933 private final ActorRef shardManagerActor;
1936 * Constructs an instance.
1938 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1939 * @param shardName The name of the shard for which the primary replica had to be found
1940 * @param persistenceId The persistenceId for the ShardManager
1941 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1943 protected AutoFindPrimaryFailureResponseHandler(final ActorRef targetActor, final String shardName,
1944 final String persistenceId, final ActorRef shardManagerActor) {
1945 this.targetActor = Preconditions.checkNotNull(targetActor);
1946 this.shardName = Preconditions.checkNotNull(shardName);
1947 this.persistenceId = Preconditions.checkNotNull(persistenceId);
1948 this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1951 public ActorRef getTargetActor() {
1955 public String getShardName() {
1960 public void onFailure(final Throwable failure) {
1961 LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1962 targetActor.tell(new Status.Failure(new RuntimeException(
1963 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1967 public void onUnknownResponse(final Object response) {
1968 String msg = String.format("Failed to find leader for shard %s: received response: %s",
1969 shardName, response);
1970 LOG.debug("{}: {}", persistenceId, msg);
1971 targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1972 new RuntimeException(msg)), shardManagerActor);
1977 * The WrappedShardResponse class wraps a response from a Shard.
1979 private static final class WrappedShardResponse {
1980 private final ShardIdentifier shardId;
1981 private final Object response;
1982 private final String leaderPath;
1984 WrappedShardResponse(final ShardIdentifier shardId, final Object response, final String leaderPath) {
1985 this.shardId = shardId;
1986 this.response = response;
1987 this.leaderPath = leaderPath;
1990 ShardIdentifier getShardId() {
1994 Object getResponse() {
1998 String getLeaderPath() {
2003 private static final class ShardNotInitializedTimeout {
2004 private final ActorRef sender;
2005 private final ShardInformation shardInfo;
2006 private final OnShardInitialized onShardInitialized;
2008 ShardNotInitializedTimeout(final ShardInformation shardInfo, final OnShardInitialized onShardInitialized,
2009 final ActorRef sender) {
2010 this.sender = sender;
2011 this.shardInfo = shardInfo;
2012 this.onShardInitialized = onShardInitialized;
2015 ActorRef getSender() {
2019 ShardInformation getShardInfo() {
2023 OnShardInitialized getOnShardInitialized() {
2024 return onShardInitialized;