e3fa649ab15294ae16d87ba9b368375020f27e91
[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
10 package org.opendaylight.controller.cluster.raft;
11
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.PoisonPill;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Optional;
17 import com.google.common.base.Preconditions;
18 import com.google.common.base.Verify;
19 import com.google.common.collect.Lists;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import org.apache.commons.lang3.time.DurationFormatUtils;
29 import org.opendaylight.controller.cluster.DataPersistenceProvider;
30 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
31 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
32 import org.opendaylight.controller.cluster.PersistentDataProvider;
33 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
34 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
35 import org.opendaylight.controller.cluster.notifications.RoleChanged;
36 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
37 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
38 import org.opendaylight.controller.cluster.raft.base.messages.LeaderTransitioning;
39 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
40 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
41 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
42 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
43 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
44 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
45 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
46 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
47 import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
48 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
49 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
50 import org.opendaylight.controller.cluster.raft.client.messages.Shutdown;
51 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
52 import org.opendaylight.controller.cluster.raft.persisted.NoopPayload;
53 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
54 import org.opendaylight.yangtools.concepts.Identifier;
55 import org.opendaylight.yangtools.concepts.Immutable;
56
57 /**
58  * RaftActor encapsulates a state machine that needs to be kept synchronized
59  * in a cluster. It implements the RAFT algorithm as described in the paper
60  * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
61  * In Search of an Understandable Consensus Algorithm</a>
62  *
63  * <p>
64  * RaftActor has 3 states and each state has a certain behavior associated
65  * with it. A Raft actor can behave as,
66  * <ul>
67  * <li> A Leader </li>
68  * <li> A Follower (or) </li>
69  * <li> A Candidate </li>
70  * </ul>
71  *
72  * <p>
73  * A RaftActor MUST be a Leader in order to accept requests from clients to
74  * change the state of it's encapsulated state machine. Once a RaftActor becomes
75  * a Leader it is also responsible for ensuring that all followers ultimately
76  * have the same log and therefore the same state machine as itself.
77  *
78  * <p>
79  * The current behavior of a RaftActor determines how election for leadership
80  * is initiated and how peer RaftActors react to request for votes.
81  *
82  * <p>
83  * Each RaftActor also needs to know the current election term. It uses this
84  * information for a couple of things. One is to simply figure out who it
85  * voted for in the last election. Another is to figure out if the message
86  * it received to update it's state is stale.
87  *
88  * <p>
89  * The RaftActor uses akka-persistence to store it's replicated log.
90  * Furthermore through it's behaviors a Raft Actor determines
91  * <ul>
92  * <li> when a log entry should be persisted </li>
93  * <li> when a log entry should be applied to the state machine (and) </li>
94  * <li> when a snapshot should be saved </li>
95  * </ul>
96  */
97 public abstract class RaftActor extends AbstractUntypedPersistentActor {
98
99     private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
100
101     /**
102      * This context should NOT be passed directly to any other actor it is
103      * only to be consumed by the RaftActorBehaviors.
104      */
105     private final RaftActorContextImpl context;
106
107     private final DelegatingPersistentDataProvider delegatingPersistenceProvider;
108
109     private final PersistentDataProvider persistentProvider;
110
111     private final BehaviorStateTracker behaviorStateTracker = new BehaviorStateTracker();
112
113     private RaftActorRecoverySupport raftRecovery;
114
115     private RaftActorSnapshotMessageSupport snapshotSupport;
116
117     private RaftActorServerConfigurationSupport serverConfigurationSupport;
118
119     private RaftActorLeadershipTransferCohort leadershipTransferInProgress;
120
121     private boolean shuttingDown;
122
123     protected RaftActor(String id, Map<String, String> peerAddresses,
124          Optional<ConfigParams> configParams, short payloadVersion) {
125
126         persistentProvider = new PersistentDataProvider(this);
127         delegatingPersistenceProvider = new RaftActorDelegatingPersistentDataProvider(null, persistentProvider);
128
129         context = new RaftActorContextImpl(this.getSelf(),
130             this.getContext(), id, new ElectionTermImpl(persistentProvider, id, LOG),
131             -1, -1, peerAddresses,
132             configParams.isPresent() ? configParams.get() : new DefaultConfigParamsImpl(),
133             delegatingPersistenceProvider, LOG);
134
135         context.setPayloadVersion(payloadVersion);
136         context.setReplicatedLog(ReplicatedLogImpl.newInstance(context));
137     }
138
139     @Override
140     public void preStart() throws Exception {
141         LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
142                 context.getConfigParams().getJournalRecoveryLogBatchSize());
143
144         super.preStart();
145
146         snapshotSupport = newRaftActorSnapshotMessageSupport();
147         serverConfigurationSupport = new RaftActorServerConfigurationSupport(this);
148     }
149
150     @Override
151     public void postStop() {
152         context.close();
153         super.postStop();
154     }
155
156     @Override
157     protected void handleRecover(Object message) {
158         if (raftRecovery == null) {
159             raftRecovery = newRaftActorRecoverySupport();
160         }
161
162         boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
163         if (recoveryComplete) {
164             onRecoveryComplete();
165
166             initializeBehavior();
167
168             raftRecovery = null;
169         }
170     }
171
172     protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
173         return new RaftActorRecoverySupport(context, getRaftActorRecoveryCohort());
174     }
175
176     @VisibleForTesting
177     void initializeBehavior() {
178         changeCurrentBehavior(new Follower(context));
179     }
180
181     @VisibleForTesting
182     @SuppressWarnings("checkstyle:IllegalCatch")
183     protected void changeCurrentBehavior(RaftActorBehavior newBehavior) {
184         final RaftActorBehavior currentBehavior = getCurrentBehavior();
185         if (currentBehavior != null) {
186             try {
187                 currentBehavior.close();
188             } catch (Exception e) {
189                 LOG.warn("{}: Error closing behavior {}", persistence(), currentBehavior, e);
190             }
191         }
192
193         final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
194         setCurrentBehavior(newBehavior);
195         handleBehaviorChange(state, newBehavior);
196     }
197
198     /**
199      * Method exposed for subclasses to plug-in their logic. This method is invoked by {@link #handleCommand(Object)}
200      * for messages which are not handled by this class. Subclasses overriding this class should fall back to this
201      * implementation for messages which they do not handle
202      *
203      * @param message Incoming command message
204      */
205     protected void handleNonRaftCommand(final Object message) {
206         unhandled(message);
207     }
208
209     /**
210      * Handles a message.
211      *
212      * @deprecated This method is not final for testing purposes. DO NOT OVERRIDE IT, override
213      * {@link #handleNonRaftCommand(Object)} instead.
214      */
215     @Deprecated
216     @Override
217     // FIXME: make this method final once our unit tests do not need to override it
218     protected void handleCommand(final Object message) {
219         if (serverConfigurationSupport.handleMessage(message, getSender())) {
220             return;
221         }
222         if (snapshotSupport.handleSnapshotMessage(message, getSender())) {
223             return;
224         }
225
226         if (message instanceof ApplyState) {
227             ApplyState applyState = (ApplyState) message;
228
229             long startTime = System.nanoTime();
230
231             if (LOG.isDebugEnabled()) {
232                 LOG.debug("{}: Applying state for log index {} data {}",
233                     persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
234                     applyState.getReplicatedLogEntry().getData());
235             }
236
237             if (!(applyState.getReplicatedLogEntry().getData() instanceof NoopPayload)) {
238                 applyState(applyState.getClientActor(), applyState.getIdentifier(),
239                     applyState.getReplicatedLogEntry().getData());
240             }
241
242             long elapsedTime = System.nanoTime() - startTime;
243             if (elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS) {
244                 LOG.debug("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
245                         TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
246             }
247
248             if (!hasFollowers()) {
249                 // for single node, the capture should happen after the apply state
250                 // as we delete messages from the persistent journal which have made it to the snapshot
251                 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
252                 // and recovery shows data missing
253                 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
254
255                 context.getSnapshotManager().trimLog(context.getLastApplied());
256             }
257
258             // Send it to the current behavior - some behaviors like PreLeader need to be notified of ApplyState.
259             possiblyHandleBehaviorMessage(message);
260
261         } else if (message instanceof ApplyJournalEntries) {
262             ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
263             LOG.debug("{}: Persisting ApplyJournalEntries with index={}", persistenceId(), applyEntries.getToIndex());
264
265             persistence().persist(applyEntries, NoopProcedure.instance());
266
267         } else if (message instanceof FindLeader) {
268             getSender().tell(
269                 new FindLeaderReply(getLeaderAddress()),
270                 getSelf()
271             );
272         } else if (message instanceof GetOnDemandRaftState) {
273             onGetOnDemandRaftStats();
274         } else if (message instanceof InitiateCaptureSnapshot) {
275             captureSnapshot();
276         } else if (message instanceof SwitchBehavior) {
277             switchBehavior((SwitchBehavior) message);
278         } else if (message instanceof LeaderTransitioning) {
279             onLeaderTransitioning();
280         } else if (message instanceof Shutdown) {
281             onShutDown();
282         } else if (message instanceof Runnable) {
283             ((Runnable)message).run();
284         } else if (message instanceof NoopPayload) {
285             persistData(null, null, (NoopPayload)message);
286         } else if (!possiblyHandleBehaviorMessage(message)) {
287             handleNonRaftCommand(message);
288         }
289     }
290
291     private boolean possiblyHandleBehaviorMessage(final Object message) {
292         final RaftActorBehavior currentBehavior = getCurrentBehavior();
293         final BehaviorState state = behaviorStateTracker.capture(currentBehavior);
294
295         // A behavior indicates that it processed the change by returning a reference to the next behavior
296         // to be used. A null return indicates it has not processed the message and we should be passing it to
297         // the subclass for handling.
298         final RaftActorBehavior nextBehavior = currentBehavior.handleMessage(getSender(), message);
299         if (nextBehavior != null) {
300             switchBehavior(state, nextBehavior);
301             return true;
302         }
303
304         return false;
305     }
306
307     private void initiateLeadershipTransfer(final RaftActorLeadershipTransferCohort.OnComplete onComplete) {
308         LOG.debug("{}: Initiating leader transfer", persistenceId());
309
310         if (leadershipTransferInProgress == null) {
311             leadershipTransferInProgress = new RaftActorLeadershipTransferCohort(this);
312             leadershipTransferInProgress.addOnComplete(new RaftActorLeadershipTransferCohort.OnComplete() {
313                 @Override
314                 public void onSuccess(ActorRef raftActorRef) {
315                     leadershipTransferInProgress = null;
316                 }
317
318                 @Override
319                 public void onFailure(ActorRef raftActorRef) {
320                     leadershipTransferInProgress = null;
321                 }
322             });
323
324             leadershipTransferInProgress.addOnComplete(onComplete);
325             leadershipTransferInProgress.init();
326         } else {
327             LOG.debug("{}: prior leader transfer in progress - adding callback", persistenceId());
328             leadershipTransferInProgress.addOnComplete(onComplete);
329         }
330     }
331
332     private void onShutDown() {
333         LOG.debug("{}: onShutDown", persistenceId());
334
335         if (shuttingDown) {
336             return;
337         }
338
339         shuttingDown = true;
340
341         final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
342         if (currentBehavior.state() != RaftState.Leader) {
343             // For non-leaders shutdown is a no-op
344             self().tell(PoisonPill.getInstance(), self());
345             return;
346         }
347
348         if (context.hasFollowers()) {
349             initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
350                 @Override
351                 public void onSuccess(ActorRef raftActorRef) {
352                     LOG.debug("{}: leader transfer succeeded - sending PoisonPill", persistenceId());
353                     raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
354                 }
355
356                 @Override
357                 public void onFailure(ActorRef raftActorRef) {
358                     LOG.debug("{}: leader transfer failed - sending PoisonPill", persistenceId());
359                     raftActorRef.tell(PoisonPill.getInstance(), raftActorRef);
360                 }
361             });
362         } else {
363             pauseLeader(new TimedRunnable(context.getConfigParams().getElectionTimeOutInterval(), this) {
364                 @Override
365                 protected void doRun() {
366                     self().tell(PoisonPill.getInstance(), self());
367                 }
368
369                 @Override
370                 protected void doCancel() {
371                     self().tell(PoisonPill.getInstance(), self());
372                 }
373             });
374         }
375     }
376
377     private void onLeaderTransitioning() {
378         LOG.debug("{}: onLeaderTransitioning", persistenceId());
379         Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
380         if (getRaftState() == RaftState.Follower && roleChangeNotifier.isPresent()) {
381             roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), null,
382                 getCurrentBehavior().getLeaderPayloadVersion()), getSelf());
383         }
384     }
385
386     private void switchBehavior(SwitchBehavior message) {
387         if (!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
388             RaftState newState = message.getNewState();
389             if ( newState == RaftState.Leader || newState == RaftState.Follower) {
390                 switchBehavior(behaviorStateTracker.capture(getCurrentBehavior()),
391                     AbstractRaftActorBehavior.createBehavior(context, message.getNewState()));
392                 getRaftActorContext().getTermInformation().updateAndPersist(message.getNewTerm(), "");
393             } else {
394                 LOG.warn("Switching to behavior : {} - not supported", newState);
395             }
396         }
397     }
398
399     private void switchBehavior(final BehaviorState oldBehaviorState, final RaftActorBehavior nextBehavior) {
400         setCurrentBehavior(nextBehavior);
401         handleBehaviorChange(oldBehaviorState, nextBehavior);
402     }
403
404     @VisibleForTesting
405     RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
406         return new RaftActorSnapshotMessageSupport(context, getRaftActorSnapshotCohort());
407     }
408
409     private void onGetOnDemandRaftStats() {
410         // Debugging message to retrieve raft stats.
411
412         Map<String, String> peerAddresses = new HashMap<>();
413         Map<String, Boolean> peerVotingStates = new HashMap<>();
414         for (PeerInfo info: context.getPeers()) {
415             peerVotingStates.put(info.getId(), info.isVoting());
416             peerAddresses.put(info.getId(), info.getAddress() != null ? info.getAddress() : "");
417         }
418
419         final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
420         OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
421                 .commitIndex(context.getCommitIndex())
422                 .currentTerm(context.getTermInformation().getCurrentTerm())
423                 .inMemoryJournalDataSize(replicatedLog().dataSize())
424                 .inMemoryJournalLogSize(replicatedLog().size())
425                 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
426                 .lastApplied(context.getLastApplied())
427                 .lastIndex(replicatedLog().lastIndex())
428                 .lastTerm(replicatedLog().lastTerm())
429                 .leader(getLeaderId())
430                 .raftState(currentBehavior.state().toString())
431                 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
432                 .snapshotIndex(replicatedLog().getSnapshotIndex())
433                 .snapshotTerm(replicatedLog().getSnapshotTerm())
434                 .votedFor(context.getTermInformation().getVotedFor())
435                 .isVoting(context.isVotingMember())
436                 .peerAddresses(peerAddresses)
437                 .peerVotingStates(peerVotingStates)
438                 .customRaftPolicyClassName(context.getConfigParams().getCustomRaftPolicyImplementationClass());
439
440         ReplicatedLogEntry lastLogEntry = replicatedLog().last();
441         if (lastLogEntry != null) {
442             builder.lastLogIndex(lastLogEntry.getIndex());
443             builder.lastLogTerm(lastLogEntry.getTerm());
444         }
445
446         if (getCurrentBehavior() instanceof AbstractLeader) {
447             AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
448             Collection<String> followerIds = leader.getFollowerIds();
449             List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
450             for (String id: followerIds) {
451                 final FollowerLogInformation info = leader.getFollower(id);
452                 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
453                         info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity()),
454                         context.getPeerInfo(info.getId()).isVoting()));
455             }
456
457             builder.followerInfoList(followerInfoList);
458         }
459
460         sender().tell(builder.build(), self());
461
462     }
463
464     private void handleBehaviorChange(BehaviorState oldBehaviorState, RaftActorBehavior currentBehavior) {
465         RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
466
467         if (oldBehavior != currentBehavior) {
468             onStateChanged();
469         }
470
471         String lastLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastLeaderId();
472         String lastValidLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastValidLeaderId();
473         String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
474
475         // it can happen that the state has not changed but the leader has changed.
476         Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
477         if (!Objects.equals(lastLeaderId, currentBehavior.getLeaderId())
478                 || oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
479             if (roleChangeNotifier.isPresent()) {
480                 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
481                         currentBehavior.getLeaderPayloadVersion()), getSelf());
482             }
483
484             onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
485
486             if (leadershipTransferInProgress != null) {
487                 leadershipTransferInProgress.onNewLeader(currentBehavior.getLeaderId());
488             }
489
490             serverConfigurationSupport.onNewLeader(currentBehavior.getLeaderId());
491         }
492
493         if (roleChangeNotifier.isPresent()
494                 && (oldBehavior == null || oldBehavior.state() != currentBehavior.state())) {
495             roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
496                     currentBehavior.state().name()), getSelf());
497         }
498     }
499
500     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
501         return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
502     }
503
504     @Override
505     public long snapshotSequenceNr() {
506         // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
507         // so that we can delete the persistent journal based on the saved sequence-number
508         // However , when akka replays the journal during recovery, it replays it from the sequence number when the
509         // snapshot was saved and not the number we saved. We would want to override it , by asking akka to use the
510         // last-sequence number known to us.
511         return context.getSnapshotManager().getLastSequenceNumber();
512     }
513
514     /**
515      * When a derived RaftActor needs to persist something it must call
516      * persistData.
517      */
518     protected final void persistData(final ActorRef clientActor, final Identifier identifier, final Payload data) {
519
520         ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
521             context.getReplicatedLog().lastIndex() + 1,
522             context.getTermInformation().getCurrentTerm(), data);
523
524         LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
525
526         final RaftActorContext raftContext = getRaftActorContext();
527
528         replicatedLog().appendAndPersist(replicatedLogEntry, replicatedLogEntry1 -> {
529             if (!hasFollowers()) {
530                 // Increment the Commit Index and the Last Applied values
531                 raftContext.setCommitIndex(replicatedLogEntry1.getIndex());
532                 raftContext.setLastApplied(replicatedLogEntry1.getIndex());
533
534                 // Apply the state immediately.
535                 self().tell(new ApplyState(clientActor, identifier, replicatedLogEntry1), self());
536
537                 // Send a ApplyJournalEntries message so that we write the fact that we applied
538                 // the state to durable storage
539                 self().tell(new ApplyJournalEntries(replicatedLogEntry1.getIndex()), self());
540
541             } else {
542                 context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry1);
543
544                 // Send message for replication
545                 getCurrentBehavior().handleMessage(getSelf(),
546                         new Replicate(clientActor, identifier, replicatedLogEntry1));
547             }
548         });
549     }
550
551     private ReplicatedLog replicatedLog() {
552         return context.getReplicatedLog();
553     }
554
555     protected String getId() {
556         return context.getId();
557     }
558
559     @VisibleForTesting
560     void setCurrentBehavior(RaftActorBehavior behavior) {
561         context.setCurrentBehavior(behavior);
562     }
563
564     protected RaftActorBehavior getCurrentBehavior() {
565         return context.getCurrentBehavior();
566     }
567
568     /**
569      * Derived actors can call the isLeader method to check if the current
570      * RaftActor is the Leader or not.
571      *
572      * @return true it this RaftActor is a Leader false otherwise
573      */
574     protected boolean isLeader() {
575         return context.getId().equals(getCurrentBehavior().getLeaderId());
576     }
577
578     protected final boolean isLeaderActive() {
579         return getRaftState() != RaftState.IsolatedLeader && getRaftState() != RaftState.PreLeader
580                 && !shuttingDown && !isLeadershipTransferInProgress();
581     }
582
583     private boolean isLeadershipTransferInProgress() {
584         return leadershipTransferInProgress != null && leadershipTransferInProgress.isTransferring();
585     }
586
587     /**
588      * Derived actor can call getLeader if they need a reference to the Leader.
589      * This would be useful for example in forwarding a request to an actor
590      * which is the leader
591      *
592      * @return A reference to the leader if known, null otherwise
593      */
594     public ActorSelection getLeader() {
595         String leaderAddress = getLeaderAddress();
596
597         if (leaderAddress == null) {
598             return null;
599         }
600
601         return context.actorSelection(leaderAddress);
602     }
603
604     /**
605      * Returns the id of the current leader.
606      *
607      * @return the current leader's id
608      */
609     protected final String getLeaderId() {
610         return getCurrentBehavior().getLeaderId();
611     }
612
613     @VisibleForTesting
614     protected final RaftState getRaftState() {
615         return getCurrentBehavior().state();
616     }
617
618     protected Long getCurrentTerm() {
619         return context.getTermInformation().getCurrentTerm();
620     }
621
622     protected RaftActorContext getRaftActorContext() {
623         return context;
624     }
625
626     protected void updateConfigParams(ConfigParams configParams) {
627
628         // obtain the RaftPolicy for oldConfigParams and the updated one.
629         String oldRaftPolicy = context.getConfigParams().getCustomRaftPolicyImplementationClass();
630         String newRaftPolicy = configParams.getCustomRaftPolicyImplementationClass();
631
632         LOG.debug("{}: RaftPolicy used with prev.config {}, RaftPolicy used with newConfig {}", persistenceId(),
633             oldRaftPolicy, newRaftPolicy);
634         context.setConfigParams(configParams);
635         if (!Objects.equals(oldRaftPolicy, newRaftPolicy)) {
636             // The RaftPolicy was modified. If the current behavior is Follower then re-initialize to Follower
637             // but transfer the previous leaderId so it doesn't immediately try to schedule an election. This
638             // avoids potential disruption. Otherwise, switch to Follower normally.
639             RaftActorBehavior behavior = getCurrentBehavior();
640             if (behavior != null && behavior.state() == RaftState.Follower) {
641                 String previousLeaderId = behavior.getLeaderId();
642                 short previousLeaderPayloadVersion = behavior.getLeaderPayloadVersion();
643
644                 LOG.debug("{}: Re-initializing to Follower with previous leaderId {}", persistenceId(),
645                         previousLeaderId);
646
647                 changeCurrentBehavior(new Follower(context, previousLeaderId, previousLeaderPayloadVersion));
648             } else {
649                 initializeBehavior();
650             }
651         }
652     }
653
654     public final DataPersistenceProvider persistence() {
655         return delegatingPersistenceProvider.getDelegate();
656     }
657
658     public void setPersistence(DataPersistenceProvider provider) {
659         delegatingPersistenceProvider.setDelegate(provider);
660     }
661
662     protected void setPersistence(boolean persistent) {
663         DataPersistenceProvider currentPersistence = persistence();
664         if (persistent && (currentPersistence == null || !currentPersistence.isRecoveryApplicable())) {
665             setPersistence(new PersistentDataProvider(this));
666
667             if (getCurrentBehavior() != null) {
668                 LOG.info("{}: Persistence has been enabled - capturing snapshot", persistenceId());
669                 captureSnapshot();
670             }
671         } else if (!persistent && (currentPersistence == null || currentPersistence.isRecoveryApplicable())) {
672             setPersistence(new NonPersistentDataProvider() {
673                 /**
674                  * The way snapshotting works is,
675                  * <ol>
676                  * <li> RaftActor calls createSnapshot on the Shard
677                  * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
678                  * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
679                  * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
680                  * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
681                  * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
682                  * </ol>
683                  */
684                 @Override
685                 public void saveSnapshot(Object object) {
686                     // Make saving Snapshot successful
687                     // Committing the snapshot here would end up calling commit in the creating state which would
688                     // be a state violation. That's why now we send a message to commit the snapshot.
689                     self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
690                 }
691             });
692         }
693     }
694
695     /**
696      * setPeerAddress sets the address of a known peer at a later time.
697      *
698      * <p>
699      * This is to account for situations where a we know that a peer
700      * exists but we do not know an address up-front. This may also be used in
701      * situations where a known peer starts off in a different location and we
702      * need to change it's address
703      *
704      * <p>
705      * Note that if the peerId does not match the list of peers passed to
706      * this actor during construction an IllegalStateException will be thrown.
707      */
708     protected void setPeerAddress(String peerId, String peerAddress) {
709         context.setPeerAddress(peerId, peerAddress);
710     }
711
712     /**
713      * The applyState method will be called by the RaftActor when some data
714      * needs to be applied to the actor's state.
715      *
716      * @param clientActor A reference to the client who sent this message. This
717      *                    is the same reference that was passed to persistData
718      *                    by the derived actor. clientActor may be null when
719      *                    the RaftActor is behaving as a follower or during
720      *                    recovery.
721      * @param identifier  The identifier of the persisted data. This is also
722      *                    the same identifier that was passed to persistData by
723      *                    the derived actor. identifier may be null when
724      *                    the RaftActor is behaving as a follower or during
725      *                    recovery
726      * @param data        A piece of data that was persisted by the persistData call.
727      *                    This should NEVER be null.
728      */
729     protected abstract void applyState(ActorRef clientActor, Identifier identifier, Object data);
730
731     /**
732      * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
733      */
734     @Nonnull
735     protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
736
737     /**
738      * This method is called when recovery is complete.
739      */
740     protected abstract void onRecoveryComplete();
741
742     /**
743      * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
744      */
745     @Nonnull
746     protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
747
748     /**
749      * This method will be called by the RaftActor when the state of the
750      * RaftActor changes. The derived actor can then use methods like
751      * isLeader or getLeader to do something useful
752      */
753     protected abstract void onStateChanged();
754
755     /**
756      * Notifier Actor for this RaftActor to notify when a role change happens.
757      *
758      * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
759      */
760     protected abstract Optional<ActorRef> getRoleChangeNotifier();
761
762     /**
763      * This method is called prior to operations such as leadership transfer and actor shutdown when the leader
764      * must pause or stop its duties. This method allows derived classes to gracefully pause or finish current
765      * work prior to performing the operation. On completion of any work, the run method must be called on the
766      * given Runnable to proceed with the given operation. <b>Important:</b> the run method must be called on
767      * this actor's thread dispatcher as as it modifies internal state.
768      *
769      * <p>
770      * The default implementation immediately runs the operation.
771      *
772      * @param operation the operation to run
773      */
774     protected void pauseLeader(Runnable operation) {
775         operation.run();
776     }
777
778     protected void onLeaderChanged(String oldLeader, String newLeader) {
779     }
780
781     private String getLeaderAddress() {
782         if (isLeader()) {
783             return getSelf().path().toString();
784         }
785         String leaderId = getLeaderId();
786         if (leaderId == null) {
787             return null;
788         }
789         String peerAddress = context.getPeerAddress(leaderId);
790         LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}", persistenceId(), leaderId, peerAddress);
791
792         return peerAddress;
793     }
794
795     protected boolean hasFollowers() {
796         return getRaftActorContext().hasFollowers();
797     }
798
799     private void captureSnapshot() {
800         SnapshotManager snapshotManager = context.getSnapshotManager();
801
802         if (!snapshotManager.isCapturing()) {
803             final long idx = getCurrentBehavior().getReplicatedToAllIndex();
804             LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
805                 replicatedLog().last(), idx);
806
807             snapshotManager.capture(replicatedLog().last(), idx);
808         }
809     }
810
811     /**
812      * Switch this member to non-voting status. This is a no-op for all behaviors except when we are the leader,
813      * in which case we need to step down.
814      */
815     void becomeNonVoting() {
816         if (isLeader()) {
817             initiateLeadershipTransfer(new RaftActorLeadershipTransferCohort.OnComplete() {
818                 @Override
819                 public void onSuccess(ActorRef raftActorRef) {
820                     LOG.debug("{}: leader transfer succeeded after change to non-voting", persistenceId());
821                     ensureFollowerState();
822                 }
823
824                 @Override
825                 public void onFailure(ActorRef raftActorRef) {
826                     LOG.debug("{}: leader transfer failed after change to non-voting", persistenceId());
827                     ensureFollowerState();
828                 }
829
830                 private void ensureFollowerState() {
831                     // Whether or not leadership transfer succeeded, we have to step down as leader and
832                     // switch to Follower so ensure that.
833                     if (getRaftState() != RaftState.Follower) {
834                         initializeBehavior();
835                     }
836                 }
837             });
838         }
839     }
840
841     /**
842      * A point-in-time capture of {@link RaftActorBehavior} state critical for transitioning between behaviors.
843      */
844     private abstract static class BehaviorState implements Immutable {
845         @Nullable abstract RaftActorBehavior getBehavior();
846
847         @Nullable abstract String getLastValidLeaderId();
848
849         @Nullable abstract String getLastLeaderId();
850
851         @Nullable abstract short getLeaderPayloadVersion();
852     }
853
854     /**
855      * A {@link BehaviorState} corresponding to non-null {@link RaftActorBehavior} state.
856      */
857     private static final class SimpleBehaviorState extends BehaviorState {
858         private final RaftActorBehavior behavior;
859         private final String lastValidLeaderId;
860         private final String lastLeaderId;
861         private final short leaderPayloadVersion;
862
863         SimpleBehaviorState(final String lastValidLeaderId, final String lastLeaderId,
864                 final RaftActorBehavior behavior) {
865             this.lastValidLeaderId = lastValidLeaderId;
866             this.lastLeaderId = lastLeaderId;
867             this.behavior = Preconditions.checkNotNull(behavior);
868             this.leaderPayloadVersion = behavior.getLeaderPayloadVersion();
869         }
870
871         @Override
872         RaftActorBehavior getBehavior() {
873             return behavior;
874         }
875
876         @Override
877         String getLastValidLeaderId() {
878             return lastValidLeaderId;
879         }
880
881         @Override
882         short getLeaderPayloadVersion() {
883             return leaderPayloadVersion;
884         }
885
886         @Override
887         String getLastLeaderId() {
888             return lastLeaderId;
889         }
890     }
891
892     /**
893      * Class tracking behavior-related information, which we need to keep around and pass across behavior switches.
894      * An instance is created for each RaftActor. It has two functions:
895      * - it keeps track of the last leader ID we have encountered since we have been created
896      * - it creates state capture needed to transition from one behavior to the next
897      */
898     private static final class BehaviorStateTracker {
899         /**
900          * A {@link BehaviorState} corresponding to null {@link RaftActorBehavior} state. Since null behavior is only
901          * allowed before we receive the first message, we know the leader ID to be null.
902          */
903         private static final BehaviorState NULL_BEHAVIOR_STATE = new BehaviorState() {
904             @Override
905             RaftActorBehavior getBehavior() {
906                 return null;
907             }
908
909             @Override
910             String getLastValidLeaderId() {
911                 return null;
912             }
913
914             @Override
915             short getLeaderPayloadVersion() {
916                 return -1;
917             }
918
919             @Override
920             String getLastLeaderId() {
921                 return null;
922             }
923         };
924
925         private String lastValidLeaderId;
926         private String lastLeaderId;
927
928         BehaviorState capture(final RaftActorBehavior behavior) {
929             if (behavior == null) {
930                 Verify.verify(lastValidLeaderId == null, "Null behavior with non-null last leader");
931                 return NULL_BEHAVIOR_STATE;
932             }
933
934             lastLeaderId = behavior.getLeaderId();
935             if (lastLeaderId != null) {
936                 lastValidLeaderId = lastLeaderId;
937             }
938
939             return new SimpleBehaviorState(lastValidLeaderId, lastLeaderId, behavior);
940         }
941     }
942
943 }