fix(plan): run the pre_stop hooks as an operation of the plan

The stop of the reconciliation plan runs the pre_stop hooks itself, in the
executor, since docker/compose#14477, except the stop of a recreate: the
replacement is created under a temporary name before the old container is
stopped, and a failing hook would leave it behind for the next up to trip on.
So a container that `up` replaces still goes without its hooks.

The hooks are now an operation of the plan, RunPreStop, that the stop depends
on. Every stop the plan makes has it: a recreated container, a scale down, the
containers of a recreated network or volume, the dependents restarted with a
recreated dependency, a service that moves to a provider. A container that has
no process to run them in skips them and is stopped all the same, as for
restart and down; a hook that fails fails the plan and leaves the container
running. A container stopped for two reasons is stopped once, and its hooks
run once.

A recreation runs the hooks before it creates the replacement: one that fails
then leaves nothing behind, and no stop has to skip them any more.

The plans of services without pre_stop hooks are unchanged.

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
This commit is contained in:
Nicolas De Loof 2026-11-25 10:03:46 +01:00 • committed by Guillaume Lours
parent 3d3c8a39cf
commit c1b1739f1c
17 changed files with 1020 additions and 265 deletions

View file

@ -354,6 +354,37 @@ func Recreated(services ...string) Check {
}
}
// RunningContainersKept expects every container of the service that was running
// before the step to be running still after it, whatever else the step created:
// a step that fails halfway must not have taken down what it was about to
// replace. It fails when nothing was running before.
func RunningContainersKept(service string) Check {
return Check{
name: fmt.Sprintf("running containers of service %q kept", service),
fn: func(ctx *CheckContext) error {
var before []string
for _, c := range ctx.prev.service(service) {
if c.State == "running" {
before = append(before, c.ID)
}
}
if len(before) == 0 {
return fmt.Errorf("service %q had no running container before the step", service)
}
running := map[string]bool{}
for _, c := range ctx.curr.service(service) {
running[c.ID] = c.State == "running"
}
for _, id := range before {
if !running[id] {
return fmt.Errorf("container %s is not running anymore", id[:12])
}
}
return nil
},
}
}
func containerIDs(containers []containerState) []string {
ids := make([]string, 0, len(containers))
for _, c := range containers {

View file

@ -0,0 +1,108 @@
//go:build e2e
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package e2e
import (
"testing"
"time"
)
// pre_stop hooks run whenever Compose stops a container, not only for `stop`,
// `restart` and `down`: the stops that `up` makes to replace a container or to
// scale a service down go through the reconciliation plan, which did not run
// them. The hook of these projects appends a line to a log in the data volume,
// so what the scenarios observe is how many times it ran.
// hookRuns reads what the hook of the project wrote to its data volume.
func hookRuns(s *Scenario) Action {
return probeVolume(s, "sh", "-c", "cat /mnt/log.txt 2>/dev/null; true")
}
func TestUpRunsPreStopHookOfTheContainerItRecreates(t *testing.T) {
s := NewScenario(t, "up must run the pre_stop hook of a container it replaces, before stopping it")
s.Step("up starts the service, whose hook has not run",
ComposeCmd("up", "-d"),
ServiceState("sample", "running")).
Step("the hook has not run yet",
hookRuns(s),
OutputNotContains("pre_stop ran")).
Step("up with a changed service replaces the container",
ComposeCmd("up", "-d").WithEnv("VERSION=2"),
Recreated("sample"),
ServiceState("sample", "running")).
Step("the hook ran once, in the container that went",
hookRuns(s),
OutputMatchesCount("pre_stop ran", 1))
}
func TestUpRunsPreStopHookOfTheReplicaItScalesDown(t *testing.T) {
s := NewScenario(t, "up must run the pre_stop hook of the replicas a scale down removes, and of no other")
s.Step("up starts two replicas",
ComposeCmd("up", "-d", "--scale", "sample=2"),
ServiceScale("sample", 2),
ServiceState("sample", "running")).
Step("up with one replica removes the second",
ComposeCmd("up", "-d", "--scale", "sample=1"),
ReplicaNumbers("sample", 1),
ServiceState("sample", "running")).
Step("the hook ran once, for the replica that went",
hookRuns(s),
OutputMatchesCount("pre_stop ran", 1))
}
// A stopped container has no process to run the hook in: the engine refuses the
// exec, as it did for `restart` and `stop` (#14545). Replacing it must neither
// fail nor pretend the hook ran.
func TestUpSkipsPreStopHookOfAStoppedContainerItRecreates(t *testing.T) {
s := NewScenario(t, "up must replace a stopped container whose service has a pre_stop hook, without running the hook again")
s.Step("up starts the service",
ComposeCmd("up", "-d"),
ServiceState("sample", "running")).
Step("stop runs the hook and halts the container",
ComposeCmd("stop"),
ServiceState("sample", "exited")).
Step("up with a changed service replaces the stopped container",
ComposeCmd("up", "-d").WithEnv("VERSION=2"),
Recreated("sample"),
ServiceState("sample", "running")).
Step("the hook ran once, when the service was stopped, and not for the replacement of the stopped container",
hookRuns(s),
OutputMatchesCount("pre_stop ran", 1))
}
func TestUpKeepsTheContainerWhoseFailingPreStopHookBlocksItsReplacement(t *testing.T) {
NewScenario(t, "up must leave the service as it was when the pre_stop hook of the container it replaces fails, and replace it once the hook is fixed").
Step("up starts the service",
ComposeCmd("up", "-d"),
ServiceState("sample", "running")).
Step("up with a changed service fails on the hook, reporting its exit status",
ComposeCmd("up", "-d").WithEnv("VERSION=2").MayFail().Within(60*time.Second),
ExitCode(1),
OutputContains("sample hook exited with status 3"),
RunningContainersKept("sample")).
Step("no replacement was left behind, for the next up to trip on",
ComposeCmd("ps", "--all"),
ServiceScale("sample", 1),
ServiceState("sample", "running")).
Step("up replaces the container once the hook is fixed",
ComposeCmd("up", "-d").WithEnv("VERSION=2", "HOOK_EXIT=0").Within(60*time.Second),
Recreated("sample"),
ServiceScale("sample", 1),
ServiceState("sample", "running"))
}

View file

@ -57,11 +57,9 @@ func TestPreStopHookSuccess(t *testing.T) {
}
// Regression test for https://github.com/docker/compose/issues/14476: up stopped
// containers without running their pre_stop hooks. The container a recreate
// replaces is the exception, as before the plan engine: its replacement already
// exists, and a failing hook would leave it behind.
// containers without running their pre_stop hooks.
func TestPreStopHookWhenUpStopsAContainer(t *testing.T) {
s := NewScenario(t, "up must run the pre_stop hooks of every container it stops, except the one a recreate replaces")
s := NewScenario(t, "up must run the pre_stop hooks of every container it stops")
s.Step("up starts the services with two replicas of scaled",
ComposeCmd("up", "-d", "--scale", "scaled=2"),
ServiceScale("scaled", 2)).
@ -80,8 +78,9 @@ func TestPreStopHookWhenUpStopsAContainer(t *testing.T) {
Step("a config change recreates the service",
ComposeCmd("up", "-d").WithEnv("DB_V=2", "RECREATED_V=2"),
Recreated("recreated")).
Step("the replaced container did not run its hook",
probeVolume(s, "test", "!", "-e", "/mnt/recreated"))
Step("the replaced container ran its hook",
probeVolume(s, "cat", "/mnt/recreated"),
OutputContains("pre_stop"))
}
func TestPreStopHookInError(t *testing.T) {

View file

@ -0,0 +1,9 @@
services:
sample:
image: alpine
init: true
command: sleep infinity
environment:
- VERSION=${VERSION:-1}
pre_stop:
- command: sh -c 'exit ${HOOK_EXIT:-3}'

View file

@ -0,0 +1,13 @@
services:
sample:
image: alpine
init: true
command: sleep infinity
environment:
- VERSION=${VERSION:-1}
volumes:
- data:/data
pre_stop:
- command: sh -c 'echo "pre_stop ran" >> /data/log.txt'
volumes:
data:

View file

@ -0,0 +1,11 @@
services:
sample:
image: alpine
init: true
command: sleep infinity
volumes:
- data:/data
pre_stop:
- command: sh -c 'echo "pre_stop ran" >> /data/log.txt'
volumes:
data:

View file

@ -0,0 +1,13 @@
services:
sample:
image: alpine
init: true
command: sleep infinity
environment:
- VERSION=${VERSION:-1}
volumes:
- data:/data
pre_stop:
- command: sh -c 'echo "pre_stop ran" >> /data/log.txt'
volumes:
data:

View file

@ -61,6 +61,9 @@ const (
// Hook operations
OpCreateHookContainer OperationType = 43
// OpRunPreStop runs the pre_stop hooks of a container Compose is about to
// stop. The stop depends on it.
OpRunPreStop OperationType = 44
)
// PlanPhase situates a node in the plan lifecycle. The Create phase converges
@ -100,6 +103,8 @@ func (o OperationType) String() string {
return "RemoveContainer"
case OpRenameContainer:
return "RenameContainer"
case OpRunPreStop:
return "RunPreStop"
case OpRunProvider:
return "RunProvider"
case OpWaitCondition:
@ -143,9 +148,6 @@ type Operation struct {
// for purging stale pre_start hook runners (a failed removal only warns:
// it leaves the container visible, never blocks).
BestEffort bool
// SkipPreStop asks OpStopContainer not to run the pre_stop hooks: set on
// the stop of a recreate, whose replacement already exists.
SkipPreStop bool
}
// PlanNode is a single node in the reconciliation DAG. It represents one

View file

@ -38,6 +38,7 @@ func TestOperationTypeString(t *testing.T) {
{OpStopContainer, "StopContainer"},
{OpRemoveContainer, "RemoveContainer"},
{OpRenameContainer, "RenameContainer"},
{OpRunPreStop, "RunPreStop"},
{OpRunProvider, "RunProvider"},
{OperationType(999), "Unknown(999)"},
}

View file

@ -44,7 +44,9 @@ type planExecutor struct {
// listener streams pre_start/post_start hook logs. It is set once, when
// the Start phase is entered (planRun.runStart): an attached caller only
// has one by then, its printer not existing before the Create phase is
// done. nil leaves hook execution silent, matching detached behavior.
// done. nil leaves hook execution silent, matching detached behavior. The
// pre_stop hooks of the Create phase (a recreation, a scale down) run before
// it is set: their output is only kept for the error of a hook that fails.
listener api.ContainerEventListener
// containersByService is a live view used to resolve service references
@ -286,8 +288,9 @@ func (r *planRun) runCreate(ctx context.Context) error {
// logs, and nil leaves them unstreamed. It is given here because an attached
// caller only has one once it has set up its session, which happens after the
// Create phase. It is set before any Start-phase node is dispatched, and the
// planner only emits the operations that read it (pre_start, post_start) in
// the Start phase, so no goroutine can observe the previous value.
// operations of the Start phase that read it (pre_start, post_start) only run
// after it is. The Create phase, whose pre_stop hooks read it and see nil, has
// ended with all its goroutines by the time it is written.
func (r *planRun) runStart(ctx context.Context, listener api.ContainerEventListener) error {
if !r.createRan || r.createErr != nil {
return errors.New("plan run: the start phase cannot run before the create phase succeeded")
@ -605,6 +608,8 @@ func (exec *planExecutor) executeNode(ctx context.Context, node *planning.PlanNo
return exec.execCreateContainer(ctx, node)
case planning.OpStartContainer:
return exec.execStartContainer(ctx, op)
case planning.OpRunPreStop:
return exec.execRunPreStop(ctx, op)
case planning.OpStopContainer:
return exec.execStopContainer(ctx, op)
case planning.OpRemoveContainer:

View file

@ -365,8 +365,6 @@ func progressName(op planning.Operation) string {
}
// emitStartEvent emits the appropriate Working event for an ungrouped node.
//
//nolint:dupl // mirrors emitDoneEvent: keeping the Working and Done events side by side keeps their pairing visible
func emitStartEvent(node *planning.PlanNode, events api.EventProcessor) {
op := node.Operation
name := progressName(op)
@ -375,16 +373,28 @@ func emitStartEvent(node *planning.PlanNode, events api.EventProcessor) {
events.On(progress.Creating(name))
case planning.OpStartContainer:
events.On(progress.New(name, api.Working, api.StatusStarting))
case planning.OpStopContainer:
case planning.OpRunPreStop:
// the row is stopping while its hooks run, as it is for a stop without
// them: the stop that follows does not say it again
events.On(progress.Stopping(name))
case planning.OpStopContainer:
if !followsPreStop(node) {
events.On(progress.Stopping(name))
}
case planning.OpRemoveContainer, planning.OpRemoveNetwork, planning.OpRemoveVolume:
events.On(progress.Removing(name))
}
}
// followsPreStop tells whether the stop is the one of a container whose pre_stop
// hooks have just run: its row is already stopping.
func followsPreStop(stop *planning.PlanNode) bool {
return slices.ContainsFunc(stop.DependsOn, func(dep *planning.PlanNode) bool {
return dep.Operation.Type == planning.OpRunPreStop
})
}
// emitDoneEvent emits the appropriate Done event for an ungrouped node.
//
//nolint:dupl // mirrors emitStartEvent, see there
func emitDoneEvent(node *planning.PlanNode, events api.EventProcessor) {
op := node.Operation
name := progressName(op)

View file

@ -317,17 +317,19 @@ func (exec *planExecutor) execRunPostStart(ctx context.Context, op planning.Oper
return nil
}
// execStopContainer runs the pre_stop hooks itself rather than as nodes of the
// plan, so that every stop of the plan runs them, except the stop of a recreate
// (see planning.Operation.SkipPreStop).
func (exec *planExecutor) execStopContainer(ctx context.Context, op planning.Operation) error {
if service, ok := exec.project.Services[op.Container.Labels[api.ServiceLabel]]; ok && !op.SkipPreStop {
// a container already gone or stopped is still handed to ContainerStop,
// as before the plan ran the hooks
if _, err := exec.compose.runPreStopHooks(ctx, *op.Container, &service, exec.listener); err != nil {
return err
}
// execRunPreStop runs the pre_stop hooks of the container the stop that depends
// on this node is about to stop. A container that has no process to run them in
// (stopped, paused) skips them, and one that is gone leaves the stop to report
// it, as it would have without hooks.
func (exec *planExecutor) execRunPreStop(ctx context.Context, op planning.Operation) error {
if err := ctx.Err(); err != nil {
return err
}
_, err := exec.compose.runPreStopHooks(ctx, *op.Container, op.Service, exec.listener)
return err
}
func (exec *planExecutor) execStopContainer(ctx context.Context, op planning.Operation) error {
_, err := exec.compose.apiClient().ContainerStop(ctx, op.Container.ID, client.ContainerStopOptions{
Timeout: utils.DurationSecondToInt(op.Timeout),
})

View file

@ -0,0 +1,313 @@
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package compose
import (
"context"
"net"
"strings"
"testing"
"github.com/compose-spec/compose-go/v2/types"
"github.com/containerd/errdefs"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
"go.uber.org/mock/gomock"
"gotest.tools/v3/assert"
"github.com/docker/compose/v5/internal/planning"
"github.com/docker/compose/v5/pkg/api"
"github.com/docker/compose/v5/pkg/mocks"
)
// expectHook expects one hook to be run in the container: its exec, with the
// given exit code. It returns the last call of the sequence, for ordering.
func expectHook(apiClient *mocks.MockAPIClient, ctr container.Summary, execID string, exitCode int) *gomock.Call {
create := apiClient.EXPECT().ExecCreate(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ExecCreateResult{ID: execID}, nil)
server, conn := net.Pipe()
_ = server.Close()
attach := apiClient.EXPECT().ExecAttach(gomock.Any(), execID, gomock.Any()).
Return(client.ExecAttachResult{HijackedResponse: client.NewHijackedResponse(conn, "")}, nil).After(create)
return apiClient.EXPECT().ExecInspect(gomock.Any(), execID, gomock.Any()).
Return(client.ExecInspectResult{ExitCode: exitCode}, nil).After(attach)
}
// preStopPlan is what the reconciler plans to stop a container whose service
// has pre_stop hooks and to remove it: the hooks, the stop that follows them,
// the removal that follows the stop.
func preStopPlan(ctr *container.Summary, service *types.ServiceConfig, group string) *planning.Plan {
plan := &planning.Plan{}
hooks := plan.AddNode(planning.Operation{
Type: planning.OpRunPreStop, ResourceID: "service:web:1", Cause: "pre_stop hooks", Service: service, Container: ctr,
}, group)
stop := plan.AddNode(planning.Operation{
Type: planning.OpStopContainer, ResourceID: "service:web:1", Cause: "scale down", Container: ctr,
}, group, hooks)
plan.AddNode(planning.Operation{
Type: planning.OpRemoveContainer, ResourceID: "service:web:1", Cause: "scale down", Container: ctr,
}, group, stop)
return plan
}
func hookedWeb(hooks ...string) *types.ServiceConfig {
service := &types.ServiceConfig{Name: "web"}
for _, h := range hooks {
service.PreStop = append(service.PreStop, types.ServiceHook{Command: types.ShellCommand{h}})
}
return service
}
func TestExecutePlanRunsPreStopHooksBeforeStoppingTheContainer(t *testing.T) {
svc, apiClient, rec := newStartTestService(t)
ctr := serviceContainer("web")
service := hookedWeb("quiesce", "flush")
flushed := expectHook(apiClient, ctr, "exec-1", 0)
flushed = expectHook(apiClient, ctr, "exec-2", 0).After(flushed) // the second hook runs after the first
stopped := apiClient.EXPECT().ContainerStop(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ContainerStopResult{}, nil).After(flushed)
apiClient.EXPECT().ContainerRemove(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ContainerRemoveResult{}, nil).After(stopped)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&ctr, service, ""))
assert.NilError(t, err)
// the hooks have no row of their own to report on: the container's row goes
// from stopping to removed, as it did without hooks
assert.DeepEqual(t, rec.summary(), []string{
"Container prj-web-1: Stopping",
"Container prj-web-1: Stopped",
"Container prj-web-1: Removing",
"Container prj-web-1: Removed",
})
}
// Hooks of a recreation belong to its group: the recreation is one row,
// working at its first node and done at its last, the hooks included.
func TestExecutePlanKeepsTheHooksOfARecreationInItsGroup(t *testing.T) {
svc, apiClient, rec := newStartTestService(t)
ctr := serviceContainer("web")
hooks := expectHook(apiClient, ctr, "exec-1", 0)
stopped := apiClient.EXPECT().ContainerStop(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ContainerStopResult{}, nil).After(hooks)
apiClient.EXPECT().ContainerRemove(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ContainerRemoveResult{}, nil).After(stopped)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&ctr, hookedWeb("quiesce"), "recreate:web:1"))
assert.NilError(t, err)
assert.DeepEqual(t, rec.summary(), []string{
"Container prj-web-1: Recreate",
"Container prj-web-1: Recreated",
})
}
// A container with no process to run the hooks in (stopped, paused) answers the
// exec with a conflict: the hooks are skipped and the stop goes on.
func TestExecutePlanStopsAContainerWhoseHooksHaveNoProcessToRunIn(t *testing.T) {
svc, apiClient, _ := newStartTestService(t)
ctr := serviceContainer("web")
ctr.State = container.StatePaused
hooks := apiClient.EXPECT().ExecCreate(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ExecCreateResult{}, errdefs.ErrConflict.WithMessage("container is paused"))
stopped := apiClient.EXPECT().ContainerStop(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ContainerStopResult{}, nil).After(hooks)
apiClient.EXPECT().ContainerRemove(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ContainerRemoveResult{}, nil).After(stopped)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&ctr, hookedWeb("quiesce", "flush"), ""))
assert.NilError(t, err)
}
// A hook that fails fails the plan, and the container is neither stopped nor
// removed: the hook was to prepare a stop that does not happen. No ContainerStop
// nor ContainerRemove expectation is set: per newStartTestService, gomock fails
// the test if either still runs.
func TestExecutePlanDoesNotStopAContainerWhoseHookFails(t *testing.T) {
svc, apiClient, rec := newStartTestService(t)
ctr := serviceContainer("web")
expectHook(apiClient, ctr, "exec-1", 3)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&ctr, hookedWeb("quiesce", "flush"), ""))
assert.ErrorContains(t, err, "web hook exited with status 3")
var reported bool
for _, e := range rec.events {
if e.ID == "Container prj-web-1" && e.Status == api.Error {
reported = true
assert.Assert(t, e.Text != "")
}
}
assert.Assert(t, reported, "the failure is reported on the row of the container: %v", rec.summary())
// the row was stopping while the hooks ran, and never got to stopped
assert.Assert(t, rec.contains("Container prj-web-1: Stopping"), "%v", rec.summary())
assert.Assert(t, !rec.contains("Container prj-web-1: Stopped"), "%v", rec.summary())
}
// The row of a container is stopping while its hooks run, once: the stop that
// follows them does not say it again, and a stop without hooks says it as ever.
func TestStoppingIsAnnouncedOnceWhetherOrNotHooksRunFirst(t *testing.T) {
ctr := serviceContainer("web")
withHooks := preStopPlan(&ctr, hookedWeb("quiesce"), "")
withoutHooks := &planning.Plan{}
stop := withoutHooks.AddNode(planning.Operation{Type: planning.OpStopContainer, ResourceID: "service:web:1", Container: &ctr}, "")
for name, tc := range map[string]struct {
node *planning.PlanNode
want []string
}{
"the hooks": {withHooks.Nodes[0], []string{"Container prj-web-1: Stopping"}},
"the stop that follows": {withHooks.Nodes[1], nil},
"a stop without hooks": {stop, []string{"Container prj-web-1: Stopping"}},
} {
t.Run(name, func(t *testing.T) {
rec := &recordingEventProcessor{}
emitStartEvent(tc.node, rec)
assert.DeepEqual(t, rec.summary(), append([]string{}, tc.want...))
})
}
// and nothing is said when the hooks end: the stop says when the row is stopped
rec := &recordingEventProcessor{}
emitDoneEvent(withHooks.Nodes[0], rec)
assert.Equal(t, len(rec.summary()), 0)
}
// The hooks that follow a failing one do not run.
func TestExecutePlanStopsRunningHooksAtTheFirstFailure(t *testing.T) {
svc, apiClient, _ := newStartTestService(t)
ctr := serviceContainer("web")
expectHook(apiClient, ctr, "exec-1", 1) // the second hook has no expectation: it must not run
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&ctr, hookedWeb("first", "second"), ""))
assert.ErrorContains(t, err, "exited with status 1")
}
// A container removed since it was listed: the hook finds nothing and the stop
// reports it, as it does for a container without hooks.
func TestExecutePlanLeavesAGoneContainerToTheStop(t *testing.T) {
svc, apiClient, _ := newStartTestService(t)
ctr := serviceContainer("web")
hooks := apiClient.EXPECT().ExecCreate(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ExecCreateResult{}, errdefs.ErrNotFound.WithMessage("No such container"))
apiClient.EXPECT().ContainerStop(gomock.Any(), ctr.ID, gomock.Any()).
Return(client.ContainerStopResult{}, errdefs.ErrNotFound.WithMessage("No such container")).After(hooks)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&ctr, hookedWeb("quiesce"), ""))
assert.Assert(t, errdefs.IsNotFound(err), "%v", err)
}
// A dry run has no side effect: the hooks are not run, and the dry-run client
// could not attach to their exec. No ExecCreate expectation is set: per
// newStartTestService, gomock fails the test if a hook still runs.
func TestExecutePlanSkipsPreStopHooksInDryRun(t *testing.T) {
svc, apiClient, _ := newStartTestService(t)
svc.dryRun = true
ctr := serviceContainer("web")
stopped := apiClient.EXPECT().ContainerStop(gomock.Any(), ctr.ID, gomock.Any()).Return(client.ContainerStopResult{}, nil)
apiClient.EXPECT().ContainerRemove(gomock.Any(), ctr.ID, gomock.Any()).Return(client.ContainerRemoveResult{}, nil).After(stopped)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&ctr, hookedWeb("quiesce"), ""))
assert.NilError(t, err)
}
// A relay has no process for a hook to act on, even if a plan names one.
func TestExecutePlanSkipsPreStopHooksOfARelay(t *testing.T) {
svc, apiClient, _ := newStartTestService(t)
relay := serviceContainer("web")
relay.Labels[api.RelayLabel] = "abc123"
stopped := apiClient.EXPECT().ContainerStop(gomock.Any(), relay.ID, gomock.Any()).Return(client.ContainerStopResult{}, nil)
apiClient.EXPECT().ContainerRemove(gomock.Any(), relay.ID, gomock.Any()).Return(client.ContainerRemoveResult{}, nil).After(stopped)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), preStopPlan(&relay, hookedWeb("quiesce"), ""))
assert.NilError(t, err)
}
// No hook runs for a plan that is already canceled: nothing is stopped for
// want of the hooks either.
func TestExecRunPreStopDoesNothingOnceCanceled(t *testing.T) {
svc, _, _ := newStartTestService(t)
ctr := serviceContainer("web")
exec := svc.newPlanExecutor(&types.Project{Name: "prj"}, emptyObservedState("prj"))
ctx, cancel := context.WithCancel(t.Context())
cancel()
err := exec.execRunPreStop(ctx, planning.Operation{Type: planning.OpRunPreStop, Service: hookedWeb("quiesce"), Container: &ctr})
assert.ErrorIs(t, err, context.Canceled)
}
// From the observed state to the calls on the daemon: what the reconciler plans
// for a scale down is what runs, hooks first, only for the replica that goes.
func TestScaleDownRunsTheHooksOfTheReplicaThatGoesThenStopsAndRemovesIt(t *testing.T) {
svc, apiClient, _ := newStartTestService(t)
web := hookedWebService()
project := &types.Project{Name: "prj", Services: types.Services{"web": web}}
replicas := runningReplicas(t, web, 2)
observed := observedOf("prj", map[string][]ObservedContainer{"web": replicas})
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
gone := replicas[1].Summary
hooks := expectHook(apiClient, gone, "exec-1", 0)
stopped := apiClient.EXPECT().ContainerStop(gomock.Any(), gone.ID, gomock.Any()).
Return(client.ContainerStopResult{}, nil).After(hooks)
apiClient.EXPECT().ContainerRemove(gomock.Any(), gone.ID, gomock.Any()).
Return(client.ContainerRemoveResult{}, nil).After(stopped)
assert.NilError(t, svc.executePlan(t.Context(), project, observed, plan))
}
// A hook that fails in a recreation fails it before anything is created: the
// row of the container is recreating, then in error, and the replacement is not
// created. No ContainerCreate expectation is set: per newStartTestService,
// gomock fails the test if it still happens.
func TestExecutePlanDoesNotCreateTheReplacementWhenTheHooksOfARecreationFail(t *testing.T) {
svc, apiClient, rec := newStartTestService(t)
ctr := serviceContainer("web")
service := hookedWeb("quiesce")
const group = "recreate:web:1"
plan := &planning.Plan{}
hooks := plan.AddNode(planning.Operation{
Type: planning.OpRunPreStop, ResourceID: "service:web:1", Cause: "pre_stop hooks", Service: service, Container: &ctr,
}, group)
create := plan.AddNode(planning.Operation{
Type: planning.OpCreateContainer, ResourceID: "service:web:1", Cause: "config changed (tmpName)", Service: service, Name: "abc_prj-web-1", Number: 1,
}, group, hooks)
stop := plan.AddNode(planning.Operation{Type: planning.OpStopContainer, ResourceID: "service:web:1", Container: &ctr}, group, create)
plan.AddNode(planning.Operation{Type: planning.OpRemoveContainer, ResourceID: "service:web:1", Container: &ctr}, group, stop)
expectHook(apiClient, ctr, "exec-1", 3)
err := svc.executePlan(t.Context(), &types.Project{Name: "prj"}, emptyObservedState("prj"), plan)
assert.ErrorContains(t, err, "web hook exited with status 3")
events := rec.summary()
assert.Equal(t, len(events), 2, "%v", events)
assert.Equal(t, events[0], "Container prj-web-1: Recreate")
assert.Assert(t, strings.HasPrefix(events[1], "Container prj-web-1: web hook exited with status 3"), "%v", events)
assert.Equal(t, rec.events[1].Status, api.Error)
}

