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