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.
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
10 package org.opendaylight.controller.cluster.raft;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.japi.Procedure;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Objects;
17 import com.google.common.base.Optional;
18 import com.google.common.base.Supplier;
19 import com.google.common.collect.Lists;
20 import java.io.Serializable;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import org.apache.commons.lang3.time.DurationFormatUtils;
28 import org.opendaylight.controller.cluster.DataPersistenceProvider;
29 import org.opendaylight.controller.cluster.DelegatingPersistentDataProvider;
30 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
31 import org.opendaylight.controller.cluster.PersistentDataProvider;
32 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
33 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
34 import org.opendaylight.controller.cluster.notifications.RoleChanged;
35 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
36 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
37 import org.opendaylight.controller.cluster.raft.base.messages.InitiateCaptureSnapshot;
38 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
39 import org.opendaylight.controller.cluster.raft.base.messages.SwitchBehavior;
40 import org.opendaylight.controller.cluster.raft.behaviors.AbstractLeader;
41 import org.opendaylight.controller.cluster.raft.behaviors.DelegatingRaftActorBehavior;
42 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
43 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
44 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
45 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
46 import org.opendaylight.controller.cluster.raft.client.messages.FollowerInfo;
47 import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
48 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
49 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * RaftActor encapsulates a state machine that needs to be kept synchronized
55 * in a cluster. It implements the RAFT algorithm as described in the paper
56 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
57 * In Search of an Understandable Consensus Algorithm</a>
59 * RaftActor has 3 states and each state has a certain behavior associated
60 * with it. A Raft actor can behave as,
63 * <li> A Follower (or) </li>
64 * <li> A Candidate </li>
68 * A RaftActor MUST be a Leader in order to accept requests from clients to
69 * change the state of it's encapsulated state machine. Once a RaftActor becomes
70 * a Leader it is also responsible for ensuring that all followers ultimately
71 * have the same log and therefore the same state machine as itself.
74 * The current behavior of a RaftActor determines how election for leadership
75 * is initiated and how peer RaftActors react to request for votes.
78 * Each RaftActor also needs to know the current election term. It uses this
79 * information for a couple of things. One is to simply figure out who it
80 * voted for in the last election. Another is to figure out if the message
81 * it received to update it's state is stale.
84 * The RaftActor uses akka-persistence to store it's replicated log.
85 * Furthermore through it's behaviors a Raft Actor determines
88 * <li> when a log entry should be persisted </li>
89 * <li> when a log entry should be applied to the state machine (and) </li>
90 * <li> when a snapshot should be saved </li>
93 public abstract class RaftActor extends AbstractUntypedPersistentActor {
95 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
97 protected final Logger LOG = LoggerFactory.getLogger(getClass());
100 * The current state determines the current behavior of a RaftActor
101 * A Raft Actor always starts off in the Follower State
103 private final DelegatingRaftActorBehavior currentBehavior = new DelegatingRaftActorBehavior();
106 * This context should NOT be passed directly to any other actor it is
107 * only to be consumed by the RaftActorBehaviors
109 private final RaftActorContextImpl context;
111 private final DelegatingPersistentDataProvider delegatingPersistenceProvider;
113 private final PersistentDataProvider persistentProvider;
115 private RaftActorRecoverySupport raftRecovery;
117 private RaftActorSnapshotMessageSupport snapshotSupport;
119 private final BehaviorStateHolder reusableBehaviorStateHolder = new BehaviorStateHolder();
121 private final SwitchBehaviorSupplier reusableSwitchBehaviorSupplier = new SwitchBehaviorSupplier();
123 private RaftActorServerConfigurationSupport serverConfigurationSupport;
125 public RaftActor(String id, Map<String, String> peerAddresses,
126 Optional<ConfigParams> configParams, short payloadVersion) {
128 persistentProvider = new PersistentDataProvider(this);
129 delegatingPersistenceProvider = new RaftActorDelegatingPersistentDataProvider(null, persistentProvider);
131 context = new RaftActorContextImpl(this.getSelf(),
132 this.getContext(), id, new ElectionTermImpl(persistentProvider, id, LOG),
133 -1, -1, peerAddresses,
134 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
135 delegatingPersistenceProvider, LOG);
137 context.setPayloadVersion(payloadVersion);
138 context.setReplicatedLog(ReplicatedLogImpl.newInstance(context, currentBehavior));
142 public void preStart() throws Exception {
143 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
144 context.getConfigParams().getJournalRecoveryLogBatchSize());
148 snapshotSupport = newRaftActorSnapshotMessageSupport();
149 serverConfigurationSupport = new RaftActorServerConfigurationSupport(this);
153 public void postStop() {
154 if(currentBehavior.getDelegate() != null) {
156 currentBehavior.close();
157 } catch (Exception e) {
158 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
166 public void handleRecover(Object message) {
167 if(raftRecovery == null) {
168 raftRecovery = newRaftActorRecoverySupport();
171 boolean recoveryComplete = raftRecovery.handleRecoveryMessage(message, persistentProvider);
172 if(recoveryComplete) {
173 onRecoveryComplete();
175 initializeBehavior();
179 if (context.getReplicatedLog().size() > 0) {
180 self().tell(new InitiateCaptureSnapshot(), self());
181 LOG.info("{}: Snapshot capture initiated after recovery", persistenceId());
183 LOG.info("{}: Snapshot capture NOT initiated after recovery, journal empty", persistenceId());
188 protected RaftActorRecoverySupport newRaftActorRecoverySupport() {
189 return new RaftActorRecoverySupport(context, currentBehavior, getRaftActorRecoveryCohort());
192 protected void initializeBehavior(){
193 changeCurrentBehavior(new Follower(context));
196 protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
197 reusableBehaviorStateHolder.init(getCurrentBehavior());
198 setCurrentBehavior(newBehavior);
199 handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
203 public void handleCommand(final Object message) {
204 if(serverConfigurationSupport.handleMessage(message, getSender())) {
206 } else if (message instanceof ApplyState){
207 ApplyState applyState = (ApplyState) message;
209 long elapsedTime = (System.nanoTime() - applyState.getStartTime());
210 if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
211 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
212 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
215 if(LOG.isDebugEnabled()) {
216 LOG.debug("{}: Applying state for log index {} data {}",
217 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
218 applyState.getReplicatedLogEntry().getData());
221 applyState(applyState.getClientActor(), applyState.getIdentifier(),
222 applyState.getReplicatedLogEntry().getData());
224 if (!hasFollowers()) {
225 // for single node, the capture should happen after the apply state
226 // as we delete messages from the persistent journal which have made it to the snapshot
227 // capturing the snapshot before applying makes the persistent journal and snapshot out of sync
228 // and recovery shows data missing
229 context.getReplicatedLog().captureSnapshotIfReady(applyState.getReplicatedLogEntry());
231 context.getSnapshotManager().trimLog(context.getLastApplied(), currentBehavior);
234 } else if (message instanceof ApplyJournalEntries){
235 ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
236 if(LOG.isDebugEnabled()) {
237 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex());
240 persistence().persist(applyEntries, NoopProcedure.instance());
242 } else if (message instanceof FindLeader) {
244 new FindLeaderReply(getLeaderAddress()),
247 } else if(message instanceof GetOnDemandRaftState) {
248 onGetOnDemandRaftStats();
249 } else if(message instanceof InitiateCaptureSnapshot) {
251 } else if(message instanceof SwitchBehavior){
252 switchBehavior(((SwitchBehavior) message));
253 } else if(!snapshotSupport.handleSnapshotMessage(message, getSender())) {
254 switchBehavior(reusableSwitchBehaviorSupplier.handleMessage(getSender(), message));
258 private void switchBehavior(SwitchBehavior message) {
259 if(!getRaftActorContext().getRaftPolicy().automaticElectionsEnabled()) {
260 RaftState newState = message.getNewState();
261 if( newState == RaftState.Leader || newState == RaftState.Follower) {
262 switchBehavior(reusableSwitchBehaviorSupplier.handleMessage(getSender(), message));
263 getRaftActorContext().getTermInformation().updateAndPersist(message.getNewTerm(), "");
265 LOG.warn("Switching to behavior : {} - not supported", newState);
270 private void switchBehavior(Supplier<RaftActorBehavior> supplier){
271 reusableBehaviorStateHolder.init(getCurrentBehavior());
273 setCurrentBehavior(supplier.get());
275 handleBehaviorChange(reusableBehaviorStateHolder, getCurrentBehavior());
278 protected RaftActorSnapshotMessageSupport newRaftActorSnapshotMessageSupport() {
279 return new RaftActorSnapshotMessageSupport(context, currentBehavior,
280 getRaftActorSnapshotCohort());
283 private void onGetOnDemandRaftStats() {
284 // Debugging message to retrieve raft stats.
286 Map<String, String> peerAddresses = new HashMap<>();
287 for(String peerId: context.getPeerIds()) {
288 peerAddresses.put(peerId, context.getPeerAddress(peerId));
291 OnDemandRaftState.Builder builder = OnDemandRaftState.builder()
292 .commitIndex(context.getCommitIndex())
293 .currentTerm(context.getTermInformation().getCurrentTerm())
294 .inMemoryJournalDataSize(replicatedLog().dataSize())
295 .inMemoryJournalLogSize(replicatedLog().size())
296 .isSnapshotCaptureInitiated(context.getSnapshotManager().isCapturing())
297 .lastApplied(context.getLastApplied())
298 .lastIndex(replicatedLog().lastIndex())
299 .lastTerm(replicatedLog().lastTerm())
300 .leader(getLeaderId())
301 .raftState(currentBehavior.state().toString())
302 .replicatedToAllIndex(currentBehavior.getReplicatedToAllIndex())
303 .snapshotIndex(replicatedLog().getSnapshotIndex())
304 .snapshotTerm(replicatedLog().getSnapshotTerm())
305 .votedFor(context.getTermInformation().getVotedFor())
306 .peerAddresses(peerAddresses)
307 .customRaftPolicyClassName(context.getConfigParams().getCustomRaftPolicyImplementationClass());
309 ReplicatedLogEntry lastLogEntry = getLastLogEntry();
310 if (lastLogEntry != null) {
311 builder.lastLogIndex(lastLogEntry.getIndex());
312 builder.lastLogTerm(lastLogEntry.getTerm());
315 if(getCurrentBehavior() instanceof AbstractLeader) {
316 AbstractLeader leader = (AbstractLeader)getCurrentBehavior();
317 Collection<String> followerIds = leader.getFollowerIds();
318 List<FollowerInfo> followerInfoList = Lists.newArrayListWithCapacity(followerIds.size());
319 for(String id: followerIds) {
320 final FollowerLogInformation info = leader.getFollower(id);
321 followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
322 info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(info.timeSinceLastActivity())));
325 builder.followerInfoList(followerInfoList);
328 sender().tell(builder.build(), self());
332 private void handleBehaviorChange(BehaviorStateHolder oldBehaviorState, RaftActorBehavior currentBehavior) {
333 RaftActorBehavior oldBehavior = oldBehaviorState.getBehavior();
335 if (oldBehavior != currentBehavior){
339 String lastValidLeaderId = oldBehavior == null ? null : oldBehaviorState.getLastValidLeaderId();
340 String oldBehaviorStateName = oldBehavior == null ? null : oldBehavior.state().name();
342 // it can happen that the state has not changed but the leader has changed.
343 Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
344 if(!Objects.equal(lastValidLeaderId, currentBehavior.getLeaderId()) ||
345 oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
346 if(roleChangeNotifier.isPresent()) {
347 roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
348 currentBehavior.getLeaderPayloadVersion()), getSelf());
351 onLeaderChanged(lastValidLeaderId, currentBehavior.getLeaderId());
354 if (roleChangeNotifier.isPresent() &&
355 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
356 roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
357 currentBehavior.state().name()), getSelf());
361 protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
362 return new LeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
366 public long snapshotSequenceNr() {
367 // When we do a snapshot capture, we also capture and save the sequence-number of the persistent journal,
368 // so that we can delete the persistent journal based on the saved sequence-number
369 // However , when akka replays the journal during recovery, it replays it from the sequence number when the snapshot
370 // was saved and not the number we saved.
371 // We would want to override it , by asking akka to use the last-sequence number known to us.
372 return context.getSnapshotManager().getLastSequenceNumber();
376 * When a derived RaftActor needs to persist something it must call
383 protected void persistData(final ActorRef clientActor, final String identifier,
384 final Payload data) {
386 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
387 context.getReplicatedLog().lastIndex() + 1,
388 context.getTermInformation().getCurrentTerm(), data);
390 if(LOG.isDebugEnabled()) {
391 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
394 final RaftActorContext raftContext = getRaftActorContext();
396 replicatedLog().appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
398 public void apply(ReplicatedLogEntry replicatedLogEntry) {
399 if (!hasFollowers()){
400 // Increment the Commit Index and the Last Applied values
401 raftContext.setCommitIndex(replicatedLogEntry.getIndex());
402 raftContext.setLastApplied(replicatedLogEntry.getIndex());
404 // Apply the state immediately.
405 self().tell(new ApplyState(clientActor, identifier, replicatedLogEntry), self());
407 // Send a ApplyJournalEntries message so that we write the fact that we applied
408 // the state to durable storage
409 self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
411 } else if (clientActor != null) {
412 context.getReplicatedLog().captureSnapshotIfReady(replicatedLogEntry);
414 // Send message for replication
415 currentBehavior.handleMessage(getSelf(),
416 new Replicate(clientActor, identifier, replicatedLogEntry));
422 private ReplicatedLog replicatedLog() {
423 return context.getReplicatedLog();
426 protected String getId() {
427 return context.getId();
431 void setCurrentBehavior(RaftActorBehavior behavior) {
432 currentBehavior.setDelegate(behavior);
435 protected RaftActorBehavior getCurrentBehavior() {
436 return currentBehavior.getDelegate();
440 * Derived actors can call the isLeader method to check if the current
441 * RaftActor is the Leader or not
443 * @return true it this RaftActor is a Leader false otherwise
445 protected boolean isLeader() {
446 return context.getId().equals(currentBehavior.getLeaderId());
450 * Derived actor can call getLeader if they need a reference to the Leader.
451 * This would be useful for example in forwarding a request to an actor
452 * which is the leader
454 * @return A reference to the leader if known, null otherwise
456 protected ActorSelection getLeader(){
457 String leaderAddress = getLeaderAddress();
459 if(leaderAddress == null){
463 return context.actorSelection(leaderAddress);
468 * @return the current leader's id
470 protected String getLeaderId(){
471 return currentBehavior.getLeaderId();
474 protected RaftState getRaftState() {
475 return currentBehavior.state();
478 protected ReplicatedLogEntry getLastLogEntry() {
479 return replicatedLog().last();
482 protected Long getCurrentTerm(){
483 return context.getTermInformation().getCurrentTerm();
486 protected Long getCommitIndex(){
487 return context.getCommitIndex();
490 protected Long getLastApplied(){
491 return context.getLastApplied();
494 protected RaftActorContext getRaftActorContext() {
498 protected void updateConfigParams(ConfigParams configParams) {
500 // obtain the RaftPolicy for oldConfigParams and the updated one.
501 String oldRaftPolicy = context.getConfigParams().
502 getCustomRaftPolicyImplementationClass();
503 String newRaftPolicy = configParams.
504 getCustomRaftPolicyImplementationClass();
506 LOG.debug("{}: RaftPolicy used with prev.config {}, RaftPolicy used with newConfig {}", persistenceId(),
507 oldRaftPolicy, newRaftPolicy);
508 context.setConfigParams(configParams);
509 if (!Objects.equal(oldRaftPolicy, newRaftPolicy)) {
510 // The RaftPolicy was modified. If the current behavior is Follower then re-initialize to Follower
511 // but transfer the previous leaderId so it doesn't immediately try to schedule an election. This
512 // avoids potential disruption. Otherwise, switch to Follower normally.
513 RaftActorBehavior behavior = currentBehavior.getDelegate();
514 if(behavior instanceof Follower) {
515 String previousLeaderId = ((Follower)behavior).getLeaderId();
517 LOG.debug("{}: Re-initializing to Follower with previous leaderId {}", persistenceId(), previousLeaderId);
519 changeCurrentBehavior(new Follower(context, previousLeaderId));
521 initializeBehavior();
526 public final DataPersistenceProvider persistence() {
527 return delegatingPersistenceProvider.getDelegate();
530 public void setPersistence(DataPersistenceProvider provider) {
531 delegatingPersistenceProvider.setDelegate(provider);
534 protected void setPersistence(boolean persistent) {
536 setPersistence(new PersistentDataProvider(this));
538 setPersistence(new NonPersistentDataProvider() {
540 * The way snapshotting works is,
542 * <li> RaftActor calls createSnapshot on the Shard
543 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
544 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save
545 * the snapshot. The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the
546 * RaftActor gets SaveSnapshot success it commits the snapshot to the in-memory journal. This
547 * commitSnapshot is mimicking what is done in SaveSnapshotSuccess.
551 public void saveSnapshot(Object o) {
552 // Make saving Snapshot successful
553 // Committing the snapshot here would end up calling commit in the creating state which would
554 // be a state violation. That's why now we send a message to commit the snapshot.
555 self().tell(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT, self());
562 * setPeerAddress sets the address of a known peer at a later time.
564 * This is to account for situations where a we know that a peer
565 * exists but we do not know an address up-front. This may also be used in
566 * situations where a known peer starts off in a different location and we
567 * need to change it's address
569 * Note that if the peerId does not match the list of peers passed to
570 * this actor during construction an IllegalStateException will be thrown.
575 protected void setPeerAddress(String peerId, String peerAddress){
576 context.setPeerAddress(peerId, peerAddress);
580 * The applyState method will be called by the RaftActor when some data
581 * needs to be applied to the actor's state
583 * @param clientActor A reference to the client who sent this message. This
584 * is the same reference that was passed to persistData
585 * by the derived actor. clientActor may be null when
586 * the RaftActor is behaving as a follower or during
588 * @param identifier The identifier of the persisted data. This is also
589 * the same identifier that was passed to persistData by
590 * the derived actor. identifier may be null when
591 * the RaftActor is behaving as a follower or during
593 * @param data A piece of data that was persisted by the persistData call.
594 * This should NEVER be null.
596 protected abstract void applyState(ActorRef clientActor, String identifier,
600 * Returns the RaftActorRecoveryCohort to participate in persistence recovery.
603 protected abstract RaftActorRecoveryCohort getRaftActorRecoveryCohort();
606 * This method is called when recovery is complete.
608 protected abstract void onRecoveryComplete();
611 * Returns the RaftActorSnapshotCohort to participate in persistence recovery.
614 protected abstract RaftActorSnapshotCohort getRaftActorSnapshotCohort();
617 * This method will be called by the RaftActor when the state of the
618 * RaftActor changes. The derived actor can then use methods like
619 * isLeader or getLeader to do something useful
621 protected abstract void onStateChanged();
624 * Notifier Actor for this RaftActor to notify when a role change happens
625 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
627 protected abstract Optional<ActorRef> getRoleChangeNotifier();
629 protected void onLeaderChanged(String oldLeader, String newLeader){};
631 private String getLeaderAddress(){
633 return getSelf().path().toString();
635 String leaderId = currentBehavior.getLeaderId();
636 if (leaderId == null) {
639 String peerAddress = context.getPeerAddress(leaderId);
640 if(LOG.isDebugEnabled()) {
641 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
642 persistenceId(), leaderId, peerAddress);
648 protected boolean hasFollowers(){
649 return getRaftActorContext().hasFollowers();
652 private void captureSnapshot() {
653 SnapshotManager snapshotManager = context.getSnapshotManager();
655 if(!snapshotManager.isCapturing()) {
656 LOG.debug("Take a snapshot of current state. lastReplicatedLog is {} and replicatedToAllIndex is {}",
657 replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
659 snapshotManager.capture(replicatedLog().last(), currentBehavior.getReplicatedToAllIndex());
664 * @deprecated Deprecated in favor of {@link org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries}
665 * whose type for fromIndex is long instead of int. This class was kept for backwards
666 * compatibility with Helium.
668 // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
669 @SuppressWarnings("serial")
671 static class DeleteEntries implements Serializable {
672 private final int fromIndex;
674 public DeleteEntries(int fromIndex) {
675 this.fromIndex = fromIndex;
678 public int getFromIndex() {
684 * @deprecated Deprecated in favor of non-inner class {@link org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm}
685 * which has serialVersionUID set. This class was kept for backwards compatibility with Helium.
687 // Suppressing this warning as we can't set serialVersionUID to maintain backwards compatibility.
688 @SuppressWarnings("serial")
690 static class UpdateElectionTerm implements Serializable {
691 private final long currentTerm;
692 private final String votedFor;
694 public UpdateElectionTerm(long currentTerm, String votedFor) {
695 this.currentTerm = currentTerm;
696 this.votedFor = votedFor;
699 public long getCurrentTerm() {
703 public String getVotedFor() {
708 private static class BehaviorStateHolder {
709 private RaftActorBehavior behavior;
710 private String lastValidLeaderId;
711 private short leaderPayloadVersion;
713 void init(RaftActorBehavior behavior) {
714 this.behavior = behavior;
715 this.leaderPayloadVersion = behavior != null ? behavior.getLeaderPayloadVersion() : -1;
717 String behaviorLeaderId = behavior != null ? behavior.getLeaderId() : null;
718 if(behaviorLeaderId != null) {
719 this.lastValidLeaderId = behaviorLeaderId;
723 RaftActorBehavior getBehavior() {
727 String getLastValidLeaderId() {
728 return lastValidLeaderId;
731 short getLeaderPayloadVersion() {
732 return leaderPayloadVersion;
736 private class SwitchBehaviorSupplier implements Supplier<RaftActorBehavior> {
737 private Object message;
738 private ActorRef sender;
740 public SwitchBehaviorSupplier handleMessage(ActorRef sender, Object message){
741 this.sender = sender;
742 this.message = message;
747 public RaftActorBehavior get() {
748 if(this.message instanceof SwitchBehavior){
749 return ((SwitchBehavior) message).getNewState().createBehavior(getRaftActorContext());
751 return currentBehavior.handleMessage(sender, message);