Skip to content

runtime: invoke shim.Delete when connection is closed - #13309

Merged
mxpv merged 1 commit into
containerd:mainfrom
ningmingxiao:fix_leak
Sep 3, 2026
Merged

mxpv merged 1 commit into
containerd:mainfrom
ningmingxiao:fix_leak

Conversation

@ningmingxiao

@ningmingxiao ningmingxiao commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

fix #13293
(ci failed for other reason I find if run github actions many times CI failure is becoming more likely )

ping @fuweid @mikebrow can you take a look thanks

Invoke shim delete to clean up shim process when connection is closed

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@ningmingxiao ningmingxiao changed the title fix: fix leak dir when shim is killed cri: fix leak dir when shim is killed Apr 28, 2026
Copilot AI review requested due to automatic review settings April 28, 2026 12:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread core/runtime/v2/shim_manager.go Resolved
@github-project-automation github-project-automation Bot moved this from Needs Triage to Needs Update in Pull Request Review Apr 28, 2026
Copilot AI review requested due to automatic review settings April 29, 2026 11:15
@ningmingxiao

Copy link
Copy Markdown
Contributor Author

done, thanks @fuweid

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Suppressed comments (1)

integration/container_leak_linux_test.go:81

  • currentProc.grpcAddress() is called and its return value is discarded. Since the address is used multiple times immediately after, store it once in a local variable and reuse it to avoid the no-op call and improve readability.
	currentProc.grpcAddress()
	ctx := namespaces.WithNamespace(context.Background(), "k8s.io")
	shimCli := connectToShim(ctx, t, currentProc.grpcAddress(), 3, podCtx.id)
	shimPid := int(shimPid(ctx, t, shimCli))
	client, err := client.New(currentProc.grpcAddress())

Copilot AI review requested due to automatic review settings August 28, 2026 01:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

Suppressed comments (3)

integration/container_leak_linux_test.go:83

  • This block has an unused call to currentProc.grpcAddress(), shadows the imported client package with a local variable named client, and never closes the containerd client or cancels the Subscribe context (which can leak goroutines/FDs across integration tests). Use a cancelable context, avoid shadowing, and close the client via t.Cleanup.
	currentProc.grpcAddress()
	ctx := namespaces.WithNamespace(context.Background(), "k8s.io")
	shimCli := connectToShim(ctx, t, currentProc.grpcAddress(), 3, podCtx.id)
	shimPid := int(shimPid(ctx, t, shimCli))
	client, err := client.New(currentProc.grpcAddress())
	require.NoError(t, err)

integration/container_leak_linux_test.go:45

  • The test is intended to cover orphaned runc state dirs, but it currently relies on the host default runc Root and only asserts TaskExit/TaskDelete + CRI EXITED. To make the regression check explicit and hermetic, set a per-test runc Root under workDir via runtime options; this also enables checking that the runc state dir for the container ID is removed.
	workDir := t.TempDir()
	configPath := filepath.Join(workDir, "config.toml")
	ctrdConfig := `
version = 4

[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runc]
  runtime_type = "io.containerd.runc.v2"
`

integration/container_leak_linux_test.go:155

  • The final Eventually() only checks CRI state==EXITED, which doesn't verify the specific regression (#13293) about leaked runc state directories. Once runc Root is set to a per-test directory, also assert the runc state dir (/k8s.io/) is removed after shim SIGKILL is processed.
	// Wait for the container to exit and ensure it is fully cleaned up.
	require.NoError(t, Eventually(func() (bool, error) {
		s, err := currentProc.criRuntimeService(t).ContainerStatus(cntr)
		if err != nil {
			return false, err
		}
		if s.State == runtime.ContainerState_CONTAINER_EXITED {
			return true, nil
		}
		return false, nil
	}, 1000*time.Millisecond, 30*time.Second))

Comment thread core/runtime/v2/shim_manager.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (4)

integration/container_leak_linux_test.go:81

  • This test currently (1) has a no-op call to currentProc.grpcAddress(), (2) doesn’t cancel the subscription context, and (3) doesn’t close the containerd client. Also, to ensure the test is actually exercising the leak, it should verify the runc state dir exists before killing the shim (otherwise a missing dir would make a later “cleanup” assertion vacuously true).
	currentProc.grpcAddress()
	ctx := namespaces.WithNamespace(context.Background(), "k8s.io")
	shimCli := connectToShim(ctx, t, currentProc.grpcAddress(), 3, podCtx.id)
	shimPid := int(shimPid(ctx, t, shimCli))
	client, err := client.New(currentProc.grpcAddress())

