BUG-3381: Capture Snapshot on recovery if journal is not empty
[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.japi.Procedure;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Objects;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Supplier;
19 import com.google.common.collect.Lists;
20 import java.io.Serializable;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import org.apache.commons.lang3.time.DurationFormatUtils;
28 import org.opendaylight.controller.cluster.DataPersistenceProvider;
29 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
30 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
31 import org.opendaylight.controller.cluster.PersistentDataProvider;
32 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
33 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
34 import org.opendaylight.controller.cluster.notifications.RoleChanged;
35 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
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.Replicate;
39 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
40 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
41 import org.opendaylight.controller.cluster.raft.behaviors.DelegatingRaftActorBehavior;
42 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
43 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
44 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
45 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
46 import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
47 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
48 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
49 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * RaftActor encapsulates a state machine that needs to be kept synchronized
55  * in a cluster. It implements the RAFT algorithm as described in the paper
56  * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
57  * In Search of an Understandable Consensus Algorithm</a>
58  * <p/>
59  * RaftActor has 3 states and each state has a certain behavior associated
60  * with it. A Raft actor can behave as,
61  * <ul>
62  * <li> A Leader </li>
63  * <li> A Follower (or) </li>
64  * <li> A Candidate </li>
65  * </ul>
66  * <p/>
67  * <p/>
68  * A RaftActor MUST be a Leader in order to accept requests from clients to
69  * change the state of it's encapsulated state machine. Once a RaftActor becomes
70  * a Leader it is also responsible for ensuring that all followers ultimately
71  * have the same log and therefore the same state machine as itself.
72  * <p/>
73  * <p/>
74  * The current behavior of a RaftActor determines how election for leadership
75  * is initiated and how peer RaftActors react to request for votes.
76  * <p/>
77  * <p/>
78  * Each RaftActor also needs to know the current election term. It uses this
79  * information for a couple of things. One is to simply figure out who it
80  * voted for in the last election. Another is to figure out if the message
81  * it received to update it's state is stale.
82  * <p/>
83  * <p/>
84  * The RaftActor uses akka-persistence to store it's replicated log.
85  * Furthermore through it's behaviors a Raft Actor determines
86  * <p/>
87  * <ul>
88  * <li> when a log entry should be persisted </li>
89  * <li> when a log entry should be applied to the state machine (and) </li>
90  * <li> when a snapshot should be saved </li>
91  * </ul>
92  */
93 public abstract class RaftActor extends AbstractUntypedPersistentActor {
94
95     private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
96
97     protected final Logger LOG = LoggerFactory.getLogger(getClass());
98
99     /**
100      * The current state determines the current behavior of a RaftActor
101      * A Raft Actor always starts off in the Follower State
102      */
103     private final DelegatingRaftActorBehavior currentBehavior = new DelegatingRaftActorBehavior();
104
105     /**
106      * This context should NOT be passed directly to any other actor it is
107      * only to be consumed by the RaftActorBehaviors
108      */
109     private final RaftActorContextImpl context;
110
111     private final DelegatingPersistentDataProvider delegatingPersistenceProvider = new DelegatingPersistentDataProvider(null);
112
113     private final PersistentDataProvider persistentProvider;
114
115     private RaftActorRecoverySupport raftRecovery;
116
117     private RaftActorSnapshotMessageSupport snapshotSupport;
118
119     private final BehaviorStateHolder reusableBehaviorStateHolder = new BehaviorStateHolder();
120
121     private final SwitchBehaviorSupplier reusableSwitchBehaviorSupplier = new SwitchBehaviorSupplier();
122
123     private RaftActorServerConfigurationSupport serverConfigurationSupport;
124
125     public RaftActor(String id, Map<String, String> peerAddresses,
126          Optional<ConfigParams> configParams, short payloadVersion) {
127
128         persistentProvider = new PersistentDataProvider(this);
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, currentBehavior));
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(getRaftActorContext());
148     }
149
150     @Override
151     public void postStop() {
152         if(currentBehavior.getDelegate() != null) {
153             try {
154                 currentBehavior.close();
155             } catch (Exception e) {
156                 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
157             }
158         }
159
160         super.postStop();
161     }
162
163     @Override
164     public void handleRecover(Object message) {
165         if(raftRecovery == null) {
166             raftRecovery = newRaftActorRecoverySupport();
167         }
168
169         boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
170         if(recoveryComplete) {
171             onRecoveryComplete();
172
173             initializeBehavior();
174
175             raftRecovery = null;
176
177             if (context.getReplicatedLog().size() > 0) {
178                 self().tell(new InitiateCaptureSnapshot(), self());
179                 LOG.info("Snapshot capture initiated after recovery");
180             } else {
181                 LOG.info("Snapshot capture NOT initiated after recovery, journal empty");
182             }
183         }
184     }
185
186     protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
187         return new RaftActorRecoverySupport(context, currentBehavior, getRaftActorRecoveryCohort());
188     }
189
190     protected void initializeBehavior(){
191         changeCurrentBehavior(new Follower(context));
192     }
193
194     protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
195         reusableBehaviorStateHolder.init(getCurrentBehavior());
196         setCurrentBehavior(newBehavior);
197         handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
198     }
199
200     @Override
201     public void handleCommand(final Object message) {
202         if(serverConfigurationSupport.handleMessage(message, this, getSender())) {
203             return;
204         } else if (message instanceof ApplyState){
205             ApplyState applyState = (ApplyState) message;
206
207             long elapsedTime = (System.nanoTime() - applyState.getStartTime());
208             if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
209                 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
210                         TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
211             }
212
213             if(LOG.isDebugEnabled()) {
214                 LOG.debug("{}: Applying state for log index {} data {}",
215                     persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
216                     applyState.getReplicatedLogEntry().getData());
217             }
218
219             applyState(applyState.getClientActor(), applyState.getIdentifier(),
220                 applyState.getReplicatedLogEntry().getData());
221
222             if (!hasFollowers()) {
223                 // for single node, the capture should happen after the apply state
224                 // as we delete messages from the persistent journal which have made it to the snapshot
225                 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
226                 // and recovery shows data missing
227                 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
228
229                 context.getSnapshotManager().trimLog(context.getLastApplied(), currentBehavior);
230             }
231
232         } else if (message instanceof ApplyJournalEntries){
233             ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
234             if(LOG.isDebugEnabled()) {
235                 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex());
236             }
237
238             persistence().persist(applyEntries, NoopProcedure.instance());
239
240         } else if (message instanceof FindLeader) {
241             getSender().tell(
242                 new FindLeaderReply(getLeaderAddress()),
243                 getSelf()
244             );
245         } else if(message instanceof GetOnDemandRaftState) {
246             onGetOnDemandRaftStats();
247         } else if(message instanceof InitiateCaptureSnapshot) {
248             captureSnapshot();
249         } else if(message instanceof SwitchBehavior){
250             switchBehavior(((SwitchBehavior) message));
251         } else if(!snapshotSupport.handleSnapshotMessage(message)) {
252             switchBehavior(reusableSwitchBehaviorSupplier.handleMessage(getSender(), message));
253         }
254     }
255
256     private void switchBehavior(SwitchBehavior message) {
257         if(!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
258             RaftState newState = message.getNewState();
259             if( newState == RaftState.Leader || newState == RaftState.Follower) {
260                 switchBehavior(reusableSwitchBehaviorSupplier.handleMessage(getSender(), message));
261                 getRaftActorContext().getTermInformation().updateAndPersist(message.getNewTerm(), "");
262             } else {
263                 LOG.warn("Switching to behavior : {} - not supported", newState);
264             }
265         }
266     }
267
268     private void switchBehavior(Supplier<RaftActorBehavior> supplier){
269         reusableBehaviorStateHolder.init(getCurrentBehavior());
270
271         setCurrentBehavior(supplier.get());
272
273         handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
274     }
275
276     protected RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
277         return new RaftActorSnapshotMessageSupport(context, currentBehavior,
278                 getRaftActorSnapshotCohort());
279     }
280
281     private void onGetOnDemandRaftStats() {
282         // Debugging message to retrieve raft stats.
283
284         Map<String, String> peerAddresses = new HashMap<>();
285         for(String peerId: context.getPeerIds()) {
286             peerAddresses.put(peerId, context.getPeerAddress(peerId));
287         }
288
289         OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
290                 .commitIndex(context.getCommitIndex())
291                 .currentTerm(context.getTermInformation().getCurrentTerm())
292                 .inMemoryJournalDataSize(replicatedLog().dataSize())
293                 .inMemoryJournalLogSize(replicatedLog().size())
294                 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
295                 .lastApplied(context.getLastApplied())
296                 .lastIndex(replicatedLog().lastIndex())
297                 .lastTerm(replicatedLog().lastTerm())
298                 .leader(getLeaderId())
299                 .raftState(currentBehavior.state().toString())
300                 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
301                 .snapshotIndex(replicatedLog().getSnapshotIndex())
302                 .snapshotTerm(replicatedLog().getSnapshotTerm())
303                 .votedFor(context.getTermInformation().getVotedFor())
304                 .peerAddresses(peerAddresses);
305
306         ReplicatedLogEntry lastLogEntry = getLastLogEntry();
307         if (lastLogEntry != null) {
308             builder.lastLogIndex(lastLogEntry.getIndex());
309             builder.lastLogTerm(lastLogEntry.getTerm());
310         }
311
312         if(getCurrentBehavior() instanceof AbstractLeader) {
313             AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
314             Collection<String> followerIds = leader.getFollowerIds();
315             List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
316             for(String id: followerIds) {
317                 final FollowerLogInformation info = leader.getFollower(id);
318                 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
319                         info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity())));
320             }
321
322             builder.followerInfoList(followerInfoList);
323         }
324
325         sender().tell(builder.build(), self());
326
327     }
328
329     private void handleBehaviorChange(BehaviorStateHolder oldBehaviorState, RaftActorBehavior currentBehavior) {
330         RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
331
332         if (oldBehavior != currentBehavior){
333             onStateChanged();
334         }
335
336         String lastValidLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastValidLeaderId();
337         String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
338
339         // it can happen that the state has not changed but the leader has changed.
340         Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
341         if(!Objects.equal(lastValidLeaderId, currentBehavior.getLeaderId()) ||
342            oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
343             if(roleChangeNotifier.isPresent()) {
344                 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
345                         currentBehavior.getLeaderPayloadVersion()), getSelf());
346             }
347
348             onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
349         }
350
351         if (roleChangeNotifier.isPresent() &&
352                 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
353             roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
354                     currentBehavior.state().name()), getSelf());
355         }
356     }
357
358     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
359         return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
360     }
361
362     @Override
363     public long snapshotSequenceNr() {
364         // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
365         // so that we can delete the persistent journal based on the saved sequence-number
366         // However , when akka replays the journal during recovery, it replays it from the sequence number when the snapshot
367         // was saved and not the number we saved.
368         // We would want to override it , by asking akka to use the last-sequence number known to us.
369         return context.getSnapshotManager().getLastSequenceNumber();
370     }
371
372     /**
373      * When a derived RaftActor needs to persist something it must call
374      * persistData.
375      *
376      * @param clientActor
377      * @param identifier
378      * @param data
379      */
380     protected void persistData(final ActorRef clientActor, final String identifier,
381         final Payload data) {
382
383         ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
384             context.getReplicatedLog().lastIndex() + 1,
385             context.getTermInformation().getCurrentTerm(), data);
386
387         if(LOG.isDebugEnabled()) {
388             LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
389         }
390
391         final RaftActorContext raftContext = getRaftActorContext();
392
393         replicatedLog().appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
394             @Override
395             public void apply(ReplicatedLogEntry replicatedLogEntry) {
396                 if (!hasFollowers()){
397                     // Increment the Commit Index and the Last Applied values
398                     raftContext.setCommitIndex(replicatedLogEntry.getIndex());
399                     raftContext.setLastApplied(replicatedLogEntry.getIndex());
400
401                     // Apply the state immediately.
402                     self().tell(new ApplyState(clientActor, identifier, replicatedLogEntry), self());
403
404                     // Send a ApplyJournalEntries message so that we write the fact that we applied
405                     // the state to durable storage
406                     self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
407
408                 } else if (clientActor != null) {
409                     context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry);
410
411                     // Send message for replication
412                     currentBehavior.handleMessage(getSelf(),
413                             new Replicate(clientActor, identifier, replicatedLogEntry));
414                 }
415             }
416         });
417     }
418
419     private ReplicatedLog replicatedLog() {
420         return context.getReplicatedLog();
421     }
422
423     protected String getId() {
424         return context.getId();
425     }
426
427     @VisibleForTesting
428     void setCurrentBehavior(RaftActorBehavior behavior) {
429         currentBehavior.setDelegate(behavior);
430     }
431
432     protected RaftActorBehavior getCurrentBehavior() {
433         return currentBehavior.getDelegate();
434     }
435
436     /**
437      * Derived actors can call the isLeader method to check if the current
438      * RaftActor is the Leader or not
439      *
440      * @return true it this RaftActor is a Leader false otherwise
441      */
442     protected boolean isLeader() {
443         return context.getId().equals(currentBehavior.getLeaderId());
444     }
445
446     /**
447      * Derived actor can call getLeader if they need a reference to the Leader.
448      * This would be useful for example in forwarding a request to an actor
449      * which is the leader
450      *
451      * @return A reference to the leader if known, null otherwise
452      */
453     protected ActorSelection getLeader(){
454         String leaderAddress = getLeaderAddress();
455
456         if(leaderAddress == null){
457             return null;
458         }
459
460         return context.actorSelection(leaderAddress);
461     }
462
463     /**
464      *
465      * @return the current leader's id
466      */
467     protected String getLeaderId(){
468         return currentBehavior.getLeaderId();
469     }
470
471     protected RaftState getRaftState() {
472         return currentBehavior.state();
473     }
474
475     protected ReplicatedLogEntry getLastLogEntry() {
476         return replicatedLog().last();
477     }
478
479     protected Long getCurrentTerm(){
480         return context.getTermInformation().getCurrentTerm();
481     }
482
483     protected Long getCommitIndex(){
484         return context.getCommitIndex();
485     }
486
487     protected Long getLastApplied(){
488         return context.getLastApplied();
489     }
490
491     protected RaftActorContext getRaftActorContext() {
492         return context;
493     }
494
495     protected void updateConfigParams(ConfigParams configParams) {
496
497         // obtain the RaftPolicy for oldConfigParams and the updated one.
498         String oldRaftPolicy = context.getConfigParams().
499             getCustomRaftPolicyImplementationClass();
500         String newRaftPolicy = configParams.
501             getCustomRaftPolicyImplementationClass();
502
503         LOG.debug ("RaftPolicy used with prev.config {}, RaftPolicy used with newConfig {}",
504             oldRaftPolicy, newRaftPolicy);
505         context.setConfigParams(configParams);
506         if (!Objects.equal(oldRaftPolicy, newRaftPolicy)) {
507             //RaftPolicy is modifed for the Actor. Re-initialize its current behaviour
508             initializeBehavior();
509         }
510     }
511
512     public final DataPersistenceProvider persistence() {
513         return delegatingPersistenceProvider.getDelegate();
514     }
515
516     public void setPersistence(DataPersistenceProvider provider) {
517         delegatingPersistenceProvider.setDelegate(provider);
518     }
519
520     protected void setPersistence(boolean persistent) {
521         if(persistent) {
522             setPersistence(new PersistentDataProvider(this));
523         } else {
524             setPersistence(new NonPersistentDataProvider() {
525                 /**
526                  * The way snapshotting works is,
527                  * <ol>
528                  * <li> RaftActor calls createSnapshot on the Shard
529                  * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
530                  * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
531                  * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
532                  * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
533                  * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
534                  * </ol>
535                  */
536                 @Override
537                 public void saveSnapshot(Object o) {
538                     // Make saving Snapshot successful
539                     // Committing the snapshot here would end up calling commit in the creating state which would
540                     // be a state violation. That's why now we send a message to commit the snapshot.
541                     self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
542                 }
543             });
544         }
545     }
546
547     /**
548      * setPeerAddress sets the address of a known peer at a later time.
549      * <p>
550      * This is to account for situations where a we know that a peer
551      * exists but we do not know an address up-front. This may also be used in
552      * situations where a known peer starts off in a different location and we
553      * need to change it's address
554      * <p>
555      * Note that if the peerId does not match the list of peers passed to
556      * this actor during construction an IllegalStateException will be thrown.
557      *
558      * @param peerId
559      * @param peerAddress
560      */
561     protected void setPeerAddress(String peerId, String peerAddress){
562         context.setPeerAddress(peerId, peerAddress);
563     }
564
565     /**
566      * The applyState method will be called by the RaftActor when some data
567      * needs to be applied to the actor's state
568      *
569      * @param clientActor A reference to the client who sent this message. This
570      *                    is the same reference that was passed to persistData
571      *                    by the derived actor. clientActor may be null when
572      *                    the RaftActor is behaving as a follower or during
573      *                    recovery.
574      * @param identifier  The identifier of the persisted data. This is also
575      *                    the same identifier that was passed to persistData by
576      *                    the derived actor. identifier may be null when
577      *                    the RaftActor is behaving as a follower or during
578      *                    recovery
579      * @param data        A piece of data that was persisted by the persistData call.
580      *                    This should NEVER be null.
581      */
582     protected abstract void applyState(ActorRef clientActor, String identifier,
583         Object data);
584
585     /**
586      * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
587      */
588     @Nonnull
589     protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
590
591     /**
592      * This method is called when recovery is complete.
593      */
594     protected abstract void onRecoveryComplete();
595
596     /**
597      * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
598      */
599     @Nonnull
600     protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
601
602     /**
603      * This method will be called by the RaftActor when the state of the
604      * RaftActor changes. The derived actor can then use methods like
605      * isLeader or getLeader to do something useful
606      */
607     protected abstract void onStateChanged();
608
609     /**
610      * Notifier Actor for this RaftActor to notify when a role change happens
611      * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
612      */
613     protected abstract Optional<ActorRef> getRoleChangeNotifier();
614
615     protected void onLeaderChanged(String oldLeader, String newLeader){};
616
617     private String getLeaderAddress(){
618         if(isLeader()){
619             return getSelf().path().toString();
620         }
621         String leaderId = currentBehavior.getLeaderId();
622         if (leaderId == null) {
623             return null;
624         }
625         String peerAddress = context.getPeerAddress(leaderId);
626         if(LOG.isDebugEnabled()) {
627             LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
628                     persistenceId(), leaderId, peerAddress);
629         }
630
631         return peerAddress;
632     }
633
634     protected boolean hasFollowers(){
635         return getRaftActorContext().hasFollowers();
636     }
637
638     private void captureSnapshot() {
639         SnapshotManager snapshotManager = context.getSnapshotManager();
640
641         if(!snapshotManager.isCapturing()) {
642             LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
643                 replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
644
645             snapshotManager.capture(replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
646         }
647     }
648
649     /**
650      * @deprecated Deprecated in favor of {@link org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries}
651      *             whose type for fromIndex is long instead of int. This class was kept for backwards
652      *             compatibility with Helium.
653      */
654     // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
655     @SuppressWarnings("serial")
656     @Deprecated
657     static class DeleteEntries implements Serializable {
658         private final int fromIndex;
659
660         public DeleteEntries(int fromIndex) {
661             this.fromIndex = fromIndex;
662         }
663
664         public int getFromIndex() {
665             return fromIndex;
666         }
667     }
668
669     /**
670      * @deprecated Deprecated in favor of non-inner class {@link org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm}
671      *             which has serialVersionUID set. This class was kept for backwards compatibility with Helium.
672      */
673     // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
674     @SuppressWarnings("serial")
675     @Deprecated
676     static class UpdateElectionTerm implements Serializable {
677         private final long currentTerm;
678         private final String votedFor;
679
680         public UpdateElectionTerm(long currentTerm, String votedFor) {
681             this.currentTerm = currentTerm;
682             this.votedFor = votedFor;
683         }
684
685         public long getCurrentTerm() {
686             return currentTerm;
687         }
688
689         public String getVotedFor() {
690             return votedFor;
691         }
692     }
693
694     private static class BehaviorStateHolder {
695         private RaftActorBehavior behavior;
696         private String lastValidLeaderId;
697         private short leaderPayloadVersion;
698
699         void init(RaftActorBehavior behavior) {
700             this.behavior = behavior;
701             this.leaderPayloadVersion = behavior != null ? behavior.getLeaderPayloadVersion() : -1;
702
703             String behaviorLeaderId = behavior != null ? behavior.getLeaderId() : null;
704             if(behaviorLeaderId != null) {
705                 this.lastValidLeaderId = behaviorLeaderId;
706             }
707         }
708
709         RaftActorBehavior getBehavior() {
710             return behavior;
711         }
712
713         String getLastValidLeaderId() {
714             return lastValidLeaderId;
715         }
716
717         short getLeaderPayloadVersion() {
718             return leaderPayloadVersion;
719         }
720     }
721
722     private class SwitchBehaviorSupplier implements Supplier<RaftActorBehavior> {
723         private Object message;
724         private ActorRef sender;
725
726         public SwitchBehaviorSupplier handleMessage(ActorRef sender, Object message){
727             this.sender = sender;
728             this.message = message;
729             return this;
730         }
731
732         @Override
733         public RaftActorBehavior get() {
734             if(this.message instanceof SwitchBehavior){
735                 return ((SwitchBehavior) message).getNewState().createBehavior(getRaftActorContext());
736             }
737             return currentBehavior.handleMessage(sender, message);
738         }
739     }
740 }