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