integration/container_leak_linux_test.go:149

  • Waiting for TaskExit/TaskDelete events (and then CRI state EXITED) does not verify the regression from #13293. cleanupAfterDeadShim publishes TaskExit/TaskDelete even when the underlying shim-binary delete fails (core/runtime/v2/shim.go:151-195), so the test can pass while the runc state dir still leaks. Add an assertion that the runc state directory (runcRoot/k8s.io/) is removed.
	// Wait for the container to exit and ensure it is fully cleaned up.
	require.NoError(t, Eventually(func() (bool, error) {
		s, err := currentProc.criRuntimeService(t).ContainerStatus(cntr)
		if err != nil {
			return false, err

integration/container_leak_linux_test.go:43

  • The test starts containerd with the default runc root, which will place runc state under the host-wide /run/containerd/runc by default (see cmd/containerd-shim-runc-v2/process/utils.go:RuncRoot). For an integration test this is not isolated and makes it hard to reliably assert cleanup. Configure a per-test runc Root under t.TempDir() via the runtime options so the test is self-contained.
	configPath := filepath.Join(workDir, "config.toml")
	ctrdConfig := `
version = 4

[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.runc]

core/runtime/v2/shim_manager.go:304

  • Grammar in this comment is off ("would always failed") and the phrasing is a bit hard to follow when scanning the disconnect cleanup path.
			// Remove self from the runtime task list. Even though the cleanupAfterDeadShim()
			// would publish taskExit event, but the shim.Delete() would always failed with ttrpc
			// disconnect and there is no chance to remove this dead task from runtime task lists.
			// Thus it's better to delete it here.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Comment thread core/runtime/v2/shim_manager.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

Suppressed comments (3)

integration/issue7496_shutdown_linux_test.go:242

  • The TaskDelete branch logs "received task exit event" (copy/paste) and logs even when ContainerID does not match the target ID, which can be misleading when analyzing failures.
					t.Logf("received task delete event: %+v", e)
					deletes++
				}
			}

integration/issue7496_shutdown_linux_test.go:236

  • The TaskExit branch logs the same event twice (once unconditionally and once again when ContainerID matches), which adds noise to test output and makes it harder to spot relevant events.

This issue also appears on line 239 of the same file.

			case *eventtypes.TaskExit:
				if e.ContainerID == id {
					t.Logf("received task exit event: %+v", e)
					exits++
				}

core/runtime/v2/shim_manager.go:304

  • This comment has grammatical issues ("would always failed") and is a bit hard to parse; tightening it up will make the intent clearer for future maintainers.
			// Remove self from the runtime task list. Even though the cleanupAfterDeadShim()
			// would publish taskExit event, but the shim.Delete() would always failed with ttrpc
			// disconnect and there is no chance to remove this dead task from runtime task lists.
			// Thus it's better to delete it here.

Comment on lines +120 to +122
// test for issue https://github.com/containerd/containerd/issues/13293
// If container exit and deletion events are received, it means the residual container directories have already been cleaned up.
func TestKillShimPublishesTaskExitAndDeleteEventsForContainer(t *testing.T) {
)

require.NoError(t, syscall.Kill(int(shimPID), syscall.SIGKILL))
waitForTaskExitDeleteEvents(t, sbID, eventCh, eventErrCh, 10*time.Second)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

Suppressed comments (3)

integration/issue7496_shutdown_linux_test.go:158

  • In this container-focused test, the event subscription is filtered by the container ID (cnID), but the helper is called with sbID. That doesn’t affect the logic, but it makes timeout/error output misleading and complicates debugging when the test fails.
	require.NoError(t, syscall.Kill(int(shimPID), syscall.SIGKILL))
	waitForTaskExitDeleteEvents(t, sbID, eventCh, eventErrCh, 10*time.Second)

integration/issue7496_shutdown_linux_test.go:122

  • This is labeled as a regression test for #13293 (orphaned shim/runc state directories), but the assertions only cover TaskExit/TaskDelete events and CRI ContainerStatus==EXITED. That won’t fail if runc state directories under the runtime root still leak, so it doesn’t directly guard the reported regression.
// Regression test for https://github.com/containerd/containerd/issues/13293 (orphaned shim state after shim SIGKILL).
// This test asserts that containerd publishes task exit and delete events for a container when the shim disconnects.
func TestKillShimPublishesTaskExitAndDeleteEventsForContainer(t *testing.T) {

core/runtime/v2/shim_manager.go:304

  • These comments mention "shim.Delete()" failing, but this block is about removing the task from the in-memory runtime task map (m.shims). Rewording would make it clearer what is failing (RPCs over the dead ttrpc connection) and why the explicit map deletion is needed.
			// Remove self from the runtime task list. Even though the cleanupAfterDeadShim()
			// would publish taskExit event, but the shim.Delete() would always failed with ttrpc
			// disconnect and there is no chance to remove this dead task from runtime task lists.
			// Thus it's better to delete it here.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/v2/shim_manager.go:301

  • The on-close callback uses the original request context (ctx) for cleanup. If that context had a deadline (typical for gRPC requests), it will likely be expired by the time the shim disconnects, which causes cleanupAfterDeadShim (and m.shims.Delete) to no-op immediately because timeout.WithContext derives from the expired parent context. Use a fresh background context (while preserving the namespace and logger) for disconnect cleanup so the shim binary delete and event publication can still run long after the original request completes.
		shim, err := loadShim(ctx, bundle, func() {
			log.G(ctx).WithField("id", id).Info("shim disconnected")

			cleanupAfterDeadShim(context.WithoutCancel(ctx), id, m.shims, m.events, b)
			// Remove self from the runtime task list. Even though the cleanupAfterDeadShim()

integration/issue7496_shutdown_linux_test.go:163

  • This new regression test targets #13293 (orphaned runc/shim state directories), but it only asserts task exit/delete events and that CRI reports the container as EXITED. cleanupAfterDeadShim publishes those events even when the shim binary Delete call fails (it logs a warning and still emits events), so the test can pass without actually verifying the leaked state directory is removed. Consider making the test assert the relevant on-disk state directory is cleaned up (ideally using a per-test isolated runc Root) so it directly covers the regression.
	// Wait for the container to exit and ensure it is fully cleaned up.
	require.NoError(t, Eventually(func() (bool, error) {
		s, err := runtimeService.ContainerStatus(cnID)
		if err != nil {
			return false, err

@mxpv

mxpv commented Aug 28, 2026

Copy link
Copy Markdown
Member

@cpuguy83 LGTY?

@mxpv

mxpv commented Nov 23, 2026

Copy link
Copy Markdown
Member

/cherry-pick 2.3
/cherry-pick 2.0

@k8s-infra-cherrypick-robot

Copy link
Copy Markdown

@mxpv: cannot checkout 2.0: error checking out "2.0": exit status 128 fatal: invalid reference: 2.0

Details

In response to this:

/cherry-pick 2.3
/cherry-pick 2.0

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@k8s-infra-cherrypick-robot

Copy link
Copy Markdown

@mxpv: cannot checkout 2.3: error checking out "2.3": exit status 128 fatal: invalid reference: 2.3

Details

In response to this:

/cherry-pick 2.3
/cherry-pick 2.0

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@mxpv

mxpv commented Nov 23, 2026

Copy link
Copy Markdown
Member

/cherry-pick release/2.3
/cherry-pick release/2.0

@k8s-infra-cherrypick-robot

Copy link
Copy Markdown

@mxpv: #13309 failed to apply on top of branch "release/2.0":

Applying: runtime: invoke shim.Delete when connection is closed
Using index info to reconstruct a base tree...
M	core/runtime/v2/shim_manager.go
M	integration/issue7496_shutdown_linux_test.go
Falling back to patching base and 3-way merge...
Auto-merging core/runtime/v2/shim_manager.go
Auto-merging integration/issue7496_shutdown_linux_test.go
CONFLICT (content): Merge conflict in integration/issue7496_shutdown_linux_test.go
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0001 runtime: invoke shim.Delete when connection is closed

Details

In response to this:

/cherry-pick release/2.3
/cherry-pick release/2.0

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@k8s-infra-cherrypick-robot

Copy link
Copy Markdown

@mxpv: #13309 failed to apply on top of branch "release/2.3":

Applying: runtime: invoke shim.Delete when connection is closed
Using index info to reconstruct a base tree...
M	core/runtime/v2/shim_manager.go
M	integration/issue7496_shutdown_linux_test.go
Falling back to patching base and 3-way merge...
Auto-merging core/runtime/v2/shim_manager.go
Auto-merging integration/issue7496_shutdown_linux_test.go
CONFLICT (content): Merge conflict in integration/issue7496_shutdown_linux_test.go
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0001 runtime: invoke shim.Delete when connection is closed

Details

In response to this:

/cherry-pick release/2.3
/cherry-pick release/2.0

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

Orphaned shim state files in /run/containerd/runc are not cleaned up after shim is SIGKILLed

9 participants