Skip to content

fix(destroy): remove netns symlinks when the topology file is missing - #3524

Open
torbbang wants to merge 3 commits into
srl-labs:mainfrom
torbbang:fix/destroy-netns-symlinks
Open

torbbang wants to merge 3 commits into
srl-labs:mainfrom
torbbang:fix/destroy-netns-symlinks

Conversation

@torbbang

Copy link
Copy Markdown
Contributor

Destroying a lab whose topology file is gone (#3038) leaves its /run/netns symlinks behind. This PR enables them to be removed them along with the containers.

@hellt

hellt commented Oct 26, 2026

Copy link
Copy Markdown
Member

/tofarev review

@tofarev

tofarev Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

ToFaRev review — completed

Reviewed 3b57a5982af4 · Session log · Workflow run

Finding Location
P3 - Netns symlink cleanup added to deleteContainersDirect but not to sibling deleteToolContainers core/destroy.go:730-730

Detailed findings:

P3 - Netns symlink cleanup added to deleteContainersDirect but not to sibling deleteToolContainers

Location: core/destroy.go:730-730

Problem: The PR fixes netns symlink cleanup in deleteContainersDirect (destroy-by-name path), but the sibling destroy path deleteToolContainers (called from destroy() at line 449) deletes sshx, gotty, and Tailscale-proxy containers without removing their /run/netns/<name> symlinks. Tool containers get symlinks because they are started via rt.StartContainer, which calls postStartActions -> clabutils.LinkContainerNS in both the Docker (runtime/docker/docker.go:1401-1422) and Podman (runtime/podman/util.go:734-754) runtimes.

Trigger: Deploy a lab with a topology file, attach a tool container (clab tools sshx attach, tools gotty, or the Tailscale SSO proxy), then run clab destroy -t <topo>. With nodes present, tool containers are only removed by deleteToolContainers, so their symlinks survive the destroy.

Impact: Stale symlinks are left in /run/netns after a normal topo-based destroy, while the destroy-by-name path (where tool containers are included in ListContainers(WithListLabName(...)) and now cleaned by deleteContainersDirect) removes them. The two destroy paths behave inconsistently for the exact defect this PR targets. The leak is pre-existing in deleteToolContainers, but the PR fixes one caller of the shared cleanup and leaves the sibling broken.

Suggested correction: Add the same best-effort one-liner in deleteToolContainers, e.g. _ = clabutils.DeleteNetnsSymlink(containerName) next to the DeleteContainer call at line 777. It is safe when no symlink exists because DeleteNetnsSymlink logs at debug level and always returns nil.

review conditions

Source inspection only; PR code, tests, and benchmarks were not executed.

  • Reviewed both changed paths from the diff against head and base: core/destroy.go and tests/15-mgmt/13-destroy-without-topo.robot.
  • Traced the destroy flow end to end: destroy() branches (node-based vs. deleteContainersDirect), the node.DeleteNetnsSymlink() loop at lines 465-471, deleteApplyNodes (line 616), deleteToolContainers, and cmd/destroy.go (confirming c.Nodes is empty for --name-only destroys, so the test exercises the fixed path).
  • Verified symlink naming: utils.LinkContainerNS writes /run/netns/<LongName>; Docker's produceGenericContainerList strips the leading / from Names[0], so removal targets match; DeleteNetnsSymlink fails silently for nonexistent paths, so the added call is safe for containers that never had a symlink.
  • Schema check: no topology API change, so schemas/clab.schema.json needs no edit; no user-facing docs required for the bug fix and docs/rn/ is untouched.
  • The Robot suite correctly gates on Docker and uses test -L, which handles dangling symlinks correctly for both existence and absence assertions.
  • Source-only review: no tests, builds, or CI checks were executed. The Robot test covers regular nodes end to end; no test layer covers tool-container symlink cleanup, which is the reported gap.
  • Long lines in head:docs/images/clabnew.svg exceed the read tool's per-line display limit.
  • Skipped head:docs/images/containerlab_black.png (LFS pointer).
  • 98 additional coverage limitations were recorded.

Powered by Nebius Token Factory

@FloSch62

FloSch62 commented Nov 6, 2026

Copy link
Copy Markdown
Member

Review — completed

Reviewed 3b57a5982af4

The fix is correct for the case it targets. Finding 1 is the only change I'd make before merge. Findings 2-6 were already there before this PR and can be handled as follow-ups.

# Finding Scope Location
1 P3 - Netns symlink is removed even when the container delete failed This PR core/destroy.go:725-730
2 P2 - Parking namespaces leak on destroy Follow-up nodes/default_node.go:1169
3 P2 - Failed container deletes are reported as success Follow-up core/destroy.go:725-728
4 P3 - Distributed SR-SIM logical symlink is left behind Follow-up nodes/sros/netns.go:151
5 P3 - Tool containers keep their symlinks (already reported by ToFaRev) Follow-up core/destroy.go:777
6 P3 - Symlinks survive when no containers remain Follow-up core/destroy.go:419

Detailed findings:

1. P3 - Netns symlink is removed even when the container delete failed

Location: core/destroy.go:725-730

Problem: When DeleteContainer returns an error, it is only logged and the new line still runs. deleteApplyNodes already returns before this step on failure (core/destroy.go:612-616).

Trigger: clab destroy --name <lab> hits a daemon timeout or a removal error for a container.

Impact: The container may still be running, but its /run/netns/<name> alias is gone, so ip netns exec <name> stops working.

Suggested correction:

if err := rt.DeleteContainer(ctx, name); err != nil {
	log.Errorf("could not remove container %q: %v", name, err)
	continue
}

_ = clabutils.DeleteNetnsSymlink(name)
2. P2 - Parking namespaces leak on destroy

Location: nodes/default_node.go:1169

Problem: clab stop moves dataplane interfaces into /run/netns/clab-park-<container> and repoints the node symlink at it. This PR removes the symlink but not that namespace. DefaultNode only removes it on a failed park or a restore. On destroy, only SR-SIM cleans it up (nodes/sros/netns.go:154).

Trigger: Run clab stop, delete the topology file, then run clab destroy --name <lab>. From reading the code, clab destroy -t on other node kinds looks affected too.

Impact: The namespace and its interfaces outlive the lab. The name is deterministic, so a later lab with the same name reuses it through CreateOrGetNamedNetNS.

Suggested correction: Remove the parking namespace on both destroy paths. The Robot test could then add a clab stop step and assert that no mgmt13 entries remain in /run/netns.

3. P2 - Failed container deletes are reported as success

Location: core/destroy.go:725-728

Problem: deleteContainersDirect returns nothing, so its caller never learns that a delete failed and failedLabDirs is not set.

Trigger: clab destroy --name <lab> --cleanup fails to remove a container.

Impact: The command can exit 0 and delete the lab directory of a container that is still running. That breaks the rule documented at core/destroy.go:80.

Suggested correction: Return the delete errors from deleteContainersDirect and propagate them, so the lab directory is kept.

4. P3 - Distributed SR-SIM logical symlink is left behind

Location: nodes/sros/netns.go:151

Problem: After a stop or start, a distributed node has a logical /run/netns/<LongName> link with no matching container (nodes/default_node.go:1188, nodes/sros/sros.go:1909). The topology path removes it explicitly, but the by-name path only sees container names.

Trigger: Stop or start a distributed nokia_srsim node, delete the topology file, then run clab destroy --name <lab>.

Impact: The component symlinks are removed, but /run/netns/<LongName> stays behind.

Suggested correction: Also delete the symlink named by the RootNodeLongName label, which the component containers already carry.

5. P3 - Tool containers keep their symlinks

Location: core/destroy.go:777

Problem: deleteToolContainers removes tool containers without removing their symlinks. core/tailscale.go:210 and the sshx and gotty detach paths (cmd/tools_sshx.go:455, cmd/tools_gotty.go:465) have the same gap.

Trigger: Attach a tool to a lab, then run clab destroy -t <topo> or detach the tool.

Impact: Stale symlinks remain in /run/netns.

Suggested correction: The runtimes create the symlink in their post-start actions, so removing it in DeleteContainer after a successful removal would cover these callers and avoid adding the call at each one. That would also handle finding 1.

6. P3 - Symlinks survive when no containers remain

Location: core/destroy.go:419

Problem: Symlink cleanup depends on a container still being listed, and destroy returns early when none are found.

Trigger: The containers were removed with docker rm -f, or an earlier destroy crashed after removing them, and the topology file is gone.

Impact: The dangling /run/netns links stay until someone removes them by hand.

Suggested correction: Low priority. It would need cleanup that finds entries by lab name rather than by container.

review conditions

Source inspection only; the PR code and tests were not executed.

  • Reviewed both changed files: core/destroy.go and tests/15-mgmt/13-destroy-without-topo.robot.
  • Verified that symlink names match: LinkContainerNS uses the node's long name, and the Docker runtime strips the leading / from Names[0].
  • The Robot test covers the by-name path with two running nodes. It does not cover stopped nodes, distributed SR-SIM nodes or tool containers.
  • The branch is 33 commits behind main. Findings 1-5 were also checked against current main, where line numbers differ but the behavior is the same. Finding 6 still holds there too: the early return remains and does no symlink cleanup.
  • codecov/project is failing, but this looks unrelated: Codecov reports every changed line as covered and compares against an older base, 97f7e1d.
  • Minor: the PR description has an extra "them" in "enables them to be removed them".

@torbbang
torbbang force-pushed the fix/destroy-netns-symlinks branch from 9c5a158 to 0b29d0f Compare November 6, 2026 16:14
@codecov

codecov Bot commented Nov 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 33.33333% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.19%. Comparing base (97f7e1d) to head (0b29d0f).
⚠️ Report is 42 commits behind head on main.

Files with missing lines Patch % Lines
core/destroy.go 33.33% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3524      +/-   ##
==========================================
+ Coverage   61.81%   62.19%   +0.38%     
==========================================
  Files         299      315      +16     
  Lines       36726    40295    +3569     
==========================================
+ Hits        22701    25063    +2362     
- Misses      11727    12792    +1065     
- Partials     2298     2440     +142     
Files with missing lines Coverage Δ
core/destroy.go 72.00% <33.33%> (+0.44%) ⬆️

... and 98 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@hellt

hellt commented Nov 6, 2026

Copy link
Copy Markdown
Member

/tofarev review

@tofarev

tofarev Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

ToFaRev review — completed

Reviewed 0b29d0fb597b · Session log · Workflow run

Finding Location
P4 - deleteContainersDirect skips symlink cleanup on NotFound, leaving the exact leak this PR fixes in a race window core/destroy.go:725-731

Detailed findings:

P4 - deleteContainersDirect skips symlink cleanup on NotFound, leaving the exact leak this PR fixes in a race window

Location: core/destroy.go:725-731

Problem: The new code only calls clabutils.DeleteNetnsSymlink(name) when rt.DeleteContainer succeeds. Both DockerRuntime.DeleteContainer (runtime/docker/docker.go:1748-1754) and PodmanRuntime.DeleteContainer (runtime/podman/podman.go:605-610) propagate a not-found error when the container is already gone, so in that case the added continue skips symlink removal and the stale /run/netns/<name> symlink — precisely what this PR sets out to clean — survives. This also diverges from the node-based path, where the symlink loop at core/destroy.go:466-471 removes symlinks regardless of node.Delete errors.

Trigger: A container vanishes between ListContainers and DeleteContainer, for example a concurrent destroy (including destroy --all racing itself) or an operator removing the container manually. DockerRuntime.produceGenericContainerList already documents this list-to-delete race at runtime/docker/docker.go:1562-1564.

Impact: Minor: one stale symlink per raced container. It self-heals when a same-named container is redeployed because LinkContainerNS removes an existing destination before symlinking (utils/netlink.go:60-63), and destroy already logs the removal error. No silent success is claimed beyond the pre-existing behavior.

Suggested correction: Either attempt symlink removal after every delete attempt in deleteContainersDirect to mirror the node-based path, or keep the guard but let a not-found error fall through to symlink removal. Given the narrow race and the self-healing outcome, this is an optional improvement rather than a blocker.

review conditions

Source inspection only; PR code, tests, and benchmarks were not executed.

  • Both changed paths were fully traced: the destroy-by-name-only flow reaching deleteContainersDirect with empty c.Nodes via WithLabNameOnly/makeCopyForDestroy, and the orphanSidecars call site when nodes exist.
  • Symlink naming verified end to end: created with the node LongName in docker and podman postStartActions, deleted with the trimmed GenericContainer.Names[0] from this PR; sibling patterns in deleteApplyNodes (core/destroy.go:616) and the node loop (core/destroy.go:466-471) were compared.
  • The Robot test additions were checked against the keywords in tests/15-mgmt/mgmt.resource and the fixture 13-destroy-without-topo.clab.yml (linux nodes n1/n2 matching the asserted long names).
  • Pre-existing gaps not worsened by this PR were noted but not raised as findings: multi-netns node kinds (e.g. SR OS component/netns/parking entries in nodes/sros/netns.go:139-156) still leave extra /run/netns entries in the name-only path, and deleteToolContainers never removed symlinks.
  • Source-only review of the snapshot; no tests or builds were executed. The mgmt Robot suite is the executable check for this change and is wired into CI.
  • No schema impact: no topology or configuration API surface changed, and no user-facing docs describe /run/netns cleanup behavior.
  • Long lines in head:docs/images/clabnew.svg exceed the read tool's per-line display limit.
  • Skipped head:docs/images/containerlab_black.png (LFS pointer).
  • 98 additional coverage limitations were recorded.

Powered by Nebius Token Factory

@torbbang

torbbang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

This is in "ugly hack" territory. I will get back with a better fix over the weekend.

@FloSch62

FloSch62 commented Nov 6, 2026

Copy link
Copy Markdown
Member

@torbbang I think you can ignore the p4

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants