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