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
9 package org.opendaylight.controller.cluster.raft;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
14 import akka.actor.ActorRef;
15 import akka.actor.ActorSelection;
16 import akka.actor.PoisonPill;
17 import akka.actor.Status;
18 import akka.persistence.JournalProtocol;
19 import akka.persistence.SnapshotProtocol;
20 import com.google.common.annotations.VisibleForTesting;
21 import com.google.common.collect.ImmutableList;
22 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
23 import java.util.HashMap;
25 import java.util.Objects;
26 import java.util.Optional;
27 import java.util.concurrent.TimeUnit;
28 import org.apache.commons.lang3.time.DurationFormatUtils;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.controller.cluster.DataPersistenceProvider;
32 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
33 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
34 import org.opendaylight.controller.cluster.PersistentDataProvider;
35 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
36 import org.opendaylight.controller.cluster.mgmt.api.FollowerInfo;
37 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
38 import org.opendaylight.controller.cluster.notifications.RoleChanged;
39 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
40 import org.opendaylight.controller.cluster.raft.base.messages.CheckConsensusReached;
41 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
42 import org.opendaylight.controller.cluster.raft.base.messages.LeaderTransitioning;
43 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
44 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
45 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
46 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
47 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
48 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
49 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
50 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
51 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
52 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
53 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
54 import org.opendaylight.controller.cluster.raft.messages.Payload;
55 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
56 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
57 import org.opendaylight.controller.cluster.raft.persisted.NoopPayload;
58 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
59 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
60 import org.opendaylight.yangtools.concepts.Identifier;
61 import org.opendaylight.yangtools.concepts.Immutable;
64 * RaftActor encapsulates a state machine that needs to be kept synchronized
65 * in a cluster. It implements the RAFT algorithm as described in the paper
66 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
67 * In Search of an Understandable Consensus Algorithm</a>
70 * RaftActor has 3 states and each state has a certain behavior associated
71 * with it. A Raft actor can behave as,
74 * <li> A Follower (or) </li>
75 * <li> A Candidate </li>
79 * A RaftActor MUST be a Leader in order to accept requests from clients to
80 * change the state of it's encapsulated state machine. Once a RaftActor becomes
81 * a Leader it is also responsible for ensuring that all followers ultimately
82 * have the same log and therefore the same state machine as itself.
85 * The current behavior of a RaftActor determines how election for leadership
86 * is initiated and how peer RaftActors react to request for votes.
89 * Each RaftActor also needs to know the current election term. It uses this
90 * information for a couple of things. One is to simply figure out who it
91 * voted for in the last election. Another is to figure out if the message
92 * it received to update it's state is stale.
95 * The RaftActor uses akka-persistence to store it's replicated log.
96 * Furthermore through it's behaviors a Raft Actor determines
98 * <li> when a log entry should be persisted </li>
99 * <li> when a log entry should be applied to the state machine (and) </li>
100 * <li> when a snapshot should be saved </li>
103 public abstract class RaftActor extends AbstractUntypedPersistentActor {
104 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50);
107 * This context should NOT be passed directly to any other actor it is
108 * only to be consumed by the RaftActorBehaviors.
110 private final RaftActorContextImpl context;
112 private final DelegatingPersistentDataProvider delegatingPersistenceProvider;
114 private final PersistentDataProvider persistentProvider;
116 private final BehaviorStateTracker behaviorStateTracker = new BehaviorStateTracker();
118 private RaftActorRecoverySupport raftRecovery;
120 private RaftActorSnapshotMessageSupport snapshotSupport;
122 private RaftActorServerConfigurationSupport serverConfigurationSupport;
124 private boolean shuttingDown;
126 @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Akka class design")
127 protected RaftActor(final String id, final Map<String, String> peerAddresses,
128 final Optional<ConfigParams> configParams, final short payloadVersion) {
130 persistentProvider = new PersistentDataProvider(this);
131 delegatingPersistenceProvider = new RaftActorDelegatingPersistentDataProvider(null, persistentProvider);
133 context = new RaftActorContextImpl(getSelf(), getContext(), id,
134 new ElectionTermImpl(persistentProvider, id, LOG), -1, -1, peerAddresses,
135 configParams.isPresent() ? configParams.get() : new DefaultConfigParamsImpl(),
136 delegatingPersistenceProvider, this::handleApplyState, LOG, this::executeInSelf);
138 context.setPayloadVersion(payloadVersion);
139 context.setReplicatedLog(ReplicatedLogImpl.newInstance(context));
143 public void preStart() throws Exception {
144 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
145 context.getConfigParams().getJournalRecoveryLogBatchSize());
149 snapshotSupport = newRaftActorSnapshotMessageSupport();
150 serverConfigurationSupport = new RaftActorServerConfigurationSupport(this);
154 public void postStop() throws Exception {
160 protected void handleRecover(final Object message) {
161 if (raftRecovery == null) {
162 raftRecovery = newRaftActorRecoverySupport();
165 boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
166 if (recoveryComplete) {
167 onRecoveryComplete();
169 initializeBehavior();
175 protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
176 return new RaftActorRecoverySupport(context, getRaftActorRecoveryCohort());
180 void initializeBehavior() {
181 changeCurrentBehavior(new Follower(context));
185 @SuppressWarnings("checkstyle:IllegalCatch")
186 protected void changeCurrentBehavior(final RaftActorBehavior newBehavior) {
187 final RaftActorBehavior currentBehavior = getCurrentBehavior();
188 if (currentBehavior != null) {
190 currentBehavior.close();
191 } catch (Exception e) {
192 LOG.warn("{}: Error closing behavior {}", persistence(), currentBehavior, e);
196 final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
197 setCurrentBehavior(newBehavior);
198 handleBehaviorChange(state, newBehavior);
202 * Method exposed for subclasses to plug-in their logic. This method is invoked by {@link #handleCommand(Object)}
203 * for messages which are not handled by this class. Subclasses overriding this class should fall back to this
204 * implementation for messages which they do not handle
206 * @param message Incoming command message
208 protected void handleNonRaftCommand(final Object message) {
215 * @deprecated This method is not final for testing purposes. DO NOT OVERRIDE IT, override
216 * {@link #handleNonRaftCommand(Object)} instead.
220 // FIXME: make this method final once our unit tests do not need to override it
221 protected void handleCommand(final Object message) {
222 if (serverConfigurationSupport.handleMessage(message, getSender())) {
225 if (snapshotSupport.handleSnapshotMessage(message, getSender())) {
228 if (message instanceof ApplyState applyState) {
229 if (!hasFollowers()) {
230 // for single node, the capture should happen after the apply state
231 // as we delete messages from the persistent journal which have made it to the snapshot
232 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
233 // and recovery shows data missing
234 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
236 context.getSnapshotManager().trimLog(context.getLastApplied());
239 possiblyHandleBehaviorMessage(message);
240 } else if (message instanceof ApplyJournalEntries applyEntries) {
241 LOG.debug("{}: Persisting ApplyJournalEntries with index={}", persistenceId(), applyEntries.getToIndex());
243 persistence().persistAsync(applyEntries, NoopProcedure.instance());
244 } else if (message instanceof FindLeader) {
245 getSender().tell(new FindLeaderReply(getLeaderAddress()), getSelf());
246 } else if (message instanceof GetOnDemandRaftState) {
247 onGetOnDemandRaftStats();
248 } else if (message instanceof InitiateCaptureSnapshot) {
250 } else if (message instanceof SwitchBehavior switchBehavior) {
251 switchBehavior(switchBehavior);
252 } else if (message instanceof LeaderTransitioning leaderTransitioning) {
253 onLeaderTransitioning(leaderTransitioning);
254 } else if (message instanceof Shutdown) {
256 } else if (message instanceof Runnable runnable) {
258 } else if (message instanceof NoopPayload noopPayload) {
259 persistData(null, null, noopPayload, false);
260 } else if (message instanceof RequestLeadership requestLeadership) {
261 onRequestLeadership(requestLeadership);
262 } else if (!possiblyHandleBehaviorMessage(message)) {
263 if (message instanceof JournalProtocol.Response response
264 && delegatingPersistenceProvider.handleJournalResponse(response)) {
265 LOG.debug("{}: handled a journal response", persistenceId());
266 } else if (message instanceof SnapshotProtocol.Response response
267 && delegatingPersistenceProvider.handleSnapshotResponse(response)) {
268 LOG.debug("{}: handled a snapshot response", persistenceId());
270 handleNonRaftCommand(message);
275 private void onRequestLeadership(final RequestLeadership message) {
276 LOG.debug("{}: onRequestLeadership {}", persistenceId(), message);
278 // non-leader cannot satisfy leadership request
279 LOG.warn("{}: onRequestLeadership {} was sent to non-leader."
280 + " Current behavior: {}. Sending failure response",
281 persistenceId(), message, getCurrentBehavior().state());
282 message.getReplyTo().tell(new LeadershipTransferFailedException("Cannot transfer leader to "
283 + message.getRequestedFollowerId()
284 + ". RequestLeadership message was sent to non-leader " + persistenceId()), getSelf());
288 final String requestedFollowerId = message.getRequestedFollowerId();
289 final ActorRef replyTo = message.getReplyTo();
290 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
292 public void onSuccess(final ActorRef raftActorRef) {
294 if (!requestedFollowerId.equals(getLeaderId())) {
295 onFailure(raftActorRef);
298 LOG.debug("{}: Leadership transferred successfully to {}", persistenceId(), requestedFollowerId);
299 replyTo.tell(new Status.Success(null), getSelf());
303 public void onFailure(final ActorRef raftActorRef) {
304 LOG.debug("{}: LeadershipTransfer request from {} failed", persistenceId(), requestedFollowerId);
305 replyTo.tell(new Status.Failure(
306 new LeadershipTransferFailedException(
307 "Failed to transfer leadership to " + requestedFollowerId
308 + ". Follower is not ready to become leader")),
311 }, message.getRequestedFollowerId(), RaftActorLeadershipTransferCohort.USE_DEFAULT_LEADER_TIMEOUT);
314 private boolean possiblyHandleBehaviorMessage(final Object message) {
315 final RaftActorBehavior currentBehavior = getCurrentBehavior();
316 final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
318 // A behavior indicates that it processed the change by returning a reference to the next behavior
319 // to be used. A null return indicates it has not processed the message and we should be passing it to
320 // the subclass for handling.
321 final RaftActorBehavior nextBehavior = currentBehavior.handleMessage(getSender(), message);
322 if (nextBehavior != null) {
323 switchBehavior(state, nextBehavior);
330 private void initiateLeadershipTransfer(final RaftActorLeadershipTransferCohort.OnComplete onComplete,
331 final @Nullable String followerId, final long newLeaderTimeoutInMillis) {
332 LOG.debug("{}: Initiating leader transfer", persistenceId());
334 RaftActorLeadershipTransferCohort leadershipTransferInProgress = context.getRaftActorLeadershipTransferCohort();
335 if (leadershipTransferInProgress == null) {
336 leadershipTransferInProgress = new RaftActorLeadershipTransferCohort(this, followerId);
337 leadershipTransferInProgress.setNewLeaderTimeoutInMillis(newLeaderTimeoutInMillis);
338 leadershipTransferInProgress.addOnComplete(new RaftActorLeadershipTransferCohort.OnComplete() {
340 public void onSuccess(final ActorRef raftActorRef) {
341 context.setRaftActorLeadershipTransferCohort(null);
345 public void onFailure(final ActorRef raftActorRef) {
346 context.setRaftActorLeadershipTransferCohort(null);
350 leadershipTransferInProgress.addOnComplete(onComplete);
352 context.setRaftActorLeadershipTransferCohort(leadershipTransferInProgress);
353 leadershipTransferInProgress.init();
356 LOG.debug("{}: prior leader transfer in progress - adding callback", persistenceId());
357 leadershipTransferInProgress.addOnComplete(onComplete);
361 private void onShutDown() {
362 LOG.debug("{}: onShutDown", persistenceId());
370 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
371 switch (currentBehavior.state()) {
374 // Fall-through to more work
377 // For non-leaders shutdown is a no-op
378 self().tell(PoisonPill.getInstance(), self());
382 if (context.hasFollowers()) {
383 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
385 public void onSuccess(final ActorRef raftActorRef) {
386 LOG.debug("{}: leader transfer succeeded - sending PoisonPill", persistenceId());
387 raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
391 public void onFailure(final ActorRef raftActorRef) {
392 LOG.debug("{}: leader transfer failed - sending PoisonPill", persistenceId());
393 raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
395 }, null, TimeUnit.MILLISECONDS.convert(2, TimeUnit.SECONDS));
397 pauseLeader(new TimedRunnable(context.getConfigParams().getElectionTimeOutInterval(), this) {
399 protected void doRun() {
400 self().tell(PoisonPill.getInstance(), self());
404 protected void doCancel() {
405 self().tell(PoisonPill.getInstance(), self());
411 private void onLeaderTransitioning(final LeaderTransitioning leaderTransitioning) {
412 LOG.debug("{}: onLeaderTransitioning: {}", persistenceId(), leaderTransitioning);
413 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
414 if (getRaftState() == RaftState.Follower && roleChangeNotifier.isPresent()
415 && leaderTransitioning.getLeaderId().equals(getCurrentBehavior().getLeaderId())) {
416 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), null,
417 getCurrentBehavior().getLeaderPayloadVersion()), getSelf());
421 private void switchBehavior(final SwitchBehavior message) {
422 if (!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
423 RaftState newState = message.getNewState();
424 if (newState == RaftState.Leader || newState == RaftState.Follower) {
425 getRaftActorContext().getTermInformation().updateAndPersist(message.getNewTerm(), "");
426 switchBehavior(behaviorStateTracker.capture(getCurrentBehavior()),
427 AbstractRaftActorBehavior.createBehavior(context, message.getNewState()));
429 LOG.warn("Switching to behavior : {} - not supported", newState);
434 private void switchBehavior(final BehaviorState oldBehaviorState, final RaftActorBehavior nextBehavior) {
435 setCurrentBehavior(nextBehavior);
436 handleBehaviorChange(oldBehaviorState, nextBehavior);
440 RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
441 return new RaftActorSnapshotMessageSupport(context, getRaftActorSnapshotCohort());
444 private void onGetOnDemandRaftStats() {
445 // Debugging message to retrieve raft stats.
447 Map<String, String> peerAddresses = new HashMap<>();
448 Map<String, Boolean> peerVotingStates = new HashMap<>();
449 for (PeerInfo info: context.getPeers()) {
450 peerVotingStates.put(info.getId(), info.isVoting());
451 peerAddresses.put(info.getId(), info.getAddress() != null ? info.getAddress() : "");
454 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
455 final var builder = newOnDemandRaftStateBuilder()
456 .commitIndex(context.getCommitIndex())
457 .currentTerm(context.getTermInformation().getCurrentTerm())
458 .inMemoryJournalDataSize(replicatedLog().dataSize())
459 .inMemoryJournalLogSize(replicatedLog().size())
460 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
461 .lastApplied(context.getLastApplied())
462 .lastIndex(replicatedLog().lastIndex())
463 .lastTerm(replicatedLog().lastTerm())
464 .leader(getLeaderId())
465 .raftState(currentBehavior.state().toString())
466 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
467 .snapshotIndex(replicatedLog().getSnapshotIndex())
468 .snapshotTerm(replicatedLog().getSnapshotTerm())
469 .votedFor(context.getTermInformation().getVotedFor())
470 .isVoting(context.isVotingMember())
471 .peerAddresses(peerAddresses)
472 .peerVotingStates(peerVotingStates)
473 .customRaftPolicyClassName(context.getConfigParams().getCustomRaftPolicyImplementationClass());
475 ReplicatedLogEntry lastLogEntry = replicatedLog().last();
476 if (lastLogEntry != null) {
477 builder.lastLogIndex(lastLogEntry.getIndex());
478 builder.lastLogTerm(lastLogEntry.getTerm());
481 if (getCurrentBehavior() instanceof AbstractLeader leader) {
482 builder.followerInfoList(leader.getFollowerIds().stream()
483 .map(leader::getFollower)
484 .map(info -> new FollowerInfo(info.getId(), info.getNextIndex(), info.getMatchIndex(),
485 info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(
486 TimeUnit.NANOSECONDS.toMillis(info.nanosSinceLastActivity())),
487 context.getPeerInfo(info.getId()).isVoting()))
488 .collect(ImmutableList.toImmutableList()));
491 sender().tell(builder.build(), self());
495 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
496 return OnDemandRaftState.builder();
499 private void handleBehaviorChange(final BehaviorState oldBehaviorState, final RaftActorBehavior currentBehavior) {
500 RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
502 if (oldBehavior != currentBehavior) {
506 String lastLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastLeaderId();
507 String lastValidLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastValidLeaderId();
508 String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
510 // it can happen that the state has not changed but the leader has changed.
511 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
512 if (!Objects.equals(lastLeaderId, currentBehavior.getLeaderId())
513 || oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
514 if (roleChangeNotifier.isPresent()) {
515 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
516 currentBehavior.getLeaderPayloadVersion()), getSelf());
519 onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
521 RaftActorLeadershipTransferCohort leadershipTransferInProgress =
522 context.getRaftActorLeadershipTransferCohort();
523 if (leadershipTransferInProgress != null) {
524 leadershipTransferInProgress.onNewLeader(currentBehavior.getLeaderId());
527 serverConfigurationSupport.onNewLeader(currentBehavior.getLeaderId());
530 if (roleChangeNotifier.isPresent()
531 && (oldBehavior == null || oldBehavior.state() != currentBehavior.state())) {
532 roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
533 currentBehavior.state().name()), getSelf());
537 private void handleApplyState(final ApplyState applyState) {
538 long startTime = System.nanoTime();
540 Payload payload = applyState.getReplicatedLogEntry().getData();
541 if (LOG.isDebugEnabled()) {
542 LOG.debug("{}: Applying state for log index {} data {}",
543 persistenceId(), applyState.getReplicatedLogEntry().getIndex(), payload);
546 if (!(payload instanceof NoopPayload) && !(payload instanceof ServerConfigurationPayload)) {
547 applyState(applyState.getClientActor(), applyState.getIdentifier(), payload);
550 long elapsedTime = System.nanoTime() - startTime;
551 if (elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS) {
552 LOG.debug("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
553 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
556 // Send the ApplyState message back to self to handle further processing asynchronously.
557 self().tell(applyState, self());
560 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
561 final short leaderPayloadVersion) {
562 return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
566 public long snapshotSequenceNr() {
567 // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
568 // so that we can delete the persistent journal based on the saved sequence-number
569 // However , when akka replays the journal during recovery, it replays it from the sequence number when the
570 // snapshot was saved and not the number we saved. We would want to override it , by asking akka to use the
571 // last-sequence number known to us.
572 return context.getSnapshotManager().getLastSequenceNumber();
576 * Persists the given Payload in the journal and replicates to any followers. After successful completion,
577 * {@link #applyState(ActorRef, Identifier, Object)} is notified.
579 * @param clientActor optional ActorRef that is provided via the applyState callback
580 * @param identifier the payload identifier
581 * @param data the payload data to persist
582 * @param batchHint if true, an attempt is made to delay immediate replication and batch the payload with
583 * subsequent payloads for efficiency. Otherwise the payload is immediately replicated.
585 protected final void persistData(final ActorRef clientActor, final Identifier identifier, final Payload data,
586 final boolean batchHint) {
587 ReplicatedLogEntry replicatedLogEntry = new SimpleReplicatedLogEntry(
588 context.getReplicatedLog().lastIndex() + 1,
589 context.getTermInformation().getCurrentTerm(), data);
590 replicatedLogEntry.setPersistencePending(true);
592 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
594 final RaftActorContext raftContext = getRaftActorContext();
596 boolean wasAppended = replicatedLog().appendAndPersist(replicatedLogEntry, persistedLogEntry -> {
597 // Clear the persistence pending flag in the log entry.
598 persistedLogEntry.setPersistencePending(false);
600 if (!hasFollowers()) {
601 // Increment the Commit Index and the Last Applied values
602 raftContext.setCommitIndex(persistedLogEntry.getIndex());
603 raftContext.setLastApplied(persistedLogEntry.getIndex());
605 // Apply the state immediately.
606 handleApplyState(new ApplyState(clientActor, identifier, persistedLogEntry));
608 // Send a ApplyJournalEntries message so that we write the fact that we applied
609 // the state to durable storage
610 self().tell(new ApplyJournalEntries(persistedLogEntry.getIndex()), self());
613 context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry);
615 // Local persistence is complete so send the CheckConsensusReached message to the behavior (which
616 // normally should still be the leader) to check if consensus has now been reached in conjunction with
617 // follower replication.
618 getCurrentBehavior().handleMessage(getSelf(), CheckConsensusReached.INSTANCE);
622 if (wasAppended && hasFollowers()) {
623 // Send log entry for replication.
624 getCurrentBehavior().handleMessage(getSelf(), new Replicate(clientActor, identifier, replicatedLogEntry,
629 private ReplicatedLog replicatedLog() {
630 return context.getReplicatedLog();
633 protected String getId() {
634 return context.getId();
638 void setCurrentBehavior(final RaftActorBehavior behavior) {
639 context.setCurrentBehavior(behavior);
642 protected RaftActorBehavior getCurrentBehavior() {
643 return context.getCurrentBehavior();
647 * Derived actors can call the isLeader method to check if the current
648 * RaftActor is the Leader or not.
650 * @return true it this RaftActor is a Leader false otherwise
652 protected boolean isLeader() {
653 return context.getId().equals(getCurrentBehavior().getLeaderId());
656 protected final boolean isLeaderActive() {
657 return getRaftState() != RaftState.IsolatedLeader && getRaftState() != RaftState.PreLeader
658 && !shuttingDown && !isLeadershipTransferInProgress();
661 protected boolean isLeadershipTransferInProgress() {
662 RaftActorLeadershipTransferCohort leadershipTransferInProgress = context.getRaftActorLeadershipTransferCohort();
663 return leadershipTransferInProgress != null && leadershipTransferInProgress.isTransferring();
667 * Derived actor can call getLeader if they need a reference to the Leader.
668 * This would be useful for example in forwarding a request to an actor
669 * which is the leader
671 * @return A reference to the leader if known, null otherwise
673 public ActorSelection getLeader() {
674 String leaderAddress = getLeaderAddress();
676 if (leaderAddress == null) {
680 return context.actorSelection(leaderAddress);
684 * Returns the id of the current leader.
686 * @return the current leader's id
688 protected final String getLeaderId() {
689 return getCurrentBehavior().getLeaderId();
693 protected final RaftState getRaftState() {
694 return getCurrentBehavior().state();
697 protected Long getCurrentTerm() {
698 return context.getTermInformation().getCurrentTerm();
701 protected RaftActorContext getRaftActorContext() {
705 protected void updateConfigParams(final ConfigParams configParams) {
707 // obtain the RaftPolicy for oldConfigParams and the updated one.
708 String oldRaftPolicy = context.getConfigParams().getCustomRaftPolicyImplementationClass();
709 String newRaftPolicy = configParams.getCustomRaftPolicyImplementationClass();
711 LOG.debug("{}: RaftPolicy used with prev.config {}, RaftPolicy used with newConfig {}", persistenceId(),
712 oldRaftPolicy, newRaftPolicy);
713 context.setConfigParams(configParams);
714 if (!Objects.equals(oldRaftPolicy, newRaftPolicy)) {
715 // The RaftPolicy was modified. If the current behavior is Follower then re-initialize to Follower
716 // but transfer the previous leaderId so it doesn't immediately try to schedule an election. This
717 // avoids potential disruption. Otherwise, switch to Follower normally.
718 RaftActorBehavior behavior = getCurrentBehavior();
719 if (behavior != null && behavior.state() == RaftState.Follower) {
720 String previousLeaderId = behavior.getLeaderId();
721 short previousLeaderPayloadVersion = behavior.getLeaderPayloadVersion();
723 LOG.debug("{}: Re-initializing to Follower with previous leaderId {}", persistenceId(),
726 changeCurrentBehavior(new Follower(context, previousLeaderId, previousLeaderPayloadVersion));
728 initializeBehavior();
733 public final DataPersistenceProvider persistence() {
734 return delegatingPersistenceProvider.getDelegate();
737 public void setPersistence(final DataPersistenceProvider provider) {
738 delegatingPersistenceProvider.setDelegate(provider);
741 protected void setPersistence(final boolean persistent) {
742 DataPersistenceProvider currentPersistence = persistence();
743 if (persistent && (currentPersistence == null || !currentPersistence.isRecoveryApplicable())) {
744 setPersistence(new PersistentDataProvider(this));
746 if (getCurrentBehavior() != null) {
747 LOG.info("{}: Persistence has been enabled - capturing snapshot", persistenceId());
750 } else if (!persistent && (currentPersistence == null || currentPersistence.isRecoveryApplicable())) {
751 setPersistence(new NonPersistentDataProvider(this) {
753 * The way snapshotting works is,
755 * <li> RaftActor calls createSnapshot on the Shard
756 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
757 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
758 * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
759 * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
760 * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
764 public void saveSnapshot(final Object object) {
765 // Make saving Snapshot successful
766 // Committing the snapshot here would end up calling commit in the creating state which would
767 // be a state violation. That's why now we send a message to commit the snapshot.
768 self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
775 * setPeerAddress sets the address of a known peer at a later time.
778 * This is to account for situations where a we know that a peer
779 * exists but we do not know an address up-front. This may also be used in
780 * situations where a known peer starts off in a different location and we
781 * need to change it's address
784 * Note that if the peerId does not match the list of peers passed to
785 * this actor during construction an IllegalStateException will be thrown.
787 protected void setPeerAddress(final String peerId, final String peerAddress) {
788 context.setPeerAddress(peerId, peerAddress);
792 * The applyState method will be called by the RaftActor when some data
793 * needs to be applied to the actor's state.
795 * @param clientActor A reference to the client who sent this message. This
796 * is the same reference that was passed to persistData
797 * by the derived actor. clientActor may be null when
798 * the RaftActor is behaving as a follower or during
800 * @param identifier The identifier of the persisted data. This is also
801 * the same identifier that was passed to persistData by
802 * the derived actor. identifier may be null when
803 * the RaftActor is behaving as a follower or during
805 * @param data A piece of data that was persisted by the persistData call.
806 * This should NEVER be null.
808 protected abstract void applyState(ActorRef clientActor, Identifier identifier, Object data);
811 * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
813 protected abstract @NonNull RaftActorRecoveryCohort getRaftActorRecoveryCohort();
816 * This method is called when recovery is complete.
818 protected abstract void onRecoveryComplete();
821 * Returns the RaftActorSnapshotCohort to participate in snapshot captures.
823 protected abstract @NonNull RaftActorSnapshotCohort getRaftActorSnapshotCohort();
826 * This method will be called by the RaftActor when the state of the
827 * RaftActor changes. The derived actor can then use methods like
828 * isLeader or getLeader to do something useful
830 protected abstract void onStateChanged();
833 * Notifier Actor for this RaftActor to notify when a role change happens.
835 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
837 protected abstract Optional<ActorRef> getRoleChangeNotifier();
840 * This method is called on the leader when a voting change operation completes.
842 protected void onVotingStateChangeComplete() {
846 * This method is called prior to operations such as leadership transfer and actor shutdown when the leader
847 * must pause or stop its duties. This method allows derived classes to gracefully pause or finish current
848 * work prior to performing the operation. On completion of any work, the run method must be called on the
849 * given Runnable to proceed with the given operation. <b>Important:</b> the run method must be called on
850 * this actor's thread dispatcher as as it modifies internal state.
853 * The default implementation immediately runs the operation.
855 * @param operation the operation to run
857 protected void pauseLeader(final Runnable operation) {
862 * This method is invoked when the actions hooked to the leader becoming paused failed to execute and the leader
863 * should resume normal operations.
866 * Note this method can be invoked even before the operation supplied to {@link #pauseLeader(Runnable)} is invoked.
868 protected void unpauseLeader() {
872 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
875 private String getLeaderAddress() {
877 return getSelf().path().toString();
879 String leaderId = getLeaderId();
880 if (leaderId == null) {
883 String peerAddress = context.getPeerAddress(leaderId);
884 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}", persistenceId(), leaderId, peerAddress);
889 protected boolean hasFollowers() {
890 return getRaftActorContext().hasFollowers();
893 private void captureSnapshot() {
894 SnapshotManager snapshotManager = context.getSnapshotManager();
896 if (!snapshotManager.isCapturing()) {
897 final long idx = getCurrentBehavior().getReplicatedToAllIndex();
898 LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
899 replicatedLog().last(), idx);
901 snapshotManager.captureWithForcedTrim(replicatedLog().last(), idx);
906 * Switch this member to non-voting status. This is a no-op for all behaviors except when we are the leader,
907 * in which case we need to step down.
909 void becomeNonVoting() {
911 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
913 public void onSuccess(final ActorRef raftActorRef) {
914 LOG.debug("{}: leader transfer succeeded after change to non-voting", persistenceId());
915 ensureFollowerState();
919 public void onFailure(final ActorRef raftActorRef) {
920 LOG.debug("{}: leader transfer failed after change to non-voting", persistenceId());
921 ensureFollowerState();
924 private void ensureFollowerState() {
925 // Whether or not leadership transfer succeeded, we have to step down as leader and
926 // switch to Follower so ensure that.
927 if (getRaftState() != RaftState.Follower) {
928 initializeBehavior();
931 }, null, RaftActorLeadershipTransferCohort.USE_DEFAULT_LEADER_TIMEOUT);
936 * A point-in-time capture of {@link RaftActorBehavior} state critical for transitioning between behaviors.
938 private abstract static class BehaviorState implements Immutable {
939 @Nullable abstract RaftActorBehavior getBehavior();
941 @Nullable abstract String getLastValidLeaderId();
943 @Nullable abstract String getLastLeaderId();
945 abstract short getLeaderPayloadVersion();
949 * A {@link BehaviorState} corresponding to non-null {@link RaftActorBehavior} state.
951 private static final class SimpleBehaviorState extends BehaviorState {
952 private final RaftActorBehavior behavior;
953 private final String lastValidLeaderId;
954 private final String lastLeaderId;
955 private final short leaderPayloadVersion;
957 SimpleBehaviorState(final String lastValidLeaderId, final String lastLeaderId,
958 final RaftActorBehavior behavior) {
959 this.lastValidLeaderId = lastValidLeaderId;
960 this.lastLeaderId = lastLeaderId;
961 this.behavior = requireNonNull(behavior);
962 leaderPayloadVersion = behavior.getLeaderPayloadVersion();
966 RaftActorBehavior getBehavior() {
971 String getLastValidLeaderId() {
972 return lastValidLeaderId;
976 short getLeaderPayloadVersion() {
977 return leaderPayloadVersion;
981 String getLastLeaderId() {
987 * Class tracking behavior-related information, which we need to keep around and pass across behavior switches.
988 * An instance is created for each RaftActor. It has two functions:
989 * - it keeps track of the last leader ID we have encountered since we have been created
990 * - it creates state capture needed to transition from one behavior to the next
992 private static final class BehaviorStateTracker {
994 * A {@link BehaviorState} corresponding to null {@link RaftActorBehavior} state. Since null behavior is only
995 * allowed before we receive the first message, we know the leader ID to be null.
997 private static final BehaviorState NULL_BEHAVIOR_STATE = new BehaviorState() {
999 RaftActorBehavior getBehavior() {
1004 String getLastValidLeaderId() {
1009 short getLeaderPayloadVersion() {
1014 String getLastLeaderId() {
1019 private String lastValidLeaderId;
1020 private String lastLeaderId;
1022 BehaviorState capture(final RaftActorBehavior behavior) {
1023 if (behavior == null) {
1024 verify(lastValidLeaderId == null, "Null behavior with non-null last leader");
1025 return NULL_BEHAVIOR_STATE;
1028 lastLeaderId = behavior.getLeaderId();
1029 if (lastLeaderId != null) {
1030 lastValidLeaderId = lastLeaderId;
1033 return new SimpleBehaviorState(lastValidLeaderId, lastLeaderId, behavior);