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());
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 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
124 // whose term matches prevLogTerm (§5.3)
126 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
127 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
129 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
131 boolean outOfSync = true;
133 // First check if the logs are in sync or not
134 long lastIndex = lastIndex();
135 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
137 // The follower's log is out of sync because the leader does have
138 // an entry at prevLogIndex and this follower has no entries in
141 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
142 logName(), appendEntries.getPrevLogIndex());
143 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
145 // The follower's log is out of sync because the Leader's
146 // prevLogIndex entry was not found in it's log
148 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
149 logName(), appendEntries.getPrevLogIndex());
150 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
152 // The follower's log is out of sync because the Leader's
153 // prevLogIndex entry does exist in the follower's log but it has
154 // a different term in it
157 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
158 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
164 // We found that the log was out of sync so just send a negative
167 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
168 logName(), lastIndex, lastTerm());
170 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
171 lastTerm()), actor());
175 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
177 LOG.debug("{}: Number of entries to be appended = {}", logName(),
178 appendEntries.getEntries().size());
180 // 3. If an existing entry conflicts with a new one (same index
181 // but different terms), delete the existing entry and all that
183 int addEntriesFrom = 0;
184 if (context.getReplicatedLog().size() > 0) {
186 // Find the entry up until which the one that is not in the follower's log
187 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
188 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
189 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
191 if (newEntry == null) {
192 //newEntry not found in the log
196 if (newEntry.getTerm() == matchEntry.getTerm()) {
200 LOG.debug("{}: Removing entries from log starting at {}", logName(),
201 matchEntry.getIndex());
203 // Entries do not match so remove all subsequent entries
204 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
209 lastIndex = lastIndex();
210 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
211 (addEntriesFrom + lastIndex));
213 // 4. Append any new entries not already in the log
214 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
215 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
217 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
219 context.getReplicatedLog().appendAndPersist(entry);
222 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
225 // 5. If leaderCommit > commitIndex, set commitIndex =
226 // min(leaderCommit, index of last new entry)
228 lastIndex = lastIndex();
229 long prevCommitIndex = context.getCommitIndex();
231 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
233 if (prevCommitIndex != context.getCommitIndex()) {
234 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
237 // If commitIndex > lastApplied: increment lastApplied, apply
238 // log[lastApplied] to state machine (§5.3)
239 // check if there are any entries to be applied. last-applied can be equal to last-index
240 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
241 context.getLastApplied() < lastIndex) {
242 if(LOG.isDebugEnabled()) {
243 LOG.debug("{}: applyLogToStateMachine, " +
244 "appendEntries.getLeaderCommit(): {}," +
245 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
246 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
249 applyLogToStateMachine(appendEntries.getLeaderCommit());
252 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
253 lastIndex, lastTerm());
255 if(LOG.isTraceEnabled()) {
256 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
257 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
258 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
261 sender.tell(reply, actor());
263 if (!context.getSnapshotManager().isCapturing()) {
264 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
270 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
271 AppendEntriesReply appendEntriesReply) {
275 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
276 RequestVoteReply requestVoteReply) {
280 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
282 Object message = fromSerializableMessage(originalMessage);
284 if (message instanceof RaftRPC) {
285 RaftRPC rpc = (RaftRPC) message;
286 // If RPC request or response contains term T > currentTerm:
287 // set currentTerm = T, convert to follower (§5.1)
288 // This applies to all RPC messages and responses
289 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
290 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
291 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
293 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
297 if (message instanceof ElectionTimeout) {
298 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
299 return switchBehavior(new Candidate(context));
301 } else if (message instanceof InstallSnapshot) {
302 InstallSnapshot installSnapshot = (InstallSnapshot) message;
303 handleInstallSnapshot(sender, installSnapshot);
306 scheduleElection(electionDuration());
308 return super.handleMessage(sender, message);
311 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
313 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
314 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
315 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
317 if(snapshotTracker == null){
318 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
321 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
324 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
325 installSnapshot.getLastChunkHashCode())){
326 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
327 new ArrayList<ReplicatedLogEntry>(),
328 installSnapshot.getLastIncludedIndex(),
329 installSnapshot.getLastIncludedTerm(),
330 installSnapshot.getLastIncludedIndex(),
331 installSnapshot.getLastIncludedTerm());
333 actor().tell(new ApplySnapshot(snapshot), actor());
335 snapshotTracker = null;
339 InstallSnapshotReply reply = new InstallSnapshotReply(
340 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
342 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
344 sender.tell(reply, actor());
346 } catch (SnapshotTracker.InvalidChunkException e) {
347 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
349 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
350 -1, false), actor());
351 snapshotTracker = null;
353 } catch (Exception e){
354 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
356 //send reply with success as false. The chunk will be sent again on failure
357 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
358 installSnapshot.getChunkIndex(), false), actor());
364 public void close() throws Exception {
369 SnapshotTracker getSnapshotTracker(){
370 return snapshotTracker;
373 private class InitialSyncStatusTracker {
375 private static final long INVALID_LOG_INDEX = -2L;
376 private long initialLeaderCommit = INVALID_LOG_INDEX;
377 private boolean initialSyncUpDone = false;
378 private String syncedLeaderId = null;
379 private final ActorRef actor;
381 public InitialSyncStatusTracker(ActorRef actor) {
385 public void update(String leaderId, long leaderCommit, long commitIndex){
387 if(!leaderId.equals(syncedLeaderId)){
388 initialSyncUpDone = false;
389 initialLeaderCommit = INVALID_LOG_INDEX;
390 syncedLeaderId = leaderId;
393 if(!initialSyncUpDone){
394 if(initialLeaderCommit == INVALID_LOG_INDEX){
395 actor.tell(new FollowerInitialSyncUpStatus(false, getId()), ActorRef.noSender());
396 initialLeaderCommit = leaderCommit;
397 } else if(commitIndex >= initialLeaderCommit){
398 actor.tell(new FollowerInitialSyncUpStatus(true, getId()), ActorRef.noSender());
399 initialSyncUpDone = true;