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;
11 import static akka.pattern.Patterns.ask;
12 import akka.actor.ActorPath;
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.Props;
19 import akka.actor.Status;
20 import akka.actor.SupervisorStrategy;
21 import akka.cluster.ClusterEvent;
22 import akka.dispatch.OnComplete;
23 import akka.japi.Function;
24 import akka.persistence.RecoveryCompleted;
25 import akka.persistence.SaveSnapshotFailure;
26 import akka.persistence.SaveSnapshotSuccess;
27 import akka.persistence.SnapshotOffer;
28 import akka.persistence.SnapshotSelectionCriteria;
29 import akka.serialization.Serialization;
30 import akka.util.Timeout;
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Objects;
33 import com.google.common.base.Optional;
34 import com.google.common.base.Preconditions;
35 import com.google.common.base.Strings;
36 import com.google.common.base.Supplier;
37 import com.google.common.collect.Sets;
38 import java.io.ByteArrayInputStream;
39 import java.io.ObjectInputStream;
40 import java.io.Serializable;
41 import java.util.ArrayList;
42 import java.util.Collection;
43 import java.util.Collections;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.Iterator;
47 import java.util.List;
50 import java.util.concurrent.CountDownLatch;
51 import java.util.concurrent.TimeUnit;
52 import java.util.concurrent.TimeoutException;
53 import javax.annotation.Nonnull;
54 import javax.annotation.Nullable;
55 import org.apache.commons.lang3.SerializationUtils;
56 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
57 import org.opendaylight.controller.cluster.datastore.config.Configuration;
58 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
59 import org.opendaylight.controller.cluster.datastore.exceptions.AlreadyExistsException;
60 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
61 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
62 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
63 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
64 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
65 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
66 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
67 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
68 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
69 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
70 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
71 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
72 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
73 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
74 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
75 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
76 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
77 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
78 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
79 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
80 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
81 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
82 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
83 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
84 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
85 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
86 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
87 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
88 import org.opendaylight.controller.cluster.raft.RaftState;
89 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
90 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
91 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
92 import org.opendaylight.controller.cluster.raft.messages.AddServer;
93 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
94 import org.opendaylight.controller.cluster.raft.messages.RemoveServer;
95 import org.opendaylight.controller.cluster.raft.messages.RemoveServerReply;
96 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
97 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
98 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
99 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
100 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
103 import scala.concurrent.Future;
104 import scala.concurrent.duration.Duration;
105 import scala.concurrent.duration.FiniteDuration;
108 * The ShardManager has the following jobs,
110 * <li> Create all the local shard replicas that belong on this cluster member
111 * <li> Find the address of the local shard
112 * <li> Find the primary replica for any given shard
113 * <li> Monitor the cluster members and store their addresses
116 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
118 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
120 // Stores a mapping between a shard name and it's corresponding information
121 // Shard names look like inventory, topology etc and are as specified in
123 private final Map<String, ShardInformation> localShards = new HashMap<>();
125 // The type of a ShardManager reflects the type of the datastore itself
126 // A data store could be of type config/operational
127 private final String type;
129 private final ClusterWrapper cluster;
131 private final Configuration configuration;
133 private final String shardDispatcherPath;
135 private final ShardManagerInfo mBean;
137 private DatastoreContextFactory datastoreContextFactory;
139 private final CountDownLatch waitTillReadyCountdownLatch;
141 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
143 private final ShardPeerAddressResolver peerAddressResolver;
145 private SchemaContext schemaContext;
147 private DatastoreSnapshot restoreFromSnapshot;
149 private ShardManagerSnapshot currentSnapshot;
151 private final Set<String> shardReplicaOperationsInProgress = new HashSet<>();
153 private final String persistenceId;
157 protected ShardManager(AbstractBuilder<?> builder) {
159 this.cluster = builder.cluster;
160 this.configuration = builder.configuration;
161 this.datastoreContextFactory = builder.datastoreContextFactory;
162 this.type = builder.datastoreContextFactory.getBaseDatastoreContext().getDataStoreName();
163 this.shardDispatcherPath =
164 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
165 this.waitTillReadyCountdownLatch = builder.waitTillReadyCountdownLatch;
166 this.primaryShardInfoCache = builder.primaryShardInfoCache;
167 this.restoreFromSnapshot = builder.restoreFromSnapshot;
169 String possiblePersistenceId = datastoreContextFactory.getBaseDatastoreContext().getShardManagerPersistenceId();
170 persistenceId = possiblePersistenceId != null ? possiblePersistenceId : "shard-manager-" + type;
172 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
174 // Subscribe this actor to cluster member events
175 cluster.subscribeToMemberEvents(getSelf());
177 List<String> localShardActorNames = new ArrayList<>();
178 mBean = ShardManagerInfo.createShardManagerMBean(cluster.getCurrentMemberName(),
179 "shard-manager-" + this.type,
180 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType(),
181 localShardActorNames);
182 mBean.setShardManager(this);
186 public void postStop() {
187 LOG.info("Stopping ShardManager");
189 mBean.unregisterMBean();
193 public void handleCommand(Object message) throws Exception {
194 if (message instanceof FindPrimary) {
195 findPrimary((FindPrimary)message);
196 } else if(message instanceof FindLocalShard){
197 findLocalShard((FindLocalShard) message);
198 } else if (message instanceof UpdateSchemaContext) {
199 updateSchemaContext(message);
200 } else if(message instanceof ActorInitialized) {
201 onActorInitialized(message);
202 } else if (message instanceof ClusterEvent.MemberUp){
203 memberUp((ClusterEvent.MemberUp) message);
204 } else if (message instanceof ClusterEvent.MemberExited){
205 memberExited((ClusterEvent.MemberExited) message);
206 } else if(message instanceof ClusterEvent.MemberRemoved) {
207 memberRemoved((ClusterEvent.MemberRemoved) message);
208 } else if(message instanceof ClusterEvent.UnreachableMember) {
209 memberUnreachable((ClusterEvent.UnreachableMember)message);
210 } else if(message instanceof ClusterEvent.ReachableMember) {
211 memberReachable((ClusterEvent.ReachableMember) message);
212 } else if(message instanceof DatastoreContextFactory) {
213 onDatastoreContextFactory((DatastoreContextFactory)message);
214 } else if(message instanceof RoleChangeNotification) {
215 onRoleChangeNotification((RoleChangeNotification) message);
216 } else if(message instanceof FollowerInitialSyncUpStatus){
217 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
218 } else if(message instanceof ShardNotInitializedTimeout) {
219 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
220 } else if(message instanceof ShardLeaderStateChanged) {
221 onLeaderStateChanged((ShardLeaderStateChanged) message);
222 } else if(message instanceof SwitchShardBehavior){
223 onSwitchShardBehavior((SwitchShardBehavior) message);
224 } else if(message instanceof CreateShard) {
225 onCreateShard((CreateShard)message);
226 } else if(message instanceof AddShardReplica){
227 onAddShardReplica((AddShardReplica)message);
228 } else if(message instanceof ForwardedAddServerReply) {
229 ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
230 onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
231 msg.removeShardOnFailure);
232 } else if(message instanceof ForwardedAddServerFailure) {
233 ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
234 onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
235 } else if(message instanceof PrimaryShardFoundForContext) {
236 PrimaryShardFoundForContext primaryShardFoundContext = (PrimaryShardFoundForContext)message;
237 onPrimaryShardFoundContext(primaryShardFoundContext);
238 } else if(message instanceof RemoveShardReplica) {
239 onRemoveShardReplica((RemoveShardReplica) message);
240 } else if(message instanceof WrappedShardResponse){
241 onWrappedShardResponse((WrappedShardResponse) message);
242 } else if(message instanceof GetSnapshot) {
244 } else if(message instanceof ServerRemoved){
245 onShardReplicaRemoved((ServerRemoved) message);
246 } else if (message instanceof SaveSnapshotSuccess) {
247 onSaveSnapshotSuccess((SaveSnapshotSuccess)message);
248 } else if (message instanceof SaveSnapshotFailure) {
249 LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards",
250 persistenceId(), ((SaveSnapshotFailure) message).cause());
252 unknownMessage(message);
256 private void onWrappedShardResponse(WrappedShardResponse message) {
257 if (message.getResponse() instanceof RemoveServerReply) {
258 onRemoveServerReply(getSender(), message.getShardName(), (RemoveServerReply) message.getResponse());
262 private void onRemoveServerReply(ActorRef originalSender, String shardName, RemoveServerReply response) {
263 shardReplicaOperationsInProgress.remove(shardName);
264 originalSender.tell(new Status.Success(null), self());
267 private void onPrimaryShardFoundContext(PrimaryShardFoundForContext primaryShardFoundContext) {
268 if(primaryShardFoundContext.getContextMessage() instanceof AddShardReplica) {
269 addShard(primaryShardFoundContext.getShardName(), primaryShardFoundContext.getRemotePrimaryShardFound(),
271 } else if(primaryShardFoundContext.getContextMessage() instanceof RemoveShardReplica){
272 removeShardReplica((RemoveShardReplica) primaryShardFoundContext.getContextMessage(),
273 primaryShardFoundContext.getShardName(), primaryShardFoundContext.getPrimaryPath(), getSender());
277 private void removeShardReplica(RemoveShardReplica contextMessage, final String shardName, final String primaryPath,
278 final ActorRef sender) {
279 if(isShardReplicaOperationInProgress(shardName, sender)) {
283 shardReplicaOperationsInProgress.add(shardName);
285 final ShardIdentifier shardId = getShardIdentifier(contextMessage.getMemberName(), shardName);
287 final DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).build();
289 //inform ShardLeader to remove this shard as a replica by sending an RemoveServer message
290 LOG.debug ("{}: Sending RemoveServer message to peer {} for shard {}", persistenceId(),
291 primaryPath, shardId);
293 Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().
295 Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
296 new RemoveServer(shardId.toString()), removeServerTimeout);
298 futureObj.onComplete(new OnComplete<Object>() {
300 public void onComplete(Throwable failure, Object response) {
301 if (failure != null) {
302 String msg = String.format("RemoveServer request to leader %s for shard %s failed",
303 primaryPath, shardName);
305 LOG.debug ("{}: {}", persistenceId(), msg, failure);
308 sender.tell(new Status.Failure(new RuntimeException(msg, failure)), self());
311 self().tell(new WrappedShardResponse(shardName, response), sender);
314 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
317 private void onShardReplicaRemoved(ServerRemoved message) {
318 final ShardIdentifier shardId = new ShardIdentifier.Builder().fromShardIdString(message.getServerId()).build();
319 final ShardInformation shardInformation = localShards.remove(shardId.getShardName());
320 if(shardInformation == null) {
321 LOG.debug("{} : Shard replica {} is not present in list", persistenceId(), shardId.toString());
323 } else if(shardInformation.getActor() != null) {
324 LOG.debug("{} : Sending PoisonPill to Shard actor {}", persistenceId(), shardInformation.getActor());
325 shardInformation.getActor().tell(PoisonPill.getInstance(), self());
327 LOG.debug("{} : Local Shard replica for shard {} has been removed", persistenceId(), shardId.getShardName());
331 private void onGetSnapshot() {
332 LOG.debug("{}: onGetSnapshot", persistenceId());
334 List<String> notInitialized = null;
335 for(ShardInformation shardInfo: localShards.values()) {
336 if(!shardInfo.isShardInitialized()) {
337 if(notInitialized == null) {
338 notInitialized = new ArrayList<>();
341 notInitialized.add(shardInfo.getShardName());
345 if(notInitialized != null) {
346 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(String.format(
347 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
351 byte[] shardManagerSnapshot = null;
352 if(currentSnapshot != null) {
353 shardManagerSnapshot = SerializationUtils.serialize(currentSnapshot);
356 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
357 new ArrayList<>(localShards.keySet()), type, shardManagerSnapshot , getSender(), persistenceId(),
358 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
360 for(ShardInformation shardInfo: localShards.values()) {
361 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
365 private void onCreateShard(CreateShard createShard) {
366 LOG.debug("{}: onCreateShard: {}", persistenceId(), createShard);
370 String shardName = createShard.getModuleShardConfig().getShardName();
371 if(localShards.containsKey(shardName)) {
372 LOG.debug("{}: Shard {} already exists", persistenceId(), shardName);
373 reply = new akka.actor.Status.Success(String.format("Shard with name %s already exists", shardName));
375 doCreateShard(createShard);
376 reply = new akka.actor.Status.Success(null);
378 } catch (Exception e) {
379 LOG.error("{}: onCreateShard failed", persistenceId(), e);
380 reply = new akka.actor.Status.Failure(e);
383 if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
384 getSender().tell(reply, getSelf());
388 private void doCreateShard(CreateShard createShard) {
389 ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
390 String shardName = moduleShardConfig.getShardName();
392 configuration.addModuleShardConfiguration(moduleShardConfig);
394 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
395 if(shardDatastoreContext == null) {
396 shardDatastoreContext = newShardDatastoreContext(shardName);
398 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
399 peerAddressResolver).build();
402 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
404 boolean shardWasInRecoveredSnapshot = currentSnapshot != null &&
405 currentSnapshot.getShardList().contains(shardName);
407 Map<String, String> peerAddresses;
408 boolean isActiveMember;
409 if(shardWasInRecoveredSnapshot || configuration.getMembersFromShardName(shardName).
410 contains(cluster.getCurrentMemberName())) {
411 peerAddresses = getPeerAddresses(shardName);
412 isActiveMember = true;
414 // The local member is not in the static shard member configuration and the shard did not
415 // previously exist (ie !shardWasInRecoveredSnapshot). In this case we'll create
416 // the shard with no peers and with elections disabled so it stays as follower. A
417 // subsequent AddServer request will be needed to make it an active member.
418 isActiveMember = false;
419 peerAddresses = Collections.emptyMap();
420 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).
421 customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName()).build();
424 LOG.debug("{} doCreateShard: shardId: {}, memberNames: {}, peerAddresses: {}, isActiveMember: {}",
425 persistenceId(), shardId, moduleShardConfig.getShardMemberNames(), peerAddresses,
428 ShardInformation info = new ShardInformation(shardName, shardId, peerAddresses,
429 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
430 info.setActiveMember(isActiveMember);
431 localShards.put(info.getShardName(), info);
433 mBean.addLocalShard(shardId.toString());
435 if(schemaContext != null) {
436 info.setActor(newShardActor(schemaContext, info));
440 private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
441 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName)).
442 shardPeerAddressResolver(peerAddressResolver);
445 private DatastoreContext newShardDatastoreContext(String shardName) {
446 return newShardDatastoreContextBuilder(shardName).build();
449 private void checkReady(){
450 if (isReadyWithLeaderId()) {
451 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
452 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
454 waitTillReadyCountdownLatch.countDown();
458 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
459 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
461 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
462 if(shardInformation != null) {
463 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
464 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
465 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
466 primaryShardInfoCache.remove(shardInformation.getShardName());
471 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
475 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
476 ShardInformation shardInfo = message.getShardInfo();
478 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
479 shardInfo.getShardName());
481 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
483 if(!shardInfo.isShardInitialized()) {
484 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
485 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
487 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
488 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
492 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
493 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
494 status.getName(), status.isInitialSyncDone());
496 ShardInformation shardInformation = findShardInformation(status.getName());
498 if(shardInformation != null) {
499 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
501 mBean.setSyncStatus(isInSync());
506 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
507 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
508 roleChanged.getOldRole(), roleChanged.getNewRole());
510 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
511 if(shardInformation != null) {
512 shardInformation.setRole(roleChanged.getNewRole());
514 mBean.setSyncStatus(isInSync());
519 private ShardInformation findShardInformation(String memberId) {
520 for(ShardInformation info : localShards.values()){
521 if(info.getShardId().toString().equals(memberId)){
529 private boolean isReadyWithLeaderId() {
530 boolean isReady = true;
531 for (ShardInformation info : localShards.values()) {
532 if(!info.isShardReadyWithLeaderId()){
540 private boolean isInSync(){
541 for (ShardInformation info : localShards.values()) {
542 if(!info.isInSync()){
549 private void onActorInitialized(Object message) {
550 final ActorRef sender = getSender();
552 if (sender == null) {
553 return; //why is a non-actor sending this message? Just ignore.
556 String actorName = sender.path().name();
557 //find shard name from actor name; actor name is stringified shardId
558 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
560 if (shardId.getShardName() == null) {
564 markShardAsInitialized(shardId.getShardName());
567 private void markShardAsInitialized(String shardName) {
568 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
570 ShardInformation shardInformation = localShards.get(shardName);
571 if (shardInformation != null) {
572 shardInformation.setActorInitialized();
574 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
579 protected void handleRecover(Object message) throws Exception {
580 if (message instanceof RecoveryCompleted) {
581 onRecoveryCompleted();
582 } else if (message instanceof SnapshotOffer) {
583 applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
587 private void onRecoveryCompleted() {
588 LOG.info("Recovery complete : {}", persistenceId());
590 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
591 // journal on upgrade from Helium.
592 deleteMessages(lastSequenceNr());
594 if(currentSnapshot == null && restoreFromSnapshot != null &&
595 restoreFromSnapshot.getShardManagerSnapshot() != null) {
596 try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
597 restoreFromSnapshot.getShardManagerSnapshot()))) {
598 ShardManagerSnapshot snapshot = (ShardManagerSnapshot) ois.readObject();
600 LOG.debug("{}: Deserialized restored ShardManagerSnapshot: {}", persistenceId(), snapshot);
602 applyShardManagerSnapshot(snapshot);
603 } catch(Exception e) {
604 LOG.error("{}: Error deserializing restored ShardManagerSnapshot", persistenceId(), e);
611 private void findLocalShard(FindLocalShard message) {
612 final ShardInformation shardInformation = localShards.get(message.getShardName());
614 if(shardInformation == null){
615 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
619 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
621 public Object get() {
622 return new LocalShardFound(shardInformation.getActor());
627 private void sendResponse(ShardInformation shardInformation, boolean doWait,
628 boolean wantShardReady, final Supplier<Object> messageSupplier) {
629 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
631 final ActorRef sender = getSender();
632 final ActorRef self = self();
634 Runnable replyRunnable = new Runnable() {
637 sender.tell(messageSupplier.get(), self);
641 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
642 new OnShardInitialized(replyRunnable);
644 shardInformation.addOnShardInitialized(onShardInitialized);
646 FiniteDuration timeout = shardInformation.getDatastoreContext().getShardInitializationTimeout().duration();
647 if(shardInformation.isShardInitialized()) {
648 // If the shard is already initialized then we'll wait enough time for the shard to
649 // elect a leader, ie 2 times the election timeout.
650 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
651 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
654 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
655 shardInformation.getShardName());
657 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
659 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
660 getContext().dispatcher(), getSelf());
662 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
664 } else if (!shardInformation.isShardInitialized()) {
665 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
666 shardInformation.getShardName());
667 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
669 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
670 shardInformation.getShardName());
671 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
677 getSender().tell(messageSupplier.get(), getSelf());
680 private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
681 return new NoShardLeaderException(null, shardId.toString());
684 private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
685 return new NotInitializedException(String.format(
686 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
689 private void memberRemoved(ClusterEvent.MemberRemoved message) {
690 String memberName = message.member().roles().head();
692 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
693 message.member().address());
695 peerAddressResolver.removePeerAddress(memberName);
697 for(ShardInformation info : localShards.values()){
698 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
702 private void memberExited(ClusterEvent.MemberExited message) {
703 String memberName = message.member().roles().head();
705 LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
706 message.member().address());
708 peerAddressResolver.removePeerAddress(memberName);
710 for(ShardInformation info : localShards.values()){
711 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
715 private void memberUp(ClusterEvent.MemberUp message) {
716 String memberName = message.member().roles().head();
718 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
719 message.member().address());
721 addPeerAddress(memberName, message.member().address());
726 private void addPeerAddress(String memberName, Address address) {
727 peerAddressResolver.addPeerAddress(memberName, address);
729 for(ShardInformation info : localShards.values()){
730 String shardName = info.getShardName();
731 String peerId = getShardIdentifier(memberName, shardName).toString();
732 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
734 info.peerUp(memberName, peerId, getSelf());
738 private void memberReachable(ClusterEvent.ReachableMember message) {
739 String memberName = message.member().roles().head();
740 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
742 addPeerAddress(memberName, message.member().address());
744 markMemberAvailable(memberName);
747 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
748 String memberName = message.member().roles().head();
749 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
751 markMemberUnavailable(memberName);
754 private void markMemberUnavailable(final String memberName) {
755 for(ShardInformation info : localShards.values()){
756 String leaderId = info.getLeaderId();
757 if(leaderId != null && leaderId.contains(memberName)) {
758 LOG.debug("Marking Leader {} as unavailable.", leaderId);
759 info.setLeaderAvailable(false);
761 primaryShardInfoCache.remove(info.getShardName());
764 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
768 private void markMemberAvailable(final String memberName) {
769 for(ShardInformation info : localShards.values()){
770 String leaderId = info.getLeaderId();
771 if(leaderId != null && leaderId.contains(memberName)) {
772 LOG.debug("Marking Leader {} as available.", leaderId);
773 info.setLeaderAvailable(true);
776 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
780 private void onDatastoreContextFactory(DatastoreContextFactory factory) {
781 datastoreContextFactory = factory;
782 for (ShardInformation info : localShards.values()) {
783 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
787 private void onSwitchShardBehavior(SwitchShardBehavior message) {
788 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
790 ShardInformation shardInformation = localShards.get(identifier.getShardName());
792 if(shardInformation != null && shardInformation.getActor() != null) {
793 shardInformation.getActor().tell(
794 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
796 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
797 message.getShardName(), message.getNewState());
802 * Notifies all the local shards of a change in the schema context
806 private void updateSchemaContext(final Object message) {
807 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
809 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
811 for (ShardInformation info : localShards.values()) {
812 if (info.getActor() == null) {
813 LOG.debug("Creating Shard {}", info.getShardId());
814 info.setActor(newShardActor(schemaContext, info));
816 info.getActor().tell(message, getSelf());
822 protected ClusterWrapper getCluster() {
827 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
828 return getContext().actorOf(info.newProps(schemaContext)
829 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
832 private void findPrimary(FindPrimary message) {
833 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
835 final String shardName = message.getShardName();
836 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
838 // First see if the there is a local replica for the shard
839 final ShardInformation info = localShards.get(shardName);
840 if (info != null && info.isActiveMember()) {
841 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
843 public Object get() {
844 String primaryPath = info.getSerializedLeaderActor();
845 Object found = canReturnLocalShardState && info.isLeader() ?
846 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
847 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
849 if(LOG.isDebugEnabled()) {
850 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
860 Collection<String> visitedAddresses;
861 if(message instanceof RemoteFindPrimary) {
862 visitedAddresses = ((RemoteFindPrimary)message).getVisitedAddresses();
864 visitedAddresses = new ArrayList<>();
867 visitedAddresses.add(peerAddressResolver.getShardManagerActorPathBuilder(cluster.getSelfAddress()).toString());
869 for(String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
870 if(visitedAddresses.contains(address)) {
874 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
877 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
878 message.isWaitUntilReady(), visitedAddresses), getContext());
882 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
884 getSender().tell(new PrimaryNotFoundException(
885 String.format("No primary shard found for %s.", shardName)), getSelf());
889 * Construct the name of the shard actor given the name of the member on
890 * which the shard resides and the name of the shard
896 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
897 return peerAddressResolver.getShardIdentifier(memberName, shardName);
901 * Create shards that are local to the member on which the ShardManager
905 private void createLocalShards() {
906 String memberName = this.cluster.getCurrentMemberName();
907 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
909 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
910 if(restoreFromSnapshot != null)
912 for(DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
913 shardSnapshots.put(snapshot.getName(), snapshot);
917 restoreFromSnapshot = null; // null out to GC
919 for(String shardName : memberShardNames){
920 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
922 LOG.debug("{}: Creating local shard: {}", persistenceId(), shardId);
924 Map<String, String> peerAddresses = getPeerAddresses(shardName);
925 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
926 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
927 shardSnapshots.get(shardName)), peerAddressResolver));
928 mBean.addLocalShard(shardId.toString());
933 * Given the name of the shard find the addresses of all it's peers
937 private Map<String, String> getPeerAddresses(String shardName) {
938 Collection<String> members = configuration.getMembersFromShardName(shardName);
939 Map<String, String> peerAddresses = new HashMap<>();
941 String currentMemberName = this.cluster.getCurrentMemberName();
943 for(String memberName : members) {
944 if(!currentMemberName.equals(memberName)) {
945 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
946 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
947 peerAddresses.put(shardId.toString(), address);
950 return peerAddresses;
954 public SupervisorStrategy supervisorStrategy() {
956 return new OneForOneStrategy(10, Duration.create("1 minute"),
957 new Function<Throwable, SupervisorStrategy.Directive>() {
959 public SupervisorStrategy.Directive apply(Throwable t) {
960 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
961 return SupervisorStrategy.resume();
969 public String persistenceId() {
970 return persistenceId;
974 ShardManagerInfoMBean getMBean(){
978 private boolean isShardReplicaOperationInProgress(final String shardName, final ActorRef sender) {
979 if (shardReplicaOperationsInProgress.contains(shardName)) {
980 String msg = String.format("A shard replica operation for %s is already in progress", shardName);
981 LOG.debug ("{}: {}", persistenceId(), msg);
982 sender.tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
989 private void onAddShardReplica (final AddShardReplica shardReplicaMsg) {
990 final String shardName = shardReplicaMsg.getShardName();
992 LOG.debug("{}: onAddShardReplica: {}", persistenceId(), shardReplicaMsg);
994 // verify the shard with the specified name is present in the cluster configuration
995 if (!(this.configuration.isShardConfigured(shardName))) {
996 String msg = String.format("No module configuration exists for shard %s", shardName);
997 LOG.debug ("{}: {}", persistenceId(), msg);
998 getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
1002 // Create the localShard
1003 if (schemaContext == null) {
1004 String msg = String.format(
1005 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
1006 LOG.debug ("{}: {}", persistenceId(), msg);
1007 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
1011 findPrimary(shardName, new AutoFindPrimaryFailureResponseHandler(getSender(), shardName, persistenceId(), getSelf()) {
1013 public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1014 getSelf().tell(new PrimaryShardFoundForContext(getShardName(), shardReplicaMsg, response), getTargetActor());
1018 public void onLocalPrimaryFound(LocalPrimaryShardFound message) {
1019 sendLocalReplicaAlreadyExistsReply(getShardName(), getTargetActor());
1025 private void sendLocalReplicaAlreadyExistsReply(String shardName, ActorRef sender) {
1026 String msg = String.format("Local shard %s already exists", shardName);
1027 LOG.debug ("{}: {}", persistenceId(), msg);
1028 sender.tell(new akka.actor.Status.Failure(new AlreadyExistsException(msg)), getSelf());
1031 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
1032 if(isShardReplicaOperationInProgress(shardName, sender)) {
1036 shardReplicaOperationsInProgress.add(shardName);
1038 final ShardInformation shardInfo;
1039 final boolean removeShardOnFailure;
1040 ShardInformation existingShardInfo = localShards.get(shardName);
1041 if(existingShardInfo == null) {
1042 removeShardOnFailure = true;
1043 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
1045 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).customRaftPolicyImplementation(
1046 DisableElectionsRaftPolicy.class.getName()).build();
1048 shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
1049 Shard.builder(), peerAddressResolver);
1050 shardInfo.setActiveMember(false);
1051 localShards.put(shardName, shardInfo);
1052 shardInfo.setActor(newShardActor(schemaContext, shardInfo));
1054 removeShardOnFailure = false;
1055 shardInfo = existingShardInfo;
1058 String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
1060 //inform ShardLeader to add this shard as a replica by sending an AddServer message
1061 LOG.debug ("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
1062 response.getPrimaryPath(), shardInfo.getShardId());
1064 Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext().getShardLeaderElectionTimeout().
1066 Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
1067 new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
1069 futureObj.onComplete(new OnComplete<Object>() {
1071 public void onComplete(Throwable failure, Object addServerResponse) {
1072 if (failure != null) {
1073 LOG.debug ("{}: AddServer request to {} for {} failed", persistenceId(),
1074 response.getPrimaryPath(), shardName, failure);
1076 String msg = String.format("AddServer request to leader %s for shard %s failed",
1077 response.getPrimaryPath(), shardName);
1078 self().tell(new ForwardedAddServerFailure(shardName, msg, failure, removeShardOnFailure), sender);
1080 self().tell(new ForwardedAddServerReply(shardInfo, (AddServerReply)addServerResponse,
1081 response.getPrimaryPath(), removeShardOnFailure), sender);
1084 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1087 private void onAddServerFailure(String shardName, String message, Throwable failure, ActorRef sender,
1088 boolean removeShardOnFailure) {
1089 shardReplicaOperationsInProgress.remove(shardName);
1091 if(removeShardOnFailure) {
1092 ShardInformation shardInfo = localShards.remove(shardName);
1093 if (shardInfo.getActor() != null) {
1094 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
1098 sender.tell(new akka.actor.Status.Failure(message == null ? failure :
1099 new RuntimeException(message, failure)), getSelf());
1102 private void onAddServerReply(ShardInformation shardInfo, AddServerReply replyMsg, ActorRef sender,
1103 String leaderPath, boolean removeShardOnFailure) {
1104 String shardName = shardInfo.getShardName();
1105 shardReplicaOperationsInProgress.remove(shardName);
1107 LOG.debug ("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
1109 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
1110 LOG.debug ("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
1112 // Make the local shard voting capable
1113 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
1114 shardInfo.setActiveMember(true);
1117 mBean.addLocalShard(shardInfo.getShardId().toString());
1118 sender.tell(new akka.actor.Status.Success(null), getSelf());
1119 } else if(replyMsg.getStatus() == ServerChangeStatus.ALREADY_EXISTS) {
1120 sendLocalReplicaAlreadyExistsReply(shardName, sender);
1122 LOG.warn ("{}: Leader failed to add shard replica {} with status {}",
1123 persistenceId(), shardName, replyMsg.getStatus());
1125 Exception failure = getServerChangeException(AddServer.class, replyMsg.getStatus(), leaderPath, shardInfo.getShardId());
1127 onAddServerFailure(shardName, null, failure, sender, removeShardOnFailure);
1131 private Exception getServerChangeException(Class<?> serverChange, ServerChangeStatus serverChangeStatus,
1132 String leaderPath, ShardIdentifier shardId) {
1134 switch (serverChangeStatus) {
1136 failure = new TimeoutException(String.format(
1137 "The shard leader %s timed out trying to replicate the initial data to the new shard %s." +
1138 "Possible causes - there was a problem replicating the data or shard leadership changed while replicating the shard data",
1139 leaderPath, shardId.getShardName()));
1142 failure = createNoShardLeaderException(shardId);
1145 failure = new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
1146 serverChange.getSimpleName(), shardId.getShardName()));
1149 failure = new RuntimeException(String.format(
1150 "%s request to leader %s for shard %s failed with status %s",
1151 serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
1156 private void onRemoveShardReplica (final RemoveShardReplica shardReplicaMsg) {
1157 findPrimary(shardReplicaMsg.getShardName(), new AutoFindPrimaryFailureResponseHandler(getSender(),
1158 shardReplicaMsg.getShardName(), persistenceId(), getSelf()) {
1160 public void onRemotePrimaryShardFound(RemotePrimaryShardFound response) {
1161 getSelf().tell(new PrimaryShardFoundForContext(getShardName(), shardReplicaMsg, response), getTargetActor());
1165 public void onLocalPrimaryFound(LocalPrimaryShardFound response) {
1166 getSelf().tell(new PrimaryShardFoundForContext(getShardName(), shardReplicaMsg, response), getTargetActor());
1171 private void persistShardList() {
1172 List<String> shardList = new ArrayList<>(localShards.keySet());
1173 for (ShardInformation shardInfo : localShards.values()) {
1174 if (!shardInfo.isActiveMember()) {
1175 shardList.remove(shardInfo.getShardName());
1178 LOG.debug ("{}: persisting the shard list {}", persistenceId(), shardList);
1179 saveSnapshot(updateShardManagerSnapshot(shardList));
1182 private ShardManagerSnapshot updateShardManagerSnapshot(List<String> shardList) {
1183 currentSnapshot = new ShardManagerSnapshot(shardList);
1184 return currentSnapshot;
1187 private void applyShardManagerSnapshot(ShardManagerSnapshot snapshot) {
1188 currentSnapshot = snapshot;
1190 LOG.debug ("{}: onSnapshotOffer: {}", persistenceId(), currentSnapshot);
1192 String currentMember = cluster.getCurrentMemberName();
1193 Set<String> configuredShardList =
1194 new HashSet<>(configuration.getMemberShardNames(currentMember));
1195 for (String shard : currentSnapshot.getShardList()) {
1196 if (!configuredShardList.contains(shard)) {
1197 // add the current member as a replica for the shard
1198 LOG.debug ("{}: adding shard {}", persistenceId(), shard);
1199 configuration.addMemberReplicaForShard(shard, currentMember);
1201 configuredShardList.remove(shard);
1204 for (String shard : configuredShardList) {
1205 // remove the member as a replica for the shard
1206 LOG.debug ("{}: removing shard {}", persistenceId(), shard);
1207 configuration.removeMemberReplicaForShard(shard, currentMember);
1211 private void onSaveSnapshotSuccess (SaveSnapshotSuccess successMessage) {
1212 LOG.debug ("{} saved ShardManager snapshot successfully. Deleting the prev snapshot if available",
1214 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), (successMessage.metadata().timestamp() - 1)));
1217 private static class ForwardedAddServerReply {
1218 ShardInformation shardInfo;
1219 AddServerReply addServerReply;
1221 boolean removeShardOnFailure;
1223 ForwardedAddServerReply(ShardInformation shardInfo, AddServerReply addServerReply, String leaderPath,
1224 boolean removeShardOnFailure) {
1225 this.shardInfo = shardInfo;
1226 this.addServerReply = addServerReply;
1227 this.leaderPath = leaderPath;
1228 this.removeShardOnFailure = removeShardOnFailure;
1232 private static class ForwardedAddServerFailure {
1234 String failureMessage;
1236 boolean removeShardOnFailure;
1238 ForwardedAddServerFailure(String shardName, String failureMessage, Throwable failure,
1239 boolean removeShardOnFailure) {
1240 this.shardName = shardName;
1241 this.failureMessage = failureMessage;
1242 this.failure = failure;
1243 this.removeShardOnFailure = removeShardOnFailure;
1248 protected static class ShardInformation {
1249 private final ShardIdentifier shardId;
1250 private final String shardName;
1251 private ActorRef actor;
1252 private ActorPath actorPath;
1253 private final Map<String, String> initialPeerAddresses;
1254 private Optional<DataTree> localShardDataTree;
1255 private boolean leaderAvailable = false;
1257 // flag that determines if the actor is ready for business
1258 private boolean actorInitialized = false;
1260 private boolean followerSyncStatus = false;
1262 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
1263 private String role ;
1264 private String leaderId;
1265 private short leaderVersion;
1267 private DatastoreContext datastoreContext;
1268 private Shard.AbstractBuilder<?, ?> builder;
1269 private final ShardPeerAddressResolver addressResolver;
1270 private boolean isActiveMember = true;
1272 private ShardInformation(String shardName, ShardIdentifier shardId,
1273 Map<String, String> initialPeerAddresses, DatastoreContext datastoreContext,
1274 Shard.AbstractBuilder<?, ?> builder, ShardPeerAddressResolver addressResolver) {
1275 this.shardName = shardName;
1276 this.shardId = shardId;
1277 this.initialPeerAddresses = initialPeerAddresses;
1278 this.datastoreContext = datastoreContext;
1279 this.builder = builder;
1280 this.addressResolver = addressResolver;
1283 Props newProps(SchemaContext schemaContext) {
1284 Preconditions.checkNotNull(builder);
1285 Props props = builder.id(shardId).peerAddresses(initialPeerAddresses).datastoreContext(datastoreContext).
1286 schemaContext(schemaContext).props();
1291 String getShardName() {
1296 ActorRef getActor(){
1300 ActorPath getActorPath() {
1304 void setActor(ActorRef actor) {
1306 this.actorPath = actor.path();
1309 ShardIdentifier getShardId() {
1313 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
1314 this.localShardDataTree = localShardDataTree;
1317 Optional<DataTree> getLocalShardDataTree() {
1318 return localShardDataTree;
1321 DatastoreContext getDatastoreContext() {
1322 return datastoreContext;
1325 void setDatastoreContext(DatastoreContext datastoreContext, ActorRef sender) {
1326 this.datastoreContext = datastoreContext;
1327 if (actor != null) {
1328 LOG.debug ("Sending new DatastoreContext to {}", shardId);
1329 actor.tell(this.datastoreContext, sender);
1333 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
1334 LOG.info("updatePeerAddress for peer {} with address {}", peerId, peerAddress);
1337 if(LOG.isDebugEnabled()) {
1338 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
1339 peerId, peerAddress, actor.path());
1342 actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
1345 notifyOnShardInitializedCallbacks();
1348 void peerDown(String memberName, String peerId, ActorRef sender) {
1350 actor.tell(new PeerDown(memberName, peerId), sender);
1354 void peerUp(String memberName, String peerId, ActorRef sender) {
1356 actor.tell(new PeerUp(memberName, peerId), sender);
1360 boolean isShardReady() {
1361 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
1364 boolean isShardReadyWithLeaderId() {
1365 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
1366 (isLeader() || addressResolver.resolve(leaderId) != null);
1369 boolean isShardInitialized() {
1370 return getActor() != null && actorInitialized;
1373 boolean isLeader() {
1374 return Objects.equal(leaderId, shardId.toString());
1377 String getSerializedLeaderActor() {
1379 return Serialization.serializedActorPath(getActor());
1381 return addressResolver.resolve(leaderId);
1385 void setActorInitialized() {
1386 LOG.debug("Shard {} is initialized", shardId);
1388 this.actorInitialized = true;
1390 notifyOnShardInitializedCallbacks();
1393 private void notifyOnShardInitializedCallbacks() {
1394 if(onShardInitializedSet.isEmpty()) {
1398 boolean ready = isShardReadyWithLeaderId();
1400 if(LOG.isDebugEnabled()) {
1401 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
1402 ready ? "ready" : "initialized", onShardInitializedSet.size());
1405 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
1406 while(iter.hasNext()) {
1407 OnShardInitialized onShardInitialized = iter.next();
1408 if(!(onShardInitialized instanceof OnShardReady) || ready) {
1410 onShardInitialized.getTimeoutSchedule().cancel();
1411 onShardInitialized.getReplyRunnable().run();
1416 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
1417 onShardInitializedSet.add(onShardInitialized);
1420 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
1421 onShardInitializedSet.remove(onShardInitialized);
1424 void setRole(String newRole) {
1425 this.role = newRole;
1427 notifyOnShardInitializedCallbacks();
1430 void setFollowerSyncStatus(boolean syncStatus){
1431 this.followerSyncStatus = syncStatus;
1435 if(RaftState.Follower.name().equals(this.role)){
1436 return followerSyncStatus;
1437 } else if(RaftState.Leader.name().equals(this.role)){
1444 boolean setLeaderId(String leaderId) {
1445 boolean changed = !Objects.equal(this.leaderId, leaderId);
1446 this.leaderId = leaderId;
1447 if(leaderId != null) {
1448 this.leaderAvailable = true;
1450 notifyOnShardInitializedCallbacks();
1455 String getLeaderId() {
1459 void setLeaderAvailable(boolean leaderAvailable) {
1460 this.leaderAvailable = leaderAvailable;
1463 short getLeaderVersion() {
1464 return leaderVersion;
1467 void setLeaderVersion(short leaderVersion) {
1468 this.leaderVersion = leaderVersion;
1471 boolean isActiveMember() {
1472 return isActiveMember;
1475 void setActiveMember(boolean isActiveMember) {
1476 this.isActiveMember = isActiveMember;
1480 private static class OnShardInitialized {
1481 private final Runnable replyRunnable;
1482 private Cancellable timeoutSchedule;
1484 OnShardInitialized(Runnable replyRunnable) {
1485 this.replyRunnable = replyRunnable;
1488 Runnable getReplyRunnable() {
1489 return replyRunnable;
1492 Cancellable getTimeoutSchedule() {
1493 return timeoutSchedule;
1496 void setTimeoutSchedule(Cancellable timeoutSchedule) {
1497 this.timeoutSchedule = timeoutSchedule;
1501 private static class OnShardReady extends OnShardInitialized {
1502 OnShardReady(Runnable replyRunnable) {
1503 super(replyRunnable);
1507 private static class ShardNotInitializedTimeout {
1508 private final ActorRef sender;
1509 private final ShardInformation shardInfo;
1510 private final OnShardInitialized onShardInitialized;
1512 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1513 this.sender = sender;
1514 this.shardInfo = shardInfo;
1515 this.onShardInitialized = onShardInitialized;
1518 ActorRef getSender() {
1522 ShardInformation getShardInfo() {
1526 OnShardInitialized getOnShardInitialized() {
1527 return onShardInitialized;
1532 * We no longer persist SchemaContextModules but keep this class around for now for backwards
1533 * compatibility so we don't get de-serialization failures on upgrade from Helium.
1536 static class SchemaContextModules implements Serializable {
1537 private static final long serialVersionUID = -8884620101025936590L;
1539 private final Set<String> modules;
1541 SchemaContextModules(Set<String> modules){
1542 this.modules = modules;
1545 public Set<String> getModules() {
1550 public static Builder builder() {
1551 return new Builder();
1554 public static abstract class AbstractBuilder<T extends AbstractBuilder<T>> {
1555 private ClusterWrapper cluster;
1556 private Configuration configuration;
1557 private DatastoreContextFactory datastoreContextFactory;
1558 private CountDownLatch waitTillReadyCountdownLatch;
1559 private PrimaryShardInfoFutureCache primaryShardInfoCache;
1560 private DatastoreSnapshot restoreFromSnapshot;
1562 private volatile boolean sealed;
1564 @SuppressWarnings("unchecked")
1569 protected void checkSealed() {
1570 Preconditions.checkState(!sealed, "Builder is already sealed - further modifications are not allowed");
1573 public T cluster(ClusterWrapper cluster) {
1575 this.cluster = cluster;
1579 public T configuration(Configuration configuration) {
1581 this.configuration = configuration;
1585 public T datastoreContextFactory(DatastoreContextFactory datastoreContextFactory) {
1587 this.datastoreContextFactory = datastoreContextFactory;
1591 public T waitTillReadyCountdownLatch(CountDownLatch waitTillReadyCountdownLatch) {
1593 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
1597 public T primaryShardInfoCache(PrimaryShardInfoFutureCache primaryShardInfoCache) {
1599 this.primaryShardInfoCache = primaryShardInfoCache;
1603 public T restoreFromSnapshot(DatastoreSnapshot restoreFromSnapshot) {
1605 this.restoreFromSnapshot = restoreFromSnapshot;
1609 protected void verify() {
1611 Preconditions.checkNotNull(cluster, "cluster should not be null");
1612 Preconditions.checkNotNull(configuration, "configuration should not be null");
1613 Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
1614 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
1615 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
1618 public Props props() {
1620 return Props.create(ShardManager.class, this);
1624 public static class Builder extends AbstractBuilder<Builder> {
1627 private void findPrimary(final String shardName, final FindPrimaryResponseHandler handler) {
1628 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext().
1629 getShardInitializationTimeout().duration().$times(2));
1632 Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
1633 futureObj.onComplete(new OnComplete<Object>() {
1635 public void onComplete(Throwable failure, Object response) {
1636 if (failure != null) {
1637 handler.onFailure(failure);
1639 if(response instanceof RemotePrimaryShardFound) {
1640 handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
1641 } else if(response instanceof LocalPrimaryShardFound) {
1642 handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
1644 handler.onUnknownResponse(response);
1648 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
1652 * The FindPrimaryResponseHandler provides specific callback methods which are invoked when a response to the
1653 * a remote or local find primary message is processed
1655 private static interface FindPrimaryResponseHandler {
1657 * Invoked when a Failure message is received as a response
1661 void onFailure(Throwable failure);
1664 * Invoked when a RemotePrimaryShardFound response is received
1668 void onRemotePrimaryShardFound(RemotePrimaryShardFound response);
1671 * Invoked when a LocalPrimaryShardFound response is received
1674 void onLocalPrimaryFound(LocalPrimaryShardFound response);
1677 * Invoked when an unknown response is received. This is another type of failure.
1681 void onUnknownResponse(Object response);
1685 * The AutoFindPrimaryFailureResponseHandler automatically processes Failure responses when finding a primary
1686 * replica and sends a wrapped Failure response to some targetActor
1688 private static abstract class AutoFindPrimaryFailureResponseHandler implements FindPrimaryResponseHandler {
1689 private final ActorRef targetActor;
1690 private final String shardName;
1691 private final String persistenceId;
1692 private final ActorRef shardManagerActor;
1695 * @param targetActor The actor to whom the Failure response should be sent when a FindPrimary failure occurs
1696 * @param shardName The name of the shard for which the primary replica had to be found
1697 * @param persistenceId The persistenceId for the ShardManager
1698 * @param shardManagerActor The ShardManager actor which triggered the call to FindPrimary
1700 protected AutoFindPrimaryFailureResponseHandler(ActorRef targetActor, String shardName, String persistenceId, ActorRef shardManagerActor){
1701 this.targetActor = Preconditions.checkNotNull(targetActor);
1702 this.shardName = Preconditions.checkNotNull(shardName);
1703 this.persistenceId = Preconditions.checkNotNull(persistenceId);
1704 this.shardManagerActor = Preconditions.checkNotNull(shardManagerActor);
1707 public ActorRef getTargetActor() {
1711 public String getShardName() {
1716 public void onFailure(Throwable failure) {
1717 LOG.debug ("{}: Received failure from FindPrimary for shard {}", persistenceId, shardName, failure);
1718 targetActor.tell(new akka.actor.Status.Failure(new RuntimeException(
1719 String.format("Failed to find leader for shard %s", shardName), failure)), shardManagerActor);
1723 public void onUnknownResponse(Object response) {
1724 String msg = String.format("Failed to find leader for shard %s: received response: %s",
1725 shardName, response);
1726 LOG.debug ("{}: {}", persistenceId, msg);
1727 targetActor.tell(new akka.actor.Status.Failure(response instanceof Throwable ? (Throwable) response :
1728 new RuntimeException(msg)), shardManagerActor);
1734 * The PrimaryShardFoundForContext is a DTO which puts together a message (aka 'Context' message) which needs to be
1735 * forwarded to the primary replica of a shard and the message (aka 'PrimaryShardFound' message) that is received
1736 * as a successful response to find primary.
1738 private static class PrimaryShardFoundForContext {
1739 private final String shardName;
1740 private final Object contextMessage;
1741 private final RemotePrimaryShardFound remotePrimaryShardFound;
1742 private final LocalPrimaryShardFound localPrimaryShardFound;
1744 public PrimaryShardFoundForContext(@Nonnull String shardName, @Nonnull Object contextMessage,
1745 @Nonnull Object primaryFoundMessage) {
1746 this.shardName = Preconditions.checkNotNull(shardName);
1747 this.contextMessage = Preconditions.checkNotNull(contextMessage);
1748 Preconditions.checkNotNull(primaryFoundMessage);
1749 this.remotePrimaryShardFound = (primaryFoundMessage instanceof RemotePrimaryShardFound) ?
1750 (RemotePrimaryShardFound) primaryFoundMessage : null;
1751 this.localPrimaryShardFound = (primaryFoundMessage instanceof LocalPrimaryShardFound) ?
1752 (LocalPrimaryShardFound) primaryFoundMessage : null;
1756 String getPrimaryPath(){
1757 if(remotePrimaryShardFound != null) {
1758 return remotePrimaryShardFound.getPrimaryPath();
1760 return localPrimaryShardFound.getPrimaryPath();
1764 Object getContextMessage() {
1765 return contextMessage;
1769 RemotePrimaryShardFound getRemotePrimaryShardFound() {
1770 return remotePrimaryShardFound;
1774 String getShardName() {
1780 * The WrappedShardResponse class wraps a response from a Shard.
1782 private static class WrappedShardResponse {
1783 private final String shardName;
1784 private final Object response;
1786 private WrappedShardResponse(String shardName, Object response) {
1787 this.shardName = shardName;
1788 this.response = response;
1791 String getShardName() {
1795 Object getResponse() {