Repository navigation
fix: fix incorrect restart=always restart logic - #13993
Conversation
There was a problem hiding this comment.
Pull request overview
This PR adjusts restart-policy handling so containers with restart=always behave correctly when the daemon restarts, using the containerd.io/restart.explicitly-stopped label as the gating signal.
Changes:
- Update restart policy reconciliation to short-circuit on
ExplicitlyStoppedLabelbefore evaluating the policy. - Treat
alwaysandunless-stoppedconsistently in reconciliation (restart allowed when not explicitly stopped). - Add a one-time monitor startup pass to clear
ExplicitlyStoppedLabelfor containers whose policy isalways.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| plugins/restart/monitor.go | Adds a one-time startup routine to reset ExplicitlyStoppedLabel for always policy containers. |
| core/runtime/restart/restart.go | Changes Reconcile logic to honor ExplicitlyStoppedLabel for all policies and simplifies policy branching. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
a5bd624 to
3745d79
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (2)
core/runtime/restart/restart.go:122
- Reconcile() now short-circuits on ExplicitlyStoppedLabel for all restart policies (including "always" and "on-failure"), but the unit tests only cover the "unless-stopped" + explicitly-stopped case. Add/adjust tests to cover the new behavior (e.g., "always" + explicitly-stopped should return false; "on-failure" + explicitly-stopped should return false even with non-zero exit).
explicitlyStopped, _ := strconv.ParseBool(labels[ExplicitlyStoppedLabel])
if explicitlyStopped {
return false
}
plugins/restart/monitor.go:120
- resetAlwaysRestartPolicyLabel() updates the ExplicitlyStopped label for every "always" container on startup, even when the label is already unset/false. This causes unnecessary container metadata writes (and can be expensive at scale). Consider only updating containers that are currently marked explicitly-stopped.
if rp.Name() == "always" {
if err := resetContainerExplicitlyStoppedLabel(ctx, c); err != nil {
log.G(ctx).WithError(err).Error("failed to reset explicitly-stopped label")
}
}
3745d79 to
6404c98
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (3)
plugins/restart/monitor.go:131
- This call site should be updated to match the renamed helper so the code continues to build.
func (m *monitor) run(interval time.Duration) {
// This function is executed exactly once.
m.resetAlwaysRestartPolicyLabel()
if interval == 0 {
core/runtime/restart/restart.go:123
Reconcilenow short-circuits onExplicitlyStoppedLabelfor all policies, which is a behavior change that isn’t covered by existing unit tests (currently onlyunless-stoppedhas an explicitly-stopped case). Please add test cases for at leastalwaysandon-failurewithExplicitlyStoppedLabel=trueto prevent regressions.
// Reconcile reconciles the restart policy of a container.
func Reconcile(status containerd.Status, labels map[string]string) bool {
explicitlyStopped, _ := strconv.ParseBool(labels[ExplicitlyStoppedLabel])
if explicitlyStopped {
return false
}
rp, err := NewPolicy(labels[PolicyLabel])
plugins/restart/monitor.go:92
- The helper name
resetAlwaysRestartPolicyLabelis misleading: it resets the explicitly-stopped label, not the restart policy label. Renaming it will make the intent clearer and avoid confusion for future maintenance.
This issue also appears on line 128 of the same file.
// Reset restart.ExplicitlyStoppedLabel to false for containers whose restart policy is "always".
// This ensures "always" containers are eligible to restart even if they were previously explicitly stopped.
func (m *monitor) resetAlwaysRestartPolicyLabel() {
ns, err := m.client.NamespaceService().List(context.Background())
6404c98 to
ea473f9
Compare
ea473f9 to
5aa9795
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
Suppressed comments (6)
integration/client/container_linux_test.go:254
- The result of setting the explicit-stop marker is ignored, so a failed update means this test may proceed without establishing the condition it claims to verify. Fail the test when this setup update fails.
if err := updateExplicitlyStoppedLabel(ctx, container, true); err != nil {
integration/client/container_linux_test.go:262
newTaskis dereferenced on the next line before the error fromcontainer.Taskis checked. If task lookup fails, the test panics instead of reporting the actual failure; checkerrimmediately after this assignment.
// should be longer than interval (10 seconds) time
time.Sleep(time.Second * 12)
newTask, err = container.Task(ctx, nil)
integration/client/container_linux_test.go:267
- The assertion message contains a spelling error.
}
integration/client/container_linux_test.go:240
- This test only sets the explicit-stop label and waits for the next reconcile; it never restarts containerd, so it does not exercise the new startup reset at all. A regression that leaves the label set after daemon startup would still pass. Add a daemon-restart or focused monitor test that verifies an explicitly stopped
alwayscontainer is restarted after startup.
time.Sleep(time.Second * 12)
integration/client/container_linux_test.go:250
- The assertion message contains a spelling error.
This issue also appears on line 267 of the same file.
t.Errorf("expected staus %s but get %s", Running, newStatus.Status)
plugins/restart/monitor.go:130
- The added integration test runs against an already-running daemon, so it never exercises this one-time startup reset. It verifies suppression while the daemon is running, but not the required behavior that an
alwayscontainer with the marker set restarts after containerd itself is restarted. Add a daemon-restart test for this path.
func (m *monitor) run(interval time.Duration) {
// This function is executed exactly once.
m.resetAlwaysContainerExplicitlyStoppedLabel()
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Suppressed comments (10)
core/runtime/restart/restart.go:121
- The new guard now applies to every restart policy, but the table only exercises
ExplicitlyStoppedLabel=trueforunless-stopped. Add cases for at leastalwaysandon-failure(with a non-zero exit for the latter) so this behavior change is directly covered.
explicitlyStopped, _ := strconv.ParseBool(labels[ExplicitlyStoppedLabel])
if explicitlyStopped {
return false
integration/client/container_linux_test.go:45
- This test imports the same
github.com/containerd/containerd/v2/clientpackage twice, once as a dot import and once ascontainerd. Go rejects duplicate imports of one package path, so this file will not compile. Keep one import form and adjust the new helper calls accordingly.
containerd "github.com/containerd/containerd/v2/client"
integration/client/container_linux_test.go:220
- After the monitor's first restart,
newTaskis the current task, but this deferred cleanup only deletes the originaltask. The second phase intentionally leavesnewTaskstopped;container.Deleterejects a container while any task exists, so this test leaks its container and snapshot. Defer deletion of the current task (or explicitly deletenewTask) before deleting the container.
defer task.Delete(ctx)
integration/client/container_linux_test.go:240
- This integration test runs against an already-running daemon and only verifies suppression while the label is true; it never exercises the one-time startup reset added at
plugins/restart/monitor.go:130. Add a daemon-restart scenario with a stoppedalwayscontainer to verify the marker is cleared and the task is restarted after startup.
// should be longer than interval (10 seconds) time
time.Sleep(time.Second * 12)
integration/client/container_linux_test.go:269
- The assertion message misspells
statusasstausand uses the ungrammaticalbut get; correct the message so a failing test is clear.
t.Errorf("expected staus %s but get %s", Stopped, newStatus.Status)
plugins/restart/monitor.go:130
InitFnstartsrunasynchronously, so this one-shot reset can still be executing after the daemon begins accepting requests. Anerdctl stopduring the scan can set the label totrueand then have it overwritten by thisfalseupdate, causing analwayscontainer to restart even though it was stopped after startup. Complete or gate this initialization before normal requests are served, and avoid overwriting a newer stop update.
m.resetAlwaysContainerExplicitlyStoppedLabel()
plugins/restart/monitor.go:120
- This startup reset runs only once. If this
Updatefails transiently, the label remains true and the newReconcileguard suppresses every later reconciliation for the rest of the daemon lifetime, so the container will not resume after the daemon restart as intended. Retain failed resets and retry them during startup (without resetting labels on every normal loop).
if err := resetContainerExplicitlyStoppedLabel(ctx, c); err != nil {
log.G(ctx).WithError(err).Error("failed to reset explicitly-stopped label")
integration/client/container_linux_test.go:263
- The error from this
container.Tasklookup is ignored beforenewTaskis dereferenced. If the task is temporarily absent while the monitor is deleting/recreating it, the test can panic instead of reporting the failure. Checkerrimmediately, as in the first lookup above.
newTask, err = container.Task(ctx, nil)
integration/client/container_linux_test.go:250
- The assertion message misspells
statusasstausand uses the ungrammaticalbut get; correct the message so a failing test is clear.
This issue also appears on line 269 of the same file.
t.Errorf("expected staus %s but get %s", Running, newStatus.Status)
plugins/restart/monitor.go:130
- The new integration test never exercises this startup reset: it sets
ExplicitlyStoppedLabeland kills the task, but does not restart containerd. Consequently the PR's key behavior—an explicitly stoppedalwayscontainer becoming eligible again after a daemon restart—can regress without failing the test. Add a daemon-restart case that persists the label and verifies the task is recreated.
m.resetAlwaysContainerExplicitlyStoppedLabel()
5aa9795 to
22c54bb
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Suppressed comments (8)
core/runtime/restart/restart.go:122
- The new guard now applies to
on-failureas well, butTestRestartPolicyReconcileonly has an explicitly-stopped case forunless-stopped. Add anon-failurecase with a non-zero exit status to protect this changed behavior.
explicitlyStopped, _ := strconv.ParseBool(labels[ExplicitlyStoppedLabel])
if explicitlyStopped {
return false
}
integration/client/container_linux_test.go:239
- This test only sets the marker after the monitor has already initialized and waits for normal reconciliation; it never restarts containerd. Consequently, the new one-shot startup reset is not exercised, and the test would pass even if
resetAlwaysContainerExplicitlyStoppedLabelwere missing or broken. Add a daemon-restart scenario that verifies an explicitly stoppedalwaystask is recreated.
time.Sleep(time.Second * 12)
newTask, err := container.Task(ctx, nil)
integration/client/container_linux_test.go:267
- The assertion message repeats the
staustypo and usesgetinstead ofgot, making failures less clear.
t.Errorf("expected staus %s but get %s", Stopped, newStatus.Status)
plugins/restart/monitor.go:98
- This one-shot startup pass swallows failures. If the namespace list or a per-container label update fails transiently, the marker can remain
true, while the normal reconciliation loop never clears it; analwayscontainer can then stay suppressed for the entire daemon lifetime instead of becoming eligible after startup. Retry the reset (or otherwise make startup retry it) before treating initialization as complete.
ns, err := m.client.NamespaceService().List(context.Background())
if err != nil {
log.G(context.Background()).WithError(err).Errorf("failed to get container namespace")
return
plugins/restart/monitor.go:64
- This one-shot reset is what makes
alwaysdiffer fromunless-stoppedafter a daemon restart, butTestContainerRestartPolicyAlwaysonly toggles the marker while the existing daemon is running and waits for reconciliation. It never restarts containerd, so a regression in this startup scan would still pass; add a daemon-restart integration case that verifies the task is recreated.
m.resetAlwaysContainerExplicitlyStoppedLabel()
core/runtime/restart/restart.go:122
- The marker is now honored for
always, but nerdctl's stop/kill paths set it before attempting the task operation and leave it set when that operation fails. If a failed stop leaves the task running and it later exits, this guard suppresses the restart until another daemon restart, even though no stop succeeded. Set the marker only after a successful operation or clear it on the error path.
explicitlyStopped, _ := strconv.ParseBool(labels[ExplicitlyStoppedLabel])
if explicitlyStopped {
return false
}
integration/client/container_linux_test.go:265
container.Taskcan return an error while the task is unavailable, but the error is ignored beforenewTask.Statusis called. Check the lookup error first so a missing task is reported as a test failure instead of causing a nil-pointer panic.
newTask, err = container.Task(ctx, nil)
integration/client/container_linux_test.go:248
- The assertion message misspells
statusasstausand usesgetinstead ofgot, making failures less clear.
This issue also appears on line 267 of the same file.
t.Errorf("expected staus %s but get %s", Running, newStatus.Status)
Signed-off-by: ningmingxiao <[email protected]>
688f5ab to
452b4d9
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
Suppressed comments (5)
core/runtime/restart/restart.go:121
- This early veto changes
on-failuresemantics as a side effect: afternerdctl stopsets this marker, a task that exits with a non-zero status is no longer eligible for anon-failurerestart. The startup reset only clears the marker foralways, so this suppression also persists across daemon restarts. Keep the marker handling scoped to the intended policies, or explicitly define and test theon-failurebehavior.
explicitlyStopped, _ := strconv.ParseBool(labels[ExplicitlyStoppedLabel])
if explicitlyStopped {
return false
plugins/restart/monitor.go:64
- Because this reset is called once and its errors are discarded, a transient namespace/list/update failure leaves
explicitly-stopped=true; the normal reconcile path then returns false at the explicit-stop guard and never retries the reset. Analwayscontainer can therefore remain stopped until a later daemon restart. Preserve the one-time semantics while retrying failed work or fail initialization when the reset cannot complete.
// This function is executed exactly once.
m.resetAlwaysContainerExplicitlyStoppedLabel()
plugins/restart/monitor.go:64
- The new startup-reset path is not covered by the added integration test: it changes the label after the daemon is already running and never restarts the daemon. Please add a case that persists an explicitly stopped
alwayscontainer, starts a fresh daemon, and verifies that it is restarted; otherwise this one-time initialization can regress unnoticed.
m.resetAlwaysContainerExplicitlyStoppedLabel()
integration/client/container_linux_test.go:261
- This test exercises the explicit-stop veto by writing the label directly, but it never restarts containerd and therefore does not cover the new startup reset path. A regression in the namespace scan or label update would still pass. Add a sequential integration case that stops an
alwayscontainer, restarts the daemon, and verifies that the task is recreated.
if err := updateExplicitlyStoppedLabel(ctx, container, true); err != nil {
t.Fatal(err)
}
integration/client/container_linux_test.go:270
container.Taskcan returnNotFoundwhile the restart monitor is deleting and recreating the task (the existing restart-monitor test explicitly handles this transient window). This code dereferencesnewTaskbefore checkingerr, so a normal restart race panics the test instead of reporting the task lookup failure. Checkerrbefore callingStatus(and preferably retry the transient lookup).
newTask, err = container.Task(ctx, nil)
newStatus, err = newTask.Status(ctx)
if err != nil {
|
There seems to be an alternative PR on nerdctl side, could you take a look @ningmingxiao |
|
done @AkihiroSuda |
|
I think pr #13993 can't fundamentally resolve the code bugs we should fix it on containerd side. @AkihiroSuda |
containerd 2.4.0 Created-by: HarmonybrewBot Commit-by: HarmonybrewBot Merged-by: HarmonybrewBot Description: Created by `brew bump` --- Created with `brew bump-formula-pr`.<details> <summary>release notes</summary> <pre>Welcome to the v2.4.0 release of containerd! containerd 2.4 is a regular (non-LTS) release with a shorter support window, intended for users who want to adopt new features sooner. As the release following the 2.3 LTS, it is the point in the release cycle where previously deprecated features may be removed, so this release may include breaking changes; check the notes below and clear any deprecation warnings from your current version before upgrading. Users prioritizing stability and a longer support lifecycle should stay on the 2.3 LTS release. ### Highlights #### Container Runtime Interface (CRI) * Enable mount manager for image mounts in CRI ([#13542](containerd/containerd#13542)) * Export sandbox image and CNI directory configuration in CRI plugin info ([#13940](containerd/containerd#13940)) * Set default runtimeFeatures.UserNamespacesHostNetwork to true ([#13162](containerd/containerd#13162)) * Support OCI runtime feature introspection for non-runc runtimes ([#13504](containerd/containerd#13504)) #### Image Distribution * Apply hardening to strip sensitive authentication headers when fetching descriptor URLs ([#12889](containerd/containerd#12889)) * Support propagating HTTP 299 warning headers from registries to the resolver ([#12698](containerd/containerd#12698)) * Use klauspost/compress for gzip layer decompression ([#13560](containerd/containerd#13560)) #### Image Storage * Add client options to fetch all layer content during unpack even when snapshots exist ([#14126](containerd/containerd#14126)) * Include media type in content create events ([#13833](containerd/containerd#13833)) * Add forward References to the GC collection context ([#13634](containerd/containerd#13634)) #### Node Resource Interface (NRI) * Expose container image name, digest, and config digest to NRI plugins ([#13960](containerd/containerd#13960)) * Emit deprecation warnings for plugins using deprecated NRI interfaces ([#13916](containerd/containerd#13916)) #### Runtime * Mask /proc/interrupts and CPU thermal throttle sysfs paths in Linux containers by default ([#14090](containerd/containerd#14090)) * Add UpdateSandbox RPC to propagate sandbox controller updates to the shim ([#14105](containerd/containerd#14105)) * Avoid immediately restarting containers with restart=always policy after they are explicitly stopped ([#13993](containerd/containerd#13993)) * Pass tracing context from shim to runc and hooks ([#14036](containerd/containerd#14036)) * Fix user and group lookup failures in container rootfs containing symlinked /etc/passwd or /etc/group ([#13818](containerd/containerd#13818)) * Implement Windows named-pipe server and log streaming support in pkg/shim ([#13948](containerd/containerd#13948)) * Enable log scrubbing by default on Windows ([#13837](containerd/containerd#13837)) * Allow specifying parent checkpoint directory when checkpointing with runc ([#13699](containerd/containerd#13699)) #### Snapshotters * Add Prometheus metrics for EROFS snapshotter layer content cache ([#13941](containerd/containerd#13941)) * Support warm image cache for erofs snapshotter ([#13813](containerd/containerd#13813)) * Add max size label for snapshots ([#13520](containerd/containerd#13520)) #### Breaking * Remove deprecated CRI and tracing configuration options: * Remove `enable_cdi` in CRI runtime configuration (CDI is now always enabled) * Remove `bin_dir` in CRI CNI configuration (use `bin_dirs`) * Remove `endpoint`, `protocol`, and `insecure` in OTLP tracing processor configuration (use standard OTLP environment variables) * Remove `service_name` and `sampling_ratio` in internal tracing configuration (use standard OpenTelemetry environment variables) ([#14166](containerd/containerd#14166)) * Remove restore in CreateContainer ([#13871](containerd/containerd#13871)) #### Deprecations * Deprecate containerd.io/runtime-allow-mounts shim annotation in favor of MountCapabilities bootstrap extension ([#14002](containerd/containerd#14002)) * Remove deprecated shim.Command from pkg ([#13991](containerd/containerd#13991)) * Deprecate task API address and version fields in runc options and move to CreateTaskRequest ([#13360](containerd/containerd#13360)) Please try out the release binaries and report any issues at https://github.com/containerd/containerd/issues. ### Contributors * Maksym Pavlenko * Sebastiaan van Stijn * Samuel Karp * Derek McGowan * Wei Fu * Akihiro Suda * Mike Brown * Paweł Gronowski * Chris Henzie * Phil Estes * Brian Goff * Austin Vazquez * ningmingxiao * Jordan Liggitt * Akhil Mohan * Eshaan Mathur * Krisztian Litkey * Chris Ayoub * Kazuyoshi Kato * Kir Kolyshkin * Sergey Kanzhelev * Ahmet Alp Balkan * Arpit Jain * Cindy Li * Damien Grisonnet * Esteban Ginez * Gao Xiang * Harsh Rawat * Laura Lorenz * Maksim An * Oleh Konko * Philip Laine * Abhishek Bhunia * Alan Grosskurth * Albin Kerouanton * Alex Lyn * Aman Raj * Amir Alavi * Amit Barve * Andrew Halaney * AprilNEA * Arjun Yogidas * Ayato Tokubi * Aysha Afrah Ziya * Ben Cressey * Bing Hongtao * Chris Crone * Craig Gumbley * Daniel De Graaf * Davanum Srinivas * Dr. Jan-Philip Gehrcke * Harshal Patel * Henry Wang * Hsiu-Chi Tsai * JP Phillips * Jing Chen * Kohei Tokunaga * LEI WANG * Martín Fernández * Mikhail Dmitrichenko * Nahum Litvin * Nikolaus Schuetz * Pablo Garcia Caceres * Paco Xu * Robert Cronin * SaloniRathi * Shambhavi Srivastava * Tianon Gravi * XlabAI * Yuanliang Zhang * ayush-panta * crawfordxx * cshung * match man * s3onghyun * 归寂 * 徐晓伟 ### Changes <details><summary>658 commits</summary> <p> * [`647fafa847`](containerd/containerd@647fafa) Prepare release notes for v2.4.0 * Prepare release notes for api/v1.12.0 ([#14170](containerd/containerd#14170)) * [`5c4ea21de3`](containerd/containerd@5c4ea21) Prepare release notes for api/v1.12.0 * Deprecations and removals for 2.4 ([#14166](containerd/containerd#14166)) * [`531b3a37b9`](containerd/containerd@531b3a3) tracing: remove deprecated tracing config options * [`ca8579a334`](containerd/containerd@ca8579a) tracing: add tests for otlp exporter and env vars * [`ee024b7c99`](containerd/containerd@ee024b7) tracing: remove deprecated otlp configs * [`f7c654fb4f`](containerd/containerd@f7c654f) cri: remove deprecated cni bin_dir * [`4f7de25abb`](containerd/containerd@4f7de25) cri: remove enable_cdi config option * [`830b48d3fd`](containerd/containerd@830b48d) cri: delay registry config removal to 2.7 * Prepare release notes for v2.4.0-rc.0 ([#14115](containerd/containerd#14115)) * [`c02620e398`](containerd/containerd@c02620e) Prepare release notes for v2.4.0-rc.0 * [`02c7c97f43`](containerd/containerd@02c7c97) Update release doc for 2.4.0 release * [`484e5aba58`](containerd/containerd@484e5ab) vendor: github.com/containerd/containerd/api v1.12.0-rc.1 * [`67174d675c`](containerd/containerd@67174d6) mailmap: add Paweł Gronowski * Update erofs snapshotter to record blob source ([#14107](containerd/containerd#14107)) * [`697a7571a4`](containerd/containerd@697a757) erofs: give a dm-verity device a name unique to its mount * [`f75817eb3b`](containerd/containerd@f75817e) erofs: record where a layer blob is * [`d92088d822`](containerd/containerd@d92088d) erofs: refuse to apply into a read-only snapshot * [`8cc0b076a6`](containerd/containerd@8cc0b07) erofs: serve layer content cache on parented Prepare * build(deps): bump the golang-x group with 4 updates ([#14150](containerd/containerd#14150)) * [`75138b3fda`](containerd/containerd@75138b3) build(deps): bump the golang-x group with 4 updates * build(deps): bump github.com/klauspost/compress from 1.19.2 to 1.20.0 ([#14153](containerd/containerd#14153)) * [`353342cae6`](containerd/containerd@353342c) build(deps): bump github.com/klauspost/compress from 1.19.2 to 1.20.0 * pkg/oci: mask thermal interrupt info ([#14090](containerd/containerd#14090)) * [`c176f185b0`](containerd/containerd@c176f185b08e14bde055d81dc509 See merge request: Harmonybrew/homebrew-core!20372
Continue the work from PR #6966.
fix containerd/nerdctl#5153
Currently, when running a container with
nerdctl run -d --restart=always busybox sh -c "top",and then performing
nerdctl stopon it, containerd still restarts the container after a few seconds.This is inconsistent with Docker behavior and not the desired outcome.
For containers with
--restart=alwayspolicy:After manually stopping the container via
nerdctl stop <id>, containerd should not restart it,until the containerd daemon itself gets restarted. This change aligns the behavior with Docker.
ping @AkihiroSuda @mxpv @dmcgowan