Improve segmented journal actor metrics
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / RaftActor.java
1 /*
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.
4  *
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
8  */
9 package org.opendaylight.controller.cluster.raft;
10
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13
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;
24 import java.util.Map;
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;
62
63 /**
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>
68  *
69  * <p>
70  * RaftActor has 3 states and each state has a certain behavior associated
71  * with it. A Raft actor can behave as,
72  * <ul>
73  * <li> A Leader </li>
74  * <li> A Follower (or) </li>
75  * <li> A Candidate </li>
76  * </ul>
77  *
78  * <p>
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.
83  *
84  * <p>
85  * The current behavior of a RaftActor determines how election for leadership
86  * is initiated and how peer RaftActors react to request for votes.
87  *
88  * <p>
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.
93  *
94  * <p>
95  * The RaftActor uses akka-persistence to store it's replicated log.
96  * Furthermore through it's behaviors a Raft Actor determines
97  * <ul>
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>
101  * </ul>
102  */
103 public abstract class RaftActor extends AbstractUntypedPersistentActor {
104     private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50);
105
106     /**
107      * This context should NOT be passed directly to any other actor it is
108      * only to be consumed by the RaftActorBehaviors.
109      */
110     private final RaftActorContextImpl context;
111
112     private final DelegatingPersistentDataProvider delegatingPersistenceProvider;
113
114     private final PersistentDataProvider persistentProvider;
115
116     private final BehaviorStateTracker behaviorStateTracker = new BehaviorStateTracker();
117
118     private RaftActorRecoverySupport raftRecovery;
119
120     private RaftActorSnapshotMessageSupport snapshotSupport;
121
122     private RaftActorServerConfigurationSupport serverConfigurationSupport;
123
124     private boolean shuttingDown;
125
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) {
129
130         persistentProvider = new PersistentDataProvider(this);
131         delegatingPersistenceProvider = new RaftActorDelegatingPersistentDataProvider(null, persistentProvider);
132
133         context = new RaftActorContextImpl(getSelf(), getContext(), id,
134             new ElectionTermImpl(persistentProvider, id, LOG), -1, -1, peerAddresses,
135             configParams.isPresent() ? configParams.orElseThrow() : new DefaultConfigParamsImpl(),
136             delegatingPersistenceProvider, this::handleApplyState, LOG, this::executeInSelf);
137
138         context.setPayloadVersion(payloadVersion);
139         context.setReplicatedLog(ReplicatedLogImpl.newInstance(context));
140     }
141
142     @Override
143     public void preStart() throws Exception {
144         LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
145                 context.getConfigParams().getJournalRecoveryLogBatchSize());
146
147         super.preStart();
148
149         snapshotSupport = newRaftActorSnapshotMessageSupport();
150         serverConfigurationSupport = new RaftActorServerConfigurationSupport(this);
151     }
152
153     @Override
154     public void postStop() throws Exception {
155         context.close();
156         super.postStop();
157     }
158
159     @Override
160     protected void handleRecover(final Object message) {
161         if (raftRecovery == null) {
162             raftRecovery = newRaftActorRecoverySupport();
163         }
164
165         boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
166         if (recoveryComplete) {
167             onRecoveryComplete();
168
169             initializeBehavior();
170
171             raftRecovery = null;
172         }
173     }
174
175     protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
176         return new RaftActorRecoverySupport(context, getRaftActorRecoveryCohort());
177     }
178
179     @VisibleForTesting
180     void initializeBehavior() {
181         changeCurrentBehavior(new Follower(context));
182     }
183
184     @VisibleForTesting
185     @SuppressWarnings("checkstyle:IllegalCatch")
186     protected void changeCurrentBehavior(final RaftActorBehavior newBehavior) {
187         final RaftActorBehavior currentBehavior = getCurrentBehavior();
188         if (currentBehavior != null) {
189             try {
190                 currentBehavior.close();
191             } catch (Exception e) {
192                 LOG.warn("{}: Error closing behavior {}", persistence(), currentBehavior, e);
193             }
194         }
195
196         final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
197         setCurrentBehavior(newBehavior);
198         handleBehaviorChange(state, newBehavior);
199     }
200
201     /**
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
205      *
206      * @param message Incoming command message
207      */
208     protected void handleNonRaftCommand(final Object message) {
209         unhandled(message);
210     }
211
212     /**
213      * Handles a message.
214      *
215      * @deprecated This method is not final for testing purposes. DO NOT OVERRIDE IT, override
216      *             {@link #handleNonRaftCommand(Object)} instead.
217      */
218     @Deprecated
219     @Override
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())) {
223             return;
224         }
225         if (snapshotSupport.handleSnapshotMessage(message, getSender())) {
226             return;
227         }
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());
235
236                 context.getSnapshotManager().trimLog(context.getLastApplied());
237             }
238
239             possiblyHandleBehaviorMessage(message);
240         } else if (message instanceof ApplyJournalEntries applyEntries) {
241             LOG.debug("{}: Persisting ApplyJournalEntries with index={}", persistenceId(), applyEntries.getToIndex());
242
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) {
249             captureSnapshot();
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) {
255             onShutDown();
256         } else if (message instanceof Runnable runnable) {
257             runnable.run();
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());
269             } else {
270                 handleNonRaftCommand(message);
271             }
272         }
273     }
274
275     private void onRequestLeadership(final RequestLeadership message) {
276         LOG.debug("{}: onRequestLeadership {}", persistenceId(), message);
277         if (!isLeader()) {
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());
285             return;
286         }
287
288         final String requestedFollowerId = message.getRequestedFollowerId();
289         final ActorRef replyTo = message.getReplyTo();
290         initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
291             @Override
292             public void onSuccess(final ActorRef raftActorRef) {
293                 // sanity check
294                 if (!requestedFollowerId.equals(getLeaderId())) {
295                     onFailure(raftActorRef);
296                 }
297
298                 LOG.debug("{}: Leadership transferred successfully to {}", persistenceId(), requestedFollowerId);
299                 replyTo.tell(new Status.Success(null), getSelf());
300             }
301
302             @Override
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")),
309                         getSelf());
310             }
311         }, message.getRequestedFollowerId(), RaftActorLeadershipTransferCohort.USE_DEFAULT_LEADER_TIMEOUT);
312     }
313
314     private boolean possiblyHandleBehaviorMessage(final Object message) {
315         final RaftActorBehavior currentBehavior = getCurrentBehavior();
316         final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
317
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);
324             return true;
325         }
326
327         return false;
328     }
329
330     private void initiateLeadershipTransfer(final RaftActorLeadershipTransferCohort.OnComplete onComplete,
331             final @Nullable String followerId, final long newLeaderTimeoutInMillis) {
332         LOG.debug("{}: Initiating leader transfer", persistenceId());
333
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() {
339                 @Override
340                 public void onSuccess(final ActorRef raftActorRef) {
341                     context.setRaftActorLeadershipTransferCohort(null);
342                 }
343
344                 @Override
345                 public void onFailure(final ActorRef raftActorRef) {
346                     context.setRaftActorLeadershipTransferCohort(null);
347                 }
348             });
349
350             leadershipTransferInProgress.addOnComplete(onComplete);
351
352             context.setRaftActorLeadershipTransferCohort(leadershipTransferInProgress);
353             leadershipTransferInProgress.init();
354
355         } else {
356             LOG.debug("{}: prior leader transfer in progress - adding callback", persistenceId());
357             leadershipTransferInProgress.addOnComplete(onComplete);
358         }
359     }
360
361     private void onShutDown() {
362         LOG.debug("{}: onShutDown", persistenceId());
363
364         if (shuttingDown) {
365             return;
366         }
367
368         shuttingDown = true;
369
370         final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
371         switch (currentBehavior.state()) {
372             case Leader:
373             case PreLeader:
374                 // Fall-through to more work
375                 break;
376             default:
377                 // For non-leaders shutdown is a no-op
378                 self().tell(PoisonPill.getInstance(), self());
379                 return;
380         }
381
382         if (context.hasFollowers()) {
383             initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
384                 @Override
385                 public void onSuccess(final ActorRef raftActorRef) {
386                     LOG.debug("{}: leader transfer succeeded - sending PoisonPill", persistenceId());
387                     raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
388                 }
389
390                 @Override
391                 public void onFailure(final ActorRef raftActorRef) {
392                     LOG.debug("{}: leader transfer failed - sending PoisonPill", persistenceId());
393                     raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
394                 }
395             }, null, TimeUnit.MILLISECONDS.convert(2, TimeUnit.SECONDS));
396         } else {
397             pauseLeader(new TimedRunnable(context.getConfigParams().getElectionTimeOutInterval(), this) {
398                 @Override
399                 protected void doRun() {
400                     self().tell(PoisonPill.getInstance(), self());
401                 }
402
403                 @Override
404                 protected void doCancel() {
405                     self().tell(PoisonPill.getInstance(), self());
406                 }
407             });
408         }
409     }
410
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.orElseThrow().tell(newLeaderStateChanged(getId(), null,
417                 getCurrentBehavior().getLeaderPayloadVersion()), getSelf());
418         }
419     }
420
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()));
428             } else {
429                 LOG.warn("Switching to behavior : {} - not supported", newState);
430             }
431         }
432     }
433
434     private void switchBehavior(final BehaviorState oldBehaviorState, final RaftActorBehavior nextBehavior) {
435         setCurrentBehavior(nextBehavior);
436         handleBehaviorChange(oldBehaviorState, nextBehavior);
437     }
438
439     @VisibleForTesting
440     RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
441         return new RaftActorSnapshotMessageSupport(context, getRaftActorSnapshotCohort());
442     }
443
444     private void onGetOnDemandRaftStats() {
445         // Debugging message to retrieve raft stats.
446
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() : "");
452         }
453
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());
474
475         ReplicatedLogEntry lastLogEntry = replicatedLog().last();
476         if (lastLogEntry != null) {
477             builder.lastLogIndex(lastLogEntry.getIndex());
478             builder.lastLogTerm(lastLogEntry.getTerm());
479         }
480
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()));
489         }
490
491         sender().tell(builder.build(), self());
492
493     }
494
495     protected OnDemandRaftState.AbstractBuilder<?, ?> newOnDemandRaftStateBuilder() {
496         return OnDemandRaftState.builder();
497     }
498
499     private void handleBehaviorChange(final BehaviorState oldBehaviorState, final RaftActorBehavior currentBehavior) {
500         RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
501
502         if (oldBehavior != currentBehavior) {
503             onStateChanged();
504         }
505
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();
509
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.orElseThrow().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
516                         currentBehavior.getLeaderPayloadVersion()), getSelf());
517             }
518
519             onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
520
521             RaftActorLeadershipTransferCohort leadershipTransferInProgress =
522                     context.getRaftActorLeadershipTransferCohort();
523             if (leadershipTransferInProgress != null) {
524                 leadershipTransferInProgress.onNewLeader(currentBehavior.getLeaderId());
525             }
526
527             serverConfigurationSupport.onNewLeader(currentBehavior.getLeaderId());
528         }
529
530         if (roleChangeNotifier.isPresent()
531                 && (oldBehavior == null || oldBehavior.state() != currentBehavior.state())) {
532             roleChangeNotifier.orElseThrow().tell(new RoleChanged(getId(), oldBehaviorStateName ,
533                     currentBehavior.state().name()), getSelf());
534         }
535     }
536
537     private void handleApplyState(final ApplyState applyState) {
538         long startTime = System.nanoTime();
539
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);
544         }
545
546         if (!(payload instanceof NoopPayload) && !(payload instanceof ServerConfigurationPayload)) {
547             applyState(applyState.getClientActor(), applyState.getIdentifier(), payload);
548         }
549
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);
554         }
555
556         // Send the ApplyState message back to self to handle further processing asynchronously.
557         self().tell(applyState, self());
558     }
559
560     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
561             final short leaderPayloadVersion) {
562         return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
563     }
564
565     @Override
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();
573     }
574
575     /**
576      * Persists the given Payload in the journal and replicates to any followers. After successful completion,
577      * {@link #applyState(ActorRef, Identifier, Object)} is notified.
578      *
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.
584      */
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);
591
592         LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
593
594         final RaftActorContext raftContext = getRaftActorContext();
595
596         boolean wasAppended = replicatedLog().appendAndPersist(replicatedLogEntry, persistedLogEntry -> {
597             // Clear the persistence pending flag in the log entry.
598             persistedLogEntry.setPersistencePending(false);
599
600             if (!hasFollowers()) {
601                 // Increment the Commit Index and the Last Applied values
602                 raftContext.setCommitIndex(persistedLogEntry.getIndex());
603                 raftContext.setLastApplied(persistedLogEntry.getIndex());
604
605                 // Apply the state immediately.
606                 handleApplyState(new ApplyState(clientActor, identifier, persistedLogEntry));
607
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());
611
612             } else {
613                 context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry);
614
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);
619             }
620         }, true);
621
622         if (wasAppended && hasFollowers()) {
623             // Send log entry for replication.
624             getCurrentBehavior().handleMessage(getSelf(),
625                 new Replicate(replicatedLogEntry.getIndex(), !batchHint, clientActor, identifier));
626         }
627     }
628
629     private ReplicatedLog replicatedLog() {
630         return context.getReplicatedLog();
631     }
632
633     protected String getId() {
634         return context.getId();
635     }
636
637     @VisibleForTesting
638     void setCurrentBehavior(final RaftActorBehavior behavior) {
639         context.setCurrentBehavior(behavior);
640     }
641
642     protected RaftActorBehavior getCurrentBehavior() {
643         return context.getCurrentBehavior();
644     }
645
646     /**
647      * Derived actors can call the isLeader method to check if the current
648      * RaftActor is the Leader or not.
649      *
650      * @return true it this RaftActor is a Leader false otherwise
651      */
652     protected boolean isLeader() {
653         return context.getId().equals(getCurrentBehavior().getLeaderId());
654     }
655
656     protected final boolean isLeaderActive() {
657         return getRaftState() != RaftState.IsolatedLeader && getRaftState() != RaftState.PreLeader
658                 && !shuttingDown && !isLeadershipTransferInProgress();
659     }
660
661     protected boolean isLeadershipTransferInProgress() {
662         RaftActorLeadershipTransferCohort leadershipTransferInProgress = context.getRaftActorLeadershipTransferCohort();
663         return leadershipTransferInProgress != null && leadershipTransferInProgress.isTransferring();
664     }
665
666     /**
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
670      *
671      * @return A reference to the leader if known, null otherwise
672      */
673     public ActorSelection getLeader() {
674         String leaderAddress = getLeaderAddress();
675
676         if (leaderAddress == null) {
677             return null;
678         }
679
680         return context.actorSelection(leaderAddress);
681     }
682
683     /**
684      * Returns the id of the current leader.
685      *
686      * @return the current leader's id
687      */
688     protected final String getLeaderId() {
689         return getCurrentBehavior().getLeaderId();
690     }
691
692     @VisibleForTesting
693     protected final RaftState getRaftState() {
694         return getCurrentBehavior().state();
695     }
696
697     protected Long getCurrentTerm() {
698         return context.getTermInformation().getCurrentTerm();
699     }
700
701     protected RaftActorContext getRaftActorContext() {
702         return context;
703     }
704
705     protected void updateConfigParams(final ConfigParams configParams) {
706
707         // obtain the RaftPolicy for oldConfigParams and the updated one.
708         String oldRaftPolicy = context.getConfigParams().getCustomRaftPolicyImplementationClass();
709         String newRaftPolicy = configParams.getCustomRaftPolicyImplementationClass();
710
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();
722
723                 LOG.debug("{}: Re-initializing to Follower with previous leaderId {}", persistenceId(),
724                         previousLeaderId);
725
726                 changeCurrentBehavior(new Follower(context, previousLeaderId, previousLeaderPayloadVersion));
727             } else {
728                 initializeBehavior();
729             }
730         }
731     }
732
733     public final DataPersistenceProvider persistence() {
734         return delegatingPersistenceProvider.getDelegate();
735     }
736
737     public void setPersistence(final DataPersistenceProvider provider) {
738         delegatingPersistenceProvider.setDelegate(provider);
739     }
740
741     protected void setPersistence(final boolean persistent) {
742         DataPersistenceProvider currentPersistence = persistence();
743         if (persistent && (currentPersistence == null || !currentPersistence.isRecoveryApplicable())) {
744             setPersistence(new PersistentDataProvider(this));
745
746             if (getCurrentBehavior() != null) {
747                 LOG.info("{}: Persistence has been enabled - capturing snapshot", persistenceId());
748                 captureSnapshot();
749             }
750         } else if (!persistent && (currentPersistence == null || currentPersistence.isRecoveryApplicable())) {
751             setPersistence(new NonPersistentDataProvider(this) {
752                 /*
753                  * The way snapshotting works is,
754                  * <ol>
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.
761                  * </ol>
762                  */
763                 @Override
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());
769                 }
770             });
771         }
772     }
773
774     /**
775      * setPeerAddress sets the address of a known peer at a later time.
776      *
777      * <p>
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
782      *
783      * <p>
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.
786      */
787     protected void setPeerAddress(final String peerId, final String peerAddress) {
788         context.setPeerAddress(peerId, peerAddress);
789     }
790
791     /**
792      * The applyState method will be called by the RaftActor when some data
793      * needs to be applied to the actor's state.
794      *
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
799      *                    recovery.
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
804      *                    recovery
805      * @param data        A piece of data that was persisted by the persistData call.
806      *                    This should NEVER be null.
807      */
808     protected abstract void applyState(ActorRef clientActor, Identifier identifier, Object data);
809
810     /**
811      * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
812      */
813     protected abstract @NonNull RaftActorRecoveryCohort getRaftActorRecoveryCohort();
814
815     /**
816      * This method is called when recovery is complete.
817      */
818     protected abstract void onRecoveryComplete();
819
820     /**
821      * Returns the RaftActorSnapshotCohort to participate in snapshot captures.
822      */
823     protected abstract @NonNull RaftActorSnapshotCohort getRaftActorSnapshotCohort();
824
825     /**
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
829      */
830     protected abstract void onStateChanged();
831
832     /**
833      * Notifier Actor for this RaftActor to notify when a role change happens.
834      *
835      * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
836      */
837     protected abstract Optional<ActorRef> getRoleChangeNotifier();
838
839     /**
840      * This method is called on the leader when a voting change operation completes.
841      */
842     protected void onVotingStateChangeComplete() {
843     }
844
845     /**
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.
851      *
852      * <p>
853      * The default implementation immediately runs the operation.
854      *
855      * @param operation the operation to run
856      */
857     protected void pauseLeader(final Runnable operation) {
858         operation.run();
859     }
860
861     /**
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.
864      *
865      * <p>
866      * Note this method can be invoked even before the operation supplied to {@link #pauseLeader(Runnable)} is invoked.
867      */
868     protected void unpauseLeader() {
869
870     }
871
872     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
873     }
874
875     private String getLeaderAddress() {
876         if (isLeader()) {
877             return getSelf().path().toString();
878         }
879         String leaderId = getLeaderId();
880         if (leaderId == null) {
881             return null;
882         }
883         String peerAddress = context.getPeerAddress(leaderId);
884         LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}", persistenceId(), leaderId, peerAddress);
885
886         return peerAddress;
887     }
888
889     protected boolean hasFollowers() {
890         return getRaftActorContext().hasFollowers();
891     }
892
893     private void captureSnapshot() {
894         SnapshotManager snapshotManager = context.getSnapshotManager();
895
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);
900
901             snapshotManager.captureWithForcedTrim(replicatedLog().last(), idx);
902         }
903     }
904
905     /**
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.
908      */
909     void becomeNonVoting() {
910         if (isLeader()) {
911             initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
912                 @Override
913                 public void onSuccess(final ActorRef raftActorRef) {
914                     LOG.debug("{}: leader transfer succeeded after change to non-voting", persistenceId());
915                     ensureFollowerState();
916                 }
917
918                 @Override
919                 public void onFailure(final ActorRef raftActorRef) {
920                     LOG.debug("{}: leader transfer failed after change to non-voting", persistenceId());
921                     ensureFollowerState();
922                 }
923
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();
929                     }
930                 }
931             }, null, RaftActorLeadershipTransferCohort.USE_DEFAULT_LEADER_TIMEOUT);
932         }
933     }
934
935     /**
936      * A point-in-time capture of {@link RaftActorBehavior} state critical for transitioning between behaviors.
937      */
938     private abstract static class BehaviorState implements Immutable {
939         @Nullable abstract RaftActorBehavior getBehavior();
940
941         @Nullable abstract String getLastValidLeaderId();
942
943         @Nullable abstract String getLastLeaderId();
944
945         abstract short getLeaderPayloadVersion();
946     }
947
948     /**
949      * A {@link BehaviorState} corresponding to non-null {@link RaftActorBehavior} state.
950      */
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;
956
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();
963         }
964
965         @Override
966         RaftActorBehavior getBehavior() {
967             return behavior;
968         }
969
970         @Override
971         String getLastValidLeaderId() {
972             return lastValidLeaderId;
973         }
974
975         @Override
976         short getLeaderPayloadVersion() {
977             return leaderPayloadVersion;
978         }
979
980         @Override
981         String getLastLeaderId() {
982             return lastLeaderId;
983         }
984     }
985
986     /**
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
991      */
992     private static final class BehaviorStateTracker {
993         /**
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.
996          */
997         private static final BehaviorState NULL_BEHAVIOR_STATE = new BehaviorState() {
998             @Override
999             RaftActorBehavior getBehavior() {
1000                 return null;
1001             }
1002
1003             @Override
1004             String getLastValidLeaderId() {
1005                 return null;
1006             }
1007
1008             @Override
1009             short getLeaderPayloadVersion() {
1010                 return -1;
1011             }
1012
1013             @Override
1014             String getLastLeaderId() {
1015                 return null;
1016             }
1017         };
1018
1019         private String lastValidLeaderId;
1020         private String lastLeaderId;
1021
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;
1026             }
1027
1028             lastLeaderId = behavior.getLeaderId();
1029             if (lastLeaderId != null) {
1030                 lastValidLeaderId = lastLeaderId;
1031             }
1032
1033             return new SimpleBehaviorState(lastValidLeaderId, lastLeaderId, behavior);
1034         }
1035     }
1036 }