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

Fix race condition in log printer #11286

Merged
merged 1 commit into from
Dec 20, 2023
Merged
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
18 changes: 12 additions & 6 deletions pkg/compose/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package compose

import (
"fmt"
"sync/atomic"
"sync"

"github.com/docker/compose/v2/pkg/api"
)
Expand All @@ -32,9 +32,10 @@ type logPrinter interface {
}

type printer struct {
sync.Mutex
queue chan api.ContainerEvent
consumer api.LogConsumer
stopped atomic.Bool
stopped bool
}

// newLogPrinter builds a LogPrinter passing containers logs to LogConsumer
Expand All @@ -53,16 +54,21 @@ func (p *printer) Cancel() {
}

func (p *printer) Stop() {
if p.stopped.CompareAndSwap(false, true) {
p.Lock()
defer p.Unlock()
if !p.stopped {
// only close if this is the first call to stop
p.stopped = true
close(p.queue)
}
}

func (p *printer) HandleEvent(event api.ContainerEvent) {
// prevent deadlocking, if the printer is done, there's no reader for
// queue, so this write could block indefinitely
if p.stopped.Load() {
p.Lock()
defer p.Unlock()
if p.stopped {
// prevent deadlocking, if the printer is done, there's no reader for
// queue, so this write could block indefinitely
return
}
p.queue <- event
Expand Down