2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft.behaviors;
10 import akka.actor.ActorRef;
11 import akka.actor.ActorSelection;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Stopwatch;
15 import java.util.concurrent.TimeUnit;
16 import javax.annotation.Nonnull;
17 import javax.annotation.Nullable;
18 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
19 import org.opendaylight.controller.cluster.raft.RaftActorContext;
20 import org.opendaylight.controller.cluster.raft.RaftActorLeadershipTransferCohort;
21 import org.opendaylight.controller.cluster.raft.RaftState;
22 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
23 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
26 * The behavior of a RaftActor when it is in the Leader state
30 * <li> Upon election: send initial empty AppendEntries RPCs
31 * (heartbeat) to each server; repeat during idle periods to
32 * prevent election timeouts (§5.2)
33 * <li> If command received from client: append entry to local log,
34 * respond after entry applied to state machine (§5.3)
35 * <li> If last log index ≥ nextIndex for a follower: send
36 * AppendEntries RPC with log entries starting at nextIndex
38 * <li> If successful: update nextIndex and matchIndex for
40 * <li> If AppendEntries fails because of log inconsistency:
41 * decrement nextIndex and retry (§5.3)
43 * <li> If there exists an N such that N > commitIndex, a majority
44 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
45 * set commitIndex = N (§5.3, §5.4).
47 public class Leader extends AbstractLeader {
49 * Internal message sent to periodically check if this leader has become isolated and should transition
50 * to {@link IsolatedLeader}.
53 static final Object ISOLATED_LEADER_CHECK = new Object();
55 private final Stopwatch isolatedLeaderCheck = Stopwatch.createStarted();
56 private @Nullable LeadershipTransferContext leadershipTransferContext;
58 Leader(RaftActorContext context, @Nullable AbstractLeader initializeFromLeader) {
59 super(context, RaftState.Leader, initializeFromLeader);
62 public Leader(RaftActorContext context) {
67 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
68 Preconditions.checkNotNull(sender, "sender should not be null");
70 if (ISOLATED_LEADER_CHECK.equals(originalMessage)) {
71 if (isLeaderIsolated()) {
72 LOG.warn("{}: At least {} followers need to be active, Switching {} from Leader to IsolatedLeader",
73 context.getId(), getMinIsolatedLeaderPeerCount(), getLeaderId());
74 return internalSwitchBehavior(RaftState.IsolatedLeader);
79 return super.handleMessage(sender, originalMessage);
84 protected void beforeSendHeartbeat(){
85 if(isolatedLeaderCheck.elapsed(TimeUnit.MILLISECONDS) > context.getConfigParams().getIsolatedCheckIntervalInMillis()){
86 context.getActor().tell(ISOLATED_LEADER_CHECK, context.getActor());
87 isolatedLeaderCheck.reset().start();
90 if(leadershipTransferContext != null && leadershipTransferContext.isExpired(
91 context.getConfigParams().getElectionTimeOutInterval().toMillis())) {
92 LOG.debug("{}: Leadership transfer expired", logName());
93 leadershipTransferContext = null;
98 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
99 RaftActorBehavior returnBehavior = super.handleAppendEntriesReply(sender, appendEntriesReply);
100 tryToCompleteLeadershipTransfer(appendEntriesReply.getFollowerId());
101 return returnBehavior;
105 * Attempts to transfer leadership to a follower as per the raft paper (§3.10) as follows:
107 * <li>Start a timer (Stopwatch).</li>
108 * <li>Send an initial AppendEntries heartbeat to all followers.</li>
109 * <li>On AppendEntriesReply, check if the follower's new match Index matches the leader's last index</li>
110 * <li>If it matches, </li>
112 * <li>Send an additional AppendEntries to ensure the follower has applied all its log entries to its state.</li>
113 * <li>Send an ElectionTimeout to the follower to immediately start an election.</li>
114 * <li>Notify {@link RaftActorLeadershipTransferCohort#transferComplete}.</li>
116 * <li>Otherwise if the election time out period elapses, notify
117 * {@link RaftActorLeadershipTransferCohort#abortTtransfer}.</li>
120 * @param leadershipTransferCohort
122 public void transferLeadership(@Nonnull RaftActorLeadershipTransferCohort leadershipTransferCohort) {
123 LOG.debug("{}: Attempting to transfer leadership", logName());
125 leadershipTransferContext = new LeadershipTransferContext(leadershipTransferCohort);
127 // Send an immediate heart beat to the followers.
128 sendAppendEntries(0, false);
131 private void tryToCompleteLeadershipTransfer(String followerId) {
132 if(leadershipTransferContext == null) {
136 FollowerLogInformation followerInfo = getFollower(followerId);
137 if(followerInfo == null) {
141 long lastIndex = context.getReplicatedLog().lastIndex();
142 boolean isVoting = context.getPeerInfo(followerId).isVoting();
144 LOG.debug("{}: tryToCompleteLeadershipTransfer: followerId: {}, matchIndex: {}, lastIndex: {}, isVoting: {}",
145 logName(), followerId, followerInfo.getMatchIndex(), lastIndex, isVoting);
147 if(isVoting && followerInfo.getMatchIndex() == lastIndex) {
148 LOG.debug("{}: Follower's log matches - sending ElectionTimeout", logName());
150 // We can't be sure if the follower has applied all its log entries to its state so send an
151 // additional AppendEntries with the latest commit index.
152 sendAppendEntries(0, false);
154 // Now send a TimeoutNow message to the matching follower to immediately start an election.
155 ActorSelection followerActor = context.getPeerActorSelection(followerId);
156 followerActor.tell(TimeoutNow.INSTANCE, context.getActor());
158 LOG.debug("{}: Leader transfer complete", logName());
160 leadershipTransferContext.transferCohort.transferComplete();
161 leadershipTransferContext = null;
166 public void close() {
167 if(leadershipTransferContext != null) {
168 LeadershipTransferContext localLeadershipTransferContext = leadershipTransferContext;
169 leadershipTransferContext = null;
170 localLeadershipTransferContext.transferCohort.abortTransfer();
177 void markFollowerActive(String followerId) {
178 getFollower(followerId).markFollowerActive();
182 void markFollowerInActive(String followerId) {
183 getFollower(followerId).markFollowerInActive();
186 private static class LeadershipTransferContext {
187 RaftActorLeadershipTransferCohort transferCohort;
188 Stopwatch timer = Stopwatch.createStarted();
190 LeadershipTransferContext(RaftActorLeadershipTransferCohort transferCohort) {
191 this.transferCohort = transferCohort;
194 boolean isExpired(long timeout) {
195 if(timer.elapsed(TimeUnit.MILLISECONDS) >= timeout) {
196 transferCohort.abortTransfer();