diff --git a/pkg/compose/watch.go b/pkg/compose/watch.go index ec1a92461..108e83287 100644 --- a/pkg/compose/watch.go +++ b/pkg/compose/watch.go @@ -56,6 +56,8 @@ type Watcher struct { watchFn WatchFunc stopFn func() errCh chan error + // mx keeps Start/Stop state changes atomic, for this watcher only. + mx gsync.Mutex } func NewWatcher(project *types.Project, options api.UpOptions, w WatchFunc, consumer api.LogConsumer) (*Watcher, error) { @@ -79,12 +81,9 @@ func NewWatcher(project *types.Project, options api.UpOptions, w WatchFunc, cons return nil, errors.New("none of the selected services is configured for watch, see https://docs.docker.com/compose/how-tos/file-watch/") } -// ensure state changes are atomic -var mx gsync.Mutex - func (w *Watcher) Start(ctx context.Context) error { - mx.Lock() - defer mx.Unlock() + w.mx.Lock() + defer w.mx.Unlock() ctx, cancelFunc := context.WithCancel(ctx) w.stopFn = cancelFunc wait, err := w.watchFn(ctx, w.project, w.options) @@ -101,8 +100,8 @@ func (w *Watcher) Start(ctx context.Context) error { } func (w *Watcher) Stop() error { - mx.Lock() - defer mx.Unlock() + w.mx.Lock() + defer w.mx.Unlock() if w.stopFn == nil { return nil } diff --git a/pkg/compose/watch_test.go b/pkg/compose/watch_test.go index a15b33651..b1d09e6b0 100644 --- a/pkg/compose/watch_test.go +++ b/pkg/compose/watch_test.go @@ -398,3 +398,45 @@ func TestPruneDanglingImagesOnRebuild(t *testing.T) { tested.(*composeService).pruneDanglingImagesOnRebuild(t.Context(), "proj", map[string]string{"app-image:latest": "sha256:justbuilt"}) } + +// TestWatcher_StartStopIndependent guards that the Start/Stop lock is per +// watcher: a Start blocked inside its WatchFunc must not stall another watcher. +func TestWatcher_StartStopIndependent(t *testing.T) { + project := &types.Project{Services: types.Services{"app": { + Name: "app", + Develop: &types.DevelopConfig{Watch: []types.Trigger{{Path: ".", Action: types.WatchActionSync}}}, + }}} + + release := make(chan struct{}) + entered := make(chan struct{}) + blocking, err := NewWatcher(project, api.UpOptions{}, func(ctx context.Context, _ *types.Project, _ api.WatchOptions) (func() error, error) { + close(entered) + <-release + return func() error { return nil }, nil + }, nil) + assert.NilError(t, err) + go func() { _ = blocking.Start(t.Context()) }() + <-entered + + other, err := NewWatcher(project, api.UpOptions{}, func(ctx context.Context, _ *types.Project, _ api.WatchOptions) (func() error, error) { + return func() error { return nil }, nil + }, nil) + assert.NilError(t, err) + + done := make(chan error, 1) + go func() { + if err := other.Start(t.Context()); err != nil { + done <- err + return + } + done <- other.Stop() + }() + select { + case err := <-done: + assert.NilError(t, err) + case <-time.After(5 * time.Second): + t.Fatal("a Watcher blocked on another Watcher's Start: the lock must not be shared") + } + close(release) + assert.NilError(t, blocking.Stop()) +}