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.RequestVote;
27 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
30 * The behavior of a RaftActor in the Follower state
33 * <li> Respond to RPCs from candidates and leaders
34 * <li> If election timeout elapses without receiving AppendEntries
35 * RPC from current leader or granting vote to candidate:
36 * convert to candidate
39 public class Follower extends AbstractRaftActorBehavior {
41 private SnapshotTracker snapshotTracker = null;
43 private final InitialSyncStatusTracker initialSyncStatusTracker;
45 public Follower(RaftActorContext context) {
46 super(context, RaftState.Follower);
48 initialSyncStatusTracker = new InitialSyncStatusTracker(context.getActor());
50 if(context.getRaftPolicy().automaticElectionsEnabled()) {
51 if (context.getPeerAddresses().isEmpty()) {
52 actor().tell(ELECTION_TIMEOUT, actor());
54 scheduleElection(electionDuration());
60 private boolean isLogEntryPresent(long index){
61 if(index == context.getReplicatedLog().getSnapshotIndex()){
65 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
68 return previousEntry != null;
72 private long getLogEntryTerm(long index){
73 if(index == context.getReplicatedLog().getSnapshotIndex()){
74 return context.getReplicatedLog().getSnapshotTerm();
77 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
80 if(previousEntry != null){
81 return previousEntry.getTerm();
87 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
88 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
91 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
92 AppendEntries appendEntries) {
94 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
95 if(LOG.isTraceEnabled()) {
96 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
97 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
98 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
101 // TODO : Refactor this method into a bunch of smaller methods
102 // to make it easier to read. Before refactoring ensure tests
103 // cover the code properly
105 if (snapshotTracker != null) {
106 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
107 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
108 lastIndex(), lastTerm(), context.getPayloadVersion());
110 if(LOG.isDebugEnabled()) {
111 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
113 sender.tell(reply, actor());
118 // If we got here then we do appear to be talking to the leader
119 leaderId = appendEntries.getLeaderId();
121 setLeaderPayloadVersion(appendEntries.getPayloadVersion());
123 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
124 // First check if the logs are in sync or not
125 long lastIndex = lastIndex();
127 if (isOutOfSync(appendEntries)) {
128 // We found that the log was out of sync so just send a negative
131 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
132 logName(), lastIndex, lastTerm());
134 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
135 lastTerm(), context.getPayloadVersion()), actor());
139 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
141 LOG.debug("{}: Number of entries to be appended = {}", logName(),
142 appendEntries.getEntries().size());
144 // 3. If an existing entry conflicts with a new one (same index
145 // but different terms), delete the existing entry and all that
147 int addEntriesFrom = 0;
148 if (context.getReplicatedLog().size() > 0) {
150 // Find the entry up until the one that is not in the follower's log
151 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
152 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
153 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
155 if (newEntry == null) {
156 //newEntry not found in the log
160 if (newEntry.getTerm() == matchEntry.getTerm()) {
164 if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
166 LOG.debug("{}: Removing entries from log starting at {}", logName(),
167 matchEntry.getIndex());
169 // Entries do not match so remove all subsequent entries
170 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
173 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
174 lastTerm(), context.getPayloadVersion(), true), actor());
180 lastIndex = lastIndex();
181 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
182 (addEntriesFrom + lastIndex));
184 // 4. Append any new entries not already in the log
185 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
186 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
188 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
190 context.getReplicatedLog().appendAndPersist(entry);
193 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
196 // 5. If leaderCommit > commitIndex, set commitIndex =
197 // min(leaderCommit, index of last new entry)
199 lastIndex = lastIndex();
200 long prevCommitIndex = context.getCommitIndex();
202 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
204 if (prevCommitIndex != context.getCommitIndex()) {
205 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
208 // If commitIndex > lastApplied: increment lastApplied, apply
209 // log[lastApplied] to state machine (ยง5.3)
210 // check if there are any entries to be applied. last-applied can be equal to last-index
211 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
212 context.getLastApplied() < lastIndex) {
213 if(LOG.isDebugEnabled()) {
214 LOG.debug("{}: applyLogToStateMachine, " +
215 "appendEntries.getLeaderCommit(): {}," +
216 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
217 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
220 applyLogToStateMachine(appendEntries.getLeaderCommit());
223 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
224 lastIndex, lastTerm(), context.getPayloadVersion());
226 if(LOG.isTraceEnabled()) {
227 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
228 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
229 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
232 sender.tell(reply, actor());
234 if (!context.getSnapshotManager().isCapturing()) {
235 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
241 private boolean isOutOfSync(AppendEntries appendEntries) {
243 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
244 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
245 long lastIndex = lastIndex();
246 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
247 boolean outOfSync = true;
249 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
251 // The follower's log is out of sync because the leader does have
252 // an entry at prevLogIndex and this follower has no entries in
255 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
256 logName(), appendEntries.getPrevLogIndex());
257 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
259 // The follower's log is out of sync because the Leader's
260 // prevLogIndex entry was not found in it's log
262 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
263 logName(), appendEntries.getPrevLogIndex());
264 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
266 // The follower's log is out of sync because the Leader's
267 // prevLogIndex entry does exist in the follower's log but it has
268 // a different term in it
271 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
272 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
273 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
274 && appendEntries.getReplicatedToAllIndex() != -1
275 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
276 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
277 // the previous entry in it's in-memory journal
280 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
281 logName(), appendEntries.getReplicatedToAllIndex());
282 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
283 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0 &&
284 !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)){
286 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
287 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
294 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
295 AppendEntriesReply appendEntriesReply) {
299 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
300 RequestVoteReply requestVoteReply) {
304 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
306 Object message = fromSerializableMessage(originalMessage);
308 if (message instanceof RaftRPC) {
309 RaftRPC rpc = (RaftRPC) message;
310 // If RPC request or response contains term T > currentTerm:
311 // set currentTerm = T, convert to follower (ยง5.1)
312 // This applies to all RPC messages and responses
313 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
314 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
315 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
317 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
321 if (message instanceof ElectionTimeout) {
322 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
323 return internalSwitchBehavior(RaftState.Candidate);
325 } else if (message instanceof InstallSnapshot) {
326 InstallSnapshot installSnapshot = (InstallSnapshot) message;
327 handleInstallSnapshot(sender, installSnapshot);
330 if(message instanceof RaftRPC && (!(message instanceof RequestVote) || (canGrantVote((RequestVote) message)))){
331 scheduleElection(electionDuration());
334 return super.handleMessage(sender, message);
337 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
339 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
340 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
341 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
343 if(snapshotTracker == null){
344 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
347 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
350 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
351 installSnapshot.getLastChunkHashCode())){
352 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
353 new ArrayList<ReplicatedLogEntry>(),
354 installSnapshot.getLastIncludedIndex(),
355 installSnapshot.getLastIncludedTerm(),
356 installSnapshot.getLastIncludedIndex(),
357 installSnapshot.getLastIncludedTerm());
359 actor().tell(new ApplySnapshot(snapshot), actor());
361 snapshotTracker = null;
365 InstallSnapshotReply reply = new InstallSnapshotReply(
366 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
368 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
370 sender.tell(reply, actor());
372 } catch (SnapshotTracker.InvalidChunkException e) {
373 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
375 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
376 -1, false), actor());
377 snapshotTracker = null;
379 } catch (Exception e){
380 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
382 //send reply with success as false. The chunk will be sent again on failure
383 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
384 installSnapshot.getChunkIndex(), false), actor());
390 public void close() throws Exception {
395 SnapshotTracker getSnapshotTracker(){
396 return snapshotTracker;
399 private class InitialSyncStatusTracker {
401 private static final long INVALID_LOG_INDEX = -2L;
402 private long initialLeaderCommit = INVALID_LOG_INDEX;
403 private boolean initialSyncUpDone = false;
404 private String syncedLeaderId = null;
405 private final ActorRef actor;
407 public InitialSyncStatusTracker(ActorRef actor) {
411 public void update(String leaderId, long leaderCommit, long commitIndex){
413 if(!leaderId.equals(syncedLeaderId)){
414 initialSyncUpDone = false;
415 initialLeaderCommit = INVALID_LOG_INDEX;
416 syncedLeaderId = leaderId;
419 if(!initialSyncUpDone){
420 if(initialLeaderCommit == INVALID_LOG_INDEX){
421 actor.tell(new FollowerInitialSyncUpStatus(false, getId()), ActorRef.noSender());
422 initialLeaderCommit = leaderCommit;
423 } else if(commitIndex >= initialLeaderCommit){
424 actor.tell(new FollowerInitialSyncUpStatus(true, getId()), ActorRef.noSender());
425 initialSyncUpDone = true;