Skip to content

[management] add monitoring for nmap update source#6036

Merged
pascal-fischer merged 1 commit intomainfrom
feature/monitor-nmap-source
Apr 30, 2026
Merged

[management] add monitoring for nmap update source#6036
pascal-fischer merged 1 commit intomainfrom
feature/monitor-nmap-source

Conversation

@pascal-fischer
Copy link
Copy Markdown
Collaborator

@pascal-fischer pascal-fischer commented Apr 30, 2026

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)

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

  • Telemetry
    • Added metrics tracking for peer synchronization events. New observability counter records when account peers updates are triggered, capturing details about affected system resources and operation types to improve visibility into network synchronization behavior and system health monitoring.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 30, 2026

📝 Walkthrough

Walkthrough

Introduces a types.UpdateReason parameter to UpdateAccountPeers and BufferUpdateAccountPeers methods to track what resource and operation triggered peer updates. Updates all call sites across account management, DNS, policy, zones, networks, and services to pass appropriate reason metadata. Adds telemetry metric counting for update triggers by resource and operation.

Changes

Cohort / File(s) Summary
Type Definitions
management/server/types/update_reason.go
New UpdateReason struct with Resource and Operation fields; defines UpdateResource constants (AccountSettings, DNSSettings, Group, NameServerGroup, Policy, PostureCheck, Route, User, Peer, Network, NetworkResource, NetworkRouter, Service, Zone, ZoneRecord) and UpdateOperation constants (Create, Update, Delete).
Controller Interfaces & Implementation
management/internals/controllers/network_map/interface.go, management/internals/controllers/network_map/interface_mock.go, management/internals/controllers/network_map/controller/controller.go
Updated UpdateAccountPeers and BufferUpdateAccountPeers method signatures to accept reason types.UpdateReason; controller increments telemetry counter using reason metadata; buffering now calls sendUpdateAccountPeers directly to count only once at buffer trigger time.
Account Manager Interfaces & Mocks
management/server/account/manager.go, management/server/account/manager_mock.go
Updated UpdateAccountPeers and BufferUpdateAccountPeers interface methods to include reason types.UpdateReason parameter; mock implementations and recorders updated accordingly.
Peer Synchronization
management/server/peer.go, management/server/peer_test.go
DefaultAccountManager.UpdateAccountPeers and BufferUpdateAccountPeers now accept and forward reason parameter to network map controller; tests updated with empty UpdateReason{} values.
Telemetry Metrics
management/server/telemetry/accountmanager_metrics.go
Added updateAccountPeersCounter metric (Int64Counter) and CountUpdateAccountPeersTriggered(resource, operation string) method to track update trigger events by resource and operation type.
Call Site Updates - Peers, Zones, Networks
management/internals/modules/peers/manager.go, management/internals/modules/peers/ephemeral/manager/ephemeral_test.go, management/internals/modules/zones/manager/manager.go, management/internals/modules/zones/records/manager/manager.go, management/server/networks/manager.go, management/server/networks/resources/manager.go, management/server/networks/routers/manager.go
Updated to pass types.UpdateReason with appropriate resource and operation constants (Create/Update/Delete).
Call Site Updates - Services & Reverse Proxy
management/internals/modules/reverseproxy/service/manager/manager.go, management/internals/modules/reverseproxy/service/manager/manager_test.go, management/internals/modules/reverseproxy/service/manager/l4_port_test.go
Service lifecycle methods (CreateService, UpdateService, DeleteService) now pass UpdateReason with ResourceService and appropriate operation; test mocks updated to expect new parameter.
Call Site Updates - Account & Server Management
management/server/account.go, management/server/peer.go, management/server/dns.go, management/server/group.go, management/server/nameserver.go, management/server/policy.go, management/server/posture_checks.go, management/server/route.go, management/server/user.go
All peer-update call sites now pass explicit types.UpdateReason values specifying affected resource (DNSSettings, Group, NameServerGroup, Policy, PostureCheck, Route, User, etc.) and operation type.
Mock Account Manager
management/server/mock_server/account_mock.go
Updated mock methods UpdateAccountPeers and BufferUpdateAccountPeers to accept and forward reason types.UpdateReason parameter; function fields updated to match new signature.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested reviewers

  • crn4

