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.Creator;
23 import akka.japi.Function;
24 import akka.persistence.RecoveryCompleted;
25 import akka.serialization.Serialization;
26 import akka.util.Timeout;
27 import com.google.common.annotations.VisibleForTesting;
28 import com.google.common.base.Objects;
29 import com.google.common.base.Optional;
30 import com.google.common.base.Preconditions;
31 import com.google.common.base.Strings;
32 import com.google.common.base.Supplier;
33 import com.google.common.collect.Sets;
34 import java.io.Serializable;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.Iterator;
39 import java.util.List;
42 import java.util.concurrent.CountDownLatch;
43 import java.util.concurrent.TimeUnit;
44 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActorWithMetering;
45 import org.opendaylight.controller.cluster.datastore.config.Configuration;
46 import org.opendaylight.controller.cluster.datastore.config.ModuleShardConfiguration;
47 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
48 import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
49 import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
50 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
51 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfo;
52 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shardmanager.ShardManagerInfoMBean;
53 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
54 import org.opendaylight.controller.cluster.datastore.messages.AddShardReplica;
55 import org.opendaylight.controller.cluster.datastore.messages.CreateShard;
56 import org.opendaylight.controller.cluster.datastore.messages.CreateShardReply;
57 import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
58 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
59 import org.opendaylight.controller.cluster.datastore.messages.LocalPrimaryShardFound;
60 import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
61 import org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound;
62 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
63 import org.opendaylight.controller.cluster.datastore.messages.PeerDown;
64 import org.opendaylight.controller.cluster.datastore.messages.PeerUp;
65 import org.opendaylight.controller.cluster.datastore.messages.RemoteFindPrimary;
66 import org.opendaylight.controller.cluster.datastore.messages.RemotePrimaryShardFound;
67 import org.opendaylight.controller.cluster.datastore.messages.RemoveShardReplica;
68 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
69 import org.opendaylight.controller.cluster.datastore.messages.SwitchShardBehavior;
70 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
71 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
72 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
73 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
74 import org.opendaylight.controller.cluster.notifications.RoleChangeNotification;
75 import org.opendaylight.controller.cluster.raft.RaftState;
76 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
77 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
78 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
79 import org.opendaylight.controller.cluster.raft.messages.AddServer;
80 import org.opendaylight.controller.cluster.raft.messages.AddServerReply;
81 import org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus;
82 import org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy;
83 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
84 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import scala.concurrent.Future;
88 import scala.concurrent.duration.Duration;
89 import scala.concurrent.duration.FiniteDuration;
92 * The ShardManager has the following jobs,
94 * <li> Create all the local shard replicas that belong on this cluster member
95 * <li> Find the address of the local shard
96 * <li> Find the primary replica for any given shard
97 * <li> Monitor the cluster members and store their addresses
100 public class ShardManager extends AbstractUntypedPersistentActorWithMetering {
102 private static final Logger LOG = LoggerFactory.getLogger(ShardManager.class);
104 // Stores a mapping between a shard name and it's corresponding information
105 // Shard names look like inventory, topology etc and are as specified in
107 private final Map<String, ShardInformation> localShards = new HashMap<>();
109 // The type of a ShardManager reflects the type of the datastore itself
110 // A data store could be of type config/operational
111 private final String type;
113 private final ClusterWrapper cluster;
115 private final Configuration configuration;
117 private final String shardDispatcherPath;
119 private ShardManagerInfo mBean;
121 private DatastoreContextFactory datastoreContextFactory;
123 private final CountDownLatch waitTillReadyCountdownLatch;
125 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
127 private final ShardPeerAddressResolver peerAddressResolver;
129 private SchemaContext schemaContext;
133 protected ShardManager(ClusterWrapper cluster, Configuration configuration,
134 DatastoreContextFactory datastoreContextFactory, CountDownLatch waitTillReadyCountdownLatch,
135 PrimaryShardInfoFutureCache primaryShardInfoCache) {
137 this.cluster = Preconditions.checkNotNull(cluster, "cluster should not be null");
138 this.configuration = Preconditions.checkNotNull(configuration, "configuration should not be null");
139 this.datastoreContextFactory = datastoreContextFactory;
140 this.type = datastoreContextFactory.getBaseDatastoreContext().getDataStoreType();
141 this.shardDispatcherPath =
142 new Dispatchers(context().system().dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
143 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
144 this.primaryShardInfoCache = primaryShardInfoCache;
146 peerAddressResolver = new ShardPeerAddressResolver(type, cluster.getCurrentMemberName());
148 // Subscribe this actor to cluster member events
149 cluster.subscribeToMemberEvents(getSelf());
154 public static Props props(
155 final ClusterWrapper cluster,
156 final Configuration configuration,
157 final DatastoreContextFactory datastoreContextFactory,
158 final CountDownLatch waitTillReadyCountdownLatch,
159 final PrimaryShardInfoFutureCache primaryShardInfoCache) {
161 Preconditions.checkNotNull(cluster, "cluster should not be null");
162 Preconditions.checkNotNull(configuration, "configuration should not be null");
163 Preconditions.checkNotNull(waitTillReadyCountdownLatch, "waitTillReadyCountdownLatch should not be null");
164 Preconditions.checkNotNull(primaryShardInfoCache, "primaryShardInfoCache should not be null");
166 return Props.create(new ShardManagerCreator(cluster, configuration, datastoreContextFactory,
167 waitTillReadyCountdownLatch, primaryShardInfoCache));
171 public void postStop() {
172 LOG.info("Stopping ShardManager");
174 mBean.unregisterMBean();
178 public void handleCommand(Object message) throws Exception {
179 if (message instanceof FindPrimary) {
180 findPrimary((FindPrimary)message);
181 } else if(message instanceof FindLocalShard){
182 findLocalShard((FindLocalShard) message);
183 } else if (message instanceof UpdateSchemaContext) {
184 updateSchemaContext(message);
185 } else if(message instanceof ActorInitialized) {
186 onActorInitialized(message);
187 } else if (message instanceof ClusterEvent.MemberUp){
188 memberUp((ClusterEvent.MemberUp) message);
189 } else if (message instanceof ClusterEvent.MemberExited){
190 memberExited((ClusterEvent.MemberExited) message);
191 } else if(message instanceof ClusterEvent.MemberRemoved) {
192 memberRemoved((ClusterEvent.MemberRemoved) message);
193 } else if(message instanceof ClusterEvent.UnreachableMember) {
194 memberUnreachable((ClusterEvent.UnreachableMember)message);
195 } else if(message instanceof ClusterEvent.ReachableMember) {
196 memberReachable((ClusterEvent.ReachableMember) message);
197 } else if(message instanceof DatastoreContextFactory) {
198 onDatastoreContextFactory((DatastoreContextFactory)message);
199 } else if(message instanceof RoleChangeNotification) {
200 onRoleChangeNotification((RoleChangeNotification) message);
201 } else if(message instanceof FollowerInitialSyncUpStatus){
202 onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
203 } else if(message instanceof ShardNotInitializedTimeout) {
204 onShardNotInitializedTimeout((ShardNotInitializedTimeout)message);
205 } else if(message instanceof ShardLeaderStateChanged) {
206 onLeaderStateChanged((ShardLeaderStateChanged) message);
207 } else if(message instanceof SwitchShardBehavior){
208 onSwitchShardBehavior((SwitchShardBehavior) message);
209 } else if(message instanceof CreateShard) {
210 onCreateShard((CreateShard)message);
211 } else if(message instanceof AddShardReplica){
212 onAddShardReplica((AddShardReplica)message);
213 } else if(message instanceof RemoveShardReplica){
214 onRemoveShardReplica((RemoveShardReplica)message);
215 } else if(message instanceof GetSnapshot) {
218 unknownMessage(message);
223 private void onGetSnapshot() {
224 LOG.debug("{}: onGetSnapshot", persistenceId());
226 List<String> notInitialized = null;
227 for(ShardInformation shardInfo: localShards.values()) {
228 if(!shardInfo.isShardInitialized()) {
229 if(notInitialized == null) {
230 notInitialized = new ArrayList<>();
233 notInitialized.add(shardInfo.getShardName());
237 if(notInitialized != null) {
238 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(String.format(
239 "%d shard(s) %s are not initialized", notInitialized.size(), notInitialized))), getSelf());
243 byte[] shardManagerSnapshot = null;
244 ActorRef replyActor = getContext().actorOf(ShardManagerGetSnapshotReplyActor.props(
245 new ArrayList<>(localShards.keySet()), type, shardManagerSnapshot , getSender(), persistenceId(),
246 datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration()));
248 for(ShardInformation shardInfo: localShards.values()) {
249 shardInfo.getActor().tell(GetSnapshot.INSTANCE, replyActor);
253 private void onCreateShard(CreateShard createShard) {
256 ModuleShardConfiguration moduleShardConfig = createShard.getModuleShardConfig();
257 if(localShards.containsKey(moduleShardConfig.getShardName())) {
258 throw new IllegalStateException(String.format("Shard with name %s already exists",
259 moduleShardConfig.getShardName()));
262 configuration.addModuleShardConfiguration(moduleShardConfig);
264 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), moduleShardConfig.getShardName());
265 Map<String, String> peerAddresses = getPeerAddresses(moduleShardConfig.getShardName()/*,
266 moduleShardConfig.getShardMemberNames()*/);
268 LOG.debug("onCreateShard: shardId: {}, memberNames: {}. peerAddresses: {}", shardId,
269 moduleShardConfig.getShardMemberNames(), peerAddresses);
271 DatastoreContext shardDatastoreContext = createShard.getDatastoreContext();
272 if(shardDatastoreContext == null) {
273 shardDatastoreContext = newShardDatastoreContext(moduleShardConfig.getShardName());
275 shardDatastoreContext = DatastoreContext.newBuilderFrom(shardDatastoreContext).shardPeerAddressResolver(
276 peerAddressResolver).build();
279 ShardInformation info = new ShardInformation(moduleShardConfig.getShardName(), shardId, peerAddresses,
280 shardDatastoreContext, createShard.getShardBuilder(), peerAddressResolver);
281 localShards.put(info.getShardName(), info);
283 mBean.addLocalShard(shardId.toString());
285 if(schemaContext != null) {
286 info.setActor(newShardActor(schemaContext, info));
289 reply = new CreateShardReply();
290 } catch (Exception e) {
291 LOG.error("onCreateShard failed", e);
292 reply = new akka.actor.Status.Failure(e);
295 if(getSender() != null && !getContext().system().deadLetters().equals(getSender())) {
296 getSender().tell(reply, getSelf());
300 private DatastoreContext.Builder newShardDatastoreContextBuilder(String shardName) {
301 return DatastoreContext.newBuilderFrom(datastoreContextFactory.getShardDatastoreContext(shardName)).
302 shardPeerAddressResolver(peerAddressResolver);
305 private DatastoreContext newShardDatastoreContext(String shardName) {
306 return newShardDatastoreContextBuilder(shardName).build();
309 private void checkReady(){
310 if (isReadyWithLeaderId()) {
311 LOG.info("{}: All Shards are ready - data store {} is ready, available count is {}",
312 persistenceId(), type, waitTillReadyCountdownLatch.getCount());
314 waitTillReadyCountdownLatch.countDown();
318 private void onLeaderStateChanged(ShardLeaderStateChanged leaderStateChanged) {
319 LOG.info("{}: Received LeaderStateChanged message: {}", persistenceId(), leaderStateChanged);
321 ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
322 if(shardInformation != null) {
323 shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
324 shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
325 if(shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
326 primaryShardInfoCache.remove(shardInformation.getShardName());
331 LOG.debug("No shard found with member Id {}", leaderStateChanged.getMemberId());
335 private void onShardNotInitializedTimeout(ShardNotInitializedTimeout message) {
336 ShardInformation shardInfo = message.getShardInfo();
338 LOG.debug("{}: Received ShardNotInitializedTimeout message for shard {}", persistenceId(),
339 shardInfo.getShardName());
341 shardInfo.removeOnShardInitialized(message.getOnShardInitialized());
343 if(!shardInfo.isShardInitialized()) {
344 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(), shardInfo.getShardName());
345 message.getSender().tell(createNotInitializedException(shardInfo.shardId), getSelf());
347 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(), shardInfo.getShardName());
348 message.getSender().tell(createNoShardLeaderException(shardInfo.shardId), getSelf());
352 private void onFollowerInitialSyncStatus(FollowerInitialSyncUpStatus status) {
353 LOG.info("{} Received follower initial sync status for {} status sync done {}", persistenceId(),
354 status.getName(), status.isInitialSyncDone());
356 ShardInformation shardInformation = findShardInformation(status.getName());
358 if(shardInformation != null) {
359 shardInformation.setFollowerSyncStatus(status.isInitialSyncDone());
361 mBean.setSyncStatus(isInSync());
366 private void onRoleChangeNotification(RoleChangeNotification roleChanged) {
367 LOG.info("{}: Received role changed for {} from {} to {}", persistenceId(), roleChanged.getMemberId(),
368 roleChanged.getOldRole(), roleChanged.getNewRole());
370 ShardInformation shardInformation = findShardInformation(roleChanged.getMemberId());
371 if(shardInformation != null) {
372 shardInformation.setRole(roleChanged.getNewRole());
374 mBean.setSyncStatus(isInSync());
379 private ShardInformation findShardInformation(String memberId) {
380 for(ShardInformation info : localShards.values()){
381 if(info.getShardId().toString().equals(memberId)){
389 private boolean isReadyWithLeaderId() {
390 boolean isReady = true;
391 for (ShardInformation info : localShards.values()) {
392 if(!info.isShardReadyWithLeaderId()){
400 private boolean isInSync(){
401 for (ShardInformation info : localShards.values()) {
402 if(!info.isInSync()){
409 private void onActorInitialized(Object message) {
410 final ActorRef sender = getSender();
412 if (sender == null) {
413 return; //why is a non-actor sending this message? Just ignore.
416 String actorName = sender.path().name();
417 //find shard name from actor name; actor name is stringified shardId
418 ShardIdentifier shardId = ShardIdentifier.builder().fromShardIdString(actorName).build();
420 if (shardId.getShardName() == null) {
424 markShardAsInitialized(shardId.getShardName());
427 private void markShardAsInitialized(String shardName) {
428 LOG.debug("{}: Initializing shard [{}]", persistenceId(), shardName);
430 ShardInformation shardInformation = localShards.get(shardName);
431 if (shardInformation != null) {
432 shardInformation.setActorInitialized();
434 shardInformation.getActor().tell(new RegisterRoleChangeListener(), self());
439 protected void handleRecover(Object message) throws Exception {
440 if (message instanceof RecoveryCompleted) {
441 LOG.info("Recovery complete : {}", persistenceId());
443 // We no longer persist SchemaContext modules so delete all the prior messages from the akka
444 // journal on upgrade from Helium.
445 deleteMessages(lastSequenceNr());
449 private void findLocalShard(FindLocalShard message) {
450 final ShardInformation shardInformation = localShards.get(message.getShardName());
452 if(shardInformation == null){
453 getSender().tell(new LocalShardNotFound(message.getShardName()), getSelf());
457 sendResponse(shardInformation, message.isWaitUntilInitialized(), false, new Supplier<Object>() {
459 public Object get() {
460 return new LocalShardFound(shardInformation.getActor());
465 private void sendResponse(ShardInformation shardInformation, boolean doWait,
466 boolean wantShardReady, final Supplier<Object> messageSupplier) {
467 if (!shardInformation.isShardInitialized() || (wantShardReady && !shardInformation.isShardReadyWithLeaderId())) {
469 final ActorRef sender = getSender();
470 final ActorRef self = self();
472 Runnable replyRunnable = new Runnable() {
475 sender.tell(messageSupplier.get(), self);
479 OnShardInitialized onShardInitialized = wantShardReady ? new OnShardReady(replyRunnable) :
480 new OnShardInitialized(replyRunnable);
482 shardInformation.addOnShardInitialized(onShardInitialized);
484 FiniteDuration timeout = shardInformation.getDatastoreContext().getShardInitializationTimeout().duration();
485 if(shardInformation.isShardInitialized()) {
486 // If the shard is already initialized then we'll wait enough time for the shard to
487 // elect a leader, ie 2 times the election timeout.
488 timeout = FiniteDuration.create(shardInformation.getDatastoreContext().getShardRaftConfig()
489 .getElectionTimeOutInterval().toMillis() * 2, TimeUnit.MILLISECONDS);
492 LOG.debug("{}: Scheduling {} ms timer to wait for shard {}", persistenceId(), timeout.toMillis(),
493 shardInformation.getShardName());
495 Cancellable timeoutSchedule = getContext().system().scheduler().scheduleOnce(
497 new ShardNotInitializedTimeout(shardInformation, onShardInitialized, sender),
498 getContext().dispatcher(), getSelf());
500 onShardInitialized.setTimeoutSchedule(timeoutSchedule);
502 } else if (!shardInformation.isShardInitialized()) {
503 LOG.debug("{}: Returning NotInitializedException for shard {}", persistenceId(),
504 shardInformation.getShardName());
505 getSender().tell(createNotInitializedException(shardInformation.shardId), getSelf());
507 LOG.debug("{}: Returning NoShardLeaderException for shard {}", persistenceId(),
508 shardInformation.getShardName());
509 getSender().tell(createNoShardLeaderException(shardInformation.shardId), getSelf());
515 getSender().tell(messageSupplier.get(), getSelf());
518 private static NoShardLeaderException createNoShardLeaderException(ShardIdentifier shardId) {
519 return new NoShardLeaderException(null, shardId.toString());
522 private static NotInitializedException createNotInitializedException(ShardIdentifier shardId) {
523 return new NotInitializedException(String.format(
524 "Found primary shard %s but it's not initialized yet. Please try again later", shardId));
527 private void memberRemoved(ClusterEvent.MemberRemoved message) {
528 String memberName = message.member().roles().head();
530 LOG.debug("{}: Received MemberRemoved: memberName: {}, address: {}", persistenceId(), memberName,
531 message.member().address());
533 peerAddressResolver.removePeerAddress(memberName);
535 for(ShardInformation info : localShards.values()){
536 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
540 private void memberExited(ClusterEvent.MemberExited message) {
541 String memberName = message.member().roles().head();
543 LOG.debug("{}: Received MemberExited: memberName: {}, address: {}", persistenceId(), memberName,
544 message.member().address());
546 peerAddressResolver.removePeerAddress(memberName);
548 for(ShardInformation info : localShards.values()){
549 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
553 private void memberUp(ClusterEvent.MemberUp message) {
554 String memberName = message.member().roles().head();
556 LOG.debug("{}: Received MemberUp: memberName: {}, address: {}", persistenceId(), memberName,
557 message.member().address());
559 addPeerAddress(memberName, message.member().address());
564 private void addPeerAddress(String memberName, Address address) {
565 peerAddressResolver.addPeerAddress(memberName, address);
567 for(ShardInformation info : localShards.values()){
568 String shardName = info.getShardName();
569 String peerId = getShardIdentifier(memberName, shardName).toString();
570 info.updatePeerAddress(peerId, peerAddressResolver.getShardActorAddress(shardName, memberName), getSelf());
572 info.peerUp(memberName, peerId, getSelf());
576 private void memberReachable(ClusterEvent.ReachableMember message) {
577 String memberName = message.member().roles().head();
578 LOG.debug("Received ReachableMember: memberName {}, address: {}", memberName, message.member().address());
580 addPeerAddress(memberName, message.member().address());
582 markMemberAvailable(memberName);
585 private void memberUnreachable(ClusterEvent.UnreachableMember message) {
586 String memberName = message.member().roles().head();
587 LOG.debug("Received UnreachableMember: memberName {}, address: {}", memberName, message.member().address());
589 markMemberUnavailable(memberName);
592 private void markMemberUnavailable(final String memberName) {
593 for(ShardInformation info : localShards.values()){
594 String leaderId = info.getLeaderId();
595 if(leaderId != null && leaderId.contains(memberName)) {
596 LOG.debug("Marking Leader {} as unavailable.", leaderId);
597 info.setLeaderAvailable(false);
599 primaryShardInfoCache.remove(info.getShardName());
602 info.peerDown(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
606 private void markMemberAvailable(final String memberName) {
607 for(ShardInformation info : localShards.values()){
608 String leaderId = info.getLeaderId();
609 if(leaderId != null && leaderId.contains(memberName)) {
610 LOG.debug("Marking Leader {} as available.", leaderId);
611 info.setLeaderAvailable(true);
614 info.peerUp(memberName, getShardIdentifier(memberName, info.getShardName()).toString(), getSelf());
618 private void onDatastoreContextFactory(DatastoreContextFactory factory) {
619 datastoreContextFactory = factory;
620 for (ShardInformation info : localShards.values()) {
621 info.setDatastoreContext(newShardDatastoreContext(info.getShardName()), getSelf());
625 private void onSwitchShardBehavior(SwitchShardBehavior message) {
626 ShardIdentifier identifier = ShardIdentifier.builder().fromShardIdString(message.getShardName()).build();
628 ShardInformation shardInformation = localShards.get(identifier.getShardName());
630 if(shardInformation != null && shardInformation.getActor() != null) {
631 shardInformation.getActor().tell(
632 new SwitchBehavior(RaftState.valueOf(message.getNewState()), message.getTerm()), getSelf());
634 LOG.warn("Could not switch the behavior of shard {} to {} - shard is not yet available",
635 message.getShardName(), message.getNewState());
640 * Notifies all the local shards of a change in the schema context
644 private void updateSchemaContext(final Object message) {
645 schemaContext = ((UpdateSchemaContext) message).getSchemaContext();
647 LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getAllModuleIdentifiers().size());
649 for (ShardInformation info : localShards.values()) {
650 if (info.getActor() == null) {
651 LOG.debug("Creating Shard {}", info.getShardId());
652 info.setActor(newShardActor(schemaContext, info));
654 info.getActor().tell(message, getSelf());
660 protected ClusterWrapper getCluster() {
665 protected ActorRef newShardActor(final SchemaContext schemaContext, ShardInformation info) {
666 return getContext().actorOf(info.newProps(schemaContext)
667 .withDispatcher(shardDispatcherPath), info.getShardId().toString());
670 private void findPrimary(FindPrimary message) {
671 LOG.debug("{}: In findPrimary: {}", persistenceId(), message);
673 final String shardName = message.getShardName();
674 final boolean canReturnLocalShardState = !(message instanceof RemoteFindPrimary);
676 // First see if the there is a local replica for the shard
677 final ShardInformation info = localShards.get(shardName);
679 sendResponse(info, message.isWaitUntilReady(), true, new Supplier<Object>() {
681 public Object get() {
682 String primaryPath = info.getSerializedLeaderActor();
683 Object found = canReturnLocalShardState && info.isLeader() ?
684 new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
685 new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
687 if(LOG.isDebugEnabled()) {
688 LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
698 for(String address: peerAddressResolver.getShardManagerPeerActorAddresses()) {
699 LOG.debug("{}: findPrimary for {} forwarding to remote ShardManager {}", persistenceId(),
702 getContext().actorSelection(address).forward(new RemoteFindPrimary(shardName,
703 message.isWaitUntilReady()), getContext());
707 LOG.debug("{}: No shard found for {}", persistenceId(), shardName);
709 getSender().tell(new PrimaryNotFoundException(
710 String.format("No primary shard found for %s.", shardName)), getSelf());
714 * Construct the name of the shard actor given the name of the member on
715 * which the shard resides and the name of the shard
721 private ShardIdentifier getShardIdentifier(String memberName, String shardName){
722 return peerAddressResolver.getShardIdentifier(memberName, shardName);
726 * Create shards that are local to the member on which the ShardManager
730 private void createLocalShards() {
731 String memberName = this.cluster.getCurrentMemberName();
732 Collection<String> memberShardNames = this.configuration.getMemberShardNames(memberName);
734 List<String> localShardActorNames = new ArrayList<>();
735 for(String shardName : memberShardNames){
736 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
737 Map<String, String> peerAddresses = getPeerAddresses(shardName);
738 localShardActorNames.add(shardId.toString());
739 localShards.put(shardName, new ShardInformation(shardName, shardId, peerAddresses,
740 newShardDatastoreContext(shardName), Shard.builder(), peerAddressResolver));
743 mBean = ShardManagerInfo.createShardManagerMBean(memberName, "shard-manager-" + this.type,
744 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType(), localShardActorNames);
746 mBean.setShardManager(this);
750 * Given the name of the shard find the addresses of all it's peers
754 private Map<String, String> getPeerAddresses(String shardName) {
755 Collection<String> members = configuration.getMembersFromShardName(shardName);
756 Map<String, String> peerAddresses = new HashMap<>();
758 String currentMemberName = this.cluster.getCurrentMemberName();
760 for(String memberName : members) {
761 if(!currentMemberName.equals(memberName)) {
762 ShardIdentifier shardId = getShardIdentifier(memberName, shardName);
763 String address = peerAddressResolver.getShardActorAddress(shardName, memberName);
764 peerAddresses.put(shardId.toString(), address);
767 return peerAddresses;
771 public SupervisorStrategy supervisorStrategy() {
773 return new OneForOneStrategy(10, Duration.create("1 minute"),
774 new Function<Throwable, SupervisorStrategy.Directive>() {
776 public SupervisorStrategy.Directive apply(Throwable t) {
777 LOG.warn("Supervisor Strategy caught unexpected exception - resuming", t);
778 return SupervisorStrategy.resume();
786 public String persistenceId() {
787 return "shard-manager-" + type;
791 ShardManagerInfoMBean getMBean(){
795 private void checkLocalShardExists(final String shardName, final ActorRef sender) {
796 if (localShards.containsKey(shardName)) {
797 String msg = String.format("Local shard %s already exists", shardName);
798 LOG.debug ("{}: {}", persistenceId(), msg);
799 sender.tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
803 private void onAddShardReplica (AddShardReplica shardReplicaMsg) {
804 final String shardName = shardReplicaMsg.getShardName();
806 // verify the local shard replica is already available in the controller node
807 LOG.debug ("onAddShardReplica: {}", shardReplicaMsg);
809 checkLocalShardExists(shardName, getSender());
811 // verify the shard with the specified name is present in the cluster configuration
812 if (!(this.configuration.isShardConfigured(shardName))) {
813 String msg = String.format("No module configuration exists for shard %s", shardName);
814 LOG.debug ("{}: {}", persistenceId(), msg);
815 getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
819 // Create the localShard
820 if (schemaContext == null) {
821 String msg = String.format(
822 "No SchemaContext is available in order to create a local shard instance for %s", shardName);
823 LOG.debug ("{}: {}", persistenceId(), msg);
824 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
828 Map<String, String> peerAddresses = getPeerAddresses(shardName);
829 if (peerAddresses.isEmpty()) {
830 String msg = String.format("Cannot add replica for shard %s because no peer is available", shardName);
831 LOG.debug ("{}: {}", persistenceId(), msg);
832 getSender().tell(new akka.actor.Status.Failure(new IllegalStateException(msg)), getSelf());
836 Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext().
837 getShardInitializationTimeout().duration().$times(2));
839 final ActorRef sender = getSender();
840 Future<Object> futureObj = ask(getSelf(), new RemoteFindPrimary(shardName, true), findPrimaryTimeout);
841 futureObj.onComplete(new OnComplete<Object>() {
843 public void onComplete(Throwable failure, Object response) {
844 if (failure != null) {
845 LOG.debug ("{}: Received failure from FindPrimary for shard {}", persistenceId(), shardName, failure);
846 sender.tell(new akka.actor.Status.Failure(new RuntimeException(
847 String.format("Failed to find leader for shard %s", shardName), failure)),
850 if (!(response instanceof RemotePrimaryShardFound)) {
851 String msg = String.format("Failed to find leader for shard %s: received response: %s",
852 shardName, response);
853 LOG.debug ("{}: {}", persistenceId(), msg);
854 sender.tell(new akka.actor.Status.Failure(new RuntimeException(msg)), getSelf());
858 RemotePrimaryShardFound message = (RemotePrimaryShardFound)response;
859 addShard (shardName, message, sender);
862 }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
865 private void addShard(final String shardName, final RemotePrimaryShardFound response, final ActorRef sender) {
866 checkLocalShardExists(shardName, sender);
868 ShardIdentifier shardId = getShardIdentifier(cluster.getCurrentMemberName(), shardName);
869 String localShardAddress = peerAddressResolver.getShardActorAddress(shardName, cluster.getCurrentMemberName());
871 DatastoreContext datastoreContext = newShardDatastoreContextBuilder(shardName).customRaftPolicyImplementation(
872 DisableElectionsRaftPolicy.class.getName()).build();
874 final ShardInformation shardInfo = new ShardInformation(shardName, shardId,
875 getPeerAddresses(shardName), datastoreContext,
876 Shard.builder(), peerAddressResolver);
877 localShards.put(shardName, shardInfo);
878 shardInfo.setActor(newShardActor(schemaContext, shardInfo));
880 //inform ShardLeader to add this shard as a replica by sending an AddServer message
881 LOG.debug ("{}: Sending AddServer message to peer {} for shard {}", persistenceId(),
882 response.getPrimaryPath(), shardId);
884 Timeout addServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(4));
885 Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
886 new AddServer(shardId.toString(), localShardAddress, true), addServerTimeout);
888 futureObj.onComplete(new OnComplete<Object>() {
890 public void onComplete(Throwable failure, Object addServerResponse) {
891 if (failure != null) {
892 LOG.debug ("{}: AddServer request to {} for {} failed", persistenceId(),
893 response.getPrimaryPath(), shardName, failure);
896 localShards.remove(shardName);
897 if (shardInfo.getActor() != null) {
898 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
901 sender.tell(new akka.actor.Status.Failure(new RuntimeException(
902 String.format("AddServer request to leader %s for shard %s failed",
903 response.getPrimaryPath(), shardName), failure)), getSelf());
905 AddServerReply reply = (AddServerReply)addServerResponse;
906 onAddServerReply(shardName, shardInfo, reply, sender, response.getPrimaryPath());
909 }, new Dispatchers(context().system().dispatchers()).
910 getDispatcher(Dispatchers.DispatcherType.Client));
914 private void onAddServerReply (String shardName, ShardInformation shardInfo,
915 AddServerReply replyMsg, ActorRef sender, String leaderPath) {
916 LOG.debug ("{}: Received {} for shard {} from leader {}", persistenceId(), replyMsg, shardName, leaderPath);
918 if (replyMsg.getStatus() == ServerChangeStatus.OK) {
919 LOG.debug ("{}: Leader shard successfully added the replica shard {}", persistenceId(), shardName);
921 // Make the local shard voting capable
922 shardInfo.setDatastoreContext(newShardDatastoreContext(shardName), getSelf());
924 mBean.addLocalShard(shardInfo.getShardId().toString());
925 sender.tell(new akka.actor.Status.Success(true), getSelf());
927 LOG.warn ("{}: Leader failed to add shard replica {} with status {} - removing the local shard",
928 persistenceId(), shardName, replyMsg.getStatus());
930 //remove the local replica created
931 localShards.remove(shardName);
932 if (shardInfo.getActor() != null) {
933 shardInfo.getActor().tell(PoisonPill.getInstance(), getSelf());
935 switch (replyMsg.getStatus()) {
937 sender.tell(new akka.actor.Status.Failure(new RuntimeException(
938 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",
939 leaderPath, shardName))), getSelf());
942 sender.tell(new akka.actor.Status.Failure(new RuntimeException(String.format(
943 "There is no shard leader available for shard %s", shardName))), getSelf());
946 sender.tell(new akka.actor.Status.Failure(new RuntimeException(String.format(
947 "AddServer request to leader %s for shard %s failed with status %s",
948 leaderPath, shardName, replyMsg.getStatus()))), getSelf());
953 private void onRemoveShardReplica (RemoveShardReplica shardReplicaMsg) {
954 String shardName = shardReplicaMsg.getShardName();
956 // verify the local shard replica is available in the controller node
957 if (!localShards.containsKey(shardName)) {
958 String msg = String.format("Local shard %s does not", shardName);
959 LOG.debug ("{}: {}", persistenceId(), msg);
960 getSender().tell(new akka.actor.Status.Failure(new IllegalArgumentException(msg)), getSelf());
963 // call RemoveShard for the shardName
964 getSender().tell(new akka.actor.Status.Success(true), getSelf());
969 protected static class ShardInformation {
970 private final ShardIdentifier shardId;
971 private final String shardName;
972 private ActorRef actor;
973 private ActorPath actorPath;
974 private final Map<String, String> initialPeerAddresses;
975 private Optional<DataTree> localShardDataTree;
976 private boolean leaderAvailable = false;
978 // flag that determines if the actor is ready for business
979 private boolean actorInitialized = false;
981 private boolean followerSyncStatus = false;
983 private final Set<OnShardInitialized> onShardInitializedSet = Sets.newHashSet();
984 private String role ;
985 private String leaderId;
986 private short leaderVersion;
988 private DatastoreContext datastoreContext;
989 private final Shard.AbstractBuilder<?, ?> builder;
990 private final ShardPeerAddressResolver addressResolver;
992 private ShardInformation(String shardName, ShardIdentifier shardId,
993 Map<String, String> initialPeerAddresses, DatastoreContext datastoreContext,
994 Shard.AbstractBuilder<?, ?> builder, ShardPeerAddressResolver addressResolver) {
995 this.shardName = shardName;
996 this.shardId = shardId;
997 this.initialPeerAddresses = initialPeerAddresses;
998 this.datastoreContext = datastoreContext;
999 this.builder = builder;
1000 this.addressResolver = addressResolver;
1003 Props newProps(SchemaContext schemaContext) {
1004 return builder.id(shardId).peerAddresses(initialPeerAddresses).datastoreContext(datastoreContext).
1005 schemaContext(schemaContext).props();
1008 String getShardName() {
1012 ActorRef getActor(){
1016 ActorPath getActorPath() {
1020 void setActor(ActorRef actor) {
1022 this.actorPath = actor.path();
1025 ShardIdentifier getShardId() {
1029 void setLocalDataTree(Optional<DataTree> localShardDataTree) {
1030 this.localShardDataTree = localShardDataTree;
1033 Optional<DataTree> getLocalShardDataTree() {
1034 return localShardDataTree;
1037 DatastoreContext getDatastoreContext() {
1038 return datastoreContext;
1041 void setDatastoreContext(DatastoreContext datastoreContext, ActorRef sender) {
1042 this.datastoreContext = datastoreContext;
1043 if (actor != null) {
1044 LOG.debug ("Sending new DatastoreContext to {}", shardId);
1045 actor.tell(this.datastoreContext, sender);
1049 void updatePeerAddress(String peerId, String peerAddress, ActorRef sender){
1050 LOG.info("updatePeerAddress for peer {} with address {}", peerId, peerAddress);
1053 if(LOG.isDebugEnabled()) {
1054 LOG.debug("Sending PeerAddressResolved for peer {} with address {} to {}",
1055 peerId, peerAddress, actor.path());
1058 actor.tell(new PeerAddressResolved(peerId, peerAddress), sender);
1061 notifyOnShardInitializedCallbacks();
1064 void peerDown(String memberName, String peerId, ActorRef sender) {
1066 actor.tell(new PeerDown(memberName, peerId), sender);
1070 void peerUp(String memberName, String peerId, ActorRef sender) {
1072 actor.tell(new PeerUp(memberName, peerId), sender);
1076 boolean isShardReady() {
1077 return !RaftState.Candidate.name().equals(role) && !Strings.isNullOrEmpty(role);
1080 boolean isShardReadyWithLeaderId() {
1081 return leaderAvailable && isShardReady() && !RaftState.IsolatedLeader.name().equals(role) &&
1082 (isLeader() || addressResolver.resolve(leaderId) != null);
1085 boolean isShardInitialized() {
1086 return getActor() != null && actorInitialized;
1089 boolean isLeader() {
1090 return Objects.equal(leaderId, shardId.toString());
1093 String getSerializedLeaderActor() {
1095 return Serialization.serializedActorPath(getActor());
1097 return addressResolver.resolve(leaderId);
1101 void setActorInitialized() {
1102 LOG.debug("Shard {} is initialized", shardId);
1104 this.actorInitialized = true;
1106 notifyOnShardInitializedCallbacks();
1109 private void notifyOnShardInitializedCallbacks() {
1110 if(onShardInitializedSet.isEmpty()) {
1114 boolean ready = isShardReadyWithLeaderId();
1116 if(LOG.isDebugEnabled()) {
1117 LOG.debug("Shard {} is {} - notifying {} OnShardInitialized callbacks", shardId,
1118 ready ? "ready" : "initialized", onShardInitializedSet.size());
1121 Iterator<OnShardInitialized> iter = onShardInitializedSet.iterator();
1122 while(iter.hasNext()) {
1123 OnShardInitialized onShardInitialized = iter.next();
1124 if(!(onShardInitialized instanceof OnShardReady) || ready) {
1126 onShardInitialized.getTimeoutSchedule().cancel();
1127 onShardInitialized.getReplyRunnable().run();
1132 void addOnShardInitialized(OnShardInitialized onShardInitialized) {
1133 onShardInitializedSet.add(onShardInitialized);
1136 void removeOnShardInitialized(OnShardInitialized onShardInitialized) {
1137 onShardInitializedSet.remove(onShardInitialized);
1140 void setRole(String newRole) {
1141 this.role = newRole;
1143 notifyOnShardInitializedCallbacks();
1146 void setFollowerSyncStatus(boolean syncStatus){
1147 this.followerSyncStatus = syncStatus;
1151 if(RaftState.Follower.name().equals(this.role)){
1152 return followerSyncStatus;
1153 } else if(RaftState.Leader.name().equals(this.role)){
1160 boolean setLeaderId(String leaderId) {
1161 boolean changed = !Objects.equal(this.leaderId, leaderId);
1162 this.leaderId = leaderId;
1163 if(leaderId != null) {
1164 this.leaderAvailable = true;
1166 notifyOnShardInitializedCallbacks();
1171 String getLeaderId() {
1175 void setLeaderAvailable(boolean leaderAvailable) {
1176 this.leaderAvailable = leaderAvailable;
1179 short getLeaderVersion() {
1180 return leaderVersion;
1183 void setLeaderVersion(short leaderVersion) {
1184 this.leaderVersion = leaderVersion;
1188 private static class ShardManagerCreator implements Creator<ShardManager> {
1189 private static final long serialVersionUID = 1L;
1191 final ClusterWrapper cluster;
1192 final Configuration configuration;
1193 final DatastoreContextFactory datastoreContextFactory;
1194 private final CountDownLatch waitTillReadyCountdownLatch;
1195 private final PrimaryShardInfoFutureCache primaryShardInfoCache;
1197 ShardManagerCreator(ClusterWrapper cluster, Configuration configuration,
1198 DatastoreContextFactory datastoreContextFactory, CountDownLatch waitTillReadyCountdownLatch,
1199 PrimaryShardInfoFutureCache primaryShardInfoCache) {
1200 this.cluster = cluster;
1201 this.configuration = configuration;
1202 this.datastoreContextFactory = datastoreContextFactory;
1203 this.waitTillReadyCountdownLatch = waitTillReadyCountdownLatch;
1204 this.primaryShardInfoCache = primaryShardInfoCache;
1208 public ShardManager create() throws Exception {
1209 return new ShardManager(cluster, configuration, datastoreContextFactory, waitTillReadyCountdownLatch,
1210 primaryShardInfoCache);
1214 private static class OnShardInitialized {
1215 private final Runnable replyRunnable;
1216 private Cancellable timeoutSchedule;
1218 OnShardInitialized(Runnable replyRunnable) {
1219 this.replyRunnable = replyRunnable;
1222 Runnable getReplyRunnable() {
1223 return replyRunnable;
1226 Cancellable getTimeoutSchedule() {
1227 return timeoutSchedule;
1230 void setTimeoutSchedule(Cancellable timeoutSchedule) {
1231 this.timeoutSchedule = timeoutSchedule;
1235 private static class OnShardReady extends OnShardInitialized {
1236 OnShardReady(Runnable replyRunnable) {
1237 super(replyRunnable);
1241 private static class ShardNotInitializedTimeout {
1242 private final ActorRef sender;
1243 private final ShardInformation shardInfo;
1244 private final OnShardInitialized onShardInitialized;
1246 ShardNotInitializedTimeout(ShardInformation shardInfo, OnShardInitialized onShardInitialized, ActorRef sender) {
1247 this.sender = sender;
1248 this.shardInfo = shardInfo;
1249 this.onShardInitialized = onShardInitialized;
1252 ActorRef getSender() {
1256 ShardInformation getShardInfo() {
1260 OnShardInitialized getOnShardInitialized() {
1261 return onShardInitialized;
1266 * We no longer persist SchemaContextModules but keep this class around for now for backwards
1267 * compatibility so we don't get de-serialization failures on upgrade from Helium.
1270 static class SchemaContextModules implements Serializable {
1271 private static final long serialVersionUID = -8884620101025936590L;
1273 private final Set<String> modules;
1275 SchemaContextModules(Set<String> modules){
1276 this.modules = modules;
1279 public Set<String> getModules() {