Skip to content

fix(links): use sync.Once for singleton init and guard nil namespace#3147

Open
Aprazor wants to merge 1 commit intosrl-labs:mainfrom
Aprazor:fix/link-singleton-nil-deref-and-race
Open

fix(links): use sync.Once for singleton init and guard nil namespace#3147
Aprazor wants to merge 1 commit intosrl-labs:mainfrom
Aprazor:fix/link-singleton-nil-deref-and-race

Conversation

@Aprazor
Copy link
Copy Markdown
Contributor

@Aprazor Aprazor commented Mar 30, 2026

Summary

Two issues in the host and mgmt-net link node singletons:

1. Race condition on singleton initialization

GetHostLinkNode() and getMgmtBrLinkNode() use a check-then-write pattern (if instance == nil { instance = ... }) on package-level variables without synchronization. Since containerlab deploys nodes in parallel (link resolution happens concurrently), two goroutines could both read nil and race on the write.

Fix: Replace manual nil check with sync.Once for thread-safe initialization.

2. Nil dereference when GetCurrentNS fails

When ns.GetCurrentNS() returns an error, currns is nil. The code logs the error but unconditionally calls currns.Path() on the next line, causing a nil pointer dereference panic.

Fix: Return early on error so the singleton remains nil rather than crashing.

Testing

  • go vet ./links/... — clean
  • go test -race ./links/... — all pass

GetHostLinkNode and getMgmtBrLinkNode use a check-then-write pattern
on package-level variables without synchronization. Since containerlab
deploys nodes in parallel, concurrent goroutines could both read nil
and race on the write.

Replace the manual nil check with sync.Once for thread-safe init.

Also fix a nil dereference: when ns.GetCurrentNS() fails, currns is
nil but the code calls currns.Path() unconditionally, panicking.
Now return early on error so the singleton remains nil rather than
crashing.
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.

1 participant