Always persist and recover election term info
[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     public RaftActor(String id, Map<String, String> peerAddresses,
124          Optional<ConfigParams> configParams, short payloadVersion) {
125
126         persistentProvider = new PersistentDataProvider(this);
127         context = new RaftActorContextImpl(this.getSelf(),
128             this.getContext(), id, new ElectionTermImpl(persistentProvider, id, LOG),
129             -1, -1, peerAddresses,
130             (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
131             delegatingPersistenceProvider, LOG);
132
133         context.setPayloadVersion(payloadVersion);
134         context.setReplicatedLog(ReplicatedLogImpl.newInstance(context, currentBehavior));
135     }
136
137     @Override
138     public void preStart() throws Exception {
139         LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
140                 context.getConfigParams().getJournalRecoveryLogBatchSize());
141
142         super.preStart();
143
144         snapshotSupport = newRaftActorSnapshotMessageSupport();
145     }
146
147     @Override
148     public void postStop() {
149         if(currentBehavior.getDelegate() != null) {
150             try {
151                 currentBehavior.close();
152             } catch (Exception e) {
153                 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
154             }
155         }
156
157         super.postStop();
158     }
159
160     @Override
161     public void handleRecover(Object message) {
162         if(raftRecovery == null) {
163             raftRecovery = newRaftActorRecoverySupport();
164         }
165
166         boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
167         if(recoveryComplete) {
168             onRecoveryComplete();
169
170             initializeBehavior();
171
172             raftRecovery = null;
173         }
174     }
175
176     protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
177         return new RaftActorRecoverySupport(context, currentBehavior, getRaftActorRecoveryCohort());
178     }
179
180     protected void initializeBehavior(){
181         changeCurrentBehavior(new Follower(context));
182     }
183
184     protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
185         reusableBehaviorStateHolder.init(getCurrentBehavior());
186         setCurrentBehavior(newBehavior);
187         handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
188     }
189
190     @Override
191     public void handleCommand(final Object message) {
192         if (message instanceof ApplyState){
193             ApplyState applyState = (ApplyState) message;
194
195             long elapsedTime = (System.nanoTime() - applyState.getStartTime());
196             if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
197                 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
198                         TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
199             }
200
201             if(LOG.isDebugEnabled()) {
202                 LOG.debug("{}: Applying state for log index {} data {}",
203                     persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
204                     applyState.getReplicatedLogEntry().getData());
205             }
206
207             applyState(applyState.getClientActor(), applyState.getIdentifier(),
208                 applyState.getReplicatedLogEntry().getData());
209
210             if (!hasFollowers()) {
211                 // for single node, the capture should happen after the apply state
212                 // as we delete messages from the persistent journal which have made it to the snapshot
213                 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
214                 // and recovery shows data missing
215                 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
216
217                 context.getSnapshotManager().trimLog(context.getLastApplied(), currentBehavior);
218             }
219
220         } else if (message instanceof ApplyJournalEntries){
221             ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
222             if(LOG.isDebugEnabled()) {
223                 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex());
224             }
225
226             persistence().persist(applyEntries, NoopProcedure.instance());
227
228         } else if (message instanceof FindLeader) {
229             getSender().tell(
230                 new FindLeaderReply(getLeaderAddress()),
231                 getSelf()
232             );
233         } else if(message instanceof GetOnDemandRaftState) {
234             onGetOnDemandRaftStats();
235         } else if(message instanceof InitiateCaptureSnapshot) {
236             captureSnapshot();
237         } else if(message instanceof SwitchBehavior){
238             switchBehavior(((SwitchBehavior) message));
239         } else if(!snapshotSupport.handleSnapshotMessage(message)) {
240             switchBehavior(reusableSwitchBehaviorSupplier.handleMessage(getSender(), message));
241         }
242     }
243
244     private void switchBehavior(SwitchBehavior message) {
245         if(!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
246             RaftState newState = message.getNewState();
247             if( newState == RaftState.Leader || newState == RaftState.Follower) {
248                 switchBehavior(reusableSwitchBehaviorSupplier.handleMessage(getSender(), message));
249                 getRaftActorContext().getTermInformation().updateAndPersist(message.getNewTerm(), "");
250             } else {
251                 LOG.warn("Switching to behavior : {} - not supported", newState);
252             }
253         }
254     }
255
256     private void switchBehavior(Supplier<RaftActorBehavior> supplier){
257         reusableBehaviorStateHolder.init(getCurrentBehavior());
258
259         setCurrentBehavior(supplier.get());
260
261         handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
262     }
263
264     protected RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
265         return new RaftActorSnapshotMessageSupport(context, currentBehavior,
266                 getRaftActorSnapshotCohort());
267     }
268
269     private void onGetOnDemandRaftStats() {
270         // Debugging message to retrieve raft stats.
271
272         OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
273                 .commitIndex(context.getCommitIndex())
274                 .currentTerm(context.getTermInformation().getCurrentTerm())
275                 .inMemoryJournalDataSize(replicatedLog().dataSize())
276                 .inMemoryJournalLogSize(replicatedLog().size())
277                 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
278                 .lastApplied(context.getLastApplied())
279                 .lastIndex(replicatedLog().lastIndex())
280                 .lastTerm(replicatedLog().lastTerm())
281                 .leader(getLeaderId())
282                 .raftState(currentBehavior.state().toString())
283                 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
284                 .snapshotIndex(replicatedLog().getSnapshotIndex())
285                 .snapshotTerm(replicatedLog().getSnapshotTerm())
286                 .votedFor(context.getTermInformation().getVotedFor())
287                 .peerAddresses(new HashMap<>(context.getPeerAddresses()));
288
289         ReplicatedLogEntry lastLogEntry = getLastLogEntry();
290         if (lastLogEntry != null) {
291             builder.lastLogIndex(lastLogEntry.getIndex());
292             builder.lastLogTerm(lastLogEntry.getTerm());
293         }
294
295         if(getCurrentBehavior() instanceof AbstractLeader) {
296             AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
297             Collection<String> followerIds = leader.getFollowerIds();
298             List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
299             for(String id: followerIds) {
300                 final FollowerLogInformation info = leader.getFollower(id);
301                 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
302                         info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity())));
303             }
304
305             builder.followerInfoList(followerInfoList);
306         }
307
308         sender().tell(builder.build(), self());
309
310     }
311
312     private void handleBehaviorChange(BehaviorStateHolder oldBehaviorState, RaftActorBehavior currentBehavior) {
313         RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
314
315         if (oldBehavior != currentBehavior){
316             onStateChanged();
317         }
318
319         String lastValidLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastValidLeaderId();
320         String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
321
322         // it can happen that the state has not changed but the leader has changed.
323         Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
324         if(!Objects.equal(lastValidLeaderId, currentBehavior.getLeaderId()) ||
325            oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
326             if(roleChangeNotifier.isPresent()) {
327                 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
328                         currentBehavior.getLeaderPayloadVersion()), getSelf());
329             }
330
331             onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
332         }
333
334         if (roleChangeNotifier.isPresent() &&
335                 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
336             roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
337                     currentBehavior.state().name()), getSelf());
338         }
339     }
340
341     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
342         return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
343     }
344
345     @Override
346     public long snapshotSequenceNr() {
347         // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
348         // so that we can delete the persistent journal based on the saved sequence-number
349         // However , when akka replays the journal during recovery, it replays it from the sequence number when the snapshot
350         // was saved and not the number we saved.
351         // We would want to override it , by asking akka to use the last-sequence number known to us.
352         return context.getSnapshotManager().getLastSequenceNumber();
353     }
354
355     /**
356      * When a derived RaftActor needs to persist something it must call
357      * persistData.
358      *
359      * @param clientActor
360      * @param identifier
361      * @param data
362      */
363     protected void persistData(final ActorRef clientActor, final String identifier,
364         final Payload data) {
365
366         ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
367             context.getReplicatedLog().lastIndex() + 1,
368             context.getTermInformation().getCurrentTerm(), data);
369
370         if(LOG.isDebugEnabled()) {
371             LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
372         }
373
374         final RaftActorContext raftContext = getRaftActorContext();
375
376         replicatedLog().appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
377             @Override
378             public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
379                 if (!hasFollowers()){
380                     // Increment the Commit Index and the Last Applied values
381                     raftContext.setCommitIndex(replicatedLogEntry.getIndex());
382                     raftContext.setLastApplied(replicatedLogEntry.getIndex());
383
384                     // Apply the state immediately.
385                     self().tell(new ApplyState(clientActor, identifier, replicatedLogEntry), self());
386
387                     // Send a ApplyJournalEntries message so that we write the fact that we applied
388                     // the state to durable storage
389                     self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
390
391                 } else if (clientActor != null) {
392                     context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry);
393
394                     // Send message for replication
395                     currentBehavior.handleMessage(getSelf(),
396                             new Replicate(clientActor, identifier, replicatedLogEntry));
397                 }
398             }
399         });
400     }
401
402     private ReplicatedLog replicatedLog() {
403         return context.getReplicatedLog();
404     }
405
406     protected String getId() {
407         return context.getId();
408     }
409
410     @VisibleForTesting
411     void setCurrentBehavior(RaftActorBehavior behavior) {
412         currentBehavior.setDelegate(behavior);
413     }
414
415     protected RaftActorBehavior getCurrentBehavior() {
416         return currentBehavior.getDelegate();
417     }
418
419     /**
420      * Derived actors can call the isLeader method to check if the current
421      * RaftActor is the Leader or not
422      *
423      * @return true it this RaftActor is a Leader false otherwise
424      */
425     protected boolean isLeader() {
426         return context.getId().equals(currentBehavior.getLeaderId());
427     }
428
429     /**
430      * Derived actor can call getLeader if they need a reference to the Leader.
431      * This would be useful for example in forwarding a request to an actor
432      * which is the leader
433      *
434      * @return A reference to the leader if known, null otherwise
435      */
436     protected ActorSelection getLeader(){
437         String leaderAddress = getLeaderAddress();
438
439         if(leaderAddress == null){
440             return null;
441         }
442
443         return context.actorSelection(leaderAddress);
444     }
445
446     /**
447      *
448      * @return the current leader's id
449      */
450     protected String getLeaderId(){
451         return currentBehavior.getLeaderId();
452     }
453
454     protected RaftState getRaftState() {
455         return currentBehavior.state();
456     }
457
458     protected ReplicatedLogEntry getLastLogEntry() {
459         return replicatedLog().last();
460     }
461
462     protected Long getCurrentTerm(){
463         return context.getTermInformation().getCurrentTerm();
464     }
465
466     protected Long getCommitIndex(){
467         return context.getCommitIndex();
468     }
469
470     protected Long getLastApplied(){
471         return context.getLastApplied();
472     }
473
474     protected RaftActorContext getRaftActorContext() {
475         return context;
476     }
477
478     protected void updateConfigParams(ConfigParams configParams) {
479         context.setConfigParams(configParams);
480     }
481
482     public final DataPersistenceProvider persistence() {
483         return delegatingPersistenceProvider.getDelegate();
484     }
485
486     public void setPersistence(DataPersistenceProvider provider) {
487         delegatingPersistenceProvider.setDelegate(provider);
488     }
489
490     protected void setPersistence(boolean persistent) {
491         if(persistent) {
492             setPersistence(new PersistentDataProvider(this));
493         } else {
494             setPersistence(new NonPersistentDataProvider() {
495                 /**
496                  * The way snapshotting works is,
497                  * <ol>
498                  * <li> RaftActor calls createSnapshot on the Shard
499                  * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
500                  * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
501                  * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
502                  * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
503                  * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
504                  * </ol>
505                  */
506                 @Override
507                 public void saveSnapshot(Object o) {
508                     // Make saving Snapshot successful
509                     // Committing the snapshot here would end up calling commit in the creating state which would
510                     // be a state violation. That's why now we send a message to commit the snapshot.
511                     self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
512                 }
513             });
514         }
515     }
516
517     /**
518      * setPeerAddress sets the address of a known peer at a later time.
519      * <p>
520      * This is to account for situations where a we know that a peer
521      * exists but we do not know an address up-front. This may also be used in
522      * situations where a known peer starts off in a different location and we
523      * need to change it's address
524      * <p>
525      * Note that if the peerId does not match the list of peers passed to
526      * this actor during construction an IllegalStateException will be thrown.
527      *
528      * @param peerId
529      * @param peerAddress
530      */
531     protected void setPeerAddress(String peerId, String peerAddress){
532         context.setPeerAddress(peerId, peerAddress);
533     }
534
535     /**
536      * The applyState method will be called by the RaftActor when some data
537      * needs to be applied to the actor's state
538      *
539      * @param clientActor A reference to the client who sent this message. This
540      *                    is the same reference that was passed to persistData
541      *                    by the derived actor. clientActor may be null when
542      *                    the RaftActor is behaving as a follower or during
543      *                    recovery.
544      * @param identifier  The identifier of the persisted data. This is also
545      *                    the same identifier that was passed to persistData by
546      *                    the derived actor. identifier may be null when
547      *                    the RaftActor is behaving as a follower or during
548      *                    recovery
549      * @param data        A piece of data that was persisted by the persistData call.
550      *                    This should NEVER be null.
551      */
552     protected abstract void applyState(ActorRef clientActor, String identifier,
553         Object data);
554
555     /**
556      * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
557      */
558     @Nonnull
559     protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
560
561     /**
562      * This method is called when recovery is complete.
563      */
564     protected abstract void onRecoveryComplete();
565
566     /**
567      * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
568      */
569     @Nonnull
570     protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
571
572     /**
573      * This method will be called by the RaftActor when the state of the
574      * RaftActor changes. The derived actor can then use methods like
575      * isLeader or getLeader to do something useful
576      */
577     protected abstract void onStateChanged();
578
579     /**
580      * Notifier Actor for this RaftActor to notify when a role change happens
581      * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
582      */
583     protected abstract Optional<ActorRef> getRoleChangeNotifier();
584
585     protected void onLeaderChanged(String oldLeader, String newLeader){};
586
587     private String getLeaderAddress(){
588         if(isLeader()){
589             return getSelf().path().toString();
590         }
591         String leaderId = currentBehavior.getLeaderId();
592         if (leaderId == null) {
593             return null;
594         }
595         String peerAddress = context.getPeerAddress(leaderId);
596         if(LOG.isDebugEnabled()) {
597             LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
598                     persistenceId(), leaderId, peerAddress);
599         }
600
601         return peerAddress;
602     }
603
604     protected boolean hasFollowers(){
605         return getRaftActorContext().hasFollowers();
606     }
607
608     private void captureSnapshot() {
609         SnapshotManager snapshotManager = context.getSnapshotManager();
610
611         if(!snapshotManager.isCapturing()) {
612             LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
613                 replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
614
615             snapshotManager.capture(replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
616         }
617     }
618
619     /**
620      * @deprecated Deprecated in favor of {@link org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries}
621      *             whose type for fromIndex is long instead of int. This class was kept for backwards
622      *             compatibility with Helium.
623      */
624     // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
625     @SuppressWarnings("serial")
626     @Deprecated
627     static class DeleteEntries implements Serializable {
628         private final int fromIndex;
629
630         public DeleteEntries(int fromIndex) {
631             this.fromIndex = fromIndex;
632         }
633
634         public int getFromIndex() {
635             return fromIndex;
636         }
637     }
638
639     /**
640      * @deprecated Deprecated in favor of non-inner class {@link org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm}
641      *             which has serialVersionUID set. This class was kept for backwards compatibility with Helium.
642      */
643     // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
644     @SuppressWarnings("serial")
645     @Deprecated
646     static class UpdateElectionTerm implements Serializable {
647         private final long currentTerm;
648         private final String votedFor;
649
650         public UpdateElectionTerm(long currentTerm, String votedFor) {
651             this.currentTerm = currentTerm;
652             this.votedFor = votedFor;
653         }
654
655         public long getCurrentTerm() {
656             return currentTerm;
657         }
658
659         public String getVotedFor() {
660             return votedFor;
661         }
662     }
663
664     private static class BehaviorStateHolder {
665         private RaftActorBehavior behavior;
666         private String lastValidLeaderId;
667         private short leaderPayloadVersion;
668
669         void init(RaftActorBehavior behavior) {
670             this.behavior = behavior;
671             this.leaderPayloadVersion = behavior != null ? behavior.getLeaderPayloadVersion() : -1;
672
673             String behaviorLeaderId = behavior != null ? behavior.getLeaderId() : null;
674             if(behaviorLeaderId != null) {
675                 this.lastValidLeaderId = behaviorLeaderId;
676             }
677         }
678
679         RaftActorBehavior getBehavior() {
680             return behavior;
681         }
682
683         String getLastValidLeaderId() {
684             return lastValidLeaderId;
685         }
686
687         short getLeaderPayloadVersion() {
688             return leaderPayloadVersion;
689         }
690     }
691
692     private class SwitchBehaviorSupplier implements Supplier<RaftActorBehavior> {
693         private Object message;
694         private ActorRef sender;
695
696         public SwitchBehaviorSupplier handleMessage(ActorRef sender, Object message){
697             this.sender = sender;
698             this.message = message;
699             return this;
700         }
701
702         @Override
703         public RaftActorBehavior get() {
704             if(this.message instanceof SwitchBehavior){
705                 return ((SwitchBehavior) message).getNewState().createBehavior(getRaftActorContext());
706             }
707             return currentBehavior.handleMessage(sender, message);
708         }
709     }
710 }