Skip to content

Commit 40a19f1

Browse files
committed
raft: exit maybeSendAppend early if term is not found
Previously, maybeSendAppend would also try to fetch entries, only to return a few lines below at the errors check. Signed-off-by: Pavel Kalinnikov <[email protected]>
1 parent ee08961 commit 40a19f1

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

raft.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -603,35 +603,38 @@ func (r *raft) maybeSendAppend(to uint64, sendIfEmpty bool) bool {
603603
return false
604604
}
605605

606-
lastIndex, nextIndex := pr.Next-1, pr.Next
607-
lastTerm, errt := r.raftLog.term(lastIndex)
606+
prevIndex := pr.Next - 1
607+
prevTerm, err := r.raftLog.term(prevIndex)
608+
if err != nil {
609+
// The log probably got truncated at >= pr.Next, so we can't catch up the
610+
// follower log anymore. Send a snapshot instead.
611+
return r.maybeSendSnapshot(to, pr)
612+
}
608613

609614
var ents []pb.Entry
610-
var erre error
611615
// In a throttled StateReplicate only send empty MsgApp, to ensure progress.
612616
// Otherwise, if we had a full Inflights and all inflight messages were in
613617
// fact dropped, replication to that follower would stall. Instead, an empty
614618
// MsgApp will eventually reach the follower (heartbeats responses prompt the
615619
// leader to send an append), allowing it to be acked or rejected, both of
616620
// which will clear out Inflights.
617621
if pr.State != tracker.StateReplicate || !pr.Inflights.Full() {
618-
ents, erre = r.raftLog.entries(nextIndex, r.maxMsgSize)
622+
ents, err = r.raftLog.entries(pr.Next, r.maxMsgSize)
619623
}
620-
621624
if len(ents) == 0 && !sendIfEmpty {
622625
return false
623626
}
624-
625-
if errt != nil || erre != nil { // send snapshot if we failed to get term or entries
627+
// TODO(pav-kv): move this check up to where err is returned.
628+
if err != nil { // send a snapshot if we failed to get the entries
626629
return r.maybeSendSnapshot(to, pr)
627630
}
628631

629632
// Send the actual MsgApp otherwise, and update the progress accordingly.
630633
r.send(pb.Message{
631634
To: to,
632635
Type: pb.MsgApp,
633-
Index: lastIndex,
634-
LogTerm: lastTerm,
636+
Index: prevIndex,
637+
LogTerm: prevTerm,
635638
Entries: ents,
636639
Commit: r.raftLog.committed,
637640
})

0 commit comments

Comments
 (0)