run() used to dispatch every node concurrently, with Create-phase and
Start-phase cancellation scoped separately via phaseCancel so a
Start-phase failure couldn't cancel unrelated in-flight Create work.
That stopped short of what the interactive up convergence (lot 2's
next step) actually needs: its attach/printer session takes exclusive
hold of the terminal for the Create phase's own progress display, and
hands it over to continuous container log streaming only once the
Create phase is entirely done project-wide -- a Start-phase node's log
output interleaving with Create's progress bars has nowhere consistent
to go. Phase-scoped cancellation alone still let an unrelated
Start-phase node begin (and start logging) while a sibling elsewhere
in the plan was still being created, or had just failed.
run() now splits plan.Nodes into createNodes/startNodes upfront and
runs them as two fully sequential runPhase() calls: Start-phase nodes
are never even dispatched until every Create-phase node has succeeded,
and a Create-phase failure returns immediately without calling
runPhase on startNodes at all. This matches the old create()-then-
start() sequence's own fail-fast behavior, which the single-plan
migration had implicitly relaxed.
Added a fast-fail validation: a Create-phase node depending on a
Start-phase node would otherwise deadlock forever (the Start phase
isn't dispatched until the Create phase blocked on it returns, so
nothing would ever close that dependency's done channel). Nothing in
the reconciler should produce that edge, but failing fast with a clear
error beats a silent hang if it ever does.
TestExecutePlanCreatePhaseIsABarrierBeforeStartPhase and
TestExecutePlanCreatePhaseFailureNeverDispatchesStartPhase cover both
directions of the barrier; both verified by ablation (reverting to a
single concurrent runPhase call reliably fails each, 5/5 runs).
Verified: go build, go test ./pkg/compose/... (incl. -race), and
golangci-lint all clean; full e2e suite re-run clean against a locally
built binary (same 3 pre-existing, environment-specific failures as
the stack's baseline: TestWatch, TestIPC, TestComposeModel). Local
Copilot CLI review found no correctness/deadlock issues in the barrier
logic itself; its two actionable findings (missing phase-ordering
guard, missing never-dispatched regression test) are both addressed
here.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review: waitDependency's optional-dependency tolerance (the
previous commit) treated ANY DeadlineExceeded on ctx as this call's own
timeout -- including one inherited from an ancestor context the caller
never gave this specific call a deadline of its own for. A plan whose
only outstanding work was an optional, never-satisfied wait could see
the API caller's own external deadline (a wrapper tool, a test
harness) expire, get silently converted to a Skipped event, and report
success despite the caller's context having actually timed out.
waitDependency gains a hasOwnDeadline bool: true only when the
specific call is responsible for ctx's deadline (waitDependencies
passes timeout > 0; execWaitCondition passes exec.waitTimeout > 0,
exactly the condition under which executor.go's dispatch wrapped ctx
with that same field). Only a DeadlineExceeded under hasOwnDeadline is
tolerated for an optional dependency; one without it still propagates,
regardless of Required.
TestWaitDependencyDeadline gains "an inherited parent deadline is not
swallowed for an optional dependency" (timeout=0, an already-expired
parent ctx) alongside the existing "own timeout is skipped" case --
verified by ablation that dropping hasOwnDeadline from the condition
makes the new test fail exactly as described.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review, following up on 374079a32's own fix: serviceNodes keeps
only the LAST node processed during a service's create-phase
convergence -- correct for a single replica, but a scaled service can
have more than one exceptional-state (paused, dead) replica, each with
its own bare-restart OpStartContainer node. Using serviceNodes alone
in planServiceStart's len(replicas) == 0 branch meant a downstream
service_started consumer only ended up depending on the highest-
numbered replica's restart, not every one of them.
exceptionalStateRestartNodes collects every OpStartContainer node from
containerNodes[service] (which tracks all of them, unlike serviceNodes),
in deterministic replica-number order. planServiceStart now merges all
of them into startChainEnds alongside the dependency prerequisites.
TestPlanStart_ScaledExceptionalStateConsumerWaitsForEveryRestart pins
it: two exceptional-state replicas, asserting the consumer depends on
both restart nodes -- verified by ablation to depend on only the last
one without the fix.
Two more small, independent fixes from the same review round:
- execWaitCondition's doc comment (executor_ops.go) described the
pre-waitTimeout "no deadline, caller wraps ctx" design; updated to
describe planExecutor.waitTimeout's actual per-node window.
- waitDependency's new optional-dependency-timeout tolerance (the
previous commit) gains its own direct regression test
(TestWaitDependencyDeadline/expired deadline on an optional
dependency is skipped, not an error) -- the existing tests covered a
required timeout, user cancellation, and an optional dependency's
definitive (non-timeout) failure, but not this specific path.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Three related findings from Copilot and docker-agent on the
phase-scoped cancellation commit, all stemming from the same root
cause: switching run() from errgroup.WithContext's own atomic
cancel-with-error-record to an explicit, separate cancelPhase() call
reopened timing windows that errgroup.WithContext used to close for
free.
- Copilot (high): cancelPhase() unblocks every sibling in that phase
before this goroutine's own error reaches errgroup.Group's internal
errOnce -- a sibling woken by the cancellation can return a bare
context.Canceled of its own and win that race, hiding the actual
daemon error or DeadlineExceeded (and making upDetached's own
DeadlineExceeded translation unreliable with it).
- docker-agent (medium): the "is this my own genuine failure"
nodeCtx.Err() == nil check and the cancellation it gates aren't
atomic -- two genuinely concurrent same-phase failures can both pass
it before either's cancelPhase() takes effect, both emitting a group
Error event for the same resource.
- docker-agent (medium): the dependency-wait loop's early return on
ctx cancellation skipped close(rs.done[node.ID]), the only exit path
that did. Not reachable today (every dependent in the same phase
shares that phase's ctx, already canceled by the time it would
matter), but latent: nothing in runNode enforces that no future
cross-phase dependency edge ever relies on this channel closing.
All three close around one new type, phaseCancel, bundling a phase's
context/cancel pair with a sync.Once: the first node in a phase to
fail records its error and emits the group event inside that Once,
cancels the phase's context, and every later caller -- genuine
concurrent failure or cancellation casualty alike -- is a silent
no-op. run() returns a phase's recorded error over whatever
eg.Wait() itself picked, so errgroup's own race can no longer surface
a cancellation casualty's error in its place. The done-channel close
moved to a single `defer` at the top of runNode, covering every exit
path uniformly instead of three separate explicit calls.
TestExecutePlanConcurrentPhaseFailureKeepsOriginatingError exercises
the first scenario under real concurrency (one immediately-failing
node alongside many siblings a dependency-wait unblocks via its
cancellation) -- see its own comment for why this specific race can't
be forced to fail by ablation in an in-process test (the Go scheduler
never actually lets a sibling win it here), so the fix's correctness
rests on reading errgroup's own errOnce.Do source directly, confirmed
independently by two reviewers, not on this test alone.
Verified: go test -race -count=10 ./pkg/compose/... clean; full e2e
suite re-run clean against a locally built binary (same 3
pre-existing, environment-specific failures as the stack's baseline).
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review ("previously missed"): the same either/or bug just
fixed for planProviderStart (e206f0566) also affects the ordinary
(non-provider) service branch of planServiceStart. A service whose
only container is in an exceptional state (paused, dead) gets a bare
create-phase restart (OpStartContainer, "not running") and takes the
len(replicas) == 0 path in the start-phase visit. When that service
also declares its own depends_on, startChainEnds used only the
dependency's wait node as ends, dropping the service's own restart
node entirely -- a downstream service_started consumer could then
start before the paused/dead service's only container was actually
running again.
ends now always includes the service's own create-phase node
(serviceNodes[service.Name]) alongside its dependency prerequisites
when it has any, instead of either/or -- the exact same fix shape as
planProviderStart.
TestPlanStart_ExceptionalStateConsumerWaitsForRestart pins it,
mirroring TestPlanStart_ProviderConsumerWaitsForDeployment: a
paused service with both an upstream dependency and a downstream
consumer, asserting the consumer's start node depends on the restart
node directly -- verified by ablation to fail, showing the exact
missing edge, without the fix.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review (High) on #14290: run() dispatched every node -- Create
and Start phase alike -- under one errgroup.WithContext(ctx), so any
node failing canceled the shared context for every other goroutine
still in flight. A required OpWaitCondition node hitting
--wait-timeout is a Start-phase failure that can now happen while
unrelated Create-phase work (a sibling service's container or network
create) is still legitimately running -- and that work got aborted
too, with nothing to do with the dependency that timed out. The old
create()-then-start() sequence never had this failure mode: the whole
create phase always finished completely before any dependency wait
even began.
run() now derives two contexts instead of one shared errgroup-context:
createCtx at the root, startCtx as its child. A node picks nodeCtx
(and the matching cancelPhase) from its own node.Phase and calls
cancelPhase() only on its own genuine failure. A Start-phase failure
cancels only startCtx, leaving createCtx and everything still running
under it untouched. A Create-phase failure still cancels the whole
plan, Start phase included, via startCtx's derivation from createCtx
-- matching the old sequence, where start() was never even invoked
once create() failed.
The node-goroutine body moved out of run()'s loop into a runNode
method (golangci-lint's cognitive-complexity limit after this change)
taking a new runState struct bundling the per-run bookkeeping every
node shares.
Two smaller, unrelated fixes bundled in:
- upDetached (up.go) keeps an origCtx snapshot so its two
DeadlineExceeded-to-friendly-message checks can tell its own
WaitTimeout window expiring apart from an inherited, unrelated
parent deadline propagating through the derived context -- both
report DeadlineExceeded on Err(), only the former earned the
"application not healthy" framing.
- waitDependency (service_containers.go), shared by the old
waitDependencies and the new execWaitCondition -- the latter can now
produce a real deadline for the first time via exec.waitTimeout --
tolerates a timeout on an optional (BestEffort) dependency the same
way it already tolerates every other definitive failure: skipped
with a warning, not a hard failure.
Two regression tests pin both cancellation directions:
TestExecutePlanStartPhaseFailureDoesNotCancelCreatePhase (a
Start-phase wait timing out must not cancel a concurrent, unrelated
Create-phase node) and TestExecutePlanCreatePhaseFailureCancelsCreatePhase
(a Create-phase failure must still fail-fast its Create-phase
siblings, same as before this change). Both verified by ablation.
Full e2e suite re-run clean against a locally built binary -- same 3
pre-existing, environment-specific failures as the stack's baseline,
no new ones.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
docker-agent review (moderate confidence): exec.run propagates any
context.DeadlineExceeded up, including one originating from ctx itself
(an outer caller's own deadline -- a test harness, a wrapper tool, a
client-side timeout) rather than from an OpWaitCondition node's own
derived timeout. The WaitTimeout > 0 guard alone doesn't distinguish
the two: a user who did configure --wait-timeout could still see
"application not healthy after Xs" when what actually happened was
the caller's own unrelated deadline firing during plan execution.
ctx at this point is still the caller-supplied, undecorated context
(the per-wait timeout is derived fresh inside executeNode, never
reassigned here) -- so ctx.Err() == nil confirms the DeadlineExceeded
didn't come from ctx's own deadline, leaving only an OpWaitCondition
node's derived timeout as the source.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review ("previously missed", code unchanged since an earlier
round): the prior fix (applyRemainingDeadline) replaced a confusing
raw DeadlineExceeded with a clearer message, but kept the underlying
design flaw it was reacting to -- a single absolute deadline
(time.Now().Add(WaitTimeout)) shared across the whole plan and the
final verification. Slow, unrelated create/start/hook work (never
meant to be bounded by --wait-timeout -- that's the entire point of
exec.waitDeadline existing) could still exhaust that shared budget on
its own, failing an otherwise healthy deployment as "not healthy" with
no health wait ever actually timing out.
start()'s real behavior never had this failure mode: waitDependencies
opens a fresh context.WithTimeout(ctx, timeout) every time it's
called, so each dependency wait gets its own full WaitTimeout window,
independent of how long anything before it took.
planExecutor.waitDeadline (an absolute time.Time) becomes waitTimeout
(a time.Duration): executeNode's OpWaitCondition case now derives a
fresh context.WithTimeout per wait node instead of a shared
context.WithDeadline. upDetached mirrors this for the final
verification -- its own fresh WaitTimeout window, not whatever's left
of one. applyRemainingDeadline's already-expired-deadline problem
disappears by construction: there's no longer a precomputed deadline
to have already expired.
Also fixes two sibling DeadlineExceeded-translation sites (the
post-plan container listing and waitDependencies' own check) that were
missing the WaitTimeout > 0 guard: without a --wait-timeout set, ctx
can still carry an external deadline (an upstream command timeout, a
cancellation) unrelated to --wait-timeout, and naming "application not
healthy after 0s" would blame a duration nobody configured.
TestExecutePlanWaitDeadlineOnlyBoundsWaitNodes and
TestExecutePlanWaitConditionRespectsContextDeadline updated for the
field rename; both still pin their original scenarios under the new
mechanism. Verified against the full e2e suite (TestUpWaitTimeout,
TestUpWait, TestRestartWithDependencies, the provider suite) on a
locally built binary.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review: planProviderStart used a provider's own depends_on
wait nodes as its startChainEnds whenever it had any, entirely
dropping its own OpRunProvider (deployment) node from that set. A
downstream consumer of the provider -- ordered after startChainEnds
-- would then only wait for the provider's dependency to become
healthy, not for the provider plugin/relay deployment itself to
finish. The old create-then-start two-phase barrier guaranteed that
ordering for free; ScopeCreateStart (inert until this PR actually
exercised it end to end) didn't reproduce it.
ends now always includes the provider's own node alongside its
dependency prerequisites when it has any, instead of either/or.
TestPlanStart_ProviderConsumerWaitsForDeployment pins it: a provider
with both an upstream dependency and a downstream consumer, asserting
the consumer's start node depends on the provider's OpRunProvider node
directly -- verified by ablation to fail (showing the exact missing
edge) without the fix.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
docker-agent review (strong confidence): exec.run only bounds
OpWaitCondition nodes with the wait deadline, not create/start/hook
ops (see the previous commit) -- a plan whose non-wait work alone
takes longer than --wait-timeout can still return nil past the
deadline. context.WithDeadline on an already-past deadline silently
produces an immediately-canceled context, failing the next daemon call
(getContainers) with a bare context.DeadlineExceeded indistinguishable
from "health never came up" -- misleading, since health was never
actually checked.
Extracted the deadline-wrapping into applyRemainingDeadline, which
checks the remaining budget first and fails immediately with a message
that says what actually happened, instead of letting a confusing
daemon-call failure stand in for it. Pinned by three unit tests
(zero deadline is a no-op, a future deadline wraps ctx normally, a
past deadline fails immediately with the expected message) -- the
past-deadline case verified by ablation to reproduce a false "nil
error" without the check.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
docker-agent review: the deadline set before executePlan is
unconditional (whenever WaitTimeout > 0, matching start()'s own
WaitTimeout threading, regardless of Wait), but the "application not
healthy" message is specifically a --wait message. `up -d
--wait-timeout=30` with no --wait, hitting the deadline during an
OpWaitCondition node, showed that message despite the user never
asking for a health check -- just a hang guard.
Gate the message on options.Start.Wait at this one call site. The two
other DeadlineExceeded-translating sites (the post-plan container
listing and the final waitDependencies check) are unaffected: both
already sit after the `if !options.Start.Wait { return nil }` early
return, so they're structurally unreachable without Wait already
being true.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review (Medium): wrapping the whole run() ctx with
WaitTimeout also capped Create-phase and Start-phase work that was
never subject to --wait-timeout in the old create()+start() sequence
-- a slow image pull or container create/recreate could now fail as
"application not healthy" with no health wait involved.
planExecutor gains a waitDeadline field, consulted only in
executeNode's OpWaitCondition case to derive a deadline-bound context
for that one call; every other operation type keeps running on the
plan's plain ctx. upDetached now builds its own planExecutor directly
(instead of going through executePlan) so it can set waitDeadline
before calling run(), and reuses the same deadline for the final
post-plan verification instead of wrapping the whole plan's ctx.
TestExecutePlanWaitDeadlineOnlyBoundsWaitNodes pins this: a plan
pairing a never-satisfied OpWaitCondition with an OpCreateNetwork
confirms the network create isn't raced by the same short deadline.
Verified by ablation that removing the OpWaitCondition dispatch's
deadline derivation makes the test hang instead of failing promptly.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
docker-agent review: moving the WaitTimeout deadline to wrap ctx before
executePlan closed the in-plan hang, but opened a narrow new one --
executePlan can return nil right as the deadline fires, leaving the
subsequent getContainers call (for the final --wait verification) to
run against an already-expired ctx and propagate a raw
context.DeadlineExceeded instead of the existing friendly
"application not healthy after %s" message. Same translation the
executePlan and waitDependencies error paths already apply.
Also, a second docker-agent finding: execRenameContainer's
containersByService refresh silently no-ops if the container isn't
found at its expected slot (can't happen today -- the DAG guarantees
execCreateContainer's append runs first -- but nothing would surface
it if a future change broke that). Logs a warning instead of staying
silent, so a regression here is visible rather than just quietly
reintroducing the stale-name bug this PR fixed.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
The previous commit gated the deadline on options.Start.Wait &&
WaitTimeout > 0, describing it as matching start()'s own gating -- it
doesn't. start()'s InDependencyOrder passes options.WaitTimeout into
every startService call unconditionally, not only when options.Wait is
set, and the CLI never requires --wait alongside --wait-timeout
(`up -d --wait-timeout 30` with no --wait is accepted as-is). Under the
previous gating, that exact combination would still hang on a stuck
OpWaitCondition node -- the same bug the deadline was just added to
fix, reintroduced for one flag combination.
Drop the options.Start.Wait condition: the deadline now applies
whenever WaitTimeout > 0, matching start()'s actual unconditional
behavior.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Copilot review (High): the plan's own OpWaitCondition nodes
(service_healthy / service_completed_successfully dependency waits,
executed as part of executePlan) have no timeout of their own -- they
block on whatever ctx they're given, unlike the imperative engine's
waitDependencies, which already threaded WaitTimeout through every
per-dependency wait, not just the final --wait check. upDetached only
wrapped ctx with WaitTimeout around that final check, established
after executePlan already returned -- so a condition that's never
satisfied hung `up -d --wait --wait-timeout N` forever instead of
failing after N seconds.
Move the deadline to wrap ctx before executePlan runs (gated on
Wait && WaitTimeout > 0, matching start()'s own gating), and reuse the
same ctx for the final verification instead of opening a second,
independent WaitTimeout window -- one overall budget for "becoming
healthy" covering both the plan's in-flight waits and the final check.
preparePlan is deliberately left outside the deadline: image pulls and
the rest of create()'s own work were never bounded by --wait-timeout
in the old create()+start() sequence either.
Regression-tested at two levels:
- TestExecutePlanWaitConditionRespectsContextDeadline drives a real
OpWaitCondition node through executePlan/run() under a short
deadline and asserts it returns promptly with ctx.Err(), proving the
deadline propagates into the plan's blocking nodes.
- The existing e2e TestUpWaitTimeout (up --wait --wait-timeout on a
service that never turns healthy) is what actually exercises
upDetached's own wiring: verified by ablation that reverting this
fix makes it hang (test timeout) instead of failing after 3s.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Detached `up` used to run create() then start() back to back: two
separate daemon snapshots, the second blind to what the first just
created or recreated. preparePlan already supports planning both
phases in one pass (ScopeCreateStart, landed across lot 1) -- this
wires it in for the one caller that can use it outright: `up -d`.
preparePlan gains an explicit scope parameter (ScopeCreate for
create(), unchanged); Up()'s detached branch now calls a new
upDetached, which runs preparePlan(..., ScopeCreateStart) +
executePlan once instead of create() + start(). --wait stays a
post-plan verification: it re-lists containers after the plan runs
(the plan may have created or recreated some, so the pre-execution
snapshot can't be reused for this) and runs the same waitDependencies
check start() already does.
Interactive up is untouched: it still runs create() then start() with
its printer/monitor listener wired in between, converging onto the
plan engine separately (a riskier, later item of the same lot).
ScopeCreateStart landed in lot 1 as inert code with no real caller;
this is the first one, and it surfaced two latent bugs in the
container-recreate path that nothing had exercised end to end before:
- planRecreateContainer plans a container's recreation as Create
(under a temporary "<shortID>_<name>" to avoid colliding with the
old container still holding the final name) -> Stop -> Remove ->
Rename(final name). The start phase's event naming and container-ID
resolution (groupEventName, resolveContainerID) read the create
node's published result by design (plannedReplica keeps every
start-phase reference pointed at CreateNodeID, not the rename node),
but execRenameContainer never updated that result after renaming --
so a recreated container's Starting/Started events kept reporting
the temporary name forever.
- execCreateContainer also publishes the new container into
containersByService (the live view OpWaitCondition reads for
depends_on health waits) under that same temporary name, with
nothing refreshing it after rename either -- a dependent waiting on
the recreated container's health reported Waiting/Healthy under the
temporary name too.
Both fixed in execRenameContainer: it now updates the create node's
pctx result in place after a successful rename, and (via a new
Service field on the rename Operation) patches the matching
containersByService entry's name too. Each pinned by a regression
test, verified by reverting the fix locally and confirming the test
catches it.
Verified with the full e2e suite (`go test -tags e2e ./pkg/e2e/...`)
against a locally built binary -- including TestRestartWithDependencies,
which is what caught both bugs in the first place -- plus the existing
unit suite and lint.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
commit 342f4de35f accidentally
bumped the minimum version in go.mod. Unfortunately, we can't
drop the patch version, but let's keep it at the lowest possible
for environments that don't have the latest Go version available.
Fixes: 342f4de ("Update to go1.26.9")
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Running a provider plugin (finding its binary, executing it, serving the
JSON messages it sends, applying the variables and endpoints it publishes,
streaming it an image) needs from the engine the Docker API, the event bus,
the Docker CLI that locates the plugin, the preparation of the environment
of a shelled-out command, and the lock that guards the project model every
concurrent provider run mutates.
It now lives in internal/provider behind a Backend interface that
composeService implements in pkg/compose/plugins.go, next to runPlugin, which
stays as a one-line forwarder so none of its callers (up, down, stop, pull)
changes. The relay it deploys goes through internal/relay, whose Backend the
new one extends. The public types and constants of the protocol (JsonMessage,
ProviderMetadata, the *Type message constants...) stay exported from
pkg/compose as aliases of the new package's.
The tests of the plugin protocol move with the code, assertions unchanged;
those of the provider image phase and of the relay link network removal
stay in pkg/compose. The forwarders to the relay that only the plugin code
used are dropped.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
The relay container and the relay link networks that stand in for a
provider service need three things from the engine: the Docker API, the
event bus and whether Docker Desktop is the engine.
They now live in internal/relay behind a Backend interface that
composeService implements in pkg/compose/relay.go, which keeps the names
the lifecycle code calls (ensureServiceRelay, isRelayContainer,
checkRelayTarget...) as one-line forwarders, so none of its callers change.
The one down-specific piece, turning the relay link networks into down
operations gated on the shared limiter, stays in pkg/compose together with
its tests; the other relay tests move with the code, assertions unchanged.
The progress events and the container name the package needs come from two
small shared packages, internal/progress and internal/naming, which the
following moves reuse. pkg/compose keeps its own copies until the shared
kernel is extracted.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Sampling a container takes about a second on the daemon side, and one
goroutine was started per container on every refresh: with all the
projects of a busy host that is hundreds of concurrent calls. Bound
them to 32.
A container that cannot be sampled is now shown without usage, like a
stopped one, instead of aborting the refresh of all the others. An
interrupted command is still reported as such, not rendered as
containers without usage.
Point containerUsage to the docker/cli helpers it follows, and cover
the --no-stream path of runStatsProjects.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
`docker compose stats` only reports on a single project. Add two
opt-in flags, the default behavior being unchanged:
--all-projects one line per container for every project, with a
PROJECT column
--aggregate one line per project, summing the resource usage of
its containers; alone, it reports on the current
project
Both support the `table` and `json` formats, the latter printing one
object per line like `docker stats`. Unless `--no-stream` is set, they
refresh 2s after each sample. They cannot be combined with a SERVICE,
and `--all-projects` cannot be combined with `--project-name`.
docker/cli does not export its stats collection, so containers are
sampled through the Engine API and the figures computed the same way
`docker stats` does.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
The dry-run client fakes ImageInspect for some callers, picked by the
name of the calling function, and fakes the push of an image. Nothing
tied --ignore-missing to the real state of the local image store in
dry-run.
Check that a missing image is skipped from what the engine really
holds, that the other images get the faked push, and that nothing is
pushed nor looked up in a registry for the skipped ones.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
`push --ignore-push-failures` ignores every push error, including
authentication and registry failures, which can hide real problems when
the only expectation is that some services have not been built.
Add `--ignore-missing`, which skips an image that is not in the local
image store and still fails on any other error. It is independent of
`--ignore-push-failures`, whose behavior is unchanged.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
The sibling's start now only returns once the wait has polled its
dependency, so without the fix the plan deadlocks whichever node takes the
single slot first, instead of depending on the scheduler. It also uses the
platform-neutral newTestService helper, so the file builds on Windows.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Every plan node acquired a concurrency slot before running, including
OpWaitCondition, which then kept it for the whole health polling. A
dependency awaited as healthy can itself need a sibling container the plan
has yet to start, so with a bounded --parallel the wait could take the slot
that sibling's start needed and only end at its timeout.
Wait nodes now skip the limiter: they only poll the daemon on a ticker, as
the imperative waitDependencies does outside the cap.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
The dependencies a one-off starts go through the regular create path
and its config-hash divergence check, with no way to opt out: any
resolution difference with the command that created them (environment,
model edit) recreates the dependency — destroying state a previous run
built up (issue #13769's database losing its users). up already offers
--no-recreate for exactly this; run now aligns: the flag maps to the
"never" recreate policy, propagated through the RunOptions.CreateOptions
fields that startDependencies previously dropped. Default behavior is
unchanged (empty policy = "diverged").
Closes#13769
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
doBuildBake waited for the buildx process in a goroutine while reading its
rawjson stderr stream. os/exec closes the pipe as soon as Wait sees the
process exit, dropping whatever was not read yet: when the consumer of the
solve statuses (the progress display) lags behind the process, the end of the
stream is lost. That is where bake tells why it failed (the Dockerfile
excerpt, then "failed to solve: ..."), so the build failed with exit code 1
but without its reason, or with it truncated.
Read the stream to EOF first, as the os/exec documentation requires, then
Wait. The os.ErrClosed case of the reader, which only existed to absorb the
pipe being closed under it, goes away with the race.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
The docker model plugin is an external process the dry-run API client
cannot intercept, so up, create and run --dry-run really pulled the
models and changed the runner configuration.
Skip pull and configure when dry-run is set while still emitting the
progress events. The read-only ls and status commands still run, so
pulling is only reported for a model that is actually missing and the
model variables are still computed.
Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
Dry-run only wraps the Docker API client, so provider services, which
are external processes, were still executed: up and create ran the
provider's up command, down and stop ran theirs.
Skip the process in executePlugin when dry-run is set while still
emitting the progress events, and return early from runPlugin so no
relay is deployed or removed for a provider that never ran. The
metadata command is still invoked to keep validating the binary and
its required parameters.
Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
LoadProject and Generate (the api.ProjectLoader operations) need two things
from the engine: the Docker API, to read the containers a project is
generated from, and the Docker CLI, which resolves remote Compose files.
They now live in internal/projectloader, along with the unsupported
attributes detection only the loader uses, behind a Backend interface that
composeService implements in a new file of pkg/compose, like internal/inspect.
The tests move with the code; their assertions are unchanged, only the way
the service is built differs.
The canonical container name, which both this package and internal/inspect
need, moves to a tiny internal/naming package instead of being copied a
third time. pkg/compose keeps its own copy until the shared kernel is
extracted.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
ps, ls, top, port, volumes, events and viz only read the state of a
project: they need the Docker API, the list of the project's containers
and the concurrency bound, nothing else of composeService.
They now live in internal/inspect, which declares that need as a Backend
interface. composeService implements it in a new file of pkg/compose and
forwards the seven api.Inspector methods, so no other file of pkg/compose
changes, and neither does the behavior: the service-level tests stay in
pkg/compose and run unchanged through the forwarders.
The few tiny helpers the operations share with the rest of pkg/compose
(canonical container name, concurrency-limited errgroup, project filter)
are copied for now: the shared kernel they belong to is a later step.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
compose run only wrapped the start of its dependencies in the "run"
progress operation. The pull of the target service's image, and the
creation of the one-off container, happened once that operation was
closed, so the TTY display fell back to one plain line per event,
including every layer, instead of the compact in-place block.
Wrap the whole preparation in the operation.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Picks up compose-spec/compose-go#938, which resolves the env_file entries
of pre_start hooks like the service ones.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Reproduces docker/compose#14287: a hook inheriting the service's
env_file (or declaring its own) runs without those variables.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Pure extraction, no behavior change: create() resolved the project
model, ensured images/models and external networks/volumes, observed
the daemon, and reconciled a Plan, all inline before calling
executePlan. That decision-making half is now its own function,
preparePlan, returning the canonical project, the daemon snapshot, and
the Plan — nothing is created, started, or otherwise touched by it.
This is Lot 1's last item (epic #14081): interactive up's eventual
create/start phase boundary needs to prepare the plan once, run the
Create phase, set up attach/printer/monitor, then run the Start phase
— which needs the plan and snapshot available between those steps,
not buried inside create()'s single call chain. create() itself is
unchanged in behavior, just now a two-line call into preparePlan
followed by the existing emitRunningEvents + executePlan.
Verified with the existing unit suite plus the create/up/down e2e
scenarios (TestLocalComposeUp, TestCreateIdempotentDefaultPlatform,
TestCreateIdempotentSharedImageMixedPlatforms, TestCreateRefusesJob,
TestCreateLocalMultiPlatformImage, TestUpWithAllResources) against a
locally built binary.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
A sync into a path that is also bind-mounted writes back to the host,
which the watcher sees as a new change and syncs again, looping
forever. isSync, which gates the bind mount check, missed sync+exec,
so only sync and sync+restart triggers were skipped with a warning.
Include sync+exec in isSync. This also makes initial_sync apply to
sync+exec triggers, as it does for the other sync+x actions.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
Grant access to SSH keys and sockets from build configuration and CLI
options, and authorize default agent forwarding, including implicit SSH
Git contexts. Serialize pathless SSH entries without an empty source so
Bake applies the agent entitlement check.
Grant read access to local cache imports and OCI layout contexts, and
write access to local cache exports. Match Bake's path and cache syntax
while excluding service, target and image references from filesystem grants.
Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
Buildx 0.37.2 enforces entitlements with rawjson progress, exposing missing
permissions in Compose's Bake invocation. Grant read access to Dockerfiles
and file secrets, including local Dockerfiles used with remote contexts,
and forward requested entitlements and host network access.
Deduplicate grants and preserve environment secrets and privileged builds.
Add regression coverage for the generated Bake configuration and arguments.
Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
The client replaced ErrSecretsEngineNotAvailable with a typed ConnectError. Any failure to reach the secrets engine now falls back to the Docker CLI credentials and is logged at debug level.
Signed-off-by: Alano Terblanche <18033717+Benehiko@users.noreply.github.com>
Compose is now composed by embedding Lifecycle, Inspector, ImageManager,
Runner, Watcher and ProjectLoader. The method set of Compose is unchanged.
ProjectOptions.ToProject and configOptions.ToProject only need to load a
project, so they now depend on api.ProjectLoader.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
Branch protection currently has to list each job and every entry of the
e2e matrix, so changing the matrix means changing repository settings.
Add a single ci-ok job that fails if any gating job failed or was
cancelled and accepts jobs skipped by their own condition, so it can be
the only required check.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
TestBuildTLS slept a fixed second after the dind daemon logged that it
listens, hoping the client certificates were written; poll for them
instead. TestForwardKeepsStreamingAfterHalfClose had 150ms of margin
between each chunk and the 300ms idle grace, which a loaded CI runner can
eat; use 100ms chunks against a 1s grace.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
The unit suite ran without -race, so data races in the concurrent code
paths (scheduler, watch, executor) were only caught if they happened to
corrupt a result. Build the test stage with cgo (gcc + musl-dev) and
pass -race to gotestsum. The suite is race-clean: 1100 tests, no report.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
The unit and e2e test runs fetched gotestsum@latest and `make fmt`
gofumpt@latest at execution time, so a new upstream release could break
the build with no change in this repository. Pin both to explicit
versions.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
keyboard.Close closes the channel handed out by GetKeys. Run kept reading
zero-value events from it until its context was done.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
pkg/compose still imported the keyboard library: it grabbed the terminal,
forwarded raw key events to the menu and released the terminal on exit.
The NavigationMenu now takes care of all of it through Open, Run and Close,
so the library no longer knows about keys or the terminal, and the menu
interface no longer exposes a third-party event type.
As a side effect, key handling no longer shares a goroutine with the
signal handling loop of `up`.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
pkg/compose imported cmd/formatter for the interactive keyboard menu of a
foreground up, so the library depended on the CLI. Define a NavigationMenu
interface (and a factory) in pkg/compose, satisfied by formatter.LogKeyboard,
and have the CLI inject it with the new WithNavigationMenu option. The terminal
code stays in cmd/formatter. Without the option no menu is displayed.
formatter.Feature moves to api.Feature so that both sides share the type, and
a depguard rule now forbids pkg/ and internal/ from importing cmd/.
Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>