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.getRaftPolicy().automaticElectionsEnabled()) {
52 if (context.getPeerAddresses().isEmpty()) {
53 actor().tell(ELECTION_TIMEOUT, actor());
55 scheduleElection(electionDuration());
61 private boolean isLogEntryPresent(long index){
62 if(index == context.getReplicatedLog().getSnapshotIndex()){
66 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
69 return previousEntry != null;
73 private long getLogEntryTerm(long index){
74 if(index == context.getReplicatedLog().getSnapshotIndex()){
75 return context.getReplicatedLog().getSnapshotTerm();
78 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
81 if(previousEntry != null){
82 return previousEntry.getTerm();
88 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
89 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
92 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
93 AppendEntries appendEntries) {
95 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
96 if(LOG.isTraceEnabled()) {
97 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
98 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
99 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
102 // TODO : Refactor this method into a bunch of smaller methods
103 // to make it easier to read. Before refactoring ensure tests
104 // cover the code properly
106 if (snapshotTracker != null) {
107 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
108 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
109 lastIndex(), lastTerm(), context.getPayloadVersion());
111 if(LOG.isDebugEnabled()) {
112 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
114 sender.tell(reply, actor());
119 // If we got here then we do appear to be talking to the leader
120 leaderId = appendEntries.getLeaderId();
122 setLeaderPayloadVersion(appendEntries.getPayloadVersion());
124 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
125 // First check if the logs are in sync or not
126 long lastIndex = lastIndex();
128 if (isOutOfSync(appendEntries)) {
129 // We found that the log was out of sync so just send a negative
132 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
133 logName(), lastIndex, lastTerm());
135 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
136 lastTerm(), context.getPayloadVersion()), actor());
140 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
142 LOG.debug("{}: Number of entries to be appended = {}", logName(),
143 appendEntries.getEntries().size());
145 // 3. If an existing entry conflicts with a new one (same index
146 // but different terms), delete the existing entry and all that
148 int addEntriesFrom = 0;
149 if (context.getReplicatedLog().size() > 0) {
151 // Find the entry up until which the one that is not in the follower's log
152 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
153 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
154 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
156 if (newEntry == null) {
157 //newEntry not found in the log
161 if (newEntry.getTerm() == matchEntry.getTerm()) {
165 LOG.debug("{}: Removing entries from log starting at {}", logName(),
166 matchEntry.getIndex());
168 // Entries do not match so remove all subsequent entries
169 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
174 lastIndex = lastIndex();
175 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
176 (addEntriesFrom + lastIndex));
178 // 4. Append any new entries not already in the log
179 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
180 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
182 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
184 context.getReplicatedLog().appendAndPersist(entry);
187 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
190 // 5. If leaderCommit > commitIndex, set commitIndex =
191 // min(leaderCommit, index of last new entry)
193 lastIndex = lastIndex();
194 long prevCommitIndex = context.getCommitIndex();
196 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
198 if (prevCommitIndex != context.getCommitIndex()) {
199 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
202 // If commitIndex > lastApplied: increment lastApplied, apply
203 // log[lastApplied] to state machine (ยง5.3)
204 // check if there are any entries to be applied. last-applied can be equal to last-index
205 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
206 context.getLastApplied() < lastIndex) {
207 if(LOG.isDebugEnabled()) {
208 LOG.debug("{}: applyLogToStateMachine, " +
209 "appendEntries.getLeaderCommit(): {}," +
210 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
211 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
214 applyLogToStateMachine(appendEntries.getLeaderCommit());
217 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
218 lastIndex, lastTerm(), context.getPayloadVersion());
220 if(LOG.isTraceEnabled()) {
221 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
222 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
223 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
226 sender.tell(reply, actor());
228 if (!context.getSnapshotManager().isCapturing()) {
229 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
235 private boolean isOutOfSync(AppendEntries appendEntries) {
237 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
238 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
239 long lastIndex = lastIndex();
240 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
241 boolean outOfSync = true;
243 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
245 // The follower's log is out of sync because the leader does have
246 // an entry at prevLogIndex and this follower has no entries in
249 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
250 logName(), appendEntries.getPrevLogIndex());
251 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
253 // The follower's log is out of sync because the Leader's
254 // prevLogIndex entry was not found in it's log
256 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
257 logName(), appendEntries.getPrevLogIndex());
258 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
260 // The follower's log is out of sync because the Leader's
261 // prevLogIndex entry does exist in the follower's log but it has
262 // a different term in it
265 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
266 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
267 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
268 && appendEntries.getReplicatedToAllIndex() != -1
269 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
270 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
271 // the previous entry in it's in-memory journal
274 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
275 logName(), appendEntries.getReplicatedToAllIndex());
276 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
277 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0 &&
278 !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)){
280 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
281 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
288 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
289 AppendEntriesReply appendEntriesReply) {
293 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
294 RequestVoteReply requestVoteReply) {
298 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
300 Object message = fromSerializableMessage(originalMessage);
302 if (message instanceof RaftRPC) {
303 RaftRPC rpc = (RaftRPC) message;
304 // If RPC request or response contains term T > currentTerm:
305 // set currentTerm = T, convert to follower (ยง5.1)
306 // This applies to all RPC messages and responses
307 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
308 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
309 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
311 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
315 if (message instanceof ElectionTimeout) {
316 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
317 return switchBehavior(new Candidate(context));
319 } else if (message instanceof InstallSnapshot) {
320 InstallSnapshot installSnapshot = (InstallSnapshot) message;
321 handleInstallSnapshot(sender, installSnapshot);
324 scheduleElection(electionDuration());
326 return super.handleMessage(sender, message);
329 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
331 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
332 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
333 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
335 if(snapshotTracker == null){
336 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
339 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
342 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
343 installSnapshot.getLastChunkHashCode())){
344 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
345 new ArrayList<ReplicatedLogEntry>(),
346 installSnapshot.getLastIncludedIndex(),
347 installSnapshot.getLastIncludedTerm(),
348 installSnapshot.getLastIncludedIndex(),
349 installSnapshot.getLastIncludedTerm());
351 actor().tell(new ApplySnapshot(snapshot), actor());
353 snapshotTracker = null;
357 InstallSnapshotReply reply = new InstallSnapshotReply(
358 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
360 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
362 sender.tell(reply, actor());
364 } catch (SnapshotTracker.InvalidChunkException e) {
365 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
367 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
368 -1, false), actor());
369 snapshotTracker = null;
371 } catch (Exception e){
372 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
374 //send reply with success as false. The chunk will be sent again on failure
375 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
376 installSnapshot.getChunkIndex(), false), actor());
382 public void close() throws Exception {
387 SnapshotTracker getSnapshotTracker(){
388 return snapshotTracker;
391 private class InitialSyncStatusTracker {
393 private static final long INVALID_LOG_INDEX = -2L;
394 private long initialLeaderCommit = INVALID_LOG_INDEX;
395 private boolean initialSyncUpDone = false;
396 private String syncedLeaderId = null;
397 private final ActorRef actor;
399 public InitialSyncStatusTracker(ActorRef actor) {
403 public void update(String leaderId, long leaderCommit, long commitIndex){
405 if(!leaderId.equals(syncedLeaderId)){
406 initialSyncUpDone = false;
407 initialLeaderCommit = INVALID_LOG_INDEX;
408 syncedLeaderId = leaderId;
411 if(!initialSyncUpDone){
412 if(initialLeaderCommit == INVALID_LOG_INDEX){
413 actor.tell(new FollowerInitialSyncUpStatus(false, getId()), ActorRef.noSender());
414 initialLeaderCommit = leaderCommit;
415 } else if(commitIndex >= initialLeaderCommit){
416 actor.tell(new FollowerInitialSyncUpStatus(true, getId()), ActorRef.noSender());
417 initialSyncUpDone = true;