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 // 1. Reply false if term < currentTerm (§5.1)
120 // This is handled in the appendEntries method of the base class
122 // If we got here then we do appear to be talking to the leader
123 leaderId = appendEntries.getLeaderId();
125 setLeaderPayloadVersion(appendEntries.getPayloadVersion());
127 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
128 // whose term matches prevLogTerm (§5.3)
130 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
131 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
133 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
135 boolean outOfSync = true;
137 // First check if the logs are in sync or not
138 long lastIndex = lastIndex();
139 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
141 // The follower's log is out of sync because the leader does have
142 // an entry at prevLogIndex and this follower has no entries in
145 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
146 logName(), appendEntries.getPrevLogIndex());
147 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
149 // The follower's log is out of sync because the Leader's
150 // prevLogIndex entry was not found in it's log
152 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
153 logName(), appendEntries.getPrevLogIndex());
154 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
156 // The follower's log is out of sync because the Leader's
157 // prevLogIndex entry does exist in the follower's log but it has
158 // a different term in it
161 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
162 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
168 // We found that the log was out of sync so just send a negative
171 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
172 logName(), lastIndex, lastTerm());
174 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
175 lastTerm(), context.getPayloadVersion()), actor());
179 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
181 LOG.debug("{}: Number of entries to be appended = {}", logName(),
182 appendEntries.getEntries().size());
184 // 3. If an existing entry conflicts with a new one (same index
185 // but different terms), delete the existing entry and all that
187 int addEntriesFrom = 0;
188 if (context.getReplicatedLog().size() > 0) {
190 // Find the entry up until which the one that is not in the follower's log
191 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
192 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
193 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
195 if (newEntry == null) {
196 //newEntry not found in the log
200 if (newEntry.getTerm() == matchEntry.getTerm()) {
204 LOG.debug("{}: Removing entries from log starting at {}", logName(),
205 matchEntry.getIndex());
207 // Entries do not match so remove all subsequent entries
208 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
213 lastIndex = lastIndex();
214 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
215 (addEntriesFrom + lastIndex));
217 // 4. Append any new entries not already in the log
218 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
219 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
221 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
223 context.getReplicatedLog().appendAndPersist(entry);
226 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
229 // 5. If leaderCommit > commitIndex, set commitIndex =
230 // min(leaderCommit, index of last new entry)
232 lastIndex = lastIndex();
233 long prevCommitIndex = context.getCommitIndex();
235 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
237 if (prevCommitIndex != context.getCommitIndex()) {
238 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
241 // If commitIndex > lastApplied: increment lastApplied, apply
242 // log[lastApplied] to state machine (§5.3)
243 // check if there are any entries to be applied. last-applied can be equal to last-index
244 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
245 context.getLastApplied() < lastIndex) {
246 if(LOG.isDebugEnabled()) {
247 LOG.debug("{}: applyLogToStateMachine, " +
248 "appendEntries.getLeaderCommit(): {}," +
249 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
250 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
253 applyLogToStateMachine(appendEntries.getLeaderCommit());
256 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
257 lastIndex, lastTerm(), context.getPayloadVersion());
259 if(LOG.isTraceEnabled()) {
260 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
261 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
262 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
265 sender.tell(reply, actor());
267 if (!context.getSnapshotManager().isCapturing()) {
268 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
274 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
275 AppendEntriesReply appendEntriesReply) {
279 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
280 RequestVoteReply requestVoteReply) {
284 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
286 Object message = fromSerializableMessage(originalMessage);
288 if (message instanceof RaftRPC) {
289 RaftRPC rpc = (RaftRPC) message;
290 // If RPC request or response contains term T > currentTerm:
291 // set currentTerm = T, convert to follower (§5.1)
292 // This applies to all RPC messages and responses
293 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
294 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
295 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
297 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
301 if (message instanceof ElectionTimeout) {
302 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
303 return switchBehavior(new Candidate(context));
305 } else if (message instanceof InstallSnapshot) {
306 InstallSnapshot installSnapshot = (InstallSnapshot) message;
307 handleInstallSnapshot(sender, installSnapshot);
310 scheduleElection(electionDuration());
312 return super.handleMessage(sender, message);
315 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
317 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
318 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
319 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
321 if(snapshotTracker == null){
322 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
325 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
328 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
329 installSnapshot.getLastChunkHashCode())){
330 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
331 new ArrayList<ReplicatedLogEntry>(),
332 installSnapshot.getLastIncludedIndex(),
333 installSnapshot.getLastIncludedTerm(),
334 installSnapshot.getLastIncludedIndex(),
335 installSnapshot.getLastIncludedTerm());
337 actor().tell(new ApplySnapshot(snapshot), actor());
339 snapshotTracker = null;
343 InstallSnapshotReply reply = new InstallSnapshotReply(
344 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
346 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
348 sender.tell(reply, actor());
350 } catch (SnapshotTracker.InvalidChunkException e) {
351 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
353 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
354 -1, false), actor());
355 snapshotTracker = null;
357 } catch (Exception e){
358 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
360 //send reply with success as false. The chunk will be sent again on failure
361 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
362 installSnapshot.getChunkIndex(), false), actor());
368 public void close() throws Exception {
373 SnapshotTracker getSnapshotTracker(){
374 return snapshotTracker;
377 private class InitialSyncStatusTracker {
379 private static final long INVALID_LOG_INDEX = -2L;
380 private long initialLeaderCommit = INVALID_LOG_INDEX;
381 private boolean initialSyncUpDone = false;
382 private String syncedLeaderId = null;
383 private final ActorRef actor;
385 public InitialSyncStatusTracker(ActorRef actor) {
389 public void update(String leaderId, long leaderCommit, long commitIndex){
391 if(!leaderId.equals(syncedLeaderId)){
392 initialSyncUpDone = false;
393 initialLeaderCommit = INVALID_LOG_INDEX;
394 syncedLeaderId = leaderId;
397 if(!initialSyncUpDone){
398 if(initialLeaderCommit == INVALID_LOG_INDEX){
399 actor.tell(new FollowerInitialSyncUpStatus(false, getId()), ActorRef.noSender());
400 initialLeaderCommit = leaderCommit;
401 } else if(commitIndex >= initialLeaderCommit){
402 actor.tell(new FollowerInitialSyncUpStatus(true, getId()), ActorRef.noSender());
403 initialSyncUpDone = true;