From 13e053387b5fbf09d2021b87586729fb63576a2a Mon Sep 17 00:00:00 2001 From: teivah Date: Tue, 10 May 2022 12:10:12 +0200 Subject: [PATCH] Fixing stats race condition Signed-off-by: teivah --- cli/command/container/stats.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cli/command/container/stats.go b/cli/command/container/stats.go index 287fe02f7c..50b1093780 100644 --- a/cli/command/container/stats.go +++ b/cli/command/container/stats.go @@ -60,7 +60,7 @@ func runStats(dockerCli command.Cli, opts *statsOptions) error { // monitorContainerEvents watches for container creation and removal (only // used when calling `docker stats` without arguments). - monitorContainerEvents := func(started chan<- struct{}, c chan events.Message) { + monitorContainerEvents := func(started chan<- struct{}, c chan events.Message, stopped <-chan struct{}) { f := filters.NewArgs() f.Add("type", "container") options := types.EventsOptions{ @@ -72,9 +72,12 @@ func runStats(dockerCli command.Cli, opts *statsOptions) error { // Whether we successfully subscribed to eventq or not, we can now // unblock the main goroutine. close(started) + defer close(c) for { select { + case <-stopped: + return case event := <-eventq: c <- event case err := <-errq: @@ -150,8 +153,9 @@ func runStats(dockerCli command.Cli, opts *statsOptions) error { eventChan := make(chan events.Message) go eh.Watch(eventChan) - go monitorContainerEvents(started, eventChan) - defer close(eventChan) + stopped := make(chan struct{}) + go monitorContainerEvents(started, eventChan, stopped) + defer close(stopped) <-started // Start a short-lived goroutine to retrieve the initial list of