Skip to content

[management] Optimize affected posture checks and add logs#6522

Merged
pascal-fischer merged 13 commits into
mainfrom
add-trace-update-logs
Jun 25, 2026
Merged

[management] Optimize affected posture checks and add logs#6522
pascal-fischer merged 13 commits into
mainfrom
add-trace-update-logs

Conversation

@mlsmaycon

@mlsmaycon mlsmaycon commented Jun 23, 2026

Copy link
Copy Markdown
Collaborator

Describe your changes

Issue ticket number and link

Stack

Checklist

  • Is it a bug fix
  • Is a typo/documentation fix
  • Is a feature enhancement
  • It is a refactor
  • Created tests that fail without the change (if possible)
  • This change does not modify the public API, gRPC protocols, functionality behavior, CLI / service flags, or introduce a new feature — OR I have discussed it with the NetBird team beforehand (link the issue / Slack thread in the description). See CONTRIBUTING.md.

By submitting this pull request, you confirm that you have read and agree to the terms of the Contributor License Agreement.

Documentation

Select exactly one:

  • I added/updated documentation for this change
  • Documentation is not needed for this change (explain why)

Docs PR URL (required if "docs added" is checked)

Paste the PR link from https://github.com/netbirdio/docs here:

https://github.com/netbirdio/docs/pull/__

Summary by CodeRabbit

  • Bug Fixes
    • Improved peer geo updates by resolving location first, ensuring location changes are detected even when only the geo details differ.
    • Network map refreshes now trigger more consistently based on meaningful peer changes (status, connectivity capabilities, metadata/posture, version, and hostname).
    • Peer updates are now skipped only when both the connection address and stored location details are unchanged, reducing missed updates.
  • Tests
    • Added unit coverage for peer location resolution, including failure and no-change scenarios.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6cccf2fe-dbe7-4d65-92de-c1c96c4f0beb

📥 Commits

Reviewing files that changed from the base of the PR and between 0ad4c9d and 573df7d.

📒 Files selected for processing (1)
  • management/internals/controllers/network_map/controller/controller.go
✅ Files skipped from review due to trivial changes (1)
  • management/internals/controllers/network_map/controller/controller.go

📝 Walkthrough

Walkthrough

The PR updates peer location persistence, centralizes SyncPeer update gating, and adjusts network-map trace logging. It also adds tests for geolocation resolution behavior.

Changes

Peer geo, update gating, and controller tracing

Layer / File(s) Summary
resolvePeerLocation: geo lookup and skip check
management/server/peer.go, management/server/peer_test.go
resolvePeerLocation now uses geolocation before deciding whether to persist peer.Location, and the new test covers missing inputs, lookup failure, unchanged location data, and changed geo or connection IP cases.
SyncPeer: requiresPeerUpdate helper
management/server/peer.go
SyncPeer replaces the inline update condition with requiresPeerUpdate, which checks the change flags and logs the selected reason when an update is required.
network-map controller trace logs
management/internals/controllers/network_map/controller/controller.go
BufferUpdateAffectedPeers now includes the update reason operation and resource in its trace message.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • netbirdio/netbird#6103: Updates BufferUpdateAffectedPeers tracing to include UpdateReason, which overlaps with the controller log change here.
  • netbirdio/netbird#6510: Also touches resolvePeerLocation and SyncPeer update-gating behavior around geo resolution and peer refresh decisions.

Suggested reviewers

  • dmitri-netbird

Poem

A bunny hopped through trace and log,
Through geo maps and update fog.
With tidy checks and reasons clear,
It twitched its nose: “the path is near!” 🐇

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is mostly template placeholders and omits the actual changes, issue link, stack, and docs-not-needed rationale. Add a real change summary, the issue ticket/link, the stack/branch details, and explain why documentation is not needed.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: optimizing affected posture checks and adding logs.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add-trace-update-logs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jun 23, 2026

Copy link
Copy Markdown

Release artifacts

Built for PR head 573df7d in workflow run #16196.

Artifact Link
All release artifacts Download
Linux packages Download
Windows packages Download
macOS packages Download
UI artifacts Download
UI macOS artifacts Download

GHCR images (amd64)

No GHCR images were pushed.

This comment is updated by the Release workflow. Artifact links expire according to the workflow retention policy.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

🧹 Nitpick comments (1)
management/internals/controllers/network_map/controller/controller.go (1)

181-183: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Guard debug.Stack() behind trace-level checks.

