Skip to content
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

[BUGFIX] Fix race condition in freeport #7567

Merged
merged 6 commits into from
Apr 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion agent/config_endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func TestConfig_Apply(t *testing.T) {
func TestConfig_Apply_TerminatingGateway(t *testing.T) {
t.Parallel()

a := NewTestAgent(t, t.Name(), "")
a := NewTestAgent(t, "")
defer a.Shutdown()
testrpc.WaitForTestAgent(t, a.RPC, "dc1")

Expand Down
47 changes: 41 additions & 6 deletions sdk/freeport/freeport.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ var (

// total is the total number of available ports in the block for use.
total int

// stopCh is used to signal to background goroutines to terminate. Only
// really exists for the safety of reset() during unit tests.
stopCh chan struct{}

// stopWg is used to keep track of background goroutines that are still
// alive. Only really exists for the safety of reset() during unit tests.
stopWg sync.WaitGroup
)

// initialize is used to initialize freeport.
Expand Down Expand Up @@ -108,16 +116,36 @@ func initialize() {
}
total = freePorts.Len()

go checkFreedPorts()
stopWg.Add(1)
stopCh = make(chan struct{})
// Note: we pass this param explicitly to the goroutine so that we can
// freely recreate the underlying stop channel during reset() after closing
// the original.
go checkFreedPorts(stopCh)
}

func shutdownGoroutine() {
mu.Lock()
if stopCh == nil {
mu.Unlock()
return
}

close(stopCh)
stopCh = nil
mu.Unlock()

stopWg.Wait()
}

// reset will reverse the setup from initialize() and then redo it (for tests)
func reset() {
logf("INFO", "resetting the freeport package state")
shutdownGoroutine()

mu.Lock()
defer mu.Unlock()

logf("INFO", "resetting the freeport package state")

effectiveMaxBlocks = 0
firstPort = 0
if lockLn != nil {
Expand All @@ -132,11 +160,18 @@ func reset() {
total = 0
}

func checkFreedPorts() {
func checkFreedPorts(stopCh <-chan struct{}) {
defer stopWg.Done()

ticker := time.NewTicker(250 * time.Millisecond)
for {
<-ticker.C
checkFreedPortsOnce()
select {
case <-stopCh:
logf("INFO", "Closing checkFreedPorts()")
return
case <-ticker.C:
checkFreedPortsOnce()
}
}
}

Expand Down