Poem

🐰 The metrics hop with glee,
Tracking reasons, wild and free,
Updates flow with purpose clear,
DNS, peers, and zones appear,
Resource-tagged, we finally see!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely incomplete. Key sections including 'Describe your changes', 'Issue ticket number and link', and 'Stack' contain no content, providing minimal context for reviewers. Fill in the 'Describe your changes' section with implementation details, link any related issue, explain the rationale for the changes, and provide any relevant context about the feature enhancement.
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% 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 '[management] add monitoring for nmap update source' clearly summarizes the main change: adding monitoring/metrics capability for tracking what triggers network map peer updates.
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 feature/monitor-nmap-source

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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@management/internals/modules/peers/manager.go`:
- Line 182: The call to m.accountManager.UpdateAccountPeers(ctx, accountID,
types.UpdateReason{Resource: types.UpdateResourcePeer, Operation:
types.UpdateOperationDelete}) must be gated so it only runs when at least one
peer was actually deleted; modify the surrounding peer deletion logic (the loop
or the function that removes peers) to produce a deletion count or boolean
(e.g., removedCount or deletedAny) and call m.accountManager.UpdateAccountPeers
only if removedCount > 0 (or deletedAny == true), otherwise skip the update.

In `@management/server/user.go`:
- Line 678: The call to am.UpdateAccountPeers currently always uses
UpdateOperationUpdate but SaveOrAddUsers can insert new users when
addIfNotExists=true; modify the flow around SaveOrAddUsers to detect whether new
users were created (e.g., via its return value or an inserted-count flag) and
call am.UpdateAccountPeers with types.UpdateReason{Resource:
types.UpdateResourceUser, Operation: types.UpdateOperationCreate} when inserts
occurred, otherwise keep UpdateOperationUpdate; reference SaveOrAddUsers,
addIfNotExists, and UpdateAccountPeers/ types.UpdateOperationCreate to locate
and implement the change.
🪄 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: 0e6fdd6b-e393-4e74-bcce-1c3da7102305

📥 Commits

Reviewing files that changed from the base of the PR and between 3fc5a8d and 42fad79.

📒 Files selected for processing (28)
  • management/internals/controllers/network_map/controller/controller.go
  • management/internals/controllers/network_map/interface.go
  • management/internals/controllers/network_map/interface_mock.go
  • management/internals/modules/peers/ephemeral/manager/ephemeral_test.go
  • management/internals/modules/peers/manager.go
  • management/internals/modules/reverseproxy/service/manager/l4_port_test.go
  • management/internals/modules/reverseproxy/service/manager/manager.go
  • management/internals/modules/reverseproxy/service/manager/manager_test.go
  • management/internals/modules/zones/manager/manager.go
  • management/internals/modules/zones/records/manager/manager.go
  • management/server/account.go
  • management/server/account/manager.go
  • management/server/account/manager_mock.go
  • management/server/dns.go
  • management/server/group.go
  • management/server/mock_server/account_mock.go
  • management/server/nameserver.go
  • management/server/networks/manager.go
  • management/server/networks/resources/manager.go
  • management/server/networks/routers/manager.go
  • management/server/peer.go
  • management/server/peer_test.go
  • management/server/policy.go
  • management/server/posture_checks.go
  • management/server/route.go
  • management/server/telemetry/accountmanager_metrics.go
  • management/server/types/update_reason.go
  • management/server/user.go

}

m.accountManager.UpdateAccountPeers(ctx, accountID)
m.accountManager.UpdateAccountPeers(ctx, accountID, types.UpdateReason{Resource: types.UpdateResourcePeer, Operation: types.UpdateOperationDelete})
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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Gate peer update trigger on actual deletions.

Line 182 runs even when all peers were skipped (e.g., not found/connected), which can inflate delete-trigger monitoring and perform unnecessary account peer updates.

Suggested fix
 func (m *managerImpl) DeletePeers(ctx context.Context, accountID string, peerIDs []string, userID string, checkConnected bool) error {
+    deletedAny := false
     for _, peerID := range peerIDs {
         var eventsToStore []func()
+        deletedInTx := false
         err = m.store.ExecuteInTransaction(ctx, func(transaction store.Store) error {
             ...
             if err = transaction.DeletePeer(ctx, accountID, peerID); err != nil {
                 return err
             }
+            deletedInTx = true
             ...
             return nil
         })
         if err != nil {
             ...
             continue
         }
+        if !deletedInTx {
+            continue
+        }
+        deletedAny = true
         ...
     }
-    m.accountManager.UpdateAccountPeers(ctx, accountID, types.UpdateReason{Resource: types.UpdateResourcePeer, Operation: types.UpdateOperationDelete})
+    if deletedAny {
+        m.accountManager.UpdateAccountPeers(ctx, accountID, types.UpdateReason{
+            Resource:  types.UpdateResourcePeer,
+            Operation: types.UpdateOperationDelete,
+        })
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/internals/modules/peers/manager.go` at line 182, The call to
m.accountManager.UpdateAccountPeers(ctx, accountID, types.UpdateReason{Resource:
types.UpdateResourcePeer, Operation: types.UpdateOperationDelete}) must be gated
so it only runs when at least one peer was actually deleted; modify the
surrounding peer deletion logic (the loop or the function that removes peers) to
produce a deletion count or boolean (e.g., removedCount or deletedAny) and call
m.accountManager.UpdateAccountPeers only if removedCount > 0 (or deletedAny ==
true), otherwise skip the update.

