-
Notifications
You must be signed in to change notification settings - Fork 1.1k
fix liveness issue when leader's disk stalls #683
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tgross
wants to merge
3
commits into
main
Choose a base branch
from
liveness-on-leader-disk-stall
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+248
−28
Open
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,4 +1,4 @@ | ||||||||||||
| // Copyright IBM Corp. 2013, 2025 | ||||||||||||
| // Copyright IBM Corp. 2013, 2026 | ||||||||||||
| // SPDX-License-Identifier: MPL-2.0 | ||||||||||||
|
|
||||||||||||
| package raft | ||||||||||||
|
|
@@ -10,7 +10,7 @@ import ( | |||||||||||
| "sync/atomic" | ||||||||||||
| "time" | ||||||||||||
|
|
||||||||||||
| "github.com/hashicorp/go-metrics/compat" | ||||||||||||
| metrics "github.com/hashicorp/go-metrics/compat" | ||||||||||||
| ) | ||||||||||||
|
|
||||||||||||
| const ( | ||||||||||||
|
|
@@ -73,6 +73,14 @@ type followerReplication struct { | |||||||||||
| // lastContactLock protects 'lastContact'. | ||||||||||||
| lastContactLock sync.RWMutex | ||||||||||||
|
|
||||||||||||
| // lastReplicationStart is updated to the current time whenever a | ||||||||||||
| // replicateTo method call is started, and is cleared when the replicateTo | ||||||||||||
| // method returns. This is used by heartbeats to check if replication has | ||||||||||||
| // stalled for too long. | ||||||||||||
| lastReplicationStart time.Time | ||||||||||||
| // lastReplicationStartLock protects 'lastReplicationStart'. | ||||||||||||
| lastReplicationStartLock sync.RWMutex | ||||||||||||
|
|
||||||||||||
| // failures counts the number of failed RPCs since the last success, which is | ||||||||||||
| // used to apply backoff. | ||||||||||||
| failures uint64 | ||||||||||||
|
|
@@ -132,6 +140,30 @@ func (s *followerReplication) setLastContact() { | |||||||||||
| s.lastContactLock.Unlock() | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| // resetLastReplicationStart clears the marker for the start of the last replication | ||||||||||||
| // attempt | ||||||||||||
| func (s *followerReplication) resetLastReplicationStart() { | ||||||||||||
| s.lastReplicationStartLock.Lock() | ||||||||||||
| s.lastReplicationStart = time.Time{} | ||||||||||||
| s.lastReplicationStartLock.Unlock() | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| // setLastReplicationStart sets the marker for the start of the last replication | ||||||||||||
| // attempt to the current time | ||||||||||||
| func (s *followerReplication) setLastReplicationStart() { | ||||||||||||
| s.lastReplicationStartLock.Lock() | ||||||||||||
| s.lastReplicationStart = time.Now() | ||||||||||||
| s.lastReplicationStartLock.Unlock() | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| // getLastReplicationStart gets the start of the last replication attempt | ||||||||||||
| func (s *followerReplication) getLastReplicationStart() time.Time { | ||||||||||||
| s.lastReplicationStartLock.RLock() | ||||||||||||
| t := s.lastReplicationStart | ||||||||||||
| s.lastReplicationStartLock.RUnlock() | ||||||||||||
| return t | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| // replicate is a long running routine that replicates log entries to a single | ||||||||||||
| // follower. | ||||||||||||
| func (r *Raft) replicate(s *followerReplication) { | ||||||||||||
|
|
@@ -140,17 +172,22 @@ func (r *Raft) replicate(s *followerReplication) { | |||||||||||
| defer close(stopHeartbeat) | ||||||||||||
| r.goFunc(func() { r.heartbeat(s, stopHeartbeat) }) | ||||||||||||
|
|
||||||||||||
| defer s.resetLastReplicationStart() | ||||||||||||
|
|
||||||||||||
| RPC: | ||||||||||||
| shouldStop := false | ||||||||||||
| for !shouldStop { | ||||||||||||
| s.resetLastReplicationStart() | ||||||||||||
| select { | ||||||||||||
| case maxIndex := <-s.stopCh: | ||||||||||||
| // Make a best effort to replicate up to this index | ||||||||||||
| if maxIndex > 0 { | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| r.replicateTo(s, maxIndex) | ||||||||||||
| } | ||||||||||||
| return | ||||||||||||
| case deferErr := <-s.triggerDeferErrorCh: | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| lastLogIdx, _ := r.getLastLog() | ||||||||||||
| shouldStop = r.replicateTo(s, lastLogIdx) | ||||||||||||
| if !shouldStop { | ||||||||||||
|
|
@@ -159,6 +196,7 @@ RPC: | |||||||||||
| deferErr.respond(fmt.Errorf("replication failed")) | ||||||||||||
| } | ||||||||||||
| case <-s.triggerCh: | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| lastLogIdx, _ := r.getLastLog() | ||||||||||||
| shouldStop = r.replicateTo(s, lastLogIdx) | ||||||||||||
| // This is _not_ our heartbeat mechanism but is to ensure | ||||||||||||
|
|
@@ -167,12 +205,14 @@ RPC: | |||||||||||
| // can't do this to keep them unblocked by disk IO on the | ||||||||||||
| // follower. See https://github.com/hashicorp/raft/issues/282. | ||||||||||||
| case <-randomTimeout(r.config().CommitTimeout): | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| lastLogIdx, _ := r.getLastLog() | ||||||||||||
| shouldStop = r.replicateTo(s, lastLogIdx) | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| // If things looks healthy, switch to pipeline mode | ||||||||||||
| if !shouldStop && s.allowPipeline { | ||||||||||||
| s.resetLastReplicationStart() | ||||||||||||
| goto PIPELINE | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
|
|
@@ -409,6 +449,30 @@ func (r *Raft) heartbeat(s *followerReplication, stopCh chan struct{}) { | |||||||||||
| s.peerLock.RUnlock() | ||||||||||||
|
|
||||||||||||
| start := time.Now() | ||||||||||||
|
|
||||||||||||
| lastReplicationStart := s.getLastReplicationStart() | ||||||||||||
| if !lastReplicationStart.IsZero() { | ||||||||||||
| maxLastReplication := r.config().HeartbeatTimeout * 10 | ||||||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's always comment magic numbers (especially since I can't remember exactly why we picked this one)
Suggested change
maybe? |
||||||||||||
| if lastReplicationStart.Add(maxLastReplication).Before(start) { | ||||||||||||
| r.logger.Warn("delaying heartbeat for peer because replication is stalled", | ||||||||||||
| "peer", peer.Address, | ||||||||||||
| "timeout", maxLastReplication, | ||||||||||||
| "replication_started", lastReplicationStart, | ||||||||||||
| ) | ||||||||||||
| // Replication has been stalled for too long. Delay the next | ||||||||||||
| // heartbeat to allow a follower to take over, but don't exit the | ||||||||||||
| // loop yet in case replication unblocks during the delay | ||||||||||||
| select { | ||||||||||||
| case <-s.notifyCh: | ||||||||||||
| case <-randomTimeout(r.config().HeartbeatTimeout): | ||||||||||||
| case <-stopCh: | ||||||||||||
| return | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| continue | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| if err := r.trans.AppendEntries(peer.ID, peer.Address, &req, &resp); err != nil { | ||||||||||||
| nextBackoffTime := cappedExponentialBackoff(failureWait, failures, maxFailureScale, r.config().HeartbeatTimeout/2) | ||||||||||||
| r.logger.Error("failed to heartbeat to", "peer", peer.Address, "backoff time", | ||||||||||||
|
|
@@ -472,16 +536,19 @@ func (r *Raft) pipelineReplicate(s *followerReplication) error { | |||||||||||
| shouldStop := false | ||||||||||||
| SEND: | ||||||||||||
| for !shouldStop { | ||||||||||||
| s.resetLastReplicationStart() | ||||||||||||
| select { | ||||||||||||
| case <-finishCh: | ||||||||||||
| break SEND | ||||||||||||
| case maxIndex := <-s.stopCh: | ||||||||||||
| // Make a best effort to replicate up to this index | ||||||||||||
| if maxIndex > 0 { | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| r.pipelineSend(s, pipeline, &nextIndex, maxIndex) | ||||||||||||
| } | ||||||||||||
| break SEND | ||||||||||||
| case deferErr := <-s.triggerDeferErrorCh: | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| lastLogIdx, _ := r.getLastLog() | ||||||||||||
| shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx) | ||||||||||||
| if !shouldStop { | ||||||||||||
|
|
@@ -490,13 +557,16 @@ SEND: | |||||||||||
| deferErr.respond(fmt.Errorf("replication failed")) | ||||||||||||
| } | ||||||||||||
| case <-s.triggerCh: | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| lastLogIdx, _ := r.getLastLog() | ||||||||||||
| shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx) | ||||||||||||
| case <-randomTimeout(r.config().CommitTimeout): | ||||||||||||
| lastLogIdx, _ := r.getLastLog() | ||||||||||||
| s.setLastReplicationStart() | ||||||||||||
| shouldStop = r.pipelineSend(s, pipeline, &nextIndex, lastLogIdx) | ||||||||||||
| } | ||||||||||||
| } | ||||||||||||
| s.resetLastReplicationStart() | ||||||||||||
|
|
||||||||||||
| // Stop our decoder, and wait for it to finish | ||||||||||||
| close(stopCh) | ||||||||||||
|
|
||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| // Copyright IBM Corp. 2013, 2026 | ||
| // SPDX-License-Identifier: MPL-2.0 | ||
|
|
||
| package raft | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "sync" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestLeaderHeartbeatsWithStalledDisk(t *testing.T) { | ||
| c := MakeClusterCustom(t, &MakeClusterOpts{ | ||
| Peers: 3, | ||
| Bootstrap: true, | ||
| LogstoreWrapperFunc: newBlockingLogStore, | ||
| }) | ||
| t.Cleanup(c.Close) | ||
|
|
||
| go func() { | ||
| i := 0 | ||
| ticker := time.NewTicker(500 * time.Millisecond) | ||
| for { | ||
| select { | ||
| case <-t.Context().Done(): | ||
| return | ||
| case <-ticker.C: | ||
| i++ | ||
| leader := c.Leader() | ||
| fut := leader.Apply(fmt.Appendf([]byte{}, "test%d", i), 0) | ||
| if err := fut.Error(); err != nil { | ||
| t.Logf("got error trying to write: %v", err) | ||
| } else { | ||
| t.Logf("write %d ok", i) | ||
| } | ||
| } | ||
| } | ||
| }() | ||
|
|
||
| t.Log("waiting for 5 seconds before partitioning leader") | ||
| time.Sleep(time.Second * 5) | ||
|
|
||
| oldLeader := c.Leader() | ||
| oldLeaderID := oldLeader.leaderID | ||
| oldLeaderTerm := oldLeader.getCurrentTerm() | ||
| c.Partition([]ServerAddress{c.Leader().localAddr}) | ||
|
|
||
| var newLeaderTerm uint64 | ||
| ctx, cancel := context.WithTimeout(t.Context(), 10*c.propagateTimeout) | ||
| t.Cleanup(cancel) | ||
| DONE: | ||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| t.Fatal("election didn't happen!") | ||
| default: | ||
| newLeader := c.Leader() | ||
| if newLeader.leaderID != oldLeaderID { | ||
| t.Log("leader has stepped down!") | ||
| newLeaderTerm = newLeader.getCurrentTerm() | ||
| require.NotEqual(t, newLeaderTerm, oldLeaderTerm) | ||
| cancel() | ||
| break DONE | ||
| } | ||
| } | ||
| } | ||
|
|
||
| require.Len(t, c.WaitForFollowers(1), 1) | ||
|
|
||
| t.Log("leader was elected. healing parition") | ||
|
|
||
| // reconnect the partitioned node | ||
| c.FullyConnect() | ||
| time.Sleep(3 * c.propagateTimeout) | ||
|
|
||
| leaderTerm := c.Leader().getCurrentTerm() | ||
| require.Equal(t, newLeaderTerm, leaderTerm) | ||
|
|
||
| t.Log("blocking disk on leader") | ||
|
|
||
| leader := c.Leader() | ||
| leaderID := leader.leaderID | ||
| leaderStore := leader.logs.(*blockingLogStore) | ||
| leaderStore.block() | ||
| t.Cleanup(leaderStore.unblock) | ||
|
|
||
| ctx, cancel = context.WithTimeout(t.Context(), 5*time.Second) | ||
| t.Cleanup(cancel) | ||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| t.Fatal("leader did not step down!") | ||
| default: | ||
| if c.Leader().leaderID != leaderID { | ||
| t.Log("leader has stepped down!") | ||
| return | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // blockingLogStore wraps a LogStore and blocks GetLog calls on demand, | ||
| // simulating disk IO stalls. | ||
| type blockingLogStore struct { | ||
| LogStore | ||
| mu sync.Mutex | ||
| blocked atomic.Bool | ||
| unblockC chan struct{} | ||
| } | ||
|
|
||
| func newBlockingLogStore(inner LogStore) LogStore { | ||
| return &blockingLogStore{ | ||
| LogStore: inner, | ||
| unblockC: make(chan struct{}), | ||
| } | ||
| } | ||
|
|
||
| func (b *blockingLogStore) block() { | ||
| b.mu.Lock() | ||
| defer b.mu.Unlock() | ||
| b.blocked.Store(true) | ||
| b.unblockC = make(chan struct{}) | ||
| } | ||
|
|
||
| func (b *blockingLogStore) unblock() { | ||
| b.mu.Lock() | ||
| defer b.mu.Unlock() | ||
| if b.blocked.Load() { | ||
| b.blocked.Store(false) | ||
| close(b.unblockC) | ||
| } | ||
| } | ||
|
|
||
| func (b *blockingLogStore) GetLog(index uint64, log *Log) error { | ||
| if b.blocked.Load() { | ||
| b.mu.Lock() | ||
| ch := b.unblockC | ||
| b.mu.Unlock() | ||
| <-ch | ||
| } | ||
| return b.LogStore.GetLog(index, log) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since the critical section is only a load or store, we could use a
sync.Pointerinstead. Your choice matches existing code (lastContact) though, so either way is fine.