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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Objects;
28 import java.util.Optional;
29 import java.util.concurrent.TimeUnit;
30 import org.apache.commons.lang3.time.DurationFormatUtils;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.opendaylight.controller.cluster.DataPersistenceProvider;
34 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
35 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
36 import org.opendaylight.controller.cluster.PersistentDataProvider;
37 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
38 import org.opendaylight.controller.cluster.mgmt.api.FollowerInfo;
39 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
40 import org.opendaylight.controller.cluster.notifications.RoleChanged;
41 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
42 import org.opendaylight.controller.cluster.raft.base.messages.CheckConsensusReached;
43 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
44 import org.opendaylight.controller.cluster.raft.base.messages.LeaderTransitioning;
45 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
46 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
47 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
48 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
49 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
50 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
51 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
52 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
53 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
54 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
55 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
56 import org.opendaylight.controller.cluster.raft.messages.Payload;
57 import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
58 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
59 import org.opendaylight.controller.cluster.raft.persisted.NoopPayload;
60 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
61 import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
62 import org.opendaylight.yangtools.concepts.Identifier;
63 import org.opendaylight.yangtools.concepts.Immutable;
66 * RaftActor encapsulates a state machine that needs to be kept synchronized
67 * in a cluster. It implements the RAFT algorithm as described in the paper
68 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
69 * In Search of an Understandable Consensus Algorithm</a>
72 * RaftActor has 3 states and each state has a certain behavior associated
73 * with it. A Raft actor can behave as,
76 * <li> A Follower (or) </li>
77 * <li> A Candidate </li>
81 * A RaftActor MUST be a Leader in order to accept requests from clients to
82 * change the state of it's encapsulated state machine. Once a RaftActor becomes
83 * a Leader it is also responsible for ensuring that all followers ultimately
84 * have the same log and therefore the same state machine as itself.
87 * The current behavior of a RaftActor determines how election for leadership
88 * is initiated and how peer RaftActors react to request for votes.
91 * Each RaftActor also needs to know the current election term. It uses this
92 * information for a couple of things. One is to simply figure out who it
93 * voted for in the last election. Another is to figure out if the message
94 * it received to update it's state is stale.
97 * The RaftActor uses akka-persistence to store it's replicated log.
98 * Furthermore through it's behaviors a Raft Actor determines
100 * <li> when a log entry should be persisted </li>
101 * <li> when a log entry should be applied to the state machine (and) </li>
102 * <li> when a snapshot should be saved </li>
105 public abstract class RaftActor extends AbstractUntypedPersistentActor {
106 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50);
109 * This context should NOT be passed directly to any other actor it is
110 * only to be consumed by the RaftActorBehaviors.
112 private final RaftActorContextImpl context;
114 private final DelegatingPersistentDataProvider delegatingPersistenceProvider;
116 private final PersistentDataProvider persistentProvider;
118 private final BehaviorStateTracker behaviorStateTracker = new BehaviorStateTracker();
120 private RaftActorRecoverySupport raftRecovery;
122 private RaftActorSnapshotMessageSupport snapshotSupport;
124 private RaftActorServerConfigurationSupport serverConfigurationSupport;
126 private boolean shuttingDown;
128 @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Akka class design")
129 protected RaftActor(final String id, final Map<String, String> peerAddresses,
130 final Optional<ConfigParams> configParams, final short payloadVersion) {
132 persistentProvider = new PersistentDataProvider(this);
133 delegatingPersistenceProvider = new RaftActorDelegatingPersistentDataProvider(null, persistentProvider);
135 context = new RaftActorContextImpl(getSelf(), getContext(), id,
136 new ElectionTermImpl(persistentProvider, id, LOG), -1, -1, peerAddresses,
137 configParams.isPresent() ? configParams.get() : new DefaultConfigParamsImpl(),
138 delegatingPersistenceProvider, this::handleApplyState, LOG, this::executeInSelf);
140 context.setPayloadVersion(payloadVersion);
141 context.setReplicatedLog(ReplicatedLogImpl.newInstance(context));
145 public void preStart() throws Exception {
146 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
147 context.getConfigParams().getJournalRecoveryLogBatchSize());
151 snapshotSupport = newRaftActorSnapshotMessageSupport();
152 serverConfigurationSupport = new RaftActorServerConfigurationSupport(this);
156 public void postStop() throws Exception {
162 protected void handleRecover(final Object message) {
163 if (raftRecovery == null) {
164 raftRecovery = newRaftActorRecoverySupport();
167 boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
168 if (recoveryComplete) {
169 onRecoveryComplete();
171 initializeBehavior();
177 protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
178 return new RaftActorRecoverySupport(context, getRaftActorRecoveryCohort());
182 void initializeBehavior() {
183 changeCurrentBehavior(new Follower(context));
187 @SuppressWarnings("checkstyle:IllegalCatch")
188 protected void changeCurrentBehavior(final RaftActorBehavior newBehavior) {
189 final RaftActorBehavior currentBehavior = getCurrentBehavior();
190 if (currentBehavior != null) {
192 currentBehavior.close();
193 } catch (Exception e) {
194 LOG.warn("{}: Error closing behavior {}", persistence(), currentBehavior, e);
198 final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
199 setCurrentBehavior(newBehavior);
200 handleBehaviorChange(state, newBehavior);
204 * Method exposed for subclasses to plug-in their logic. This method is invoked by {@link #handleCommand(Object)}
205 * for messages which are not handled by this class. Subclasses overriding this class should fall back to this
206 * implementation for messages which they do not handle
208 * @param message Incoming command message
210 protected void handleNonRaftCommand(final Object message) {
217 * @deprecated This method is not final for testing purposes. DO NOT OVERRIDE IT, override
218 * {@link #handleNonRaftCommand(Object)} instead.
222 // FIXME: make this method final once our unit tests do not need to override it
223 protected void handleCommand(final Object message) {
224 if (serverConfigurationSupport.handleMessage(message, getSender())) {
227 if (snapshotSupport.handleSnapshotMessage(message, getSender())) {
230 if (message instanceof ApplyState applyState) {
231 if (!hasFollowers()) {
232 // for single node, the capture should happen after the apply state
233 // as we delete messages from the persistent journal which have made it to the snapshot
234 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
235 // and recovery shows data missing
236 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
238 context.getSnapshotManager().trimLog(context.getLastApplied());
241 possiblyHandleBehaviorMessage(message);
242 } else if (message instanceof ApplyJournalEntries applyEntries) {
243 LOG.debug("{}: Persisting ApplyJournalEntries with index={}", persistenceId(), applyEntries.getToIndex());
245 persistence().persistAsync(applyEntries, NoopProcedure.instance());
246 } else if (message instanceof FindLeader) {
247 getSender().tell(new FindLeaderReply(getLeaderAddress()), getSelf());
248 } else if (message instanceof GetOnDemandRaftState) {
249 onGetOnDemandRaftStats();
250 } else if (message instanceof InitiateCaptureSnapshot) {
252 } else if (message instanceof SwitchBehavior switchBehavior) {
253 switchBehavior(switchBehavior);
254 } else if (message instanceof LeaderTransitioning leaderTransitioning) {
255 onLeaderTransitioning(leaderTransitioning);
256 } else if (message instanceof Shutdown) {
258 } else if (message instanceof Runnable runnable) {
260 } else if (message instanceof NoopPayload noopPayload) {
261 persistData(null, null, noopPayload, false);
262 } else if (message instanceof RequestLeadership requestLeadership) {
263 onRequestLeadership(requestLeadership);
264 } else if (!possiblyHandleBehaviorMessage(message)) {
265 if (message instanceof JournalProtocol.Response response
266 && delegatingPersistenceProvider.handleJournalResponse(response)) {
267 LOG.debug("{}: handled a journal response", persistenceId());
268 } else if (message instanceof SnapshotProtocol.Response response
269 && delegatingPersistenceProvider.handleSnapshotResponse(response)) {
270 LOG.debug("{}: handled a snapshot response", persistenceId());
272 handleNonRaftCommand(message);
277 private void onRequestLeadership(final RequestLeadership message) {
278 LOG.debug("{}: onRequestLeadership {}", persistenceId(), message);
280 // non-leader cannot satisfy leadership request
281 LOG.warn("{}: onRequestLeadership {} was sent to non-leader."
282 + " Current behavior: {}. Sending failure response",
283 persistenceId(), message, getCurrentBehavior().state());
284 message.getReplyTo().tell(new LeadershipTransferFailedException("Cannot transfer leader to "
285 + message.getRequestedFollowerId()
286 + ". RequestLeadership message was sent to non-leader " + persistenceId()), getSelf());
290 final String requestedFollowerId = message.getRequestedFollowerId();
291 final ActorRef replyTo = message.getReplyTo();
292 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
294 public void onSuccess(final ActorRef raftActorRef) {
296 if (!requestedFollowerId.equals(getLeaderId())) {
297 onFailure(raftActorRef);
300 LOG.debug("{}: Leadership transferred successfully to {}", persistenceId(), requestedFollowerId);
301 replyTo.tell(new Status.Success(null), getSelf());
305 public void onFailure(final ActorRef raftActorRef) {
306 LOG.debug("{}: LeadershipTransfer request from {} failed", persistenceId(), requestedFollowerId);
307 replyTo.tell(new Status.Failure(
308 new LeadershipTransferFailedException(
309 "Failed to transfer leadership to " + requestedFollowerId
310 + ". Follower is not ready to become leader")),
313 }, message.getRequestedFollowerId(), RaftActorLeadershipTransferCohort.USE_DEFAULT_LEADER_TIMEOUT);
316 private boolean possiblyHandleBehaviorMessage(final Object message) {
317 final RaftActorBehavior currentBehavior = getCurrentBehavior();
318 final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
320 // A behavior indicates that it processed the change by returning a reference to the next behavior
321 // to be used. A null return indicates it has not processed the message and we should be passing it to
322 // the subclass for handling.
323 final RaftActorBehavior nextBehavior = currentBehavior.handleMessage(getSender(), message);
324 if (nextBehavior != null) {
325 switchBehavior(state, nextBehavior);
332 private void initiateLeadershipTransfer(final RaftActorLeadershipTransferCohort.OnComplete onComplete,
333 final @Nullable String followerId, final long newLeaderTimeoutInMillis) {
334 LOG.debug("{}: Initiating leader transfer", persistenceId());
336 RaftActorLeadershipTransferCohort leadershipTransferInProgress = context.getRaftActorLeadershipTransferCohort();
337 if (leadershipTransferInProgress == null) {
338 leadershipTransferInProgress = new RaftActorLeadershipTransferCohort(this, followerId);
339 leadershipTransferInProgress.setNewLeaderTimeoutInMillis(newLeaderTimeoutInMillis);
340 leadershipTransferInProgress.addOnComplete(new RaftActorLeadershipTransferCohort.OnComplete() {
342 public void onSuccess(final ActorRef raftActorRef) {
343 context.setRaftActorLeadershipTransferCohort(null);
347 public void onFailure(final ActorRef raftActorRef) {
348 context.setRaftActorLeadershipTransferCohort(null);
352 leadershipTransferInProgress.addOnComplete(onComplete);
354 context.setRaftActorLeadershipTransferCohort(leadershipTransferInProgress);
355 leadershipTransferInProgress.init();
358 LOG.debug("{}: prior leader transfer in progress - adding callback", persistenceId());
359 leadershipTransferInProgress.addOnComplete(onComplete);
363 private void onShutDown() {
364 LOG.debug("{}: onShutDown", persistenceId());
372 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
373 switch (currentBehavior.state()) {
376 // Fall-through to more work
379 // For non-leaders shutdown is a no-op
380 self().tell(PoisonPill.getInstance(), self());
384 if (context.hasFollowers()) {
385 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
387 public void onSuccess(final ActorRef raftActorRef) {
388 LOG.debug("{}: leader transfer succeeded - sending PoisonPill", persistenceId());
389 raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
393 public void onFailure(final ActorRef raftActorRef) {
394 LOG.debug("{}: leader transfer failed - sending PoisonPill", persistenceId());
395 raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
397 }, null, TimeUnit.MILLISECONDS.convert(2, TimeUnit.SECONDS));
399 pauseLeader(new TimedRunnable(context.getConfigParams().getElectionTimeOutInterval(), this) {
401 protected void doRun() {
402 self().tell(PoisonPill.getInstance(), self());
406 protected void doCancel() {
407 self().tell(PoisonPill.getInstance(), self());
413 private void onLeaderTransitioning(final LeaderTransitioning leaderTransitioning) {
414 LOG.debug("{}: onLeaderTransitioning: {}", persistenceId(), leaderTransitioning);
415 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
416 if (getRaftState() == RaftState.Follower && roleChangeNotifier.isPresent()
417 && leaderTransitioning.getLeaderId().equals(getCurrentBehavior().getLeaderId())) {
418 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), null,
419 getCurrentBehavior().getLeaderPayloadVersion()), getSelf());
423 private void switchBehavior(final SwitchBehavior message) {
424 if (!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
425 RaftState newState = message.getNewState();
426 if (newState == RaftState.Leader || newState == RaftState.Follower) {
427 getRaftActorContext().getTermInformation().updateAndPersist(message.getNewTerm(), "");
428 switchBehavior(behaviorStateTracker.capture(getCurrentBehavior()),
429 AbstractRaftActorBehavior.createBehavior(context, message.getNewState()));
431 LOG.warn("Switching to behavior : {} - not supported", newState);
436 private void switchBehavior(final BehaviorState oldBehaviorState, final RaftActorBehavior nextBehavior) {
437 setCurrentBehavior(nextBehavior);
438 handleBehaviorChange(oldBehaviorState, nextBehavior);
442 RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
443 return new RaftActorSnapshotMessageSupport(context, getRaftActorSnapshotCohort());
446 private void onGetOnDemandRaftStats() {
447 // Debugging message to retrieve raft stats.
449 Map<String, String> peerAddresses = new HashMap<>();
450 Map<String, Boolean> peerVotingStates = new HashMap<>();
451 for (PeerInfo info: context.getPeers()) {
452 peerVotingStates.put(info.getId(), info.isVoting());
453 peerAddresses.put(info.getId(), info.getAddress() != null ? info.getAddress() : "");
456 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
457 OnDemandRaftState.AbstractBuilder<?, ?> builder = newOnDemandRaftStateBuilder()
458 .commitIndex(context.getCommitIndex())
459 .currentTerm(context.getTermInformation().getCurrentTerm())
460 .inMemoryJournalDataSize(replicatedLog().dataSize())
461 .inMemoryJournalLogSize(replicatedLog().size())
462 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
463 .lastApplied(context.getLastApplied())
464 .lastIndex(replicatedLog().lastIndex())
465 .lastTerm(replicatedLog().lastTerm())
466 .leader(getLeaderId())
467 .raftState(currentBehavior.state().toString())
468 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
469 .snapshotIndex(replicatedLog().getSnapshotIndex())
470 .snapshotTerm(replicatedLog().getSnapshotTerm())
471 .votedFor(context.getTermInformation().getVotedFor())
472 .isVoting(context.isVotingMember())
473 .peerAddresses(peerAddresses)
474 .peerVotingStates(peerVotingStates)
475 .customRaftPolicyClassName(context.getConfigParams().getCustomRaftPolicyImplementationClass());
477 ReplicatedLogEntry lastLogEntry = replicatedLog().last();
478 if (lastLogEntry != null) {
479 builder.lastLogIndex(lastLogEntry.getIndex());
480 builder.lastLogTerm(lastLogEntry.getTerm());
483 if (getCurrentBehavior() instanceof AbstractLeader leader) {
484 Collection<String> followerIds = leader.getFollowerIds();
485 List<FollowerInfo> followerInfoList = new ArrayList<>(followerIds.size());
486 for (String id : followerIds) {
487 final FollowerLogInformation info = leader.getFollower(id);
488 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
489 info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(
490 TimeUnit.NANOSECONDS.toMillis(info.nanosSinceLastActivity())),
491 context.getPeerInfo(info.getId()).isVoting()));
494 builder.followerInfoList(followerInfoList);
497 sender().tell(builder.build(), self());
501 protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
502 return OnDemandRaftState.builder();
505 private void handleBehaviorChange(final BehaviorState oldBehaviorState, final RaftActorBehavior currentBehavior) {
506 RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
508 if (oldBehavior != currentBehavior) {
512 String lastLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastLeaderId();
513 String lastValidLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastValidLeaderId();
514 String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
516 // it can happen that the state has not changed but the leader has changed.
517 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
518 if (!Objects.equals(lastLeaderId, currentBehavior.getLeaderId())
519 || oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
520 if (roleChangeNotifier.isPresent()) {
521 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
522 currentBehavior.getLeaderPayloadVersion()), getSelf());
525 onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
527 RaftActorLeadershipTransferCohort leadershipTransferInProgress =
528 context.getRaftActorLeadershipTransferCohort();
529 if (leadershipTransferInProgress != null) {
530 leadershipTransferInProgress.onNewLeader(currentBehavior.getLeaderId());
533 serverConfigurationSupport.onNewLeader(currentBehavior.getLeaderId());
536 if (roleChangeNotifier.isPresent()
537 && (oldBehavior == null || oldBehavior.state() != currentBehavior.state())) {
538 roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
539 currentBehavior.state().name()), getSelf());
543 private void handleApplyState(final ApplyState applyState) {
544 long startTime = System.nanoTime();
546 Payload payload = applyState.getReplicatedLogEntry().getData();
547 if (LOG.isDebugEnabled()) {
548 LOG.debug("{}: Applying state for log index {} data {}",
549 persistenceId(), applyState.getReplicatedLogEntry().getIndex(), payload);
552 if (!(payload instanceof NoopPayload) && !(payload instanceof ServerConfigurationPayload)) {
553 applyState(applyState.getClientActor(), applyState.getIdentifier(), payload);
556 long elapsedTime = System.nanoTime() - startTime;
557 if (elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS) {
558 LOG.debug("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
559 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
562 // Send the ApplyState message back to self to handle further processing asynchronously.
563 self().tell(applyState, self());
566 protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
567 final short leaderPayloadVersion) {
568 return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
572 public long snapshotSequenceNr() {
573 // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
574 // so that we can delete the persistent journal based on the saved sequence-number
575 // However , when akka replays the journal during recovery, it replays it from the sequence number when the
576 // snapshot was saved and not the number we saved. We would want to override it , by asking akka to use the
577 // last-sequence number known to us.
578 return context.getSnapshotManager().getLastSequenceNumber();
582 * Persists the given Payload in the journal and replicates to any followers. After successful completion,
583 * {@link #applyState(ActorRef, Identifier, Object)} is notified.
585 * @param clientActor optional ActorRef that is provided via the applyState callback
586 * @param identifier the payload identifier
587 * @param data the payload data to persist
588 * @param batchHint if true, an attempt is made to delay immediate replication and batch the payload with
589 * subsequent payloads for efficiency. Otherwise the payload is immediately replicated.
591 protected final void persistData(final ActorRef clientActor, final Identifier identifier, final Payload data,
592 final boolean batchHint) {
593 ReplicatedLogEntry replicatedLogEntry = new SimpleReplicatedLogEntry(
594 context.getReplicatedLog().lastIndex() + 1,
595 context.getTermInformation().getCurrentTerm(), data);
596 replicatedLogEntry.setPersistencePending(true);
598 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
600 final RaftActorContext raftContext = getRaftActorContext();
602 boolean wasAppended = replicatedLog().appendAndPersist(replicatedLogEntry, persistedLogEntry -> {
603 // Clear the persistence pending flag in the log entry.
604 persistedLogEntry.setPersistencePending(false);
606 if (!hasFollowers()) {
607 // Increment the Commit Index and the Last Applied values
608 raftContext.setCommitIndex(persistedLogEntry.getIndex());
609 raftContext.setLastApplied(persistedLogEntry.getIndex());
611 // Apply the state immediately.
612 handleApplyState(new ApplyState(clientActor, identifier, persistedLogEntry));
614 // Send a ApplyJournalEntries message so that we write the fact that we applied
615 // the state to durable storage
616 self().tell(new ApplyJournalEntries(persistedLogEntry.getIndex()), self());
619 context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry);
621 // Local persistence is complete so send the CheckConsensusReached message to the behavior (which
622 // normally should still be the leader) to check if consensus has now been reached in conjunction with
623 // follower replication.
624 getCurrentBehavior().handleMessage(getSelf(), CheckConsensusReached.INSTANCE);
628 if (wasAppended && hasFollowers()) {
629 // Send log entry for replication.
630 getCurrentBehavior().handleMessage(getSelf(), new Replicate(clientActor, identifier, replicatedLogEntry,
635 private ReplicatedLog replicatedLog() {
636 return context.getReplicatedLog();
639 protected String getId() {
640 return context.getId();
644 void setCurrentBehavior(final RaftActorBehavior behavior) {
645 context.setCurrentBehavior(behavior);
648 protected RaftActorBehavior getCurrentBehavior() {
649 return context.getCurrentBehavior();
653 * Derived actors can call the isLeader method to check if the current
654 * RaftActor is the Leader or not.
656 * @return true it this RaftActor is a Leader false otherwise
658 protected boolean isLeader() {
659 return context.getId().equals(getCurrentBehavior().getLeaderId());
662 protected final boolean isLeaderActive() {
663 return getRaftState() != RaftState.IsolatedLeader && getRaftState() != RaftState.PreLeader
664 && !shuttingDown && !isLeadershipTransferInProgress();
667 protected boolean isLeadershipTransferInProgress() {
668 RaftActorLeadershipTransferCohort leadershipTransferInProgress = context.getRaftActorLeadershipTransferCohort();
669 return leadershipTransferInProgress != null && leadershipTransferInProgress.isTransferring();
673 * Derived actor can call getLeader if they need a reference to the Leader.
674 * This would be useful for example in forwarding a request to an actor
675 * which is the leader
677 * @return A reference to the leader if known, null otherwise
679 public ActorSelection getLeader() {
680 String leaderAddress = getLeaderAddress();
682 if (leaderAddress == null) {
686 return context.actorSelection(leaderAddress);
690 * Returns the id of the current leader.
692 * @return the current leader's id
694 protected final String getLeaderId() {
695 return getCurrentBehavior().getLeaderId();
699 protected final RaftState getRaftState() {
700 return getCurrentBehavior().state();
703 protected Long getCurrentTerm() {
704 return context.getTermInformation().getCurrentTerm();
707 protected RaftActorContext getRaftActorContext() {
711 protected void updateConfigParams(final ConfigParams configParams) {
713 // obtain the RaftPolicy for oldConfigParams and the updated one.
714 String oldRaftPolicy = context.getConfigParams().getCustomRaftPolicyImplementationClass();
715 String newRaftPolicy = configParams.getCustomRaftPolicyImplementationClass();
717 LOG.debug("{}: RaftPolicy used with prev.config {}, RaftPolicy used with newConfig {}", persistenceId(),
718 oldRaftPolicy, newRaftPolicy);
719 context.setConfigParams(configParams);
720 if (!Objects.equals(oldRaftPolicy, newRaftPolicy)) {
721 // The RaftPolicy was modified. If the current behavior is Follower then re-initialize to Follower
722 // but transfer the previous leaderId so it doesn't immediately try to schedule an election. This
723 // avoids potential disruption. Otherwise, switch to Follower normally.
724 RaftActorBehavior behavior = getCurrentBehavior();
725 if (behavior != null && behavior.state() == RaftState.Follower) {
726 String previousLeaderId = behavior.getLeaderId();
727 short previousLeaderPayloadVersion = behavior.getLeaderPayloadVersion();
729 LOG.debug("{}: Re-initializing to Follower with previous leaderId {}", persistenceId(),
732 changeCurrentBehavior(new Follower(context, previousLeaderId, previousLeaderPayloadVersion));
734 initializeBehavior();
739 public final DataPersistenceProvider persistence() {
740 return delegatingPersistenceProvider.getDelegate();
743 public void setPersistence(final DataPersistenceProvider provider) {
744 delegatingPersistenceProvider.setDelegate(provider);
747 protected void setPersistence(final boolean persistent) {
748 DataPersistenceProvider currentPersistence = persistence();
749 if (persistent && (currentPersistence == null || !currentPersistence.isRecoveryApplicable())) {
750 setPersistence(new PersistentDataProvider(this));
752 if (getCurrentBehavior() != null) {
753 LOG.info("{}: Persistence has been enabled - capturing snapshot", persistenceId());
756 } else if (!persistent && (currentPersistence == null || currentPersistence.isRecoveryApplicable())) {
757 setPersistence(new NonPersistentDataProvider(this) {
759 * The way snapshotting works is,
761 * <li> RaftActor calls createSnapshot on the Shard
762 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
763 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
764 * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
765 * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
766 * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
770 public void saveSnapshot(final Object object) {
771 // Make saving Snapshot successful
772 // Committing the snapshot here would end up calling commit in the creating state which would
773 // be a state violation. That's why now we send a message to commit the snapshot.
774 self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
781 * setPeerAddress sets the address of a known peer at a later time.
784 * This is to account for situations where a we know that a peer
785 * exists but we do not know an address up-front. This may also be used in
786 * situations where a known peer starts off in a different location and we
787 * need to change it's address
790 * Note that if the peerId does not match the list of peers passed to
791 * this actor during construction an IllegalStateException will be thrown.
793 protected void setPeerAddress(final String peerId, final String peerAddress) {
794 context.setPeerAddress(peerId, peerAddress);
798 * The applyState method will be called by the RaftActor when some data
799 * needs to be applied to the actor's state.
801 * @param clientActor A reference to the client who sent this message. This
802 * is the same reference that was passed to persistData
803 * by the derived actor. clientActor may be null when
804 * the RaftActor is behaving as a follower or during
806 * @param identifier The identifier of the persisted data. This is also
807 * the same identifier that was passed to persistData by
808 * the derived actor. identifier may be null when
809 * the RaftActor is behaving as a follower or during
811 * @param data A piece of data that was persisted by the persistData call.
812 * This should NEVER be null.
814 protected abstract void applyState(ActorRef clientActor, Identifier identifier, Object data);
817 * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
819 protected abstract @NonNull RaftActorRecoveryCohort getRaftActorRecoveryCohort();
822 * This method is called when recovery is complete.
824 protected abstract void onRecoveryComplete();
827 * Returns the RaftActorSnapshotCohort to participate in snapshot captures.
829 protected abstract @NonNull RaftActorSnapshotCohort getRaftActorSnapshotCohort();
832 * This method will be called by the RaftActor when the state of the
833 * RaftActor changes. The derived actor can then use methods like
834 * isLeader or getLeader to do something useful
836 protected abstract void onStateChanged();
839 * Notifier Actor for this RaftActor to notify when a role change happens.
841 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
843 protected abstract Optional<ActorRef> getRoleChangeNotifier();
846 * This method is called on the leader when a voting change operation completes.
848 protected void onVotingStateChangeComplete() {
852 * This method is called prior to operations such as leadership transfer and actor shutdown when the leader
853 * must pause or stop its duties. This method allows derived classes to gracefully pause or finish current
854 * work prior to performing the operation. On completion of any work, the run method must be called on the
855 * given Runnable to proceed with the given operation. <b>Important:</b> the run method must be called on
856 * this actor's thread dispatcher as as it modifies internal state.
859 * The default implementation immediately runs the operation.
861 * @param operation the operation to run
863 protected void pauseLeader(final Runnable operation) {
868 * This method is invoked when the actions hooked to the leader becoming paused failed to execute and the leader
869 * should resume normal operations.
872 * Note this method can be invoked even before the operation supplied to {@link #pauseLeader(Runnable)} is invoked.
874 protected void unpauseLeader() {
878 protected void onLeaderChanged(final String oldLeader, final String newLeader) {
881 private String getLeaderAddress() {
883 return getSelf().path().toString();
885 String leaderId = getLeaderId();
886 if (leaderId == null) {
889 String peerAddress = context.getPeerAddress(leaderId);
890 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}", persistenceId(), leaderId, peerAddress);
895 protected boolean hasFollowers() {
896 return getRaftActorContext().hasFollowers();
899 private void captureSnapshot() {
900 SnapshotManager snapshotManager = context.getSnapshotManager();
902 if (!snapshotManager.isCapturing()) {
903 final long idx = getCurrentBehavior().getReplicatedToAllIndex();
904 LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
905 replicatedLog().last(), idx);
907 snapshotManager.captureWithForcedTrim(replicatedLog().last(), idx);
912 * Switch this member to non-voting status. This is a no-op for all behaviors except when we are the leader,
913 * in which case we need to step down.
915 void becomeNonVoting() {
917 initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
919 public void onSuccess(final ActorRef raftActorRef) {
920 LOG.debug("{}: leader transfer succeeded after change to non-voting", persistenceId());
921 ensureFollowerState();
925 public void onFailure(final ActorRef raftActorRef) {
926 LOG.debug("{}: leader transfer failed after change to non-voting", persistenceId());
927 ensureFollowerState();
930 private void ensureFollowerState() {
931 // Whether or not leadership transfer succeeded, we have to step down as leader and
932 // switch to Follower so ensure that.
933 if (getRaftState() != RaftState.Follower) {
934 initializeBehavior();
937 }, null, RaftActorLeadershipTransferCohort.USE_DEFAULT_LEADER_TIMEOUT);
942 * A point-in-time capture of {@link RaftActorBehavior} state critical for transitioning between behaviors.
944 private abstract static class BehaviorState implements Immutable {
945 @Nullable abstract RaftActorBehavior getBehavior();
947 @Nullable abstract String getLastValidLeaderId();
949 @Nullable abstract String getLastLeaderId();
951 abstract short getLeaderPayloadVersion();
955 * A {@link BehaviorState} corresponding to non-null {@link RaftActorBehavior} state.
957 private static final class SimpleBehaviorState extends BehaviorState {
958 private final RaftActorBehavior behavior;
959 private final String lastValidLeaderId;
960 private final String lastLeaderId;
961 private final short leaderPayloadVersion;
963 SimpleBehaviorState(final String lastValidLeaderId, final String lastLeaderId,
964 final RaftActorBehavior behavior) {
965 this.lastValidLeaderId = lastValidLeaderId;
966 this.lastLeaderId = lastLeaderId;
967 this.behavior = requireNonNull(behavior);
968 leaderPayloadVersion = behavior.getLeaderPayloadVersion();
972 RaftActorBehavior getBehavior() {
977 String getLastValidLeaderId() {
978 return lastValidLeaderId;
982 short getLeaderPayloadVersion() {
983 return leaderPayloadVersion;
987 String getLastLeaderId() {
993 * Class tracking behavior-related information, which we need to keep around and pass across behavior switches.
994 * An instance is created for each RaftActor. It has two functions:
995 * - it keeps track of the last leader ID we have encountered since we have been created
996 * - it creates state capture needed to transition from one behavior to the next
998 private static final class BehaviorStateTracker {
1000 * A {@link BehaviorState} corresponding to null {@link RaftActorBehavior} state. Since null behavior is only
1001 * allowed before we receive the first message, we know the leader ID to be null.
1003 private static final BehaviorState NULL_BEHAVIOR_STATE = new BehaviorState() {
1005 RaftActorBehavior getBehavior() {
1010 String getLastValidLeaderId() {
1015 short getLeaderPayloadVersion() {
1020 String getLastLeaderId() {
1025 private String lastValidLeaderId;
1026 private String lastLeaderId;
1028 BehaviorState capture(final RaftActorBehavior behavior) {
1029 if (behavior == null) {
1030 verify(lastValidLeaderId == null, "Null behavior with non-null last leader");
1031 return NULL_BEHAVIOR_STATE;
1034 lastLeaderId = behavior.getLeaderId();
1035 if (lastLeaderId != null) {
1036 lastValidLeaderId = lastLeaderId;
1039 return new SimpleBehaviorState(lastValidLeaderId, lastLeaderId, behavior);