2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
10 package org.opendaylight.controller.cluster.raft;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.PoisonPill;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Optional;
17 import com.google.common.base.Preconditions;
18 import com.google.common.base.Verify;
19 import com.google.common.collect.Lists;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.Objects;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import org.apache.commons.lang3.time.DurationFormatUtils;
29 import org.opendaylight.controller.cluster.DataPersistenceProvider;
30 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
31 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
32 import org.opendaylight.controller.cluster.PersistentDataProvider;
33 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
34 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
35 import org.opendaylight.controller.cluster.notifications.RoleChanged;
36 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
37 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
38 import org.opendaylight.controller.cluster.raft.base.messages.LeaderTransitioning;
39 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
40 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
41 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
42 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
43 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
44 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
45 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
46 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
47 import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
48 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
49 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
50 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
51 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
52 import org.opendaylight.controller.cluster.raft.persisted.NoopPayload;
53 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
54 import org.opendaylight.yangtools.concepts.Identifier;
55 import org.opendaylight.yangtools.concepts.Immutable;
58 * RaftActor encapsulates a state machine that needs to be kept synchronized
59 * in a cluster. It implements the RAFT algorithm as described in the paper
60 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
61 * In Search of an Understandable Consensus Algorithm</a>
64 * RaftActor has 3 states and each state has a certain behavior associated
65 * with it. A Raft actor can behave as,
68 * <li> A Follower (or) </li>
69 * <li> A Candidate </li>
73 * A RaftActor MUST be a Leader in order to accept requests from clients to
74 * change the state of it's encapsulated state machine. Once a RaftActor becomes
75 * a Leader it is also responsible for ensuring that all followers ultimately
76 * have the same log and therefore the same state machine as itself.
79 * The current behavior of a RaftActor determines how election for leadership
80 * is initiated and how peer RaftActors react to request for votes.
83 * Each RaftActor also needs to know the current election term. It uses this
84 * information for a couple of things. One is to simply figure out who it
85 * voted for in the last election. Another is to figure out if the message
86 * it received to update it's state is stale.
89 * The RaftActor uses akka-persistence to store it's replicated log.
90 * Furthermore through it's behaviors a Raft Actor determines
92 * <li> when a log entry should be persisted </li>
93 * <li> when a log entry should be applied to the state machine (and) </li>
94 * <li> when a snapshot should be saved </li>
97 public abstract class RaftActor extends AbstractUntypedPersistentActor {
99 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
102 * This context should NOT be passed directly to any other actor it is
103 * only to be consumed by the RaftActorBehaviors.
105 private final RaftActorContextImpl context;
107 private final DelegatingPersistentDataProvider delegatingPersistenceProvider;
109 private final PersistentDataProvider persistentProvider;
111 private final BehaviorStateTracker behaviorStateTracker = new BehaviorStateTracker();
113 private RaftActorRecoverySupport raftRecovery;
115 private RaftActorSnapshotMessageSupport snapshotSupport;
117 private RaftActorServerConfigurationSupport serverConfigurationSupport;
119 private RaftActorLeadershipTransferCohort leadershipTransferInProgress;
121 private boolean shuttingDown;
123 protected RaftActor(String id, Map<String, String> peerAddresses,
124 Optional<ConfigParams> configParams, short payloadVersion) {
126 persistentProvider = new PersistentDataProvider(this);
127 delegatingPersistenceProvider = new RaftActorDelegatingPersistentDataProvider(null, persistentProvider);
129 context = new RaftActorContextImpl(this.getSelf(),
130 this.getContext(), id, new ElectionTermImpl(persistentProvider, id, LOG),
131 -1, -1, peerAddresses,
132 configParams.isPresent() ? configParams.get() : new DefaultConfigParamsImpl(),
133 delegatingPersistenceProvider, LOG);
135 context.setPayloadVersion(payloadVersion);
136 context.setReplicatedLog(ReplicatedLogImpl.newInstance(context));
140 public void preStart() throws Exception {
141 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
142 context.getConfigParams().getJournalRecoveryLogBatchSize());
146 snapshotSupport = newRaftActorSnapshotMessageSupport();
147 serverConfigurationSupport = new RaftActorServerConfigurationSupport(this);
151 public void postStop() {
157 protected void handleRecover(Object message) {
158 if (raftRecovery == null) {
159 raftRecovery = newRaftActorRecoverySupport();
162 boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
163 if (recoveryComplete) {
164 onRecoveryComplete();
166 initializeBehavior();
172 protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
173 return new RaftActorRecoverySupport(context, getRaftActorRecoveryCohort());
177 void initializeBehavior() {
178 changeCurrentBehavior(new Follower(context));
182 @SuppressWarnings("checkstyle:IllegalCatch")
183 protected void changeCurrentBehavior(RaftActorBehavior newBehavior) {
184 final RaftActorBehavior currentBehavior = getCurrentBehavior();
185 if (currentBehavior != null) {
187 currentBehavior.close();
188 } catch (Exception e) {
189 LOG.warn("{}: Error closing behavior {}", persistence(), currentBehavior, e);
193 final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
194 setCurrentBehavior(newBehavior);
195 handleBehaviorChange(state, newBehavior);
199 * Method exposed for subclasses to plug-in their logic. This method is invoked by {@link #handleCommand(Object)}
200 * for messages which are not handled by this class. Subclasses overriding this class should fall back to this
201 * implementation for messages which they do not handle
203 * @param message Incoming command message
205 protected void handleNonRaftCommand(final Object message) {
212 * @deprecated This method is not final for testing purposes. DO NOT OVERRIDE IT, override
213 * {@link #handleNonRaftCommand(Object)} instead.
217 // FIXME: make this method final once our unit tests do not need to override it
218 protected void handleCommand(final Object message) {
219 if (serverConfigurationSupport.handleMessage(message, getSender())) {
222 if (snapshotSupport.handleSnapshotMessage(message, getSender())) {
226 if (message instanceof ApplyState) {
227 ApplyState applyState = (ApplyState) message;
229 long startTime = System.nanoTime();
231 if (LOG.isDebugEnabled()) {
232 LOG.debug("{}: Applying state for log index {} data {}",
233 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
234 applyState.getReplicatedLogEntry().getData());
237 if (!(applyState.getReplicatedLogEntry().getData() instanceof NoopPayload)) {
238 applyState(applyState.getClientActor(), applyState.getIdentifier(),
239 applyState.getReplicatedLogEntry().getData());
242 long elapsedTime = System.nanoTime() - startTime;
243 if (elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS) {
244 LOG.debug("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
245 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
248 if (!hasFollowers()) {
249 // for single node, the capture should happen after the apply state
250 // as we delete messages from the persistent journal which have made it to the snapshot
251 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
252 // and recovery shows data missing
253 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
255 context.getSnapshotManager().trimLog(context.getLastApplied());
258 // Send it to the current behavior - some behaviors like PreLeader need to be notified of ApplyState.
259 possiblyHandleBehaviorMessage(message);
261 } else if (message instanceof ApplyJournalEntries) {
262 ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
263 LOG.debug("{}: Persisting ApplyJournalEntries with index={}", persistenceId(), applyEntries.getToIndex());
265 persistence().persist(applyEntries, NoopProcedure.instance());
267 } else if (message instanceof FindLeader) {
269 new FindLeaderReply(getLeaderAddress()),
272 } else if (message instanceof GetOnDemandRaftState) {
273 onGetOnDemandRaftStats();
274 } else if (message instanceof InitiateCaptureSnapshot) {
276 } else if (message instanceof SwitchBehavior) {
277 switchBehavior((SwitchBehavior) message);
278 } else if (message instanceof LeaderTransitioning) {
279 onLeaderTransitioning();
280 } else if (message instanceof Shutdown) {
282 } else if (message instanceof Runnable) {
283 ((Runnable)message).run();
284 } else if (message instanceof NoopPayload) {
285 persistData(null, null, (NoopPayload)message);
286 } else if (!possiblyHandleBehaviorMessage(message)) {
287 handleNonRaftCommand(message);
291 private boolean possiblyHandleBehaviorMessage(final Object message) {
292 final RaftActorBehavior currentBehavior = getCurrentBehavior();
293 final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
295 // A behavior indicates that it processed the change by returning a reference to the next behavior
296 // to be used. A null return indicates it has not processed the message and we should be passing it to
297 // the subclass for handling.
298 final RaftActorBehavior nextBehavior = currentBehavior.handleMessage(getSender(), message);
299 if (nextBehavior != null) {
300 switchBehavior(state, nextBehavior);
307 private void initiateLeadershipTransfer(final RaftActorLeadershipTransferCohort.OnComplete onComplete) {
308 LOG.debug("{}: Initiating leader transfer", persistenceId());
310 if (leadershipTransferInProgress == null) {
311 leadershipTransferInProgress = new RaftActorLeadershipTransferCohort(this);
312 leadershipTransferInProgress.addOnComplete(new RaftActorLeadershipTransferCohort.OnComplete() {
314 public void onSuccess(ActorRef raftActorRef) {
315 leadershipTransferInProgress = null;
319 public void onFailure(ActorRef raftActorRef) {
320 leadershipTransferInProgress = null;
324 leadershipTransferInProgress.addOnComplete(onComplete);
325 leadershipTransferInProgress.init();
327 LOG.debug("{}: prior leader transfer in progress - adding callback", persistenceId());
328 leadershipTransferInProgress.addOnComplete(onComplete);
332 private void onShutDown() {
333 LOG.debug("{}: onShutDown", persistenceId());
341 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
342 if (currentBehavior.state() != RaftState.Leader) {
343 // For non-leaders shutdown is a no-op
344 self().tell(PoisonPill.getInstance(), self());
348 if (context.hasFollowers()) {
349 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
351 public void onSuccess(ActorRef raftActorRef) {
352 LOG.debug("{}: leader transfer succeeded - sending PoisonPill", persistenceId());
353 raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
357 public void onFailure(ActorRef raftActorRef) {
358 LOG.debug("{}: leader transfer failed - sending PoisonPill", persistenceId());
359 raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
363 pauseLeader(new TimedRunnable(context.getConfigParams().getElectionTimeOutInterval(), this) {
365 protected void doRun() {
366 self().tell(PoisonPill.getInstance(), self());
370 protected void doCancel() {
371 self().tell(PoisonPill.getInstance(), self());
377 private void onLeaderTransitioning() {
378 LOG.debug("{}: onLeaderTransitioning", persistenceId());
379 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
380 if (getRaftState() == RaftState.Follower && roleChangeNotifier.isPresent()) {
381 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), null,
382 getCurrentBehavior().getLeaderPayloadVersion()), getSelf());
386 private void switchBehavior(SwitchBehavior message) {
387 if (!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
388 RaftState newState = message.getNewState();
389 if ( newState == RaftState.Leader || newState == RaftState.Follower) {
390 switchBehavior(behaviorStateTracker.capture(getCurrentBehavior()),
391 AbstractRaftActorBehavior.createBehavior(context, message.getNewState()));
392 getRaftActorContext().getTermInformation().updateAndPersist(message.getNewTerm(), "");
394 LOG.warn("Switching to behavior : {} - not supported", newState);
399 private void switchBehavior(final BehaviorState oldBehaviorState, final RaftActorBehavior nextBehavior) {
400 setCurrentBehavior(nextBehavior);
401 handleBehaviorChange(oldBehaviorState, nextBehavior);
405 RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
406 return new RaftActorSnapshotMessageSupport(context, getRaftActorSnapshotCohort());
409 private void onGetOnDemandRaftStats() {
410 // Debugging message to retrieve raft stats.
412 Map<String, String> peerAddresses = new HashMap<>();
413 Map<String, Boolean> peerVotingStates = new HashMap<>();
414 for (PeerInfo info: context.getPeers()) {
415 peerVotingStates.put(info.getId(), info.isVoting());
416 peerAddresses.put(info.getId(), info.getAddress() != null ? info.getAddress() : "");
419 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
420 OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
421 .commitIndex(context.getCommitIndex())
422 .currentTerm(context.getTermInformation().getCurrentTerm())
423 .inMemoryJournalDataSize(replicatedLog().dataSize())
424 .inMemoryJournalLogSize(replicatedLog().size())
425 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
426 .lastApplied(context.getLastApplied())
427 .lastIndex(replicatedLog().lastIndex())
428 .lastTerm(replicatedLog().lastTerm())
429 .leader(getLeaderId())
430 .raftState(currentBehavior.state().toString())
431 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
432 .snapshotIndex(replicatedLog().getSnapshotIndex())
433 .snapshotTerm(replicatedLog().getSnapshotTerm())
434 .votedFor(context.getTermInformation().getVotedFor())
435 .isVoting(context.isVotingMember())
436 .peerAddresses(peerAddresses)
437 .peerVotingStates(peerVotingStates)
438 .customRaftPolicyClassName(context.getConfigParams().getCustomRaftPolicyImplementationClass());
440 ReplicatedLogEntry lastLogEntry = replicatedLog().last();
441 if (lastLogEntry != null) {
442 builder.lastLogIndex(lastLogEntry.getIndex());
443 builder.lastLogTerm(lastLogEntry.getTerm());
446 if (getCurrentBehavior() instanceof AbstractLeader) {
447 AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
448 Collection<String> followerIds = leader.getFollowerIds();
449 List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
450 for (String id: followerIds) {
451 final FollowerLogInformation info = leader.getFollower(id);
452 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
453 info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity()),
454 context.getPeerInfo(info.getId()).isVoting()));
457 builder.followerInfoList(followerInfoList);
460 sender().tell(builder.build(), self());
464 private void handleBehaviorChange(BehaviorState oldBehaviorState, RaftActorBehavior currentBehavior) {
465 RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
467 if (oldBehavior != currentBehavior) {
471 String lastLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastLeaderId();
472 String lastValidLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastValidLeaderId();
473 String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
475 // it can happen that the state has not changed but the leader has changed.
476 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
477 if (!Objects.equals(lastLeaderId, currentBehavior.getLeaderId())
478 || oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
479 if (roleChangeNotifier.isPresent()) {
480 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
481 currentBehavior.getLeaderPayloadVersion()), getSelf());
484 onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
486 if (leadershipTransferInProgress != null) {
487 leadershipTransferInProgress.onNewLeader(currentBehavior.getLeaderId());
490 serverConfigurationSupport.onNewLeader(currentBehavior.getLeaderId());
493 if (roleChangeNotifier.isPresent()
494 && (oldBehavior == null || oldBehavior.state() != currentBehavior.state())) {
495 roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
496 currentBehavior.state().name()), getSelf());
500 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
501 return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
505 public long snapshotSequenceNr() {
506 // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
507 // so that we can delete the persistent journal based on the saved sequence-number
508 // However , when akka replays the journal during recovery, it replays it from the sequence number when the
509 // snapshot was saved and not the number we saved. We would want to override it , by asking akka to use the
510 // last-sequence number known to us.
511 return context.getSnapshotManager().getLastSequenceNumber();
515 * When a derived RaftActor needs to persist something it must call
518 protected final void persistData(final ActorRef clientActor, final Identifier identifier, final Payload data) {
520 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
521 context.getReplicatedLog().lastIndex() + 1,
522 context.getTermInformation().getCurrentTerm(), data);
524 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
526 final RaftActorContext raftContext = getRaftActorContext();
528 replicatedLog().appendAndPersist(replicatedLogEntry, replicatedLogEntry1 -> {
529 if (!hasFollowers()) {
530 // Increment the Commit Index and the Last Applied values
531 raftContext.setCommitIndex(replicatedLogEntry1.getIndex());
532 raftContext.setLastApplied(replicatedLogEntry1.getIndex());
534 // Apply the state immediately.
535 self().tell(new ApplyState(clientActor, identifier, replicatedLogEntry1), self());
537 // Send a ApplyJournalEntries message so that we write the fact that we applied
538 // the state to durable storage
539 self().tell(new ApplyJournalEntries(replicatedLogEntry1.getIndex()), self());
542 context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry1);
544 // Send message for replication
545 getCurrentBehavior().handleMessage(getSelf(),
546 new Replicate(clientActor, identifier, replicatedLogEntry1));
551 private ReplicatedLog replicatedLog() {
552 return context.getReplicatedLog();
555 protected String getId() {
556 return context.getId();
560 void setCurrentBehavior(RaftActorBehavior behavior) {
561 context.setCurrentBehavior(behavior);
564 protected RaftActorBehavior getCurrentBehavior() {
565 return context.getCurrentBehavior();
569 * Derived actors can call the isLeader method to check if the current
570 * RaftActor is the Leader or not.
572 * @return true it this RaftActor is a Leader false otherwise
574 protected boolean isLeader() {
575 return context.getId().equals(getCurrentBehavior().getLeaderId());
578 protected final boolean isLeaderActive() {
579 return getRaftState() != RaftState.IsolatedLeader && getRaftState() != RaftState.PreLeader
580 && !shuttingDown && !isLeadershipTransferInProgress();
583 private boolean isLeadershipTransferInProgress() {
584 return leadershipTransferInProgress != null && leadershipTransferInProgress.isTransferring();
588 * Derived actor can call getLeader if they need a reference to the Leader.
589 * This would be useful for example in forwarding a request to an actor
590 * which is the leader
592 * @return A reference to the leader if known, null otherwise
594 public ActorSelection getLeader() {
595 String leaderAddress = getLeaderAddress();
597 if (leaderAddress == null) {
601 return context.actorSelection(leaderAddress);
605 * Returns the id of the current leader.
607 * @return the current leader's id
609 protected final String getLeaderId() {
610 return getCurrentBehavior().getLeaderId();
614 protected final RaftState getRaftState() {
615 return getCurrentBehavior().state();
618 protected Long getCurrentTerm() {
619 return context.getTermInformation().getCurrentTerm();
622 protected RaftActorContext getRaftActorContext() {
626 protected void updateConfigParams(ConfigParams configParams) {
628 // obtain the RaftPolicy for oldConfigParams and the updated one.
629 String oldRaftPolicy = context.getConfigParams().getCustomRaftPolicyImplementationClass();
630 String newRaftPolicy = configParams.getCustomRaftPolicyImplementationClass();
632 LOG.debug("{}: RaftPolicy used with prev.config {}, RaftPolicy used with newConfig {}", persistenceId(),
633 oldRaftPolicy, newRaftPolicy);
634 context.setConfigParams(configParams);
635 if (!Objects.equals(oldRaftPolicy, newRaftPolicy)) {
636 // The RaftPolicy was modified. If the current behavior is Follower then re-initialize to Follower
637 // but transfer the previous leaderId so it doesn't immediately try to schedule an election. This
638 // avoids potential disruption. Otherwise, switch to Follower normally.
639 RaftActorBehavior behavior = getCurrentBehavior();
640 if (behavior != null && behavior.state() == RaftState.Follower) {
641 String previousLeaderId = behavior.getLeaderId();
642 short previousLeaderPayloadVersion = behavior.getLeaderPayloadVersion();
644 LOG.debug("{}: Re-initializing to Follower with previous leaderId {}", persistenceId(),
647 changeCurrentBehavior(new Follower(context, previousLeaderId, previousLeaderPayloadVersion));
649 initializeBehavior();
654 public final DataPersistenceProvider persistence() {
655 return delegatingPersistenceProvider.getDelegate();
658 public void setPersistence(DataPersistenceProvider provider) {
659 delegatingPersistenceProvider.setDelegate(provider);
662 protected void setPersistence(boolean persistent) {
663 DataPersistenceProvider currentPersistence = persistence();
664 if (persistent && (currentPersistence == null || !currentPersistence.isRecoveryApplicable())) {
665 setPersistence(new PersistentDataProvider(this));
667 if (getCurrentBehavior() != null) {
668 LOG.info("{}: Persistence has been enabled - capturing snapshot", persistenceId());
671 } else if (!persistent && (currentPersistence == null || currentPersistence.isRecoveryApplicable())) {
672 setPersistence(new NonPersistentDataProvider() {
674 * The way snapshotting works is,
676 * <li> RaftActor calls createSnapshot on the Shard
677 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
678 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
679 * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
680 * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
681 * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
685 public void saveSnapshot(Object object) {
686 // Make saving Snapshot successful
687 // Committing the snapshot here would end up calling commit in the creating state which would
688 // be a state violation. That's why now we send a message to commit the snapshot.
689 self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
696 * setPeerAddress sets the address of a known peer at a later time.
699 * This is to account for situations where a we know that a peer
700 * exists but we do not know an address up-front. This may also be used in
701 * situations where a known peer starts off in a different location and we
702 * need to change it's address
705 * Note that if the peerId does not match the list of peers passed to
706 * this actor during construction an IllegalStateException will be thrown.
708 protected void setPeerAddress(String peerId, String peerAddress) {
709 context.setPeerAddress(peerId, peerAddress);
713 * The applyState method will be called by the RaftActor when some data
714 * needs to be applied to the actor's state.
716 * @param clientActor A reference to the client who sent this message. This
717 * is the same reference that was passed to persistData
718 * by the derived actor. clientActor may be null when
719 * the RaftActor is behaving as a follower or during
721 * @param identifier The identifier of the persisted data. This is also
722 * the same identifier that was passed to persistData by
723 * the derived actor. identifier may be null when
724 * the RaftActor is behaving as a follower or during
726 * @param data A piece of data that was persisted by the persistData call.
727 * This should NEVER be null.
729 protected abstract void applyState(ActorRef clientActor, Identifier identifier, Object data);
732 * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
735 protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
738 * This method is called when recovery is complete.
740 protected abstract void onRecoveryComplete();
743 * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
746 protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
749 * This method will be called by the RaftActor when the state of the
750 * RaftActor changes. The derived actor can then use methods like
751 * isLeader or getLeader to do something useful
753 protected abstract void onStateChanged();
756 * Notifier Actor for this RaftActor to notify when a role change happens.
758 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
760 protected abstract Optional<ActorRef> getRoleChangeNotifier();
763 * This method is called prior to operations such as leadership transfer and actor shutdown when the leader
764 * must pause or stop its duties. This method allows derived classes to gracefully pause or finish current
765 * work prior to performing the operation. On completion of any work, the run method must be called on the
766 * given Runnable to proceed with the given operation. <b>Important:</b> the run method must be called on
767 * this actor's thread dispatcher as as it modifies internal state.
770 * The default implementation immediately runs the operation.
772 * @param operation the operation to run
774 protected void pauseLeader(Runnable operation) {
778 protected void onLeaderChanged(String oldLeader, String newLeader) {
781 private String getLeaderAddress() {
783 return getSelf().path().toString();
785 String leaderId = getLeaderId();
786 if (leaderId == null) {
789 String peerAddress = context.getPeerAddress(leaderId);
790 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}", persistenceId(), leaderId, peerAddress);
795 protected boolean hasFollowers() {
796 return getRaftActorContext().hasFollowers();
799 private void captureSnapshot() {
800 SnapshotManager snapshotManager = context.getSnapshotManager();
802 if (!snapshotManager.isCapturing()) {
803 final long idx = getCurrentBehavior().getReplicatedToAllIndex();
804 LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
805 replicatedLog().last(), idx);
807 snapshotManager.capture(replicatedLog().last(), idx);
812 * Switch this member to non-voting status. This is a no-op for all behaviors except when we are the leader,
813 * in which case we need to step down.
815 void becomeNonVoting() {
817 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
819 public void onSuccess(ActorRef raftActorRef) {
820 LOG.debug("{}: leader transfer succeeded after change to non-voting", persistenceId());
821 ensureFollowerState();
825 public void onFailure(ActorRef raftActorRef) {
826 LOG.debug("{}: leader transfer failed after change to non-voting", persistenceId());
827 ensureFollowerState();
830 private void ensureFollowerState() {
831 // Whether or not leadership transfer succeeded, we have to step down as leader and
832 // switch to Follower so ensure that.
833 if (getRaftState() != RaftState.Follower) {
834 initializeBehavior();
842 * A point-in-time capture of {@link RaftActorBehavior} state critical for transitioning between behaviors.
844 private abstract static class BehaviorState implements Immutable {
845 @Nullable abstract RaftActorBehavior getBehavior();
847 @Nullable abstract String getLastValidLeaderId();
849 @Nullable abstract String getLastLeaderId();
851 @Nullable abstract short getLeaderPayloadVersion();
855 * A {@link BehaviorState} corresponding to non-null {@link RaftActorBehavior} state.
857 private static final class SimpleBehaviorState extends BehaviorState {
858 private final RaftActorBehavior behavior;
859 private final String lastValidLeaderId;
860 private final String lastLeaderId;
861 private final short leaderPayloadVersion;
863 SimpleBehaviorState(final String lastValidLeaderId, final String lastLeaderId,
864 final RaftActorBehavior behavior) {
865 this.lastValidLeaderId = lastValidLeaderId;
866 this.lastLeaderId = lastLeaderId;
867 this.behavior = Preconditions.checkNotNull(behavior);
868 this.leaderPayloadVersion = behavior.getLeaderPayloadVersion();
872 RaftActorBehavior getBehavior() {
877 String getLastValidLeaderId() {
878 return lastValidLeaderId;
882 short getLeaderPayloadVersion() {
883 return leaderPayloadVersion;
887 String getLastLeaderId() {
893 * Class tracking behavior-related information, which we need to keep around and pass across behavior switches.
894 * An instance is created for each RaftActor. It has two functions:
895 * - it keeps track of the last leader ID we have encountered since we have been created
896 * - it creates state capture needed to transition from one behavior to the next
898 private static final class BehaviorStateTracker {
900 * A {@link BehaviorState} corresponding to null {@link RaftActorBehavior} state. Since null behavior is only
901 * allowed before we receive the first message, we know the leader ID to be null.
903 private static final BehaviorState NULL_BEHAVIOR_STATE = new BehaviorState() {
905 RaftActorBehavior getBehavior() {
910 String getLastValidLeaderId() {
915 short getLeaderPayloadVersion() {
920 String getLastLeaderId() {
925 private String lastValidLeaderId;
926 private String lastLeaderId;
928 BehaviorState capture(final RaftActorBehavior behavior) {
929 if (behavior == null) {
930 Verify.verify(lastValidLeaderId == null, "Null behavior with non-null last leader");
931 return NULL_BEHAVIOR_STATE;
934 lastLeaderId = behavior.getLeaderId();
935 if (lastLeaderId != null) {
936 lastValidLeaderId = lastLeaderId;
939 return new SimpleBehaviorState(lastValidLeaderId, lastLeaderId, behavior);