-
-
Notifications
You must be signed in to change notification settings - Fork 6.1k
fix(graceful): prevent WaitGroup panic on Ctrl+C shutdown #35578
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
Draft
ita004
wants to merge
2
commits into
go-gitea:main
Choose a base branch
from
ita004:fix/waitgroup-shutdown-35559
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.
+262
−30
Draft
Changes from all 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
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
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,49 @@ | ||
// Copyright 2025 The Gitea Authors. All rights reserved. | ||
// SPDX-License-Identifier: MIT | ||
|
||
package graceful | ||
|
||
import ( | ||
"sync" | ||
) | ||
|
||
// SafeWaitGroup is a small wrapper around sync.WaitGroup that prevents | ||
// new Adds after Shutdown has been requested. It prevents the "WaitGroup | ||
// is reused before previous Wait has returned" panic by gating Add calls. | ||
type SafeWaitGroup struct { | ||
mu sync.Mutex | ||
wg sync.WaitGroup | ||
shutting bool | ||
} | ||
|
||
// AddIfRunning attempts to add one to the waitgroup. It returns true if | ||
// the add succeeded; false if shutdown has already started and add was rejected. | ||
func (s *SafeWaitGroup) AddIfRunning() bool { | ||
s.mu.Lock() | ||
defer s.mu.Unlock() | ||
if s.shutting { | ||
return false | ||
} | ||
s.wg.Add(1) | ||
return true | ||
} | ||
|
||
// Done decrements the wait group counter. | ||
// Call only if AddIfRunning returned true previously. | ||
func (s *SafeWaitGroup) Done() { | ||
s.wg.Done() | ||
} | ||
|
||
// Wait waits for the waitgroup to complete. | ||
func (s *SafeWaitGroup) Wait() { | ||
s.wg.Wait() | ||
} | ||
|
||
// Shutdown marks the group as shutting and then waits for all existing | ||
// routines to finish. After Shutdown returns, AddIfRunning will return false. | ||
func (s *SafeWaitGroup) Shutdown() { | ||
s.mu.Lock() | ||
s.shutting = true | ||
s.mu.Unlock() | ||
s.wg.Wait() | ||
} |
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,178 @@ | ||
// Copyright 2025 The Gitea Authors. All rights reserved. | ||
// SPDX-License-Identifier: MIT | ||
|
||
package graceful | ||
|
||
import ( | ||
"sync" | ||
"sync/atomic" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestSafeWaitGroup_AddIfRunning(t *testing.T) { | ||
var swg SafeWaitGroup | ||
|
||
// Test that AddIfRunning succeeds before shutdown | ||
assert.True(t, swg.AddIfRunning(), "AddIfRunning should succeed before shutdown") | ||
swg.Done() | ||
|
||
// Test that AddIfRunning fails after shutdown | ||
swg.Shutdown() | ||
assert.False(t, swg.AddIfRunning(), "AddIfRunning should fail after shutdown") | ||
} | ||
|
||
func TestSafeWaitGroup_Shutdown(t *testing.T) { | ||
var swg SafeWaitGroup | ||
|
||
// Add some work | ||
assert.True(t, swg.AddIfRunning()) | ||
assert.True(t, swg.AddIfRunning()) | ||
|
||
// Complete work in goroutines | ||
go func() { | ||
time.Sleep(50 * time.Millisecond) | ||
swg.Done() | ||
}() | ||
go func() { | ||
time.Sleep(100 * time.Millisecond) | ||
swg.Done() | ||
}() | ||
|
||
// Shutdown should wait for all work to complete | ||
start := time.Now() | ||
swg.Shutdown() | ||
elapsed := time.Since(start) | ||
|
||
assert.GreaterOrEqual(t, elapsed, 100*time.Millisecond, "Shutdown should wait for all work") | ||
} | ||
|
||
func TestSafeWaitGroup_ConcurrentAddAndShutdown(t *testing.T) { | ||
var swg SafeWaitGroup | ||
var addCount atomic.Int32 | ||
var successCount atomic.Int32 | ||
|
||
// Start many goroutines trying to add | ||
const numGoroutines = 100 | ||
var wg sync.WaitGroup | ||
wg.Add(numGoroutines) | ||
|
||
for range numGoroutines { | ||
go func() { | ||
defer wg.Done() | ||
if swg.AddIfRunning() { | ||
addCount.Add(1) | ||
time.Sleep(10 * time.Millisecond) | ||
swg.Done() | ||
successCount.Add(1) | ||
} | ||
}() | ||
} | ||
|
||
// Give some goroutines time to add | ||
time.Sleep(5 * time.Millisecond) | ||
|
||
// Now shutdown | ||
swg.Shutdown() | ||
|
||
// Wait for all goroutines to finish | ||
wg.Wait() | ||
|
||
// All adds that succeeded should have completed | ||
assert.Equal(t, addCount.Load(), successCount.Load(), "All successful adds should complete") | ||
|
||
// After shutdown, no new adds should succeed | ||
assert.False(t, swg.AddIfRunning(), "No adds should succeed after shutdown") | ||
} | ||
|
||
func TestSafeWaitGroup_MultipleShutdowns(t *testing.T) { | ||
var swg SafeWaitGroup | ||
|
||
// First shutdown | ||
swg.Shutdown() | ||
|
||
// Second shutdown should not panic | ||
assert.NotPanics(t, func() { | ||
swg.Shutdown() | ||
}, "Multiple shutdowns should not panic") | ||
} | ||
|
||
func TestSafeWaitGroup_WaitWithoutAdd(t *testing.T) { | ||
var swg SafeWaitGroup | ||
|
||
// Wait without any adds should not block | ||
done := make(chan struct{}) | ||
go func() { | ||
swg.Wait() | ||
close(done) | ||
}() | ||
|
||
select { | ||
case <-done: | ||
// Success | ||
case <-time.After(100 * time.Millisecond): | ||
t.Fatal("Wait should not block when no work is added") | ||
} | ||
} | ||
|
||
func TestSafeWaitGroup_PreventsPanic(t *testing.T) { | ||
var swg SafeWaitGroup | ||
|
||
// This pattern would cause a panic with sync.WaitGroup: | ||
// Add -> Wait (in goroutine) -> Add (would panic) | ||
|
||
assert.True(t, swg.AddIfRunning()) | ||
|
||
go func() { | ||
time.Sleep(10 * time.Millisecond) | ||
swg.Done() | ||
}() | ||
|
||
// Start shutdown which will wait | ||
go swg.Shutdown() | ||
|
||
// Give shutdown time to start | ||
time.Sleep(5 * time.Millisecond) | ||
|
||
// This should not panic, just return false | ||
assert.NotPanics(t, func() { | ||
result := swg.AddIfRunning() | ||
assert.False(t, result, "Add should be rejected during shutdown") | ||
}, "AddIfRunning should not panic during shutdown") | ||
} | ||
|
||
func TestSafeWaitGroup_RaceCondition(t *testing.T) { | ||
// This test is designed to catch race conditions | ||
// Run with: go test -race | ||
var swg SafeWaitGroup | ||
var wg sync.WaitGroup | ||
|
||
const numWorkers = 50 | ||
wg.Add(numWorkers * 2) // workers + shutdown goroutines | ||
|
||
// Start workers | ||
for range numWorkers { | ||
go func() { | ||
defer wg.Done() | ||
for range 10 { | ||
if swg.AddIfRunning() { | ||
time.Sleep(time.Millisecond) | ||
swg.Done() | ||
} | ||
} | ||
}() | ||
} | ||
|
||
// Start shutdown attempts | ||
for range numWorkers { | ||
go func() { | ||
defer wg.Done() | ||
time.Sleep(5 * time.Millisecond) | ||
swg.Shutdown() | ||
}() | ||
} | ||
|
||
wg.Wait() | ||
} |
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.
I don't think the current design would work or it can be improved.
doHammer
means that it will stop the server immediately without waiting for any running tasks (for example: existing user request connection).The
graceful
package's design overall looks problematic and it seems unfixable to me.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.
thanks for clarifying, i understand what you mean now... that makes sense: doHammer should remain immediate and not wait for any running connections, just forcefully stop the server....
i'll keep this note in mind, and if there’s a future plan to refactor or redesign the graceful manager to address the deeper issues, i'd be happy to participate or help with that whenever it’s appropriate...