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