debug.Stack() allocates/captures even when trace logging is off. Add a trace-level guard so stack collection only happens when it can actually be emitted.

💡 Proposed fix
-	if reason.Operation == types.UpdateOperationUpdate && reason.Resource == types.UpdateResourceUser {
+	if reason.Operation == types.UpdateOperationUpdate &&
+		reason.Resource == types.UpdateResourceUser &&
+		log.IsLevelEnabled(log.TraceLevel) {
 		log.WithContext(ctx).Tracef("got an user update, stack: %s", debug.Stack())
 	}
@@
-	if reason.Operation == types.UpdateOperationUpdate && reason.Resource == types.UpdateResourceUser {
+	if reason.Operation == types.UpdateOperationUpdate &&
+		reason.Resource == types.UpdateResourceUser &&
+		log.IsLevelEnabled(log.TraceLevel) {
 		log.WithContext(ctx).Tracef("got an user update, stack: %s", debug.Stack())
 	}

Also applies to: 506-510

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@management/internals/controllers/network_map/controller/controller.go` around
lines 181 - 183, The debug.Stack() function is being called unconditionally in
the trace log statement, which allocates memory and captures the stack even when
trace logging is disabled. Add a trace-level check before calling debug.Stack()
to ensure the expensive stack collection only occurs when trace logging is
actually enabled. Guard the log statement containing debug.Stack() with a
conditional check that verifies trace level logging is enabled (such as
log.IsLevelEnabled() or similar), and apply this same pattern to all similar
instances mentioned in the comment (around lines 506-510).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@management/server/peer.go`:
- Around line 1058-1060: Remove the redundant initial assignment of the reason
variable in the requiresPeerUpdate function. The reason variable is declared and
assigned an empty string on line 1059, but this value is never used because all
switch cases that reference reason overwrite it before use, and the default case
returns early. Delete the line `reason := ""` entirely since the variable will
be properly initialized in each switch case that needs it.

In `@management/server/posture/affects_test.go`:
- Around line 38-122: Add a new test case to the tests slice that verifies the
function properly evaluates multiple checks in a single slice without
short-circuiting. Create a test case where the checks slice contains a public
range check followed by another check type (such as a process check or geo
check) with a diff that should NOT affect the public range check but SHOULD
affect the second check. Set the expected result to true to ensure the function
continues evaluating all checks in the slice rather than returning early based
on the first check's result.

In `@management/server/posture/checks.go`:
- Around line 81-93: The issue is that the function returns false after checking
the PeerNetworkRangeCheck ranges when all ranges are public (line 92), which
prevents subsequent posture checks from being evaluated. Instead of returning
false immediately when no private ranges are found in the loop within the
PeerNetworkRangeCheck block, the code should continue to the next posture check.
Remove the return false statement after the range loop so that the function
continues to evaluate other posture check conditions, only returning false after
all applicable checks have been examined.

---

Nitpick comments:
In `@management/internals/controllers/network_map/controller/controller.go`:
- Around line 181-183: The debug.Stack() function is being called
unconditionally in the trace log statement, which allocates memory and captures
the stack even when trace logging is disabled. Add a trace-level check before
calling debug.Stack() to ensure the expensive stack collection only occurs when
trace logging is actually enabled. Guard the log statement containing
debug.Stack() with a conditional check that verifies trace level logging is
enabled (such as log.IsLevelEnabled() or similar), and apply this same pattern
to all similar instances mentioned in the comment (around lines 506-510).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f40da02d-40f3-4f61-9cbe-1aaefcffed30

📥 Commits

Reviewing files that changed from the base of the PR and between 51b6f62 and ecd133c.

📒 Files selected for processing (5)
  • management/internals/controllers/network_map/controller/controller.go
  • management/server/peer.go
  • management/server/peer_test.go
  • management/server/posture/affects_test.go
  • management/server/posture/checks.go

Comment thread management/server/peer.go
Comment thread management/server/posture/affects_test.go Outdated
Comment thread management/server/posture/checks.go Outdated
@pascal-fischer
pascal-fischer marked this pull request as ready for review June 25, 2026 15:10
pascal-fischer
pascal-fischer previously approved these changes Jun 25, 2026
@pascal-fischer
pascal-fischer merged commit ff2787e into main Jun 25, 2026
44 checks passed
@pascal-fischer
pascal-fischer deleted the add-trace-update-logs branch June 25, 2026 15:15
@sonarqubecloud

Copy link
Copy Markdown

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.

2 participants