Comment thread management/server/user.go
return nil, fmt.Errorf("failed to increment network serial: %w", err)
}
am.UpdateAccountPeers(ctx, accountID)
am.UpdateAccountPeers(ctx, accountID, types.UpdateReason{Resource: types.UpdateResourceUser, Operation: types.UpdateOperationUpdate})
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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use create reason when SaveOrAddUsers inserts new users.

Line 678 always reports UpdateOperationUpdate, but this path can create users (addIfNotExists=true). That will skew the new trigger metrics for user-create flows.

Suggested fix
-        am.UpdateAccountPeers(ctx, accountID, types.UpdateReason{Resource: types.UpdateResourceUser, Operation: types.UpdateOperationUpdate})
+        op := types.UpdateOperationUpdate
+        if hasNewUsers {
+            op = types.UpdateOperationCreate
+        }
+        am.UpdateAccountPeers(ctx, accountID, types.UpdateReason{
+            Resource:  types.UpdateResourceUser,
+            Operation: op,
+        })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@management/server/user.go` at line 678, The call to am.UpdateAccountPeers
currently always uses UpdateOperationUpdate but SaveOrAddUsers can insert new
users when addIfNotExists=true; modify the flow around SaveOrAddUsers to detect
whether new users were created (e.g., via its return value or an inserted-count
flag) and call am.UpdateAccountPeers with types.UpdateReason{Resource:
types.UpdateResourceUser, Operation: types.UpdateOperationCreate} when inserts
occurred, otherwise keep UpdateOperationUpdate; reference SaveOrAddUsers,
addIfNotExists, and UpdateAccountPeers/ types.UpdateOperationCreate to locate
and implement the change.

@github-actions
Copy link
Copy Markdown

Release artifacts

Built for PR head 42fad79 in workflow run #14802.

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)

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

@pascal-fischer pascal-fischer merged commit f29f5a0 into main Apr 30, 2026
48 checks passed
@pascal-fischer pascal-fischer deleted the feature/monitor-nmap-source branch April 30, 2026 12:52
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