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
9 package org.opendaylight.controller.cluster.raft.behaviors;
11 import akka.actor.ActorRef;
12 import com.google.common.annotations.VisibleForTesting;
13 import java.util.ArrayList;
14 import org.opendaylight.controller.cluster.raft.RaftActorContext;
15 import org.opendaylight.controller.cluster.raft.RaftState;
16 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
17 import org.opendaylight.controller.cluster.raft.Snapshot;
18 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
19 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
20 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
21 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
22 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
23 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
24 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
25 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
26 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
29 * The behavior of a RaftActor in the Follower state
32 * <li> Respond to RPCs from candidates and leaders
33 * <li> If election timeout elapses without receiving AppendEntries
34 * RPC from current leader or granting vote to candidate:
35 * convert to candidate
38 public class Follower extends AbstractRaftActorBehavior {
42 private SnapshotTracker snapshotTracker = null;
44 private final InitialSyncStatusTracker initialSyncStatusTracker;
46 public Follower(RaftActorContext context) {
47 super(context, RaftState.Follower);
49 initialSyncStatusTracker = new InitialSyncStatusTracker(context.getActor());
51 if(context.getPeerAddresses().isEmpty()){
52 actor().tell(ELECTION_TIMEOUT, actor());
54 scheduleElection(electionDuration());
59 private boolean isLogEntryPresent(long index){
60 if(index == context.getReplicatedLog().getSnapshotIndex()){
64 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
67 return previousEntry != null;
71 private long getLogEntryTerm(long index){
72 if(index == context.getReplicatedLog().getSnapshotIndex()){
73 return context.getReplicatedLog().getSnapshotTerm();
76 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
79 if(previousEntry != null){
80 return previousEntry.getTerm();
86 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
87 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
90 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
91 AppendEntries appendEntries) {
93 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
94 if(LOG.isTraceEnabled()) {
95 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
96 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
97 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
100 // TODO : Refactor this method into a bunch of smaller methods
101 // to make it easier to read. Before refactoring ensure tests
102 // cover the code properly
104 if (snapshotTracker != null) {
105 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
106 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
107 lastIndex(), lastTerm(), context.getPayloadVersion());
109 if(LOG.isDebugEnabled()) {
110 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
112 sender.tell(reply, actor());
117 // 1. Reply false if term < currentTerm (§5.1)
118 // This is handled in the appendEntries method of the base class
120 // If we got here then we do appear to be talking to the leader
121 leaderId = appendEntries.getLeaderId();
123 setLeaderPayloadVersion(appendEntries.getPayloadVersion());
125 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
126 // whose term matches prevLogTerm (§5.3)
128 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
129 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
131 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
133 boolean outOfSync = true;
135 // First check if the logs are in sync or not
136 long lastIndex = lastIndex();
137 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
139 // The follower's log is out of sync because the leader does have
140 // an entry at prevLogIndex and this follower has no entries in
143 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
144 logName(), appendEntries.getPrevLogIndex());
145 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
147 // The follower's log is out of sync because the Leader's
148 // prevLogIndex entry was not found in it's log
150 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
151 logName(), appendEntries.getPrevLogIndex());
152 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
154 // The follower's log is out of sync because the Leader's
155 // prevLogIndex entry does exist in the follower's log but it has
156 // a different term in it
159 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
160 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
166 // We found that the log was out of sync so just send a negative
169 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
170 logName(), lastIndex, lastTerm());
172 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
173 lastTerm(), context.getPayloadVersion()), actor());
177 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
179 LOG.debug("{}: Number of entries to be appended = {}", logName(),
180 appendEntries.getEntries().size());
182 // 3. If an existing entry conflicts with a new one (same index
183 // but different terms), delete the existing entry and all that
185 int addEntriesFrom = 0;
186 if (context.getReplicatedLog().size() > 0) {
188 // Find the entry up until which the one that is not in the follower's log
189 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
190 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
191 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
193 if (newEntry == null) {
194 //newEntry not found in the log
198 if (newEntry.getTerm() == matchEntry.getTerm()) {
202 LOG.debug("{}: Removing entries from log starting at {}", logName(),
203 matchEntry.getIndex());
205 // Entries do not match so remove all subsequent entries
206 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
211 lastIndex = lastIndex();
212 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
213 (addEntriesFrom + lastIndex));
215 // 4. Append any new entries not already in the log
216 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
217 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
219 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
221 context.getReplicatedLog().appendAndPersist(entry);
224 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
227 // 5. If leaderCommit > commitIndex, set commitIndex =
228 // min(leaderCommit, index of last new entry)
230 lastIndex = lastIndex();
231 long prevCommitIndex = context.getCommitIndex();
233 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
235 if (prevCommitIndex != context.getCommitIndex()) {
236 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
239 // If commitIndex > lastApplied: increment lastApplied, apply
240 // log[lastApplied] to state machine (§5.3)
241 // check if there are any entries to be applied. last-applied can be equal to last-index
242 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
243 context.getLastApplied() < lastIndex) {
244 if(LOG.isDebugEnabled()) {
245 LOG.debug("{}: applyLogToStateMachine, " +
246 "appendEntries.getLeaderCommit(): {}," +
247 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
248 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
251 applyLogToStateMachine(appendEntries.getLeaderCommit());
254 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
255 lastIndex, lastTerm(), context.getPayloadVersion());
257 if(LOG.isTraceEnabled()) {
258 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
259 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
260 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
263 sender.tell(reply, actor());
265 if (!context.getSnapshotManager().isCapturing()) {
266 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
272 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
273 AppendEntriesReply appendEntriesReply) {
277 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
278 RequestVoteReply requestVoteReply) {
282 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
284 Object message = fromSerializableMessage(originalMessage);
286 if (message instanceof RaftRPC) {
287 RaftRPC rpc = (RaftRPC) message;
288 // If RPC request or response contains term T > currentTerm:
289 // set currentTerm = T, convert to follower (§5.1)
290 // This applies to all RPC messages and responses
291 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
292 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
293 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
295 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
299 if (message instanceof ElectionTimeout) {
300 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
301 return switchBehavior(new Candidate(context));
303 } else if (message instanceof InstallSnapshot) {
304 InstallSnapshot installSnapshot = (InstallSnapshot) message;
305 handleInstallSnapshot(sender, installSnapshot);
308 scheduleElection(electionDuration());
310 return super.handleMessage(sender, message);
313 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
315 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
316 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
317 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
319 if(snapshotTracker == null){
320 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
323 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
326 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
327 installSnapshot.getLastChunkHashCode())){
328 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
329 new ArrayList<ReplicatedLogEntry>(),
330 installSnapshot.getLastIncludedIndex(),
331 installSnapshot.getLastIncludedTerm(),
332 installSnapshot.getLastIncludedIndex(),
333 installSnapshot.getLastIncludedTerm());
335 actor().tell(new ApplySnapshot(snapshot), actor());
337 snapshotTracker = null;
341 InstallSnapshotReply reply = new InstallSnapshotReply(
342 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
344 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
346 sender.tell(reply, actor());
348 } catch (SnapshotTracker.InvalidChunkException e) {
349 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
351 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
352 -1, false), actor());
353 snapshotTracker = null;
355 } catch (Exception e){
356 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
358 //send reply with success as false. The chunk will be sent again on failure
359 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
360 installSnapshot.getChunkIndex(), false), actor());
366 public void close() throws Exception {
371 SnapshotTracker getSnapshotTracker(){
372 return snapshotTracker;
375 private class InitialSyncStatusTracker {
377 private static final long INVALID_LOG_INDEX = -2L;
378 private long initialLeaderCommit = INVALID_LOG_INDEX;
379 private boolean initialSyncUpDone = false;
380 private String syncedLeaderId = null;
381 private final ActorRef actor;
383 public InitialSyncStatusTracker(ActorRef actor) {
387 public void update(String leaderId, long leaderCommit, long commitIndex){
389 if(!leaderId.equals(syncedLeaderId)){
390 initialSyncUpDone = false;
391 initialLeaderCommit = INVALID_LOG_INDEX;
392 syncedLeaderId = leaderId;
395 if(!initialSyncUpDone){
396 if(initialLeaderCommit == INVALID_LOG_INDEX){
397 actor.tell(new FollowerInitialSyncUpStatus(false, getId()), ActorRef.noSender());
398 initialLeaderCommit = leaderCommit;
399 } else if(commitIndex >= initialLeaderCommit){
400 actor.tell(new FollowerInitialSyncUpStatus(true, getId()), ActorRef.noSender());
401 initialSyncUpDone = true;