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.RecoveryCompleted;
29 import akka.persistence.SaveSnapshotFailure;
30 import akka.persistence.SaveSnapshotSuccess;
31 import akka.persistence.SnapshotOffer;
32 import akka.persistence.SnapshotSelectionCriteria;
33 import akka.util.Timeout;
34 import com.google.common.annotations.VisibleForTesting;
35 import com.google.common.base.Preconditions;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
43 import java.util.Map.Entry;
45 import java.util.concurrent.CountDownLatch;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.TimeoutException;
48 import java.util.function.Consumer;
49 import java.util.function.Supplier;
50 import org.opendaylight.controller.cluster.access.concepts.MemberName;
51 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
52 import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
53 import org.opendaylight.controller.cluster.datastore.ClusterWrapper;
54 import org.opendaylight.controller.cluster.datastore.DatastoreContext;
55 import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
56 import org.opendaylight.controller.cluster.datastore.DatastoreContextFactory;
57 import org.opendaylight.controller.cluster.datastore.Shard;
58 import org.opendaylight.controller.cluster.datastore.config.Configuration;
59 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
60 import org.opendaylight.controller.cluster.datastore.config.PrefixShardConfiguration;
61 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
62 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
63 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
64 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
65 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
66 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
67 import org.opendaylight.controller.cluster.datastore.messages.AddPrefixShardReplica;
68 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
69 import org.opendaylight.controller.cluster.datastore.messages.ChangeShardMembersVotingStatus;
70 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
71 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
72 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
73 import org.opendaylight.controller.cluster.datastore.messages.FlipShardMembersVotingStatus;
74 import org.opendaylight.controller.cluster.datastore.messages.GetShardRole;
75 import org.opendaylight.controller.cluster.datastore.messages.GetShardRoleReply;
76 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
77 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
78 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
79 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
80 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
81 import org.opendaylight.controller.cluster.datastore.messages.RemovePrefixShardReplica;
82 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
83 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
84 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
85 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
86 import org.opendaylight.controller.cluster.datastore.persisted.ShardManagerSnapshot;
87 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
88 import org.opendaylight.controller.cluster.datastore.utils.CompositeOnComplete;
89 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
90 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
91 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
92 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
93 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
94 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
95 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
96 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
97 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
98 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
99 import org.opendaylight.controller.cluster.raft.messages.AddServer;
100 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
101 import org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus;
102 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
103 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
104 import org.opendaylight.controller.cluster.raft.messages.ServerChangeReply;
105 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
106 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
107 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
108 import org.opendaylight.controller.cluster.sharding.PrefixedShardConfigUpdateHandler;
109 import org.opendaylight.controller.cluster.sharding.messages.InitConfigListener;
110 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardCreated;
111 import org.opendaylight.controller.cluster.sharding.messages.PrefixShardRemoved;
112 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
113 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
114 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
115 import org.opendaylight.yangtools.concepts.ListenerRegistration;
116 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
117 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
118 import org.slf4j.Logger;
119 import org.slf4j.LoggerFactory;
120 import scala.concurrent.ExecutionContext;
121 import scala.concurrent.Future;
122 import scala.concurrent.duration.Duration;
123 import scala.concurrent.duration.FiniteDuration;
126 * Manages the shards for a data store. The ShardManager has the following jobs:
128 * <li> Create all the local shard replicas that belong on this cluster member
129 * <li> Find the address of the local shard
130 * <li> Find the primary replica for any given shard
131 * <li> Monitor the cluster members and store their addresses
134 class ShardManager extends AbstractUntypedPersistentActorWithMetering {
135 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
137 // Stores a mapping between a shard name and it's corresponding information
138 // Shard names look like inventory, topology etc and are as specified in
140 private final Map<String, ShardInformation> localShards = new HashMap<>();
142 // The type of a ShardManager reflects the type of the datastore itself
143 // A data store could be of type config/operational
144 private final String type;
146 private final ClusterWrapper cluster;
148 private final Configuration configuration;
150 private final String shardDispatcherPath;
152 private final ShardManagerInfo shardManagerMBean;
154 private DatastoreContextFactory datastoreContextFactory;
156 private final CountDownLatch waitTillReadyCountdownLatch;
158 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
160 private final ShardPeerAddressResolver peerAddressResolver;
162 private SchemaContext schemaContext;
164 private DatastoreSnapshot restoreFromSnapshot;
166 private ShardManagerSnapshot currentSnapshot;
168 private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
170 private final Map<String, CompositeOnComplete<Boolean>> shardActorsStopping = new HashMap<>();
172 private final String persistenceId;
173 private final AbstractDataStore dataStore;
175 private ListenerRegistration<DOMDataTreeChangeListener> configListenerReg = null;
176 private PrefixedShardConfigUpdateHandler configUpdateHandler;
178 ShardManager(final AbstractShardManagerCreator<?> builder) {
179 this.cluster = builder.getCluster();
180 this.configuration = builder.getConfiguration();
181 this.datastoreContextFactory = builder.getDatastoreContextFactory();
182 this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
183 this.shardDispatcherPath =
184 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
185 this.waitTillReadyCountdownLatch = builder.getWaitTillReadyCountDownLatch();
186 this.primaryShardInfoCache = builder.getPrimaryShardInfoCache();
187 this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
189 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
190 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
192 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
194 // Subscribe this actor to cluster member events
195 cluster.subscribeToMemberEvents(getSelf());
197 shardManagerMBean = new ShardManagerInfo(getSelf(), cluster.getCurrentMemberName(),
198 "shard-manager-" + this.type,
199 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
200 shardManagerMBean.registerMBean();
202 dataStore = builder.getDistributedDataStore();
206 public void preStart() {
207 LOG.info("Starting ShardManager {}", persistenceId);
211 public void postStop() {
212 LOG.info("Stopping ShardManager {}", persistenceId());
214 shardManagerMBean.unregisterMBean();
216 if (configListenerReg != null) {
217 configListenerReg.close();
218 configListenerReg = null;
223 public void handleCommand(final Object message) throws Exception {
224 if (message instanceof FindPrimary) {
225 findPrimary((FindPrimary)message);
226 } else if (message instanceof FindLocalShard) {
227 findLocalShard((FindLocalShard) message);
228 } else if (message instanceof UpdateSchemaContext) {
229 updateSchemaContext(message);
230 } else if (message instanceof ActorInitialized) {
231 onActorInitialized(message);
232 } else if (message instanceof ClusterEvent.MemberUp) {
233 memberUp((ClusterEvent.MemberUp) message);
234 } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
235 memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
236 } else if (message instanceof ClusterEvent.MemberExited) {
237 memberExited((ClusterEvent.MemberExited) message);
238 } else if (message instanceof ClusterEvent.MemberRemoved) {
239 memberRemoved((ClusterEvent.MemberRemoved) message);
240 } else if (message instanceof ClusterEvent.UnreachableMember) {
241 memberUnreachable((ClusterEvent.UnreachableMember) message);
242 } else if (message instanceof ClusterEvent.ReachableMember) {
243 memberReachable((ClusterEvent.ReachableMember) message);
244 } else if (message instanceof DatastoreContextFactory) {
245 onDatastoreContextFactory((DatastoreContextFactory) message);
246 } else if (message instanceof RoleChangeNotification) {
247 onRoleChangeNotification((RoleChangeNotification) message);
248 } else if (message instanceof FollowerInitialSyncUpStatus) {
249 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
250 } else if (message instanceof ShardNotInitializedTimeout) {
251 onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
252 } else if (message instanceof ShardLeaderStateChanged) {
253 onLeaderStateChanged((ShardLeaderStateChanged) message);
254 } else if (message instanceof SwitchShardBehavior) {
255 onSwitchShardBehavior((SwitchShardBehavior) message);
256 } else if (message instanceof CreateShard) {
257 onCreateShard((CreateShard)message);
258 } else if (message instanceof AddShardReplica) {
259 onAddShardReplica((AddShardReplica) message);
260 } else if (message instanceof AddPrefixShardReplica) {
261 onAddPrefixShardReplica((AddPrefixShardReplica) message);
262 } else if (message instanceof PrefixShardCreated) {
263 onPrefixShardCreated((PrefixShardCreated) message);
264 } else if (message instanceof PrefixShardRemoved) {
265 onPrefixShardRemoved((PrefixShardRemoved) message);
266 } else if (message instanceof InitConfigListener) {
267 onInitConfigListener();
268 } else if (message instanceof ForwardedAddServerReply) {
269 ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
270 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
271 msg.removeShardOnFailure);
272 } else if (message instanceof ForwardedAddServerFailure) {
273 ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
274 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
275 } else if (message instanceof RemoveShardReplica) {
276 onRemoveShardReplica((RemoveShardReplica) message);
277 } else if (message instanceof RemovePrefixShardReplica) {
278 onRemovePrefixShardReplica((RemovePrefixShardReplica) message);
279 } else if (message instanceof WrappedShardResponse) {
280 onWrappedShardResponse((WrappedShardResponse) message);
281 } else if (message instanceof GetSnapshot) {
283 } else if (message instanceof ServerRemoved) {
284 onShardReplicaRemoved((ServerRemoved) message);
285 } else if (message instanceof ChangeShardMembersVotingStatus) {
286 onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
287 } else if (message instanceof FlipShardMembersVotingStatus) {
288 onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
289 } else if (message instanceof SaveSnapshotSuccess) {
290 onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
291 } else if (message instanceof SaveSnapshotFailure) {
292 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
293 ((SaveSnapshotFailure) message).cause());
294 } else if (message instanceof Shutdown) {
296 } else if (message instanceof GetLocalShardIds) {
297 onGetLocalShardIds();
298 } else if (message instanceof GetShardRole) {
299 onGetShardRole((GetShardRole) message);
300 } else if (message instanceof RunnableMessage) {
301 ((RunnableMessage)message).run();
303 unknownMessage(message);
307 private void onGetShardRole(final GetShardRole message) {
308 LOG.debug("{}: onGetShardRole for shard: {}", persistenceId(), message.getName());
310 final String name = message.getName();
312 final ShardInformation shardInformation = localShards.get(name);
314 if (shardInformation == null) {
315 LOG.info("{}: no shard information for {} found", persistenceId(), name);
316 getSender().tell(new Status.Failure(
317 new IllegalArgumentException("Shard with name " + name + " not present.")), ActorRef.noSender());
321 getSender().tell(new GetShardRoleReply(shardInformation.getRole()), ActorRef.noSender());
324 private void onInitConfigListener() {
325 LOG.debug("{}: Initializing config listener on {}", persistenceId(), cluster.getCurrentMemberName());
327 final org.opendaylight.mdsal.common.api.LogicalDatastoreType type =
328 org.opendaylight.mdsal.common.api.LogicalDatastoreType
329 .valueOf(datastoreContextFactory.getBaseDatastoreContext().getLogicalStoreType().name());
331 if (configUpdateHandler != null) {
332 configUpdateHandler.close();
335 configUpdateHandler = new PrefixedShardConfigUpdateHandler(self(), cluster.getCurrentMemberName());
336 configUpdateHandler.initListener(dataStore, type);
339 private void onShutDown() {
340 List<Future<Boolean>> stopFutures = new ArrayList<>(localShards.size());
341 for (ShardInformation info : localShards.values()) {
342 if (info.getActor() != null) {
343 LOG.debug("{}: Issuing gracefulStop to shard {}", persistenceId(), info.getShardId());
345 FiniteDuration duration = info.getDatastoreContext().getShardRaftConfig()
346 .getElectionTimeOutInterval().$times(2);
347 stopFutures.add(Patterns.gracefulStop(info.getActor(), duration, Shutdown.INSTANCE));
351 LOG.info("Shutting down ShardManager {} - waiting on {} shards", persistenceId(), stopFutures.size());
353 ExecutionContext dispatcher = new Dispatchers(context().system().dispatchers())
354 .getDispatcher(Dispatchers.DispatcherType.Client);
355 Future<Iterable<Boolean>> combinedFutures = Futures.sequence(stopFutures, dispatcher);
357 combinedFutures.onComplete(new OnComplete<Iterable<Boolean>>() {
359 public void onComplete(final Throwable failure, final Iterable<Boolean> results) {
360 LOG.debug("{}: All shards shutdown - sending PoisonPill to self", persistenceId());
362 self().tell(PoisonPill.getInstance(), self());
364 if (failure != null) {
365 LOG.warn("{}: An error occurred attempting to shut down the shards", persistenceId(), failure);
368 for (Boolean result : results) {
375 LOG.warn("{}: {} shards did not shut down gracefully", persistenceId(), nfailed);
382 private void onWrappedShardResponse(final WrappedShardResponse message) {
383 if (message.getResponse() instanceof RemoveServerReply) {
384 onRemoveServerReply(getSender(), message.getShardId(), (RemoveServerReply) message.getResponse(),
385 message.getLeaderPath());
389 private void onRemoveServerReply(final ActorRef originalSender, final ShardIdentifier shardId,
390 final RemoveServerReply replyMsg, final String leaderPath) {
391 shardReplicaOperationsInProgress.remove(shardId.getShardName());
393 LOG.debug("{}: Received {} for shard {}", persistenceId(), replyMsg, shardId.getShardName());
395 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
396 LOG.debug("{}: Leader shard successfully removed the replica shard {}", persistenceId(),
397 shardId.getShardName());
398 originalSender.tell(new Status.Success(null), getSelf());
400 LOG.warn("{}: Leader failed to remove shard replica {} with status {}",
401 persistenceId(), shardId, replyMsg.getStatus());
403 Exception failure = getServerChangeException(RemoveServer.class, replyMsg.getStatus(), leaderPath, shardId);
404 originalSender.tell(new Status.Failure(failure), getSelf());
408 private void removePrefixShardReplica(final RemovePrefixShardReplica contextMessage, final String shardName,
409 final String primaryPath, final ActorRef sender) {
410 if (isShardReplicaOperationInProgress(shardName, sender)) {
414 shardReplicaOperationsInProgress.add(shardName);
416 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
418 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
420 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
421 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
422 primaryPath, shardId);
424 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
425 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
426 new RemoveServer(shardId.toString()), removeServerTimeout);
428 futureObj.onComplete(new OnComplete<Object>() {
430 public void onComplete(final Throwable failure, final Object response) {
431 if (failure != null) {
432 shardReplicaOperationsInProgress.remove(shardName);
433 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
434 primaryPath, shardName);
436 LOG.debug("{}: {}", persistenceId(), msg, failure);
439 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
442 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
445 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
448 private void removeShardReplica(final RemoveShardReplica contextMessage, final String shardName,
449 final String primaryPath, final ActorRef sender) {
450 if (isShardReplicaOperationInProgress(shardName, sender)) {
454 shardReplicaOperationsInProgress.add(shardName);
456 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
458 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
460 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
461 LOG.debug("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
462 primaryPath, shardId);
464 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
465 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
466 new RemoveServer(shardId.toString()), removeServerTimeout);
468 futureObj.onComplete(new OnComplete<Object>() {
470 public void onComplete(final Throwable failure, final Object response) {
471 if (failure != null) {
472 shardReplicaOperationsInProgress.remove(shardName);
473 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
474 primaryPath, shardName);
476 LOG.debug("{}: {}", persistenceId(), msg, failure);
479 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
482 self().tell(new WrappedShardResponse(shardId, response, primaryPath), sender);
485 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
488 private void onShardReplicaRemoved(final ServerRemoved message) {
489 removeShard(new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build());
492 @SuppressWarnings("checkstyle:IllegalCatch")
493 private void removeShard(final ShardIdentifier shardId) {
494 final String shardName = shardId.getShardName();
495 final ShardInformation shardInformation = localShards.remove(shardName);
496 if (shardInformation == null) {
497 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
501 final ActorRef shardActor = shardInformation.getActor();
502 if (shardActor != null) {
503 long timeoutInMS = Math.max(shardInformation.getDatastoreContext().getShardRaftConfig()
504 .getElectionTimeOutInterval().$times(3).toMillis(), 10000);
506 LOG.debug("{} : Sending Shutdown to Shard actor {} with {} ms timeout", persistenceId(), shardActor,
509 final Future<Boolean> stopFuture = Patterns.gracefulStop(shardActor,
510 FiniteDuration.apply(timeoutInMS, TimeUnit.MILLISECONDS), Shutdown.INSTANCE);
512 final CompositeOnComplete<Boolean> onComplete = new CompositeOnComplete<Boolean>() {
514 public void onComplete(final Throwable failure, final Boolean result) {
515 if (failure == null) {
516 LOG.debug("{} : Successfully shut down Shard actor {}", persistenceId(), shardActor);
518 LOG.warn("{}: Failed to shut down Shard actor {}", persistenceId(), shardActor, failure);
521 self().tell((RunnableMessage) () -> {
522 shardActorsStopping.remove(shardName);
523 notifyOnCompleteTasks(failure, result);
524 }, ActorRef.noSender());
528 shardActorsStopping.put(shardName, onComplete);
529 stopFuture.onComplete(onComplete, new Dispatchers(context().system().dispatchers())
530 .getDispatcher(Dispatchers.DispatcherType.Client));
533 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardName);
537 private void onGetSnapshot() {
538 LOG.debug("{}: onGetSnapshot", persistenceId());
540 List<String> notInitialized = null;
541 for (ShardInformation shardInfo : localShards.values()) {
542 if (!shardInfo.isShardInitialized()) {
543 if (notInitialized == null) {
544 notInitialized = new ArrayList<>();
547 notInitialized.add(shardInfo.getShardName());
551 if (notInitialized != null) {
552 getSender().tell(new Status.Failure(new IllegalStateException(String.format(
553 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
557 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
558 new ArrayList<>(localShards.keySet()), type, currentSnapshot , getSender(), persistenceId(),
559 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
561 for (ShardInformation shardInfo: localShards.values()) {
562 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
566 @SuppressWarnings("checkstyle:IllegalCatch")
567 private void onCreateShard(final CreateShard createShard) {
568 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
572 String shardName = createShard.getModuleShardConfig().getShardName();
573 if (localShards.containsKey(shardName)) {
574 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
575 reply = new Status.Success(String.format("Shard with name %s already exists", shardName));
577 doCreateShard(createShard);
578 reply = new Status.Success(null);
580 } catch (Exception e) {
581 LOG.error("{}: onCreateShard failed", persistenceId(), e);
582 reply = new Status.Failure(e);
585 if (getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
586 getSender().tell(reply, getSelf());
590 private void onPrefixShardCreated(final PrefixShardCreated message) {
591 LOG.debug("{}: onPrefixShardCreated: {}", persistenceId(), message);
593 final PrefixShardConfiguration config = message.getConfiguration();
594 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
595 ClusterUtils.getCleanShardName(config.getPrefix().getRootIdentifier()));
596 final String shardName = shardId.getShardName();
598 if (isPreviousShardActorStopInProgress(shardName, message)) {
602 if (localShards.containsKey(shardName)) {
603 LOG.debug("{}: Received create for an already existing shard {}", persistenceId(), shardName);
604 final PrefixShardConfiguration existing =
605 configuration.getAllPrefixShardConfigurations().get(config.getPrefix());
607 if (existing != null && existing.equals(config)) {
608 // we don't have to do nothing here
613 doCreatePrefixShard(config, shardId, shardName);
616 private boolean isPreviousShardActorStopInProgress(final String shardName, final Object messageToDefer) {
617 final CompositeOnComplete<Boolean> stopOnComplete = shardActorsStopping.get(shardName);
618 if (stopOnComplete == null) {
622 LOG.debug("{} : Stop is in progress for shard {} - adding OnComplete callback to defer {}", persistenceId(),
623 shardName, messageToDefer);
624 final ActorRef sender = getSender();
625 stopOnComplete.addOnComplete(new OnComplete<Boolean>() {
627 public void onComplete(final Throwable failure, final Boolean result) {
628 LOG.debug("{} : Stop complete for shard {} - re-queing {}", persistenceId(), shardName, messageToDefer);
629 self().tell(messageToDefer, sender);
636 private void doCreatePrefixShard(final PrefixShardConfiguration config, final ShardIdentifier shardId,
637 final String shardName) {
638 configuration.addPrefixShardConfiguration(config);
640 final Builder builder = newShardDatastoreContextBuilder(shardName);
641 builder.logicalStoreType(LogicalDatastoreType.valueOf(config.getPrefix().getDatastoreType().name()))
642 .storeRoot(config.getPrefix().getRootIdentifier());
643 DatastoreContext shardDatastoreContext = builder.build();
645 final Map<String, String> peerAddresses = getPeerAddresses(shardName);
646 final boolean isActiveMember = true;
648 LOG.debug("{} doCreatePrefixShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
649 persistenceId(), shardId, config.getShardMemberNames(), peerAddresses, isActiveMember);
651 final ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
652 shardDatastoreContext, Shard.builder(), peerAddressResolver);
653 info.setActiveMember(isActiveMember);
654 localShards.put(info.getShardName(), info);
656 if (schemaContext != null) {
657 info.setSchemaContext(schemaContext);
658 info.setActor(newShardActor(info));
662 private void onPrefixShardRemoved(final PrefixShardRemoved message) {
663 LOG.debug("{}: onPrefixShardRemoved : {}", persistenceId(), message);
665 final DOMDataTreeIdentifier prefix = message.getPrefix();
666 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
667 ClusterUtils.getCleanShardName(prefix.getRootIdentifier()));
669 configuration.removePrefixShardConfiguration(prefix);
670 removeShard(shardId);
673 private void doCreateShard(final CreateShard createShard) {
674 final ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
675 final String shardName = moduleShardConfig.getShardName();
677 configuration.addModuleShardConfiguration(moduleShardConfig);
679 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
680 if (shardDatastoreContext == null) {
681 shardDatastoreContext = newShardDatastoreContext(shardName);
683 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
684 peerAddressResolver).build();
687 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
689 boolean shardWasInRecoveredSnapshot = currentSnapshot != null
690 && currentSnapshot.getShardList().contains(shardName);
692 Map<String, String> peerAddresses;
693 boolean isActiveMember;
694 if (shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName)
695 .contains(cluster.getCurrentMemberName())) {
696 peerAddresses = getPeerAddresses(shardName);
697 isActiveMember = true;
699 // The local member is not in the static shard member configuration and the shard did not
700 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
701 // the shard with no peers and with elections disabled so it stays as follower. A
702 // subsequent AddServer request will be needed to make it an active member.
703 isActiveMember = false;
704 peerAddresses = Collections.emptyMap();
705 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext)
706 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
709 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
710 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
713 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
714 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
715 info.setActiveMember(isActiveMember);
716 localShards.put(info.getShardName(), info);
718 if (schemaContext != null) {
719 info.setSchemaContext(schemaContext);
720 info.setActor(newShardActor(info));
724 private DatastoreContext.Builder newShardDatastoreContextBuilder(final String shardName) {
725 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName))
726 .shardPeerAddressResolver(peerAddressResolver);
729 private DatastoreContext newShardDatastoreContext(final String shardName) {
730 return newShardDatastoreContextBuilder(shardName).build();
733 private void checkReady() {
734 if (isReadyWithLeaderId()) {
735 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
736 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
738 waitTillReadyCountdownLatch.countDown();
742 private void onLeaderStateChanged(final ShardLeaderStateChanged leaderStateChanged) {
743 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
745 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
746 if (shardInformation != null) {
747 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
748 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
749 if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
750 primaryShardInfoCache.remove(shardInformation.getShardName());
755 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
759 private void onShardNotInitializedTimeout(final ShardNotInitializedTimeout message) {
760 ShardInformation shardInfo = message.getShardInfo();
762 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
763 shardInfo.getShardName());
765 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
767 if (!shardInfo.isShardInitialized()) {
768 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
769 message.getSender().tell(createNotInitializedException(shardInfo.getShardId()), getSelf());
771 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
772 message.getSender().tell(createNoShardLeaderException(shardInfo.getShardId()), getSelf());
776 private void onFollowerInitialSyncStatus(final FollowerInitialSyncUpStatus status) {
777 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
778 status.getName(), status.isInitialSyncDone());
780 ShardInformation shardInformation = findShardInformation(status.getName());
782 if (shardInformation != null) {
783 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
785 shardManagerMBean.setSyncStatus(isInSync());
790 private void onRoleChangeNotification(final RoleChangeNotification roleChanged) {
791 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
792 roleChanged.getOldRole(), roleChanged.getNewRole());
794 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
795 if (shardInformation != null) {
796 shardInformation.setRole(roleChanged.getNewRole());
798 shardManagerMBean.setSyncStatus(isInSync());
803 private ShardInformation findShardInformation(final String memberId) {
804 for (ShardInformation info : localShards.values()) {
805 if (info.getShardId().toString().equals(memberId)) {
813 private boolean isReadyWithLeaderId() {
814 boolean isReady = true;
815 for (ShardInformation info : localShards.values()) {
816 if (!info.isShardReadyWithLeaderId()) {
824 private boolean isInSync() {
825 for (ShardInformation info : localShards.values()) {
826 if (!info.isInSync()) {
833 private void onActorInitialized(final Object message) {
834 final ActorRef sender = getSender();
836 if (sender == null) {
837 return; //why is a non-actor sending this message? Just ignore.
840 String actorName = sender.path().name();
841 //find shard name from actor name; actor name is stringified shardId
843 final ShardIdentifier shardId;
845 shardId = ShardIdentifier.fromShardIdString(actorName);
846 } catch (IllegalArgumentException e) {
847 LOG.debug("{}: ignoring actor {}", actorName, e);
851 markShardAsInitialized(shardId.getShardName());
854 private void markShardAsInitialized(final String shardName) {
855 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
857 ShardInformation shardInformation = localShards.get(shardName);
858 if (shardInformation != null) {
859 shardInformation.setActorInitialized();
861 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
866 protected void handleRecover(final Object message) throws Exception {
867 if (message instanceof RecoveryCompleted) {
868 onRecoveryCompleted();
869 } else if (message instanceof SnapshotOffer) {
870 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
874 @SuppressWarnings("checkstyle:IllegalCatch")
875 private void onRecoveryCompleted() {
876 LOG.info("Recovery complete : {}", persistenceId());
878 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
879 // journal on upgrade from Helium.
880 deleteMessages(lastSequenceNr());
882 if (currentSnapshot == null && restoreFromSnapshot != null
883 && restoreFromSnapshot.getShardManagerSnapshot() != null) {
884 ShardManagerSnapshot snapshot = restoreFromSnapshot.getShardManagerSnapshot();
886 LOG.debug("{}: Restoring from ShardManagerSnapshot: {}", persistenceId(), snapshot);
888 applyShardManagerSnapshot(snapshot);
894 private void sendResponse(final ShardInformation shardInformation, final boolean doWait,
895 final boolean wantShardReady, final Supplier<Object> messageSupplier) {
896 if (!shardInformation.isShardInitialized() || wantShardReady && !shardInformation.isShardReadyWithLeaderId()) {
898 final ActorRef sender = getSender();
899 final ActorRef self = self();
901 Runnable replyRunnable = () -> sender.tell(messageSupplier.get(), self);
903 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
904 new OnShardInitialized(replyRunnable);
906 shardInformation.addOnShardInitialized(onShardInitialized);
908 FiniteDuration timeout = shardInformation.getDatastoreContext()
909 .getShardInitializationTimeout().duration();
910 if (shardInformation.isShardInitialized()) {
911 // If the shard is already initialized then we'll wait enough time for the shard to
912 // elect a leader, ie 2 times the election timeout.
913 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
914 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
917 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
918 shardInformation.getShardName());
920 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
922 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
923 getContext().dispatcher(), getSelf());
925 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
927 } else if (!shardInformation.isShardInitialized()) {
928 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
929 shardInformation.getShardName());
930 getSender().tell(createNotInitializedException(shardInformation.getShardId()), getSelf());
932 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
933 shardInformation.getShardName());
934 getSender().tell(createNoShardLeaderException(shardInformation.getShardId()), getSelf());
940 getSender().tell(messageSupplier.get(), getSelf());
943 private static NoShardLeaderException createNoShardLeaderException(final ShardIdentifier shardId) {
944 return new NoShardLeaderException(null, shardId.toString());
947 private static NotInitializedException createNotInitializedException(final ShardIdentifier shardId) {
948 return new NotInitializedException(String.format(
949 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
953 static MemberName memberToName(final Member member) {
954 return MemberName.forName(member.roles().iterator().next());
957 private void memberRemoved(final ClusterEvent.MemberRemoved message) {
958 MemberName memberName = memberToName(message.member());
960 LOG.info("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
961 message.member().address());
963 peerAddressResolver.removePeerAddress(memberName);
965 for (ShardInformation info : localShards.values()) {
966 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
970 private void memberExited(final ClusterEvent.MemberExited message) {
971 MemberName memberName = memberToName(message.member());
973 LOG.info("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
974 message.member().address());
976 peerAddressResolver.removePeerAddress(memberName);
978 for (ShardInformation info : localShards.values()) {
979 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
983 private void memberUp(final ClusterEvent.MemberUp message) {
984 MemberName memberName = memberToName(message.member());
986 LOG.info("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
987 message.member().address());
989 memberUp(memberName, message.member().address());
992 private void memberUp(final MemberName memberName, final Address address) {
993 addPeerAddress(memberName, address);
997 private void memberWeaklyUp(final MemberWeaklyUp message) {
998 MemberName memberName = memberToName(message.member());
1000 LOG.info("{}: Received MemberWeaklyUp: memberName: {}, address: {}", persistenceId(), memberName,
1001 message.member().address());
1003 memberUp(memberName, message.member().address());
1006 private void addPeerAddress(final MemberName memberName, final Address address) {
1007 peerAddressResolver.addPeerAddress(memberName, address);
1009 for (ShardInformation info : localShards.values()) {
1010 String shardName = info.getShardName();
1011 String peerId = getShardIdentifier(memberName, shardName).toString();
1012 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
1014 info.peerUp(memberName, peerId, getSelf());
1018 private void memberReachable(final ClusterEvent.ReachableMember message) {
1019 MemberName memberName = memberToName(message.member());
1020 LOG.info("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
1022 addPeerAddress(memberName, message.member().address());
1024 markMemberAvailable(memberName);
1027 private void memberUnreachable(final ClusterEvent.UnreachableMember message) {
1028 MemberName memberName = memberToName(message.member());
1029 LOG.info("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
1031 markMemberUnavailable(memberName);
1034 private void markMemberUnavailable(final MemberName memberName) {
1035 final String memberStr = memberName.getName();
1036 for (ShardInformation info : localShards.values()) {
1037 String leaderId = info.getLeaderId();
1038 // XXX: why are we using String#contains() here?
1039 if (leaderId != null && leaderId.contains(memberStr)) {
1040 LOG.debug("Marking Leader {} as unavailable.", leaderId);
1041 info.setLeaderAvailable(false);
1043 primaryShardInfoCache.remove(info.getShardName());
1046 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1050 private void markMemberAvailable(final MemberName memberName) {
1051 final String memberStr = memberName.getName();
1052 for (ShardInformation info : localShards.values()) {
1053 String leaderId = info.getLeaderId();
1054 // XXX: why are we using String#contains() here?
1055 if (leaderId != null && leaderId.contains(memberStr)) {
1056 LOG.debug("Marking Leader {} as available.", leaderId);
1057 info.setLeaderAvailable(true);
1060 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
1064 private void onDatastoreContextFactory(final DatastoreContextFactory factory) {
1065 datastoreContextFactory = factory;
1066 for (ShardInformation info : localShards.values()) {
1067 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
1071 private void onGetLocalShardIds() {
1072 final List<String> response = new ArrayList<>(localShards.size());
1074 for (ShardInformation info : localShards.values()) {
1075 response.add(info.getShardId().toString());
1078 getSender().tell(new Status.Success(response), getSelf());
1081 private void onSwitchShardBehavior(final SwitchShardBehavior message) {
1082 final ShardIdentifier identifier = message.getShardId();
1084 if (identifier != null) {
1085 final ShardInformation info = localShards.get(identifier.getShardName());
1087 getSender().tell(new Status.Failure(
1088 new IllegalArgumentException("Shard " + identifier + " is not local")), getSelf());
1092 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1094 for (ShardInformation info : localShards.values()) {
1095 switchShardBehavior(info, new SwitchBehavior(message.getNewState(), message.getTerm()));
1099 getSender().tell(new Status.Success(null), getSelf());
1102 private void switchShardBehavior(final ShardInformation info, final SwitchBehavior switchBehavior) {
1103 final ActorRef actor = info.getActor();
1104 if (actor != null) {
1105 actor.tell(switchBehavior, getSelf());
1107 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
1108 info.getShardName(), switchBehavior.getNewState());
1113 * Notifies all the local shards of a change in the schema context.
1115 * @param message the message to send
1117 private void updateSchemaContext(final Object message) {
1118 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
1120 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
1122 for (ShardInformation info : localShards.values()) {
1123 info.setSchemaContext(schemaContext);
1125 if (info.getActor() == null) {
1126 LOG.debug("Creating Shard {}", info.getShardId());
1127 info.setActor(newShardActor(info));
1129 info.getActor().tell(message, getSelf());
1135 protected ClusterWrapper getCluster() {
1140 protected ActorRef newShardActor(final ShardInformation info) {
1141 return getContext().actorOf(info.newProps().withDispatcher(shardDispatcherPath),
1142 info.getShardId().toString());
1145 private void findPrimary(final FindPrimary message) {
1146 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
1148 final String shardName = message.getShardName();
1149 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
1151 // First see if the there is a local replica for the shard
1152 final ShardInformation info = localShards.get(shardName);
1153 if (info != null && info.isActiveMember()) {
1154 sendResponse(info, message.isWaitUntilReady(), true, () -> {
1155 String primaryPath = info.getSerializedLeaderActor();
1156 Object found = canReturnLocalShardState && info.isLeader()
1157 ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
1158 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
1160 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
1167 final Collection<String> visitedAddresses;
1168 if (message instanceof RemoteFindPrimary) {
1169 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
1171 visitedAddresses = new ArrayList<>(1);
1174 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
1176 for (String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
1177 if (visitedAddresses.contains(address)) {
1181 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}, visitedAddresses: {}",
1182 persistenceId(), shardName, address, visitedAddresses);
1184 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
1185 message.isWaitUntilReady(), visitedAddresses), getContext());
1189 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
1191 getSender().tell(new PrimaryNotFoundException(
1192 String.format("No primary shard found for %s.", shardName)), getSelf());
1195 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1196 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1197 .getShardInitializationTimeout().duration().$times(2));
1199 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1200 futureObj.onComplete(new OnComplete<Object>() {
1202 public void onComplete(final Throwable failure, final Object response) {
1203 if (failure != null) {
1204 handler.onFailure(failure);
1206 if (response instanceof RemotePrimaryShardFound) {
1207 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1208 } else if (response instanceof LocalPrimaryShardFound) {
1209 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1211 handler.onUnknownResponse(response);
1215 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1219 * Construct the name of the shard actor given the name of the member on
1220 * which the shard resides and the name of the shard.
1222 * @param memberName the member name
1223 * @param shardName the shard name
1226 private ShardIdentifier getShardIdentifier(final MemberName memberName, final String shardName) {
1227 return peerAddressResolver.getShardIdentifier(memberName, shardName);
1231 * Create shards that are local to the member on which the ShardManager runs.
1233 private void createLocalShards() {
1234 MemberName memberName = this.cluster.getCurrentMemberName();
1235 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
1237 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
1238 if (restoreFromSnapshot != null) {
1239 for (DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
1240 shardSnapshots.put(snapshot.getName(), snapshot);
1244 restoreFromSnapshot = null; // null out to GC
1246 for (String shardName : memberShardNames) {
1247 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1249 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
1251 Map<String, String> peerAddresses = getPeerAddresses(shardName);
1252 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
1253 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
1254 shardSnapshots.get(shardName)), peerAddressResolver));
1259 * Given the name of the shard find the addresses of all it's peers.
1261 * @param shardName the shard name
1263 private Map<String, String> getPeerAddresses(final String shardName) {
1264 final Collection<MemberName> members = configuration.getMembersFromShardName(shardName);
1265 return getPeerAddresses(shardName, members);
1268 private Map<String, String> getPeerAddresses(final String shardName, final Collection<MemberName> members) {
1269 Map<String, String> peerAddresses = new HashMap<>();
1270 MemberName currentMemberName = this.cluster.getCurrentMemberName();
1272 for (MemberName memberName : members) {
1273 if (!currentMemberName.equals(memberName)) {
1274 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
1275 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
1276 peerAddresses.put(shardId.toString(), address);
1279 return peerAddresses;
1283 public SupervisorStrategy supervisorStrategy() {
1285 return new OneForOneStrategy(10, Duration.create("1 minute"),
1286 (Function<Throwable, Directive>) t -> {
1287 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
1288 return SupervisorStrategy.resume();
1293 public String persistenceId() {
1294 return persistenceId;
1298 ShardManagerInfoMBean getMBean() {
1299 return shardManagerMBean;
1302 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
1303 if (shardReplicaOperationsInProgress.contains(shardName)) {
1304 String msg = String.format("A shard replica operation for %s is already in progress", shardName);
1305 LOG.debug("{}: {}", persistenceId(), msg);
1306 sender.tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1313 private void onAddPrefixShardReplica(final AddPrefixShardReplica message) {
1314 LOG.debug("{}: onAddPrefixShardReplica: {}", persistenceId(), message);
1316 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1317 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1318 final String shardName = shardId.getShardName();
1320 // Create the localShard
1321 if (schemaContext == null) {
1322 String msg = String.format(
1323 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1324 LOG.debug("{}: {}", persistenceId(), msg);
1325 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1329 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1332 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1333 final RunnableMessage runnable = (RunnableMessage) () -> addPrefixShard(getShardName(),
1334 message.getShardPrefix(), response, getSender());
1335 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1336 getSelf().tell(runnable, getTargetActor());
1341 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1342 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1347 private void onAddShardReplica(final AddShardReplica shardReplicaMsg) {
1348 final String shardName = shardReplicaMsg.getShardName();
1350 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
1352 // verify the shard with the specified name is present in the cluster configuration
1353 if (!this.configuration.isShardConfigured(shardName)) {
1354 String msg = String.format("No module configuration exists for shard %s", shardName);
1355 LOG.debug("{}: {}", persistenceId(), msg);
1356 getSender().tell(new Status.Failure(new IllegalArgumentException(msg)), getSelf());
1360 // Create the localShard
1361 if (schemaContext == null) {
1362 String msg = String.format(
1363 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1364 LOG.debug("{}: {}", persistenceId(), msg);
1365 getSender().tell(new Status.Failure(new IllegalStateException(msg)), getSelf());
1369 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(),
1372 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1373 final RunnableMessage runnable = (RunnableMessage) () ->
1374 addShard(getShardName(), response, getSender());
1375 if (!isPreviousShardActorStopInProgress(getShardName(), runnable)) {
1376 getSelf().tell(runnable, getTargetActor());
1381 public void onLocalPrimaryFound(final LocalPrimaryShardFound message) {
1382 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1387 private void sendLocalReplicaAlreadyExistsReply(final String shardName, final ActorRef sender) {
1388 String msg = String.format("Local shard %s already exists", shardName);
1389 LOG.debug("{}: {}", persistenceId(), msg);
1390 sender.tell(new Status.Failure(new AlreadyExistsException(msg)), getSelf());
1393 private void addPrefixShard(final String shardName, final YangInstanceIdentifier shardPrefix,
1394 final RemotePrimaryShardFound response, final ActorRef sender) {
1395 if (isShardReplicaOperationInProgress(shardName, sender)) {
1399 shardReplicaOperationsInProgress.add(shardName);
1401 final ShardInformation shardInfo;
1402 final boolean removeShardOnFailure;
1403 ShardInformation existingShardInfo = localShards.get(shardName);
1404 if (existingShardInfo == null) {
1405 removeShardOnFailure = true;
1406 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1408 final Builder builder = newShardDatastoreContextBuilder(shardName);
1409 builder.storeRoot(shardPrefix).customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName());
1411 DatastoreContext datastoreContext = builder.build();
1413 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1414 Shard.builder(), peerAddressResolver);
1415 shardInfo.setActiveMember(false);
1416 shardInfo.setSchemaContext(schemaContext);
1417 localShards.put(shardName, shardInfo);
1418 shardInfo.setActor(newShardActor(shardInfo));
1420 removeShardOnFailure = false;
1421 shardInfo = existingShardInfo;
1424 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1427 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1428 if (isShardReplicaOperationInProgress(shardName, sender)) {
1432 shardReplicaOperationsInProgress.add(shardName);
1434 final ShardInformation shardInfo;
1435 final boolean removeShardOnFailure;
1436 ShardInformation existingShardInfo = localShards.get(shardName);
1437 if (existingShardInfo == null) {
1438 removeShardOnFailure = true;
1439 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1441 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName)
1442 .customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
1444 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1445 Shard.builder(), peerAddressResolver);
1446 shardInfo.setActiveMember(false);
1447 shardInfo.setSchemaContext(schemaContext);
1448 localShards.put(shardName, shardInfo);
1449 shardInfo.setActor(newShardActor(shardInfo));
1451 removeShardOnFailure = false;
1452 shardInfo = existingShardInfo;
1455 execAddShard(shardName, shardInfo, response, removeShardOnFailure, sender);
1458 private void execAddShard(final String shardName,
1459 final ShardInformation shardInfo,
1460 final RemotePrimaryShardFound response,
1461 final boolean removeShardOnFailure,
1462 final ActorRef sender) {
1464 final String localShardAddress =
1465 peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1467 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1468 LOG.debug("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1469 response.getPrimaryPath(), shardInfo.getShardId());
1471 final Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
1472 .getShardLeaderElectionTimeout().duration());
1473 final Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1474 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1476 futureObj.onComplete(new OnComplete<Object>() {
1478 public void onComplete(final Throwable failure, final Object addServerResponse) {
1479 if (failure != null) {
1480 LOG.debug("{}: AddServer request to {} for {} failed", persistenceId(),
1481 response.getPrimaryPath(), shardName, failure);
1483 final String msg = String.format("AddServer request to leader %s for shard %s failed",
1484 response.getPrimaryPath(), shardName);
1485 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1487 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1488 response.getPrimaryPath(), removeShardOnFailure), sender);
1491 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1494 private void onAddServerFailure(final String shardName, final String message, final Throwable failure,
1495 final ActorRef sender, final boolean removeShardOnFailure) {
1496 shardReplicaOperationsInProgress.remove(shardName);
1498 if (removeShardOnFailure) {
1499 ShardInformation shardInfo = localShards.remove(shardName);
1500 if (shardInfo.getActor() != null) {
1501 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1505 sender.tell(new Status.Failure(message == null ? failure :
1506 new RuntimeException(message, failure)), getSelf());
1509 private void onAddServerReply(final ShardInformation shardInfo, final AddServerReply replyMsg,
1510 final ActorRef sender, final String leaderPath, final boolean removeShardOnFailure) {
1511 String shardName = shardInfo.getShardName();
1512 shardReplicaOperationsInProgress.remove(shardName);
1514 LOG.debug("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1516 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1517 LOG.debug("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1519 // Make the local shard voting capable
1520 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1521 shardInfo.setActiveMember(true);
1524 sender.tell(new Status.Success(null), getSelf());
1525 } else if (replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1526 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1528 LOG.warn("{}: Leader failed to add shard replica {} with status {}",
1529 persistenceId(), shardName, replyMsg.getStatus());
1531 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath,
1532 shardInfo.getShardId());
1534 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1538 private static Exception getServerChangeException(final Class<?> serverChange,
1539 final ServerChangeStatus serverChangeStatus, final String leaderPath, final ShardIdentifier shardId) {
1540 switch (serverChangeStatus) {
1542 return new TimeoutException(String.format(
1543 "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
1544 + "Possible causes - there was a problem replicating the data or shard leadership changed "
1545 + "while replicating the shard data", leaderPath, shardId.getShardName()));
1547 return createNoShardLeaderException(shardId);
1549 return new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1550 serverChange.getSimpleName(), shardId.getShardName()));
1552 return new RuntimeException(String.format("%s request to leader %s for shard %s failed with status %s",
1553 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1557 private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
1558 LOG.debug("{}: onRemoveShardReplica: {}", persistenceId(), shardReplicaMsg);
1560 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1561 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1563 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1564 doRemoveShardReplicaAsync(response.getPrimaryPath());
1568 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1569 doRemoveShardReplicaAsync(response.getPrimaryPath());
1572 private void doRemoveShardReplicaAsync(final String primaryPath) {
1573 getSelf().tell((RunnableMessage) () -> removeShardReplica(shardReplicaMsg, getShardName(),
1574 primaryPath, getSender()), getTargetActor());
1579 private void onRemovePrefixShardReplica(final RemovePrefixShardReplica message) {
1580 LOG.debug("{}: onRemovePrefixShardReplica: {}", persistenceId(), message);
1582 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(),
1583 ClusterUtils.getCleanShardName(message.getShardPrefix()));
1584 final String shardName = shardId.getShardName();
1586 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(),
1587 shardName, persistenceId(), getSelf()) {
1589 public void onRemotePrimaryShardFound(final RemotePrimaryShardFound response) {
1590 doRemoveShardReplicaAsync(response.getPrimaryPath());
1594 public void onLocalPrimaryFound(final LocalPrimaryShardFound response) {
1595 doRemoveShardReplicaAsync(response.getPrimaryPath());
1598 private void doRemoveShardReplicaAsync(final String primaryPath) {
1599 getSelf().tell((RunnableMessage) () -> removePrefixShardReplica(message, getShardName(),
1600 primaryPath, getSender()), getTargetActor());
1605 private void persistShardList() {
1606 List<String> shardList = new ArrayList<>(localShards.keySet());
1607 for (ShardInformation shardInfo : localShards.values()) {
1608 if (!shardInfo.isActiveMember()) {
1609 shardList.remove(shardInfo.getShardName());
1612 LOG.debug("{}: persisting the shard list {}", persistenceId(), shardList);
1613 saveSnapshot(updateShardManagerSnapshot(shardList, configuration.getAllPrefixShardConfigurations()));
1616 private ShardManagerSnapshot updateShardManagerSnapshot(
1617 final List<String> shardList,
1618 final Map<DOMDataTreeIdentifier, PrefixShardConfiguration> allPrefixShardConfigurations) {
1619 currentSnapshot = new ShardManagerSnapshot(shardList, allPrefixShardConfigurations);
1620 return currentSnapshot;
1623 private void applyShardManagerSnapshot(final ShardManagerSnapshot snapshot) {
1624 currentSnapshot = snapshot;
1626 LOG.debug("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1628 final MemberName currentMember = cluster.getCurrentMemberName();
1629 Set<String> configuredShardList =
1630 new HashSet<>(configuration.getMemberShardNames(currentMember));
1631 for (String shard : currentSnapshot.getShardList()) {
1632 if (!configuredShardList.contains(shard)) {
1633 // add the current member as a replica for the shard
1634 LOG.debug("{}: adding shard {}", persistenceId(), shard);
1635 configuration.addMemberReplicaForShard(shard, currentMember);
1637 configuredShardList.remove(shard);
1640 for (String shard : configuredShardList) {
1641 // remove the member as a replica for the shard
1642 LOG.debug("{}: removing shard {}", persistenceId(), shard);
1643 configuration.removeMemberReplicaForShard(shard, currentMember);
1647 private void onSaveSnapshotSuccess(final SaveSnapshotSuccess successMessage) {
1648 LOG.debug("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1650 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), successMessage.metadata().timestamp() - 1,
1654 private void onChangeShardServersVotingStatus(final ChangeShardMembersVotingStatus changeMembersVotingStatus) {
1655 LOG.debug("{}: onChangeShardServersVotingStatus: {}", persistenceId(), changeMembersVotingStatus);
1657 String shardName = changeMembersVotingStatus.getShardName();
1658 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1659 for (Entry<String, Boolean> e: changeMembersVotingStatus.getMeberVotingStatusMap().entrySet()) {
1660 serverVotingStatusMap.put(getShardIdentifier(MemberName.forName(e.getKey()), shardName).toString(),
1664 ChangeServersVotingStatus changeServersVotingStatus = new ChangeServersVotingStatus(serverVotingStatusMap);
1666 findLocalShard(shardName, getSender(),
1667 localShardFound -> changeShardMembersVotingStatus(changeServersVotingStatus, shardName,
1668 localShardFound.getPath(), getSender()));
1671 private void onFlipShardMembersVotingStatus(final FlipShardMembersVotingStatus flipMembersVotingStatus) {
1672 LOG.debug("{}: onFlipShardMembersVotingStatus: {}", persistenceId(), flipMembersVotingStatus);
1674 ActorRef sender = getSender();
1675 final String shardName = flipMembersVotingStatus.getShardName();
1676 findLocalShard(shardName, sender, localShardFound -> {
1677 Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
1678 Timeout.apply(30, TimeUnit.SECONDS));
1680 future.onComplete(new OnComplete<Object>() {
1682 public void onComplete(final Throwable failure, final Object response) {
1683 if (failure != null) {
1684 sender.tell(new Status.Failure(new RuntimeException(
1685 String.format("Failed to access local shard %s", shardName), failure)), self());
1689 OnDemandRaftState raftState = (OnDemandRaftState) response;
1690 Map<String, Boolean> serverVotingStatusMap = new HashMap<>();
1691 for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
1692 serverVotingStatusMap.put(e.getKey(), !e.getValue());
1695 serverVotingStatusMap.put(getShardIdentifier(cluster.getCurrentMemberName(), shardName)
1696 .toString(), !raftState.isVoting());
1698 changeShardMembersVotingStatus(new ChangeServersVotingStatus(serverVotingStatusMap),
1699 shardName, localShardFound.getPath(), sender);
1701 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1706 private void findLocalShard(final FindLocalShard message) {
1707 LOG.debug("{}: findLocalShard : {}", persistenceId(), message.getShardName());
1709 final ShardInformation shardInformation = localShards.get(message.getShardName());
1711 if (shardInformation == null) {
1712 LOG.debug("{}: Local shard {} not found - shards present: {}",
1713 persistenceId(), message.getShardName(), localShards.keySet());
1715 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
1719 sendResponse(shardInformation, message.isWaitUntilInitialized(), false,
1720 () -> new LocalShardFound(shardInformation.getActor()));
1723 private void findLocalShard(final String shardName, final ActorRef sender,
1724 final Consumer<LocalShardFound> onLocalShardFound) {
1725 Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
1726 .getShardInitializationTimeout().duration().$times(2));
1728 Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
1729 futureObj.onComplete(new OnComplete<Object>() {
1731 public void onComplete(final Throwable failure, final Object response) {
1732 if (failure != null) {
1733 LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
1735 sender.tell(new Status.Failure(new RuntimeException(
1736 String.format("Failed to find local shard %s", shardName), failure)), self());
1738 if (response instanceof LocalShardFound) {
1739 getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
1741 } else if (response instanceof LocalShardNotFound) {
1742 String msg = String.format("Local shard %s does not exist", shardName);
1743 LOG.debug("{}: {}", persistenceId, msg);
1744 sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
1746 String msg = String.format("Failed to find local shard %s: received response: %s",
1747 shardName, response);
1748 LOG.debug("{}: {}", persistenceId, msg);
1749 sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1750 new RuntimeException(msg)), self());
1754 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1757 private void changeShardMembersVotingStatus(final ChangeServersVotingStatus changeServersVotingStatus,
1758 final String shardName, final ActorRef shardActorRef, final ActorRef sender) {
1759 if (isShardReplicaOperationInProgress(shardName, sender)) {
1763 shardReplicaOperationsInProgress.add(shardName);
1765 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
1766 final ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1768 LOG.debug("{}: Sending ChangeServersVotingStatus message {} to local shard {}", persistenceId(),
1769 changeServersVotingStatus, shardActorRef.path());
1771 Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
1772 Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
1774 futureObj.onComplete(new OnComplete<Object>() {
1776 public void onComplete(final Throwable failure, final Object response) {
1777 shardReplicaOperationsInProgress.remove(shardName);
1778 if (failure != null) {
1779 String msg = String.format("ChangeServersVotingStatus request to local shard %s failed",
1780 shardActorRef.path());
1781 LOG.debug("{}: {}", persistenceId(), msg, failure);
1782 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
1784 LOG.debug("{}: Received {} from local shard {}", persistenceId(), response, shardActorRef.path());
1786 ServerChangeReply replyMsg = (ServerChangeReply) response;
1787 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1788 LOG.debug("{}: ChangeServersVotingStatus succeeded for shard {}", persistenceId(), shardName);
1789 sender.tell(new Status.Success(null), getSelf());
1790 } else if (replyMsg.getStatus() == ServerChangeStatus.INVALID_REQUEST) {
1791 sender.tell(new Status.Failure(new IllegalArgumentException(String.format(
1792 "The requested voting state change for shard %s is invalid. At least one member "
1793 + "must be voting", shardId.getShardName()))), getSelf());
1795 LOG.warn("{}: ChangeServersVotingStatus failed for shard {} with status {}",
1796 persistenceId(), shardName, replyMsg.getStatus());
1798 Exception error = getServerChangeException(ChangeServersVotingStatus.class,
1799 replyMsg.getStatus(), shardActorRef.path().toString(), shardId);
1800 sender.tell(new Status.Failure(error), getSelf());
1804 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1807 private static final class ForwardedAddServerReply {
1808 ShardInformation shardInfo;
1809 AddServerReply addServerReply;
1811 boolean removeShardOnFailure;
1813 ForwardedAddServerReply(final ShardInformation shardInfo, final AddServerReply addServerReply,
1814 final String leaderPath, final boolean removeShardOnFailure) {
1815 this.shardInfo = shardInfo;
1816 this.addServerReply = addServerReply;
1817 this.leaderPath = leaderPath;
1818 this.removeShardOnFailure = removeShardOnFailure;
1822 private static final class ForwardedAddServerFailure {
1824 String failureMessage;
1826 boolean removeShardOnFailure;
1828 ForwardedAddServerFailure(final String shardName, final String failureMessage, final Throwable failure,
1829 final boolean removeShardOnFailure) {
1830 this.shardName = shardName;
1831 this.failureMessage = failureMessage;
1832 this.failure = failure;
1833 this.removeShardOnFailure = removeShardOnFailure;
1837 static class OnShardInitialized {
1838 private final Runnable replyRunnable;
1839 private Cancellable timeoutSchedule;
1841 OnShardInitialized(final Runnable replyRunnable) {
1842 this.replyRunnable = replyRunnable;
1845 Runnable getReplyRunnable() {
1846 return replyRunnable;
1849 Cancellable getTimeoutSchedule() {
1850 return timeoutSchedule;
1853 void setTimeoutSchedule(final Cancellable timeoutSchedule) {
1854 this.timeoutSchedule = timeoutSchedule;
1858 static class OnShardReady extends OnShardInitialized {
1859 OnShardReady(final Runnable replyRunnable) {
1860 super(replyRunnable);
1864 private interface RunnableMessage extends Runnable {
1868 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1869 * a remote or local find primary message is processed.
1871 private interface FindPrimaryResponseHandler {
1873 * Invoked when a Failure message is received as a response.
1875 * @param failure the failure exception
1877 void onFailure(Throwable failure);
1880 * Invoked when a RemotePrimaryShardFound response is received.
1882 * @param response the response
1884 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1887 * Invoked when a LocalPrimaryShardFound response is received.
1889 * @param response the response
1891 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1894 * Invoked when an unknown response is received. This is another type of failure.
1896 * @param response the response
1898 void onUnknownResponse(Object response);
1902 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1903 * replica and sends a wrapped Failure response to some targetActor.
1905 private abstract static class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1906 private final ActorRef targetActor;
1907 private final String shardName;
1908 private final String persistenceId;
1909 private final ActorRef shardManagerActor;
1912 * Constructs an instance.
1914 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1915 * @param shardName The name of the shard for which the primary replica had to be found
1916 * @param persistenceId The persistenceId for the ShardManager
1917 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1919 protected AutoFindPrimaryFailureResponseHandler(final ActorRef targetActor, final String shardName,
1920 final String persistenceId, final ActorRef shardManagerActor) {
1921 this.targetActor = Preconditions.checkNotNull(targetActor);
1922 this.shardName = Preconditions.checkNotNull(shardName);
1923 this.persistenceId = Preconditions.checkNotNull(persistenceId);
1924 this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1927 public ActorRef getTargetActor() {
1931 public String getShardName() {
1936 public void onFailure(final Throwable failure) {
1937 LOG.debug("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1938 targetActor.tell(new Status.Failure(new RuntimeException(
1939 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1943 public void onUnknownResponse(final Object response) {
1944 String msg = String.format("Failed to find leader for shard %s: received response: %s",
1945 shardName, response);
1946 LOG.debug("{}: {}", persistenceId, msg);
1947 targetActor.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response :
1948 new RuntimeException(msg)), shardManagerActor);
1953 * The WrappedShardResponse class wraps a response from a Shard.
1955 private static final class WrappedShardResponse {
1956 private final ShardIdentifier shardId;
1957 private final Object response;
1958 private final String leaderPath;
1960 WrappedShardResponse(final ShardIdentifier shardId, final Object response, final String leaderPath) {
1961 this.shardId = shardId;
1962 this.response = response;
1963 this.leaderPath = leaderPath;
1966 ShardIdentifier getShardId() {
1970 Object getResponse() {
1974 String getLeaderPath() {
1979 private static final class ShardNotInitializedTimeout {
1980 private final ActorRef sender;
1981 private final ShardInformation shardInfo;
1982 private final OnShardInitialized onShardInitialized;
1984 ShardNotInitializedTimeout(final ShardInformation shardInfo, final OnShardInitialized onShardInitialized,
1985 final ActorRef sender) {
1986 this.sender = sender;
1987 this.shardInfo = shardInfo;
1988 this.onShardInitialized = onShardInitialized;
1991 ActorRef getSender() {
1995 ShardInformation getShardInfo() {
1999 OnShardInitialized getOnShardInitialized() {
2000 return onShardInitialized;