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