View file

@ -20,8 +20,6 @@ import (
"context"
"errors"
"fmt"
"maps"
"net"
"strconv"
"sync"
"testing"
@ -203,156 +201,6 @@ func TestExecutePlanStopRemoveContainer(t *testing.T) {
assert.NilError(t, err)
}
// Regression test for docker/compose#14476.
func TestExecutePlanStopContainerRunsPreStop(t *testing.T) {
service := types.ServiceConfig{
Name: "web",
ContainerSpec: types.ContainerSpec{Image: "alpine"},
PreStop: []types.ServiceHook{{Command: types.ShellCommand{"drain"}}},
}
project := &types.Project{Name: "test", Services: types.Services{"web": service}}
webContainer := func(extraLabels map[string]string) container.Summary {
labels := map[string]string{api.ServiceLabel: "web", api.ContainerNumberLabel: "1"}
maps.Copy(labels, extraLabels)
return container.Summary{ID: "c1", Names: []string{"/test-web-1"}, State: container.StateRunning, Labels: labels}
}
stopPlan := func(ctr container.Summary) *planning.Plan {
plan := &planning.Plan{}
plan.AddNode(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: "service:web:1",
Cause: "scale down",
Container: &ctr,
}, "")
return plan
}
// the nodes of a recreate, as reconcile plans them: the replacement is
// created under a temporary name before the old container is stopped
recreatePlan := func(old container.Summary) *planning.Plan {
plan := &planning.Plan{}
create := plan.AddNode(planning.Operation{
Type: planning.OpCreateContainer,
ResourceID: "service:web:1",
Cause: "config changed",
Service: &service,
Name: "abc123456789_test-web-1",
Number: 1,
}, "")
stop := plan.AddNode(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: "service:web:1",
Cause: fmt.Sprintf("replaced by #%d", create.ID),
Container: &old,
SkipPreStop: true,
}, "", create)
remove := plan.AddNode(planning.Operation{
Type: planning.OpRemoveContainer,
ResourceID: "service:web:1",
Cause: "replaced",
Container: &old,
}, "", stop)
plan.AddNode(planning.Operation{
Type: planning.OpRenameContainer,
ResourceID: "service:web:1",
Cause: "finalize recreate",
Name: "test-web-1",
Service: &service,
CreateNodeID: create.ID,
}, "", remove)
return plan
}
expectReplacementCreated := func(apiClient *mocks.MockAPIClient) *gomock.Call {
apiClient.EXPECT().Ping(gomock.Any(), gomock.Any()).Return(client.PingResult{APIVersion: "1.44"}, nil).AnyTimes()
apiClient.EXPECT().ClientVersion().Return("1.44").AnyTimes()
apiClient.EXPECT().ContainerCreate(gomock.Any(), gomock.Any()).
Return(client.ContainerCreateResult{ID: "new-id"}, nil)
return apiClient.EXPECT().ContainerInspect(gomock.Any(), "new-id", gomock.Any()).
Return(client.ContainerInspectResult{Container: container.InspectResponse{
ID: "new-id",
Name: "/abc123456789_test-web-1",
Config: &container.Config{},
NetworkSettings: &container.NetworkSettings{},
}}, nil)
}
expectHook := func(apiClient *mocks.MockAPIClient, exitCode int) *gomock.Call {
serverConn, clientConn := net.Pipe()
go func() {
_ = writeStdcopyFrame(serverConn, 1, "draining\n")
_ = serverConn.Close()
}()
create := apiClient.EXPECT().ExecCreate(gomock.Any(), "c1", gomock.Any()).
DoAndReturn(func(_ context.Context, _ string, opts client.ExecCreateOptions) (client.ExecCreateResult, error) {
assert.DeepEqual(t, opts.Cmd, []string{"drain"})
return client.ExecCreateResult{ID: "exec1"}, nil
})
attach := apiClient.EXPECT().ExecAttach(gomock.Any(), "exec1", gomock.Any()).
Return(client.ExecAttachResult{HijackedResponse: client.NewHijackedResponse(clientConn, "")}, nil)
inspect := apiClient.EXPECT().ExecInspect(gomock.Any(), "exec1", gomock.Any()).
Return(client.ExecInspectResult{ExitCode: exitCode}, nil)
gomock.InOrder(create, attach, inspect)
return inspect
}
t.Run("the hook runs before the container is stopped", func(t *testing.T) {
svc, apiClient := newTestService(t)
hook := expectHook(apiClient, 0)
apiClient.EXPECT().ContainerStop(gomock.Any(), "c1", gomock.Any()).
Return(client.ContainerStopResult{}, nil).After(hook)
err := svc.executePlan(t.Context(), project, emptyObservedState("test"), stopPlan(webContainer(nil)))
assert.NilError(t, err)
})
t.Run("a failing hook fails the plan and the container is not stopped", func(t *testing.T) {
svc, apiClient := newTestService(t)
expectHook(apiClient, 1)
err := svc.executePlan(t.Context(), project, emptyObservedState("test"), stopPlan(webContainer(nil)))
assert.ErrorContains(t, err, "web hook exited with status 1")
})
t.Run("a container stopped since the plan was built is still stopped", func(t *testing.T) {
svc, apiClient := newTestService(t)
exec := apiClient.EXPECT().ExecCreate(gomock.Any(), "c1", gomock.Any()).
Return(client.ExecCreateResult{}, conflictError{})
apiClient.EXPECT().ContainerStop(gomock.Any(), "c1", gomock.Any()).
Return(client.ContainerStopResult{}, nil).After(exec)
err := svc.executePlan(t.Context(), project, emptyObservedState("test"), stopPlan(webContainer(nil)))
assert.NilError(t, err)
})
for name, ctr := range map[string]container.Summary{
"a container of no service of the project has no hook": webContainer(map[string]string{api.ServiceLabel: "orphan"}),
"a relay container has no hook": webContainer(map[string]string{api.RelayLabel: "relay-identity"}),
} {
t.Run(name, func(t *testing.T) {
svc, apiClient := newTestService(t)
apiClient.EXPECT().ContainerStop(gomock.Any(), "c1", gomock.Any()).
Return(client.ContainerStopResult{}, nil)
err := svc.executePlan(t.Context(), project, emptyObservedState("test"), stopPlan(ctr))
assert.NilError(t, err)
})
}
// The replacement already exists when the old container is stopped: a
// failing hook there would leave it behind under its temporary name.
t.Run("a recreate does not run the hook of the replaced container", func(t *testing.T) {
svc, apiClient := newTestService(t)
created := expectReplacementCreated(apiClient)
apiClient.EXPECT().ContainerStop(gomock.Any(), "c1", gomock.Any()).
Return(client.ContainerStopResult{}, nil).After(created)
apiClient.EXPECT().ContainerRemove(gomock.Any(), "c1", gomock.Any()).
Return(client.ContainerRemoveResult{}, nil)
apiClient.EXPECT().ContainerRename(gomock.Any(), "new-id", client.ContainerRenameOptions{NewName: "test-web-1"}).
Return(client.ContainerRenameResult{}, nil)
err := svc.executePlan(t.Context(), project, emptyObservedState("test"), recreatePlan(webContainer(nil)))
assert.NilError(t, err)
})
}
// emptyObservedState returns an ObservedState with no containers/networks/volumes,
// suitable for executor tests that don't exercise service-reference resolution.
func emptyObservedState(project string) *ObservedState {

View file

@ -345,13 +345,13 @@ func (r *reconciler) planRecreateNetworks(keys []string) {
resID := serviceReplicaID(oc.Summary.Labels[api.ServiceLabel], oc.Number)
stopNode, alreadyStopped := r.stoppedByPlan[oc.ID]
if !alreadyStopped {
stopNode = r.plan.AddNode(planning.Operation{
stopNode = r.planStop(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: resID,
Cause: fmt.Sprintf("network %s config changed", key),
Container: &oc.Summary,
Timeout: r.options.Timeout,
}, "")
})
r.stoppedByPlan[oc.ID] = stopNode
}
disconnectNodes = append(disconnectNodes, r.plan.AddNode(planning.Operation{
@ -540,13 +540,13 @@ func (r *reconciler) planRecreateVolumes(keys []string) {
resID := serviceReplicaID(oc.Summary.Labels[api.ServiceLabel], oc.Number)
stopNode, alreadyStopped := r.stoppedByPlan[oc.ID]
if !alreadyStopped {
stopNode = r.plan.AddNode(planning.Operation{
stopNode = r.planStop(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: resID,
Cause: "mounted volume config changed",
Container: &oc.Summary,
Timeout: r.options.Timeout,
}, "")
})
r.stoppedByPlan[oc.ID] = stopNode
}
removeNode := r.plan.AddNode(planning.Operation{
@ -802,13 +802,13 @@ func (r *reconciler) reconcileService(service types.ServiceConfig) error {
continue
}
resID := serviceReplicaID(service.Name, oc.Number)
stopNode := r.plan.AddNode(planning.Operation{
stopNode := r.planStop(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: resID,
Cause: "service is now provider-backed",
Container: &oc.Summary,
Timeout: r.options.Timeout,
}, "")
})
removeNode := r.plan.AddNode(planning.Operation{
Type: planning.OpRemoveContainer,
ResourceID: resID,
@ -877,13 +877,13 @@ func (r *reconciler) reconcileService(service types.ServiceConfig) error {
// node so dependent services wait for the scale-down to finish
// even when no other operation runs on this service.
resID := serviceReplicaID(service.Name, oc.Number)
stopNode := r.plan.AddNode(planning.Operation{
stopNode := r.planStop(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: resID,
Cause: "scale down",
Container: &containers[i].Summary,
Timeout: r.options.Timeout,
}, "")
})
lastNode = r.plan.AddNode(planning.Operation{
Type: planning.OpRemoveContainer,
ResourceID: resID,
@ -1639,6 +1639,58 @@ func (r *reconciler) chainStartReplicas(service types.ServiceConfig, replicas []
return chainEnd
}
// planStop adds the stop of a container to the plan. When the service of the
// container has pre_stop hooks they run first, as a node of their own that the
// stop depends on: whichever operation decides to stop a container (a recreate,
// a scale down, a recreated network or volume...) runs them, as a restart or a
// down does. The node returned is the stop, so whatever depends on it waits for
// the hooks too. (A recreation runs them before it creates the replacement, see
// planRecreateContainer.)
func (r *reconciler) planStop(op planning.Operation) *planning.PlanNode {
if hooks := r.planPreStop(op.ResourceID, op.Container, ""); hooks != nil {
return r.plan.AddNode(op, "", hooks)
}
return r.plan.AddNode(op, "")
}
// preStopOf returns the node of the pre_stop hooks a stop waits for, nil when it
// waits for none.
func preStopOf(stop *planning.PlanNode) *planning.PlanNode {
for _, dep := range stop.DependsOn {
if dep.Operation.Type == planning.OpRunPreStop {
return dep
}
}
return nil
}
// planPreStop adds the pre_stop hooks of the service of ctr to the plan, and
// returns their node: nil when there are none to run.
func (r *reconciler) planPreStop(resourceID string, ctr *container.Summary, group string, deps ...*planning.PlanNode) *planning.PlanNode {
service, ok := r.serviceWithPreStopHooks(ctr)
if !ok {
return nil
}
return r.plan.AddNode(planning.Operation{
Type: planning.OpRunPreStop,
ResourceID: resourceID,
Cause: "pre_stop hooks",
Service: &service,
Container: ctr,
}, group, deps...)
}
// serviceWithPreStopHooks returns the service ctr belongs to when it declares
// pre_stop hooks to run in it. An orphan, whose service is not in the model,
// has none to run, and a relay has no process for a hook to act on.
func (r *reconciler) serviceWithPreStopHooks(ctr *container.Summary) (types.ServiceConfig, bool) {
if ctr == nil || isRelayContainer(*ctr) {
return types.ServiceConfig{}, false
}
service, ok := r.project.Services[ctr.Labels[api.ServiceLabel]]
return service, ok && len(service.PreStop) > 0
}
// planRecreateContainer decomposes container recreation into 4 atomic operations:
// CreateContainer(tmpName) → StopContainer → RemoveContainer → RenameContainer
func (r *reconciler) planRecreateContainer(service types.ServiceConfig, oc *ObservedContainer, infraDeps []*planning.PlanNode) *planning.PlanNode {
@ -1658,6 +1710,24 @@ func (r *reconciler) planRecreateContainer(service types.ServiceConfig, oc *Obse
inherited = &oc.Summary
}
// 0. The pre_stop hooks of the container this replaces run before anything
// is created: a hook that fails then leaves nothing behind, where a
// replacement already created under its temporary name would be left for the
// next up to trip on. The old container stays up from the end of its hooks
// to its stop, the creation of the replacement included.
//
// A container an earlier stage of the plan already schedules a stop for has
// its hooks there, which the creation waits for all the same.
stopNode, alreadyStopped := r.stoppedByPlan[oc.ID]
createDeps := allDeps
if alreadyStopped {
if hooks := preStopOf(stopNode); hooks != nil {
createDeps = append(slices.Clone(allDeps), hooks)
}
} else if hooks := r.planPreStop(resID, &oc.Summary, group, allDeps...); hooks != nil {
createDeps = []*planning.PlanNode{hooks}
}
// 1. Create new container with temporary name
createNode := r.plan.AddNode(planning.Operation{
Type: planning.OpCreateContainer,
@ -1667,24 +1737,20 @@ func (r *reconciler) planRecreateContainer(service types.ServiceConfig, oc *Obse
Inherited: inherited,
Number: oc.Number,
Name: tmpName,
}, group, allDeps...)
}, group, createDeps...)
// 2. Stop old container. If an earlier stage of the plan (e.g.
// planRecreateNetwork) already scheduled a Stop for this container,
// reuse it instead of emitting a second one against an already-stopped
// container. The reused node carries no group, which is fine: the
// recreate's group tracker still drives Working/Done from the create.
// A reused Stop keeps running the pre_stop hooks: it stops the container
// for its own reason, before the replacement is created.
stopNode, alreadyStopped := r.stoppedByPlan[oc.ID]
if !alreadyStopped {
stopNode = r.plan.AddNode(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: resID,
Cause: fmt.Sprintf("replaced by #%d", createNode.ID),
Container: &oc.Summary,
Timeout: r.options.Timeout,
SkipPreStop: true,
Type: planning.OpStopContainer,
ResourceID: resID,
Cause: fmt.Sprintf("replaced by #%d", createNode.ID),
Container: &oc.Summary,
Timeout: r.options.Timeout,
}, group, createNode)
r.stoppedByPlan[oc.ID] = stopNode
}
@ -1747,13 +1813,13 @@ func (r *reconciler) planStopDependents(service types.ServiceConfig) []*planning
if _, already := r.stoppedByPlan[oc.ID]; already {
continue
}
node := r.plan.AddNode(planning.Operation{
node := r.planStop(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: serviceReplicaID(depName, oc.Number),
Cause: fmt.Sprintf("dependency %s being recreated", service.Name),
Container: &r.observed.Containers[depName][i].Summary,
Timeout: r.options.Timeout,
}, "")
})
r.stoppedByPlan[oc.ID] = node
nodes = append(nodes, node)
}
@ -1819,13 +1885,13 @@ func (r *reconciler) sortContainers(containers []ObservedContainer, service type
// reconcileOrphans plans stop + remove for orphaned containers.
func (r *reconciler) reconcileOrphans() {
for i, oc := range r.observed.Orphans {
stopNode := r.plan.AddNode(planning.Operation{
stopNode := r.planStop(planning.Operation{
Type: planning.OpStopContainer,
ResourceID: "orphan:" + oc.Name,
Cause: "orphaned container",
Container: &r.observed.Orphans[i].Summary,
Timeout: r.options.Timeout,
}, "")
})
r.plan.AddNode(planning.Operation{
Type: planning.OpRemoveContainer,
ResourceID: "orphan:" + oc.Name,

View file

@ -0,0 +1,388 @@
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package compose
import (
"slices"
"strconv"
"strings"
"testing"
"github.com/compose-spec/compose-go/v2/types"
"github.com/moby/moby/api/types/container"
"gotest.tools/v3/assert"
"github.com/docker/compose/v5/internal/planning"
"github.com/docker/compose/v5/pkg/api"
)
// Whichever operation of the plan decides to stop a container, the pre_stop
// hooks of its service run first, as a node of their own that the stop depends
// on. Before, only `restart` and `down` ran them: an `up` that recreated a
// container, or scaled a service down, did not.
var quiesceHook = []types.ServiceHook{{Command: types.ShellCommand{"quiesce"}}}
// hookedWebService is the service "web", with a pre_stop hook.
func hookedWebService() types.ServiceConfig {
return types.ServiceConfig{Name: "web", Scale: intPtr(1), PreStop: quiesceHook}
}
// runningReplicas observes the replicas 1..n of svc, running and up to date.
func runningReplicas(t *testing.T, svc types.ServiceConfig, n int) []ObservedContainer {
t.Helper()
hash := mustServiceHash(t, svc)
var replicas []ObservedContainer
for i := 1; i <= n; i++ {
id := svc.Name + "-" + strconv.Itoa(i)
replicas = append(replicas, ObservedContainer{
ID: id, Number: i, State: container.StateRunning, ConfigHash: hash,
Summary: container.Summary{
ID: id, Names: []string{"/prj-" + svc.Name + "-" + strconv.Itoa(i)}, State: container.StateRunning,
Labels: map[string]string{api.ServiceLabel: svc.Name, api.ContainerNumberLabel: strconv.Itoa(i), api.ConfigHashLabel: hash},
},
})
}
return replicas
}
func observedOf(project string, containers map[string][]ObservedContainer) *ObservedState {
return &ObservedState{
ProjectName: project,
Containers: containers,
Networks: map[string][]ObservedNetwork{},
Volumes: map[string][]ObservedVolume{},
}
}
// nodesOf lists the nodes of a type, in plan order.
func nodesOf(plan *planning.Plan, t planning.OperationType) []*planning.PlanNode {
var nodes []*planning.PlanNode
for _, node := range plan.Nodes {
if node.Operation.Type == t {
nodes = append(nodes, node)
}
}
return nodes
}
// hooksBeforeStop checks that the container is stopped once, and that this stop
// has the hooks of the container as its only dependency: whatever the stop was
// waiting for, the hooks wait for. It returns the two nodes.
func hooksBeforeStop(t *testing.T, plan *planning.Plan, containerID string) (hooks, stop *planning.PlanNode) {
t.Helper()
for _, node := range nodesOf(plan, planning.OpStopContainer) {
if node.Operation.Container.ID == containerID {
assert.Assert(t, stop == nil, "container %s is stopped twice:\n%s", containerID, plan)
stop = node
}
}
assert.Assert(t, stop != nil, "container %s is not stopped:\n%s", containerID, plan)
assert.Equal(t, len(stop.DependsOn), 1, "the stop of %s waits for its hooks and for them only (they wait for the rest):\n%s", containerID, plan)
hooks = stop.DependsOn[0]
assert.Equal(t, hooks.Operation.Type, planning.OpRunPreStop, "the stop of %s does not follow its hooks:\n%s", containerID, plan)
assert.Equal(t, hooks.Operation.Container.ID, containerID)
assert.Assert(t, hooks.Operation.Service != nil && len(hooks.Operation.Service.PreStop) > 0, "the hooks node carries the hooks to run")
return hooks, stop
}
func TestReconcileRunsPreStopHooksBeforeAScaleDown(t *testing.T) {
svc := hookedWebService()
project := &types.Project{Name: "myproject", Services: types.Services{"web": svc}}
observed := observedOf("myproject", map[string][]ObservedContainer{"web": runningReplicas(t, svc, 2)})
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
assert.Equal(t, plan.String(), strings.TrimSpace(`
[] -> #1 service:web:2, RunPreStop, pre_stop hooks
[1] -> #2 service:web:2, StopContainer, scale down
[2] -> #3 service:web:2, RemoveContainer, scale down
`)+"\n")
hooksBeforeStop(t, plan, "web-2")
assert.Equal(t, len(nodesOf(plan, planning.OpRunPreStop)), 1, "only the replica that goes has hooks to run:\n%s", plan)
}
func TestReconcileRunsPreStopHooksOfTheContainerItReplacesBeforeCreatingTheReplacement(t *testing.T) {
svc := hookedWebService()
project := &types.Project{Name: "myproject", Services: types.Services{"web": svc}}
replicas := runningReplicas(t, svc, 1)
replicas[0].ConfigHash = "stale"
replicas[0].Summary.Labels[api.ConfigHashLabel] = "stale"
observed := observedOf("myproject", map[string][]ObservedContainer{"web": replicas})
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
// the hooks come first: one that fails leaves no replacement, under its
// temporary name, for the next up to trip on. Then the replacement is created,
// and only then is the old container stopped and removed.
assert.Equal(t, plan.String(), strings.TrimSpace(`
[] -> #1 service:web:1, RunPreStop, pre_stop hooks [recreate:web:1]
[1] -> #2 service:web:1, CreateContainer, config changed (tmpName) [recreate:web:1]
[2] -> #3 service:web:1, StopContainer, replaced by #2 [recreate:web:1]
[3] -> #4 service:web:1, RemoveContainer, replaced by #2 [recreate:web:1]
[4] -> #5 service:web:1, RenameContainer, finalize recreate [recreate:web:1]
`)+"\n")
hooks := nodesOf(plan, planning.OpRunPreStop)[0]
create := nodesOf(plan, planning.OpCreateContainer)[0]
stop := nodesOf(plan, planning.OpStopContainer)[0]
assert.DeepEqual(t, create.DependsOn, []*planning.PlanNode{hooks})
assert.DeepEqual(t, stop.DependsOn, []*planning.PlanNode{create})
assert.Equal(t, hooks.Operation.Container.ID, "web-1")
assert.Equal(t, hooks.Group, "recreate:web:1", "the hooks belong to the recreation, which reports as one row")
}
func TestReconcileRecreatesWithoutHooksAsItAlwaysDid(t *testing.T) {
svc := types.ServiceConfig{Name: "web", Scale: intPtr(1)}
project := &types.Project{Name: "myproject", Services: types.Services{"web": svc}}
replicas := runningReplicas(t, svc, 1)
replicas[0].ConfigHash = "stale"
replicas[0].Summary.Labels[api.ConfigHashLabel] = "stale"
observed := observedOf("myproject", map[string][]ObservedContainer{"web": replicas})
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
assert.Equal(t, plan.String(), strings.TrimSpace(`
[] -> #1 service:web:1, CreateContainer, config changed (tmpName) [recreate:web:1]
[1] -> #2 service:web:1, StopContainer, replaced by #1 [recreate:web:1]
[2] -> #3 service:web:1, RemoveContainer, replaced by #1 [recreate:web:1]
[3] -> #4 service:web:1, RenameContainer, finalize recreate [recreate:web:1]
`)+"\n")
}
func TestReconcileRunsPreStopHooksOfTheContainersOfARecreatedNetwork(t *testing.T) {
web := types.ServiceConfig{
Name: "web", Scale: intPtr(1), PreStop: quiesceHook,
ContainerSpec: types.ContainerSpec{Networks: map[string]*types.ServiceNetworkConfig{"frontend": {}}},
}
project := &types.Project{
Name: "myproject",
Networks: types.Networks{"frontend": {Name: "myproject_frontend", Driver: "overlay"}},
Services: types.Services{"web": web},
}
observed := observedOf("myproject", map[string][]ObservedContainer{"web": {networkAttachedContainer(t, web, "web-1")}})
observed.Networks["frontend"] = []ObservedNetwork{{ID: "net1", Name: "myproject_frontend", ConfigHash: "oldhash"}}
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
hooks, stop := hooksBeforeStop(t, plan, "web-1")
assert.Equal(t, hooks.Operation.Cause, "pre_stop hooks")
// the container is disconnected once it is stopped, not before
disconnect := nodesOf(plan, planning.OpDisconnectNetwork)
assert.Equal(t, len(disconnect), 1)
assert.Equal(t, disconnect[0].DependsOn[0], stop)
}
func TestReconcileRunsPreStopHooksOfTheContainersOfARecreatedVolume(t *testing.T) {
project, observed := divergedVolumeProject(t, 1, 2)
svc := project.Services["db0"]
svc.PreStop = quiesceHook
project.Services["db0"] = svc
// the hooks are part of what the containers were created from
for i, oc := range observed.Containers["db0"] {
hash := mustServiceHash(t, svc)
observed.Containers["db0"][i].ConfigHash = hash
oc.Summary.Labels[api.ConfigHashLabel] = hash
}
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), yesPrompt)
assert.NilError(t, err)
for _, id := range []string{"db0-1", "db0-2"} {
_, stop := hooksBeforeStop(t, plan, id)
assert.Equal(t, stop.Operation.Cause, "mounted volume config changed")
}
assert.Equal(t, len(nodesOf(plan, planning.OpRunPreStop)), 2)
}
// A dependent that restarts with its dependency is stopped, with its hooks,
// when the dependency is recreated.
func TestReconcileRunsPreStopHooksOfTheDependentsOfARecreatedService(t *testing.T) {
parent := types.ServiceConfig{Name: "parent", Scale: intPtr(1), ContainerSpec: types.ContainerSpec{Image: "alpine"}}
dependent := types.ServiceConfig{
Name: "dependent", Scale: intPtr(1), PreStop: quiesceHook,
ContainerSpec: types.ContainerSpec{Image: "alpine"},
WorkloadSpec: types.WorkloadSpec{
DependsOn: types.DependsOnConfig{"parent": {Condition: types.ServiceConditionStarted, Restart: true, Required: true}},
},
}
project := &types.Project{Name: "myproject", Services: types.Services{"parent": parent, "dependent": dependent}}
observed := parentDependentObserved(t, parent, dependent)
observed.Containers["parent"][0].ConfigHash = "stale_parent_hash"
observed.Containers["parent"][0].Summary.Labels[api.ConfigHashLabel] = "stale_parent_hash"
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
hooksBeforeStop(t, plan, "dependent_container_xyz")
// stopped for the cascade and replaced with it: one stop, so one run of hooks
assert.Equal(t, len(nodesOf(plan, planning.OpRunPreStop)), 1, "\n%s", plan)
}
// A container that two decisions of the plan want stopped is stopped once, and
// its hooks run once: here a recreated network and a changed service.
func TestReconcileRunsPreStopHooksOnceForAContainerStoppedForTwoReasons(t *testing.T) {
web := types.ServiceConfig{
Name: "web", Scale: intPtr(1), PreStop: quiesceHook,
ContainerSpec: types.ContainerSpec{Networks: map[string]*types.ServiceNetworkConfig{"frontend": {}}},
}
project := &types.Project{
Name: "myproject",
Networks: types.Networks{"frontend": {Name: "myproject_frontend", Driver: "overlay"}},
Services: types.Services{"web": web},
}
oc := networkAttachedContainer(t, web, "web-1")
oc.ConfigHash = "stale"
oc.Summary.Labels[api.ConfigHashLabel] = "stale"
observed := observedOf("myproject", map[string][]ObservedContainer{"web": {oc}})
observed.Networks["frontend"] = []ObservedNetwork{{ID: "net1", Name: "myproject_frontend", ConfigHash: "oldhash"}}
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
assert.Equal(t, len(nodesOf(plan, planning.OpStopContainer)), 1, "\n%s", plan)
assert.Equal(t, len(nodesOf(plan, planning.OpRunPreStop)), 1, "\n%s", plan)
_, stop := hooksBeforeStop(t, plan, "web-1")
// the stop was scheduled by the network, ahead of the recreation: the
// replacement is not created before its hooks have run, so that a hook that
// fails leaves none behind, and the old container is still not removed before
// the replacement exists
hooks, _ := hooksBeforeStop(t, plan, "web-1")
create := nodesOf(plan, planning.OpCreateContainer)[0]
assert.Assert(t, slices.Contains(create.DependsOn, hooks), "the replacement is created while the hooks may still fail:\n%s", plan)
remove := nodesOf(plan, planning.OpRemoveContainer)[0]
assert.Assert(t, slices.Contains(remove.DependsOn, create), "the removal does not wait for the replacement:\n%s", plan)
assert.Assert(t, slices.Contains(remove.DependsOn, stop), "the removal does not wait for the stop:\n%s", plan)
}
// No hooks node where there is no hook to run: the plans of services without
// pre_stop hooks are the ones they always were.
func TestReconcileAddsNoPreStopNodeWithoutHooksToRun(t *testing.T) {
t.Run("a service without hooks", func(t *testing.T) {
svc := types.ServiceConfig{Name: "web", Scale: intPtr(1)}
project := &types.Project{Name: "myproject", Services: types.Services{"web": svc}}
observed := observedOf("myproject", map[string][]ObservedContainer{"web": runningReplicas(t, svc, 2)})
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
assert.Equal(t, plan.String(), strings.TrimSpace(`
[] -> #1 service:web:2, StopContainer, scale down
[1] -> #2 service:web:2, RemoveContainer, scale down
`)+"\n")
})
t.Run("an orphan, which is not in the model and has no hooks to know", func(t *testing.T) {
project := &types.Project{Name: "myproject", Services: types.Services{}}
observed := observedOf("myproject", map[string][]ObservedContainer{})
observed.Orphans = []ObservedContainer{{
ID: "orphan1", Number: 1, Name: "myproject-old-1",
Summary: container.Summary{ID: "orphan1", Labels: map[string]string{api.ServiceLabel: "old"}},
}}
opts := defaultReconcileOptions()
opts.RemoveOrphans = true
plan, err := reconcile(t.Context(), project, observed, opts, noPrompt)
assert.NilError(t, err)
assert.Equal(t, len(nodesOf(plan, planning.OpRunPreStop)), 0, "\n%s", plan)
assert.Equal(t, len(nodesOf(plan, planning.OpStopContainer)), 1)
})
}
func TestServiceWithPreStopHooks(t *testing.T) {
web := hookedWebService()
plain := types.ServiceConfig{Name: "plain", Scale: intPtr(1)}
r := &reconciler{project: &types.Project{Services: types.Services{"web": web, "plain": plain}}}
ctr := func(service string, labels ...string) *container.Summary {
c := &container.Summary{Labels: map[string]string{api.ServiceLabel: service}}
for i := 0; i+1 < len(labels); i += 2 {
c.Labels[labels[i]] = labels[i+1]
}
return c
}
service, ok := r.serviceWithPreStopHooks(ctr("web"))
assert.Assert(t, ok)
assert.Equal(t, service.Name, "web")
assert.Equal(t, len(service.PreStop), 1)
for name, c := range map[string]*container.Summary{
"no container": nil,
"a service without hooks": ctr("plain"),
"a service that is not in the model": ctr("gone"),
"a relay, which has no process to run a hook in": ctr("web", api.RelayLabel, "abc123"),
} {
_, ok := r.serviceWithPreStopHooks(c)
assert.Assert(t, !ok, name)
}
}
// A service that used to run containers and is now served by a provider: the
// replicas it leaves behind are stopped, with their hooks, before the provider
// takes their name.
func TestReconcileRunsPreStopHooksOfTheReplicasAServiceLeavesForAProvider(t *testing.T) {
db := types.ServiceConfig{Name: "db", PreStop: quiesceHook, Provider: &types.ServiceProviderConfig{Type: "test"}}
project := &types.Project{Name: "myproject", Services: types.Services{"db": db}}
stale := runningReplicas(t, types.ServiceConfig{Name: "db"}, 1)
observed := observedOf("myproject", map[string][]ObservedContainer{"db": stale})
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
assert.Equal(t, plan.String(), strings.TrimSpace(`
[] -> #1 service:db:1, RunPreStop, pre_stop hooks
[1] -> #2 service:db:1, StopContainer, service is now provider-backed
[2] -> #3 service:db:1, RemoveContainer, service is now provider-backed
[3] -> #4 provider:db, RunProvider, provider service
`)+"\n")
hooksBeforeStop(t, plan, "db-1")
}
// The hooks of a recreation wait for what the creation waited for, which
// includes the stop of the dependents the recreation restarts.
func TestReconcileRunsPreStopHooksOfARecreatedServiceAfterTheStopOfItsDependents(t *testing.T) {
parent := types.ServiceConfig{Name: "parent", Scale: intPtr(1), PreStop: quiesceHook, ContainerSpec: types.ContainerSpec{Image: "alpine"}}
dependent := types.ServiceConfig{
Name: "dependent", Scale: intPtr(1), ContainerSpec: types.ContainerSpec{Image: "alpine"},
WorkloadSpec: types.WorkloadSpec{
DependsOn: types.DependsOnConfig{"parent": {Condition: types.ServiceConditionStarted, Restart: true, Required: true}},
},
}
project := &types.Project{Name: "myproject", Services: types.Services{"parent": parent, "dependent": dependent}}
observed := parentDependentObserved(t, parent, dependent)
observed.Containers["parent"][0].ConfigHash = "stale_parent_hash"
observed.Containers["parent"][0].Summary.Labels[api.ConfigHashLabel] = "stale_parent_hash"
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
var dependentStop *planning.PlanNode
for _, node := range nodesOf(plan, planning.OpStopContainer) {
if node.Operation.Container.ID == "dependent_container_xyz" {
dependentStop = node
}
}
assert.Assert(t, dependentStop != nil, "\n%s", plan)
hooks := nodesOf(plan, planning.OpRunPreStop)
assert.Equal(t, len(hooks), 1, "only the parent has hooks:\n%s", plan)
assert.Assert(t, slices.Contains(hooks[0].DependsOn, dependentStop), "the hooks of the parent do not wait for the stop of its dependent:\n%s", plan)
create := nodesOf(plan, planning.OpCreateContainer)[0]
assert.DeepEqual(t, create.DependsOn, []*planning.PlanNode{hooks[0]})
}

View file

@ -330,70 +330,6 @@ func TestReconcileNetworks_DivergedAlsoRecreatesChangedContainer(t *testing.T) {
`)+"\n")
}
// Only the Stop a recreate emits itself skips the pre_stop hooks. A Stop the
// recreate reuses (here the network recreate's) still runs them.
func TestReconcile_RecreateStopSkipsPreStop(t *testing.T) {
skipPreStopByCause := func(plan *planning.Plan) map[string]bool {
stops := map[string]bool{}
for _, n := range plan.Nodes {
if n.Operation.Type == planning.OpStopContainer {
stops[n.Operation.Cause] = n.Operation.SkipPreStop
}
}
return stops
}
t.Run("recreate", func(t *testing.T) {
svc := types.ServiceConfig{Name: "web", Scale: intPtr(1)}
hash := mustServiceHash(t, svc)
project := &types.Project{Name: "myproject", Services: types.Services{"web": svc}}
observed := &ObservedState{
ProjectName: "myproject",
Containers: map[string][]ObservedContainer{
"web": {{
ID: "c1aabbccddee", Number: 1, State: container.StateRunning, ConfigHash: hash,
Summary: container.Summary{
ID: "c1aabbccddee", State: container.StateRunning,
Labels: map[string]string{api.ServiceLabel: "web", api.ContainerNumberLabel: "1", api.ConfigHashLabel: hash},
},
}},
},
Networks: map[string][]ObservedNetwork{},
Volumes: map[string][]ObservedVolume{},
}
opts := defaultReconcileOptions()
opts.Recreate = api.RecreateForce
plan, err := reconcile(t.Context(), project, observed, opts, noPrompt)
assert.NilError(t, err)
assert.DeepEqual(t, skipPreStopByCause(plan), map[string]bool{"replaced by #1": true})
})
t.Run("recreate reusing the stop of a network recreate", func(t *testing.T) {
web := types.ServiceConfig{Name: "web", Scale: intPtr(1), ContainerSpec: types.ContainerSpec{Networks: map[string]*types.ServiceNetworkConfig{"frontend": {}}}}
project := &types.Project{
Name: "myproject",
Networks: types.Networks{"frontend": {Name: "myproject_frontend", Driver: "overlay"}},
Services: types.Services{"web": web},
}
oc := networkAttachedContainer(t, web, "c1aabbccddee")
oc.ConfigHash = "stale"
oc.Summary.Labels[api.ConfigHashLabel] = "stale"
observed := &ObservedState{
ProjectName: "myproject",
Containers: map[string][]ObservedContainer{"web": {oc}},
Networks: map[string][]ObservedNetwork{
"frontend": {{ID: "net1", Name: "myproject_frontend", ConfigHash: "oldhash"}},
},
Volumes: map[string][]ObservedVolume{},
}
plan, err := reconcile(t.Context(), project, observed, defaultReconcileOptions(), noPrompt)
assert.NilError(t, err)
assert.DeepEqual(t, skipPreStopByCause(plan), map[string]bool{"network frontend config changed": false})
})
}
func TestReconcileNetworks_DivergedMultipleServices(t *testing.T) {
project := &types.Project{
Name: "myproject",