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.SupervisorStrategy;
20 import akka.cluster.ClusterEvent;
21 import akka.dispatch.OnComplete;
22 import akka.japi.Function;
23 import akka.persistence.RecoveryCompleted;
24 import akka.persistence.SaveSnapshotFailure;
25 import akka.persistence.SaveSnapshotSuccess;
26 import akka.persistence.SnapshotOffer;
27 import akka.serialization.Serialization;
28 import akka.util.Timeout;
29 import com.google.common.annotations.VisibleForTesting;
30 import com.google.common.base.Objects;
31 import com.google.common.base.Optional;
32 import com.google.common.base.Preconditions;
33 import com.google.common.base.Strings;
34 import com.google.common.base.Supplier;
35 import com.google.common.collect.Sets;
36 import java.io.Serializable;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Iterator;
42 import java.util.List;
45 import java.util.concurrent.CountDownLatch;
46 import java.util.concurrent.TimeUnit;
47 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
48 import org.opendaylight.controller.cluster.datastore.config.Configuration;
49 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
50 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
51 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
52 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
53 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
54 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
55 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
56 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
57 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
58 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
59 import org.opendaylight.controller.cluster.datastore.messages.CreateShardReply;
60 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
61 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
62 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
63 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
64 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
65 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
66 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
67 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
68 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
69 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
70 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
71 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
72 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
73 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
74 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
75 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
76 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
77 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
78 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
79 import org.opendaylight.controller.cluster.raft.RaftState;
80 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
81 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
82 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
83 import org.opendaylight.controller.cluster.raft.messages.AddServer;
84 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
85 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
86 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
87 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
88 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91 import scala.concurrent.Future;
92 import scala.concurrent.duration.Duration;
93 import scala.concurrent.duration.FiniteDuration;
96 * The ShardManager has the following jobs,
98 * <li> Create all the local shard replicas that belong on this cluster member
99 * <li> Find the address of the local shard
100 * <li> Find the primary replica for any given shard
101 * <li> Monitor the cluster members and store their addresses
104 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
106 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
108 // Stores a mapping between a shard name and it's corresponding information
109 // Shard names look like inventory, topology etc and are as specified in
111 private final Map<String, ShardInformation> localShards = new HashMap<>();
113 // The type of a ShardManager reflects the type of the datastore itself
114 // A data store could be of type config/operational
115 private final String type;
117 private final ClusterWrapper cluster;
119 private final Configuration configuration;
121 private final String shardDispatcherPath;
123 private final ShardManagerInfo mBean;
125 private DatastoreContextFactory datastoreContextFactory;
127 private final CountDownLatch waitTillReadyCountdownLatch;
129 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
131 private final ShardPeerAddressResolver peerAddressResolver;
133 private SchemaContext schemaContext;
135 private DatastoreSnapshot restoreFromSnapshot;
139 protected ShardManager(Builder builder) {
141 this.cluster = builder.cluster;
142 this.configuration = builder.configuration;
143 this.datastoreContextFactory = builder.datastoreContextFactory;
144 this.type = builder.datastoreContextFactory.getBaseDatastoreContext().getDataStoreType();
145 this.shardDispatcherPath =
146 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
147 this.waitTillReadyCountdownLatch = builder.waitTillReadyCountdownLatch;
148 this.primaryShardInfoCache = builder.primaryShardInfoCache;
149 this.restoreFromSnapshot = builder.restoreFromSnapshot;
151 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
153 // Subscribe this actor to cluster member events
154 cluster.subscribeToMemberEvents(getSelf());
156 List<String> localShardActorNames = new ArrayList<>();
157 mBean = ShardManagerInfo.createShardManagerMBean(cluster.getCurrentMemberName(),
158 "shard-manager-" + this.type,
159 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType(),
160 localShardActorNames);
161 mBean.setShardManager(this);
165 public void postStop() {
166 LOG.info("Stopping ShardManager");
168 mBean.unregisterMBean();
172 public void handleCommand(Object message) throws Exception {
173 if (message instanceof FindPrimary) {
174 findPrimary((FindPrimary)message);
175 } else if(message instanceof FindLocalShard){
176 findLocalShard((FindLocalShard) message);
177 } else if (message instanceof UpdateSchemaContext) {
178 updateSchemaContext(message);
179 } else if(message instanceof ActorInitialized) {
180 onActorInitialized(message);
181 } else if (message instanceof ClusterEvent.MemberUp){
182 memberUp((ClusterEvent.MemberUp) message);
183 } else if (message instanceof ClusterEvent.MemberExited){
184 memberExited((ClusterEvent.MemberExited) message);
185 } else if(message instanceof ClusterEvent.MemberRemoved) {
186 memberRemoved((ClusterEvent.MemberRemoved) message);
187 } else if(message instanceof ClusterEvent.UnreachableMember) {
188 memberUnreachable((ClusterEvent.UnreachableMember)message);
189 } else if(message instanceof ClusterEvent.ReachableMember) {
190 memberReachable((ClusterEvent.ReachableMember) message);
191 } else if(message instanceof DatastoreContextFactory) {
192 onDatastoreContextFactory((DatastoreContextFactory)message);
193 } else if(message instanceof RoleChangeNotification) {
194 onRoleChangeNotification((RoleChangeNotification) message);
195 } else if(message instanceof FollowerInitialSyncUpStatus){
196 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
197 } else if(message instanceof ShardNotInitializedTimeout) {
198 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
199 } else if(message instanceof ShardLeaderStateChanged) {
200 onLeaderStateChanged((ShardLeaderStateChanged) message);
201 } else if(message instanceof SwitchShardBehavior){
202 onSwitchShardBehavior((SwitchShardBehavior) message);
203 } else if(message instanceof CreateShard) {
204 onCreateShard((CreateShard)message);
205 } else if(message instanceof AddShardReplica){
206 onAddShardReplica((AddShardReplica)message);
207 } else if(message instanceof RemoveShardReplica){
208 onRemoveShardReplica((RemoveShardReplica)message);
209 } else if(message instanceof GetSnapshot) {
211 } else if (message instanceof SaveSnapshotSuccess) {
212 LOG.debug ("{} saved ShardManager snapshot successfully", persistenceId());
213 } else if (message instanceof SaveSnapshotFailure) {
214 LOG.error ("{}: SaveSnapshotFailure received for saving snapshot of shards",
215 persistenceId(), ((SaveSnapshotFailure)message).cause());
217 unknownMessage(message);
222 private void onGetSnapshot() {
223 LOG.debug("{}: onGetSnapshot", persistenceId());
225 List<String> notInitialized = null;
226 for(ShardInformation shardInfo: localShards.values()) {
227 if(!shardInfo.isShardInitialized()) {
228 if(notInitialized == null) {
229 notInitialized = new ArrayList<>();
232 notInitialized.add(shardInfo.getShardName());
236 if(notInitialized != null) {
237 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(String.format(
238 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
242 byte[] shardManagerSnapshot = null;
243 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
244 new ArrayList<>(localShards.keySet()), type, shardManagerSnapshot , getSender(), persistenceId(),
245 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
247 for(ShardInformation shardInfo: localShards.values()) {
248 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
252 private void onCreateShard(CreateShard createShard) {
255 ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
256 if(localShards.containsKey(moduleShardConfig.getShardName())) {
257 throw new IllegalStateException(String.format("Shard with name %s already exists",
258 moduleShardConfig.getShardName()));
261 configuration.addModuleShardConfiguration(moduleShardConfig);
263 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), moduleShardConfig.getShardName());
264 Map<String, String> peerAddresses = getPeerAddresses(moduleShardConfig.getShardName()/*,
265 moduleShardConfig.getShardMemberNames()*/);
267 LOG.debug("onCreateShard: shardId: {}, memberNames: {}. peerAddresses: {}", shardId,
268 moduleShardConfig.getShardMemberNames(), peerAddresses);
270 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
271 if(shardDatastoreContext == null) {
272 shardDatastoreContext = newShardDatastoreContext(moduleShardConfig.getShardName());
274 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
275 peerAddressResolver).build();
278 ShardInformation info = new ShardInformation(moduleShardConfig.getShardName(), shardId, peerAddresses,
279 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
280 localShards.put(info.getShardName(), info);
282 mBean.addLocalShard(shardId.toString());
284 if(schemaContext != null) {
285 info.setActor(newShardActor(schemaContext, info));
288 reply = new CreateShardReply();
289 } catch (Exception e) {
290 LOG.error("onCreateShard failed", e);
291 reply = new akka.actor.Status.Failure(e);
294 if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
295 getSender().tell(reply, getSelf());
299 private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
300 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName)).
301 shardPeerAddressResolver(peerAddressResolver);
304 private DatastoreContext newShardDatastoreContext(String shardName) {
305 return newShardDatastoreContextBuilder(shardName).build();
308 private void checkReady(){
309 if (isReadyWithLeaderId()) {
310 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
311 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
313 waitTillReadyCountdownLatch.countDown();
317 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
318 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
320 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
321 if(shardInformation != null) {
322 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
323 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
324 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
325 primaryShardInfoCache.remove(shardInformation.getShardName());
330 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
334 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
335 ShardInformation shardInfo = message.getShardInfo();
337 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
338 shardInfo.getShardName());
340 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
342 if(!shardInfo.isShardInitialized()) {
343 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
344 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
346 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
347 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
351 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
352 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
353 status.getName(), status.isInitialSyncDone());
355 ShardInformation shardInformation = findShardInformation(status.getName());
357 if(shardInformation != null) {
358 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
360 mBean.setSyncStatus(isInSync());
365 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
366 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
367 roleChanged.getOldRole(), roleChanged.getNewRole());
369 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
370 if(shardInformation != null) {
371 shardInformation.setRole(roleChanged.getNewRole());
373 mBean.setSyncStatus(isInSync());
378 private ShardInformation findShardInformation(String memberId) {
379 for(ShardInformation info : localShards.values()){
380 if(info.getShardId().toString().equals(memberId)){
388 private boolean isReadyWithLeaderId() {
389 boolean isReady = true;
390 for (ShardInformation info : localShards.values()) {
391 if(!info.isShardReadyWithLeaderId()){
399 private boolean isInSync(){
400 for (ShardInformation info : localShards.values()) {
401 if(!info.isInSync()){
408 private void onActorInitialized(Object message) {
409 final ActorRef sender = getSender();
411 if (sender == null) {
412 return; //why is a non-actor sending this message? Just ignore.
415 String actorName = sender.path().name();
416 //find shard name from actor name; actor name is stringified shardId
417 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
419 if (shardId.getShardName() == null) {
423 markShardAsInitialized(shardId.getShardName());
426 private void markShardAsInitialized(String shardName) {
427 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
429 ShardInformation shardInformation = localShards.get(shardName);
430 if (shardInformation != null) {
431 shardInformation.setActorInitialized();
433 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
438 protected void handleRecover(Object message) throws Exception {
439 if (message instanceof RecoveryCompleted) {
440 LOG.info("Recovery complete : {}", persistenceId());
442 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
443 // journal on upgrade from Helium.
444 deleteMessages(lastSequenceNr());
446 } else if (message instanceof SnapshotOffer) {
447 handleShardRecovery((SnapshotOffer) message);
451 private void findLocalShard(FindLocalShard message) {
452 final ShardInformation shardInformation = localShards.get(message.getShardName());
454 if(shardInformation == null){
455 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
459 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
461 public Object get() {
462 return new LocalShardFound(shardInformation.getActor());
467 private void sendResponse(ShardInformation shardInformation, boolean doWait,
468 boolean wantShardReady, final Supplier<Object> messageSupplier) {
469 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
471 final ActorRef sender = getSender();
472 final ActorRef self = self();
474 Runnable replyRunnable = new Runnable() {
477 sender.tell(messageSupplier.get(), self);
481 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
482 new OnShardInitialized(replyRunnable);
484 shardInformation.addOnShardInitialized(onShardInitialized);
486 FiniteDuration timeout = shardInformation.getDatastoreContext().getShardInitializationTimeout().duration();
487 if(shardInformation.isShardInitialized()) {
488 // If the shard is already initialized then we'll wait enough time for the shard to
489 // elect a leader, ie 2 times the election timeout.
490 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
491 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
494 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
495 shardInformation.getShardName());
497 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
499 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
500 getContext().dispatcher(), getSelf());
502 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
504 } else if (!shardInformation.isShardInitialized()) {
505 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
506 shardInformation.getShardName());
507 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
509 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
510 shardInformation.getShardName());
511 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
517 getSender().tell(messageSupplier.get(), getSelf());
520 private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
521 return new NoShardLeaderException(null, shardId.toString());
524 private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
525 return new NotInitializedException(String.format(
526 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
529 private void memberRemoved(ClusterEvent.MemberRemoved message) {
530 String memberName = message.member().roles().head();
532 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
533 message.member().address());
535 peerAddressResolver.removePeerAddress(memberName);
537 for(ShardInformation info : localShards.values()){
538 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
542 private void memberExited(ClusterEvent.MemberExited message) {
543 String memberName = message.member().roles().head();
545 LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
546 message.member().address());
548 peerAddressResolver.removePeerAddress(memberName);
550 for(ShardInformation info : localShards.values()){
551 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
555 private void memberUp(ClusterEvent.MemberUp message) {
556 String memberName = message.member().roles().head();
558 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
559 message.member().address());
561 addPeerAddress(memberName, message.member().address());
566 private void addPeerAddress(String memberName, Address address) {
567 peerAddressResolver.addPeerAddress(memberName, address);
569 for(ShardInformation info : localShards.values()){
570 String shardName = info.getShardName();
571 String peerId = getShardIdentifier(memberName, shardName).toString();
572 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
574 info.peerUp(memberName, peerId, getSelf());
578 private void memberReachable(ClusterEvent.ReachableMember message) {
579 String memberName = message.member().roles().head();
580 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
582 addPeerAddress(memberName, message.member().address());
584 markMemberAvailable(memberName);
587 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
588 String memberName = message.member().roles().head();
589 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
591 markMemberUnavailable(memberName);
594 private void markMemberUnavailable(final String memberName) {
595 for(ShardInformation info : localShards.values()){
596 String leaderId = info.getLeaderId();
597 if(leaderId != null && leaderId.contains(memberName)) {
598 LOG.debug("Marking Leader {} as unavailable.", leaderId);
599 info.setLeaderAvailable(false);
601 primaryShardInfoCache.remove(info.getShardName());
604 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
608 private void markMemberAvailable(final String memberName) {
609 for(ShardInformation info : localShards.values()){
610 String leaderId = info.getLeaderId();
611 if(leaderId != null && leaderId.contains(memberName)) {
612 LOG.debug("Marking Leader {} as available.", leaderId);
613 info.setLeaderAvailable(true);
616 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
620 private void onDatastoreContextFactory(DatastoreContextFactory factory) {
621 datastoreContextFactory = factory;
622 for (ShardInformation info : localShards.values()) {
623 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
627 private void onSwitchShardBehavior(SwitchShardBehavior message) {
628 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
630 ShardInformation shardInformation = localShards.get(identifier.getShardName());
632 if(shardInformation != null && shardInformation.getActor() != null) {
633 shardInformation.getActor().tell(
634 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
636 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
637 message.getShardName(), message.getNewState());
642 * Notifies all the local shards of a change in the schema context
646 private void updateSchemaContext(final Object message) {
647 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
649 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
651 for (ShardInformation info : localShards.values()) {
652 if (info.getActor() == null) {
653 LOG.debug("Creating Shard {}", info.getShardId());
654 info.setActor(newShardActor(schemaContext, info));
656 info.getActor().tell(message, getSelf());
662 protected ClusterWrapper getCluster() {
667 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
668 return getContext().actorOf(info.newProps(schemaContext)
669 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
672 private void findPrimary(FindPrimary message) {
673 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
675 final String shardName = message.getShardName();
676 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
678 // First see if the there is a local replica for the shard
679 final ShardInformation info = localShards.get(shardName);
681 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
683 public Object get() {
684 String primaryPath = info.getSerializedLeaderActor();
685 Object found = canReturnLocalShardState && info.isLeader() ?
686 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
687 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
689 if(LOG.isDebugEnabled()) {
690 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
700 for(String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
701 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
704 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
705 message.isWaitUntilReady()), getContext());
709 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
711 getSender().tell(new PrimaryNotFoundException(
712 String.format("No primary shard found for %s.", shardName)), getSelf());
716 * Construct the name of the shard actor given the name of the member on
717 * which the shard resides and the name of the shard
723 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
724 return peerAddressResolver.getShardIdentifier(memberName, shardName);
728 * Create shards that are local to the member on which the ShardManager
732 private void createLocalShards() {
733 String memberName = this.cluster.getCurrentMemberName();
734 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
736 Map<String, DatastoreSnapshot.ShardSnapshot> shardSnapshots = new HashMap<>();
737 if(restoreFromSnapshot != null)
739 for(DatastoreSnapshot.ShardSnapshot snapshot: restoreFromSnapshot.getShardSnapshots()) {
740 shardSnapshots.put(snapshot.getName(), snapshot);
744 restoreFromSnapshot = null; // null out to GC
746 for(String shardName : memberShardNames){
747 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
748 Map<String, String> peerAddresses = getPeerAddresses(shardName);
749 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
750 newShardDatastoreContext(shardName), Shard.builder().restoreFromSnapshot(
751 shardSnapshots.get(shardName)), peerAddressResolver));
752 mBean.addLocalShard(shardId.toString());
757 * Given the name of the shard find the addresses of all it's peers
761 private Map<String, String> getPeerAddresses(String shardName) {
762 Collection<String> members = configuration.getMembersFromShardName(shardName);
763 Map<String, String> peerAddresses = new HashMap<>();
765 String currentMemberName = this.cluster.getCurrentMemberName();
767 for(String memberName : members) {
768 if(!currentMemberName.equals(memberName)) {
769 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
770 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
771 peerAddresses.put(shardId.toString(), address);
774 return peerAddresses;
778 public SupervisorStrategy supervisorStrategy() {
780 return new OneForOneStrategy(10, Duration.create("1 minute"),
781 new Function<Throwable, SupervisorStrategy.Directive>() {
783 public SupervisorStrategy.Directive apply(Throwable t) {
784 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
785 return SupervisorStrategy.resume();
793 public String persistenceId() {
794 return "shard-manager-" + type;
798 ShardManagerInfoMBean getMBean(){
802 private void checkLocalShardExists(final String shardName, final ActorRef sender) {
803 if (localShards.containsKey(shardName)) {
804 String msg = String.format("Local shard %s already exists", shardName);
805 LOG.debug ("{}: {}", persistenceId(), msg);
806 sender.tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
810 private void onAddShardReplica (AddShardReplica shardReplicaMsg) {
811 final String shardName = shardReplicaMsg.getShardName();
813 // verify the local shard replica is already available in the controller node
814 LOG.debug ("onAddShardReplica: {}", shardReplicaMsg);
816 checkLocalShardExists(shardName, getSender());
818 // verify the shard with the specified name is present in the cluster configuration
819 if (!(this.configuration.isShardConfigured(shardName))) {
820 String msg = String.format("No module configuration exists for shard %s", shardName);
821 LOG.debug ("{}: {}", persistenceId(), msg);
822 getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
826 // Create the localShard
827 if (schemaContext == null) {
828 String msg = String.format(
829 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
830 LOG.debug ("{}: {}", persistenceId(), msg);
831 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
835 Map<String, String> peerAddresses = getPeerAddresses(shardName);
836 if (peerAddresses.isEmpty()) {
837 String msg = String.format("Cannot add replica for shard %s because no peer is available", shardName);
838 LOG.debug ("{}: {}", persistenceId(), msg);
839 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
843 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext().
844 getShardInitializationTimeout().duration().$times(2));
846 final ActorRef sender = getSender();
847 Future<Object> futureObj = ask(getSelf(), new RemoteFindPrimary(shardName, true), findPrimaryTimeout);
848 futureObj.onComplete(new OnComplete<Object>() {
850 public void onComplete(Throwable failure, Object response) {
851 if (failure != null) {
852 LOG.debug ("{}: Received failure from FindPrimary for shard {}", persistenceId(), shardName, failure);
853 sender.tell(new akka.actor.Status.Failure(new RuntimeException(
854 String.format("Failed to find leader for shard %s", shardName), failure)),
857 if (!(response instanceof RemotePrimaryShardFound)) {
858 String msg = String.format("Failed to find leader for shard %s: received response: %s",
859 shardName, response);
860 LOG.debug ("{}: {}", persistenceId(), msg);
861 sender.tell(new akka.actor.Status.Failure(new RuntimeException(msg)), getSelf());
865 RemotePrimaryShardFound message = (RemotePrimaryShardFound)response;
866 addShard (shardName, message, sender);
869 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
872 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
873 checkLocalShardExists(shardName, sender);
875 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
876 String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
878 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).customRaftPolicyImplementation(
879 DisableElectionsRaftPolicy.class.getName()).build();
881 final ShardInformation shardInfo = new ShardInformation(shardName, shardId,
882 getPeerAddresses(shardName), datastoreContext,
883 Shard.builder(), peerAddressResolver);
884 shardInfo.setShardActiveMember(false);
885 localShards.put(shardName, shardInfo);
886 shardInfo.setActor(newShardActor(schemaContext, shardInfo));
888 //inform ShardLeader to add this shard as a replica by sending an AddServer message
889 LOG.debug ("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
890 response.getPrimaryPath(), shardId);
892 Timeout addServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(4));
893 Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
894 new AddServer(shardId.toString(), localShardAddress, true), addServerTimeout);
896 futureObj.onComplete(new OnComplete<Object>() {
898 public void onComplete(Throwable failure, Object addServerResponse) {
899 if (failure != null) {
900 LOG.debug ("{}: AddServer request to {} for {} failed", persistenceId(),
901 response.getPrimaryPath(), shardName, failure);
904 localShards.remove(shardName);
905 if (shardInfo.getActor() != null) {
906 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
909 sender.tell(new akka.actor.Status.Failure(new RuntimeException(
910 String.format("AddServer request to leader %s for shard %s failed",
911 response.getPrimaryPath(), shardName), failure)), getSelf());
913 AddServerReply reply = (AddServerReply)addServerResponse;
914 onAddServerReply(shardName, shardInfo, reply, sender, response.getPrimaryPath());
917 }, new Dispatchers(context().system().dispatchers()).
918 getDispatcher(Dispatchers.DispatcherType.Client));
922 private void onAddServerReply (String shardName, ShardInformation shardInfo,
923 AddServerReply replyMsg, ActorRef sender, String leaderPath) {
924 LOG.debug ("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
926 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
927 LOG.debug ("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
929 // Make the local shard voting capable
930 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
931 shardInfo.setShardActiveMember(true);
934 mBean.addLocalShard(shardInfo.getShardId().toString());
935 sender.tell(new akka.actor.Status.Success(true), getSelf());
937 LOG.warn ("{}: Leader failed to add shard replica {} with status {} - removing the local shard",
938 persistenceId(), shardName, replyMsg.getStatus());
940 //remove the local replica created
941 localShards.remove(shardName);
942 if (shardInfo.getActor() != null) {
943 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
945 switch (replyMsg.getStatus()) {
947 sender.tell(new akka.actor.Status.Failure(new RuntimeException(
948 String.format("The shard leader %s timed out trying to replicate the initial data to the new shard %s. Possible causes - there was a problem replicating the data or shard leadership changed while replicating the shard data",
949 leaderPath, shardName))), getSelf());
952 sender.tell(new akka.actor.Status.Failure(new RuntimeException(String.format(
953 "There is no shard leader available for shard %s", shardName))), getSelf());
956 sender.tell(new akka.actor.Status.Failure(new RuntimeException(String.format(
957 "AddServer request to leader %s for shard %s failed with status %s",
958 leaderPath, shardName, replyMsg.getStatus()))), getSelf());
963 private void onRemoveShardReplica (RemoveShardReplica shardReplicaMsg) {
964 String shardName = shardReplicaMsg.getShardName();
966 // verify the local shard replica is available in the controller node
967 if (!localShards.containsKey(shardName)) {
968 String msg = String.format("Local shard %s does not", shardName);
969 LOG.debug ("{}: {}", persistenceId(), msg);
970 getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
973 // call RemoveShard for the shardName
974 getSender().tell(new akka.actor.Status.Success(true), getSelf());
978 private void persistShardList() {
979 List<String> shardList = new ArrayList(localShards.keySet());
980 for (ShardInformation shardInfo : localShards.values()) {
981 if (!shardInfo.isShardActiveMember()) {
982 shardList.remove(shardInfo.getShardName());
985 LOG.debug ("{}: persisting the shard list {}", persistenceId(), shardList);
986 saveSnapshot(new ShardManagerSnapshot(shardList));
989 private void handleShardRecovery(SnapshotOffer offer) {
990 LOG.debug ("{}: in handleShardRecovery", persistenceId());
991 ShardManagerSnapshot snapshot = (ShardManagerSnapshot)offer.snapshot();
992 String currentMember = cluster.getCurrentMemberName();
993 Set<String> configuredShardList =
994 new HashSet<>(configuration.getMemberShardNames(currentMember));
995 for (String shard : snapshot.getShardList()) {
996 if (!configuredShardList.contains(shard)) {
997 // add the current member as a replica for the shard
998 LOG.debug ("{}: adding shard {}", persistenceId(), shard);
999 configuration.addMemberReplicaForShard(shard, currentMember);
1001 configuredShardList.remove(shard);
1004 for (String shard : configuredShardList) {
1005 // remove the member as a replica for the shard
1006 LOG.debug ("{}: removing shard {}", persistenceId(), shard);
1007 configuration.removeMemberReplicaForShard(shard, currentMember);
1012 protected static class ShardInformation {
1013 private final ShardIdentifier shardId;
1014 private final String shardName;
1015 private ActorRef actor;
1016 private ActorPath actorPath;
1017 private final Map<String, String> initialPeerAddresses;
1018 private Optional<DataTree> localShardDataTree;
1019 private boolean leaderAvailable = false;
1021 // flag that determines if the actor is ready for business
1022 private boolean actorInitialized = false;
1024 private boolean followerSyncStatus = false;
1026 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
1027 private String role ;
1028 private String leaderId;
1029 private short leaderVersion;
1031 private DatastoreContext datastoreContext;
1032 private Shard.AbstractBuilder<?, ?> builder;
1033 private final ShardPeerAddressResolver addressResolver;
1034 private boolean shardActiveStatus = true;
1036 private ShardInformation(String shardName, ShardIdentifier shardId,
1037 Map<String, String> initialPeerAddresses, DatastoreContext datastoreContext,
1038 Shard.AbstractBuilder<?, ?> builder, ShardPeerAddressResolver addressResolver) {
1039 this.shardName = shardName;
1040 this.shardId = shardId;
1041 this.initialPeerAddresses = initialPeerAddresses;
1042 this.datastoreContext = datastoreContext;
1043 this.builder = builder;
1044 this.addressResolver = addressResolver;
1047 Props newProps(SchemaContext schemaContext) {
1048 Preconditions.checkNotNull(builder);
1049 Props props = builder.id(shardId).peerAddresses(initialPeerAddresses).datastoreContext(datastoreContext).
1050 schemaContext(schemaContext).props();
1055 String getShardName() {
1059 ActorRef getActor(){
1063 ActorPath getActorPath() {
1067 void setActor(ActorRef actor) {
1069 this.actorPath = actor.path();
1072 ShardIdentifier getShardId() {
1076 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
1077 this.localShardDataTree = localShardDataTree;
1080 Optional<DataTree> getLocalShardDataTree() {
1081 return localShardDataTree;
1084 DatastoreContext getDatastoreContext() {
1085 return datastoreContext;
1088 void setDatastoreContext(DatastoreContext datastoreContext, ActorRef sender) {
1089 this.datastoreContext = datastoreContext;
1090 if (actor != null) {
1091 LOG.debug ("Sending new DatastoreContext to {}", shardId);
1092 actor.tell(this.datastoreContext, sender);
1096 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
1097 LOG.info("updatePeerAddress for peer {} with address {}", peerId, peerAddress);
1100 if(LOG.isDebugEnabled()) {
1101 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
1102 peerId, peerAddress, actor.path());
1105 actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
1108 notifyOnShardInitializedCallbacks();
1111 void peerDown(String memberName, String peerId, ActorRef sender) {
1113 actor.tell(new PeerDown(memberName, peerId), sender);
1117 void peerUp(String memberName, String peerId, ActorRef sender) {
1119 actor.tell(new PeerUp(memberName, peerId), sender);
1123 boolean isShardReady() {
1124 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
1127 boolean isShardReadyWithLeaderId() {
1128 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
1129 (isLeader() || addressResolver.resolve(leaderId) != null);
1132 boolean isShardInitialized() {
1133 return getActor() != null && actorInitialized;
1136 boolean isLeader() {
1137 return Objects.equal(leaderId, shardId.toString());
1140 String getSerializedLeaderActor() {
1142 return Serialization.serializedActorPath(getActor());
1144 return addressResolver.resolve(leaderId);
1148 void setActorInitialized() {
1149 LOG.debug("Shard {} is initialized", shardId);
1151 this.actorInitialized = true;
1153 notifyOnShardInitializedCallbacks();
1156 private void notifyOnShardInitializedCallbacks() {
1157 if(onShardInitializedSet.isEmpty()) {
1161 boolean ready = isShardReadyWithLeaderId();
1163 if(LOG.isDebugEnabled()) {
1164 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
1165 ready ? "ready" : "initialized", onShardInitializedSet.size());
1168 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
1169 while(iter.hasNext()) {
1170 OnShardInitialized onShardInitialized = iter.next();
1171 if(!(onShardInitialized instanceof OnShardReady) || ready) {
1173 onShardInitialized.getTimeoutSchedule().cancel();
1174 onShardInitialized.getReplyRunnable().run();
1179 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
1180 onShardInitializedSet.add(onShardInitialized);
1183 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
1184 onShardInitializedSet.remove(onShardInitialized);
1187 void setRole(String newRole) {
1188 this.role = newRole;
1190 notifyOnShardInitializedCallbacks();
1193 void setFollowerSyncStatus(boolean syncStatus){
1194 this.followerSyncStatus = syncStatus;
1198 if(RaftState.Follower.name().equals(this.role)){
1199 return followerSyncStatus;
1200 } else if(RaftState.Leader.name().equals(this.role)){
1207 boolean setLeaderId(String leaderId) {
1208 boolean changed = !Objects.equal(this.leaderId, leaderId);
1209 this.leaderId = leaderId;
1210 if(leaderId != null) {
1211 this.leaderAvailable = true;
1213 notifyOnShardInitializedCallbacks();
1218 String getLeaderId() {
1222 void setLeaderAvailable(boolean leaderAvailable) {
1223 this.leaderAvailable = leaderAvailable;
1226 short getLeaderVersion() {
1227 return leaderVersion;
1230 void setLeaderVersion(short leaderVersion) {
1231 this.leaderVersion = leaderVersion;
1234 void setShardActiveMember(boolean flag) {
1235 shardActiveStatus = flag;
1238 boolean isShardActiveMember() {
1239 return shardActiveStatus;
1243 private static class OnShardInitialized {
1244 private final Runnable replyRunnable;
1245 private Cancellable timeoutSchedule;
1247 OnShardInitialized(Runnable replyRunnable) {
1248 this.replyRunnable = replyRunnable;
1251 Runnable getReplyRunnable() {
1252 return replyRunnable;
1255 Cancellable getTimeoutSchedule() {
1256 return timeoutSchedule;
1259 void setTimeoutSchedule(Cancellable timeoutSchedule) {
1260 this.timeoutSchedule = timeoutSchedule;
1264 private static class OnShardReady extends OnShardInitialized {
1265 OnShardReady(Runnable replyRunnable) {
1266 super(replyRunnable);
1270 private static class ShardNotInitializedTimeout {
1271 private final ActorRef sender;
1272 private final ShardInformation shardInfo;
1273 private final OnShardInitialized onShardInitialized;
1275 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1276 this.sender = sender;
1277 this.shardInfo = shardInfo;
1278 this.onShardInitialized = onShardInitialized;
1281 ActorRef getSender() {
1285 ShardInformation getShardInfo() {
1289 OnShardInitialized getOnShardInitialized() {
1290 return onShardInitialized;
1295 * We no longer persist SchemaContextModules but keep this class around for now for backwards
1296 * compatibility so we don't get de-serialization failures on upgrade from Helium.
1299 static class SchemaContextModules implements Serializable {
1300 private static final long serialVersionUID = -8884620101025936590L;
1302 private final Set<String> modules;
1304 SchemaContextModules(Set<String> modules){
1305 this.modules = modules;
1308 public Set<String> getModules() {
1313 public static Builder builder() {
1314 return new Builder();
1317 public static class Builder {
1318 private ClusterWrapper cluster;
1319 private Configuration configuration;
1320 private DatastoreContextFactory datastoreContextFactory;
1321 private CountDownLatch waitTillReadyCountdownLatch;
1322 private PrimaryShardInfoFutureCache primaryShardInfoCache;
1323 private DatastoreSnapshot restoreFromSnapshot;
1324 private volatile boolean sealed;
1326 protected void checkSealed() {
1327 Preconditions.checkState(!sealed, "Builder is already sealed - further modifications are not allowed");
1330 public Builder cluster(ClusterWrapper cluster) {
1332 this.cluster = cluster;
1336 public Builder configuration(Configuration configuration) {
1338 this.configuration = configuration;
1342 public Builder datastoreContextFactory(DatastoreContextFactory datastoreContextFactory) {
1344 this.datastoreContextFactory = datastoreContextFactory;
1348 public Builder waitTillReadyCountdownLatch(CountDownLatch waitTillReadyCountdownLatch) {
1350 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
1354 public Builder primaryShardInfoCache(PrimaryShardInfoFutureCache primaryShardInfoCache) {
1356 this.primaryShardInfoCache = primaryShardInfoCache;
1360 public Builder restoreFromSnapshot(DatastoreSnapshot restoreFromSnapshot) {
1362 this.restoreFromSnapshot = restoreFromSnapshot;
1366 protected void verify() {
1368 Preconditions.checkNotNull(cluster, "cluster should not be null");
1369 Preconditions.checkNotNull(configuration, "configuration should not be null");
1370 Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
1371 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
1372 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
1375 public Props props() {
1377 return Props.create(ShardManager.class, this);