Files
mirror-3x-ui/internal/web/job/node_traffic_sync_job.go
T
Hamed 12e0b076a8 fix(database): coordinate migrations and restores across processes (#7322)
Coordinate database maintenance across panel, CLI, node synchronization, and restore paths.

- Add cross-process PostgreSQL advisory locks and pinned execution fences; cancel CLI work when its lease session is lost.
- Serialize SQLite file replacement with OS-level process locks and stable lock identity.
- Drain traffic writers and node-sync work before restore, then resume after migration and validation.
- Persist PostgreSQL restore-pending state and recover interrupted restores on startup.
- Add regression coverage for concurrent migrations/restores, session-loss fencing, CLI work cancellation, and recovery.

Closes #7318.
2026-12-03 12:05:51 +03:30

731 lines
23 KiB
Go

package job
import (
"context"
"errors"
"maps"
"strings"
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
const (
// The heartbeat's bound: at 8, 300 nodes 80ms away took 25-30s per 5s tick on SQLite
// and 6-9s at 32; neither SQLite nor Postgres raised lock or pool errors.
nodeTrafficSyncConcurrency = 32
nodeTrafficSyncRequestTimeout = 4 * time.Second
nodeReconcileTimeout = 30 * time.Second
nodeClientIpSyncInterval = 10 * time.Second
nodeClientIpSyncTimeout = 6 * time.Second
nodeGlobalPushInterval = 30 * time.Second
// Match the UI speed expiry: two normal five-second polling windows.
nodeClientSampleTTL = 10 * time.Second
// nodeInboundSpeedWindowMs is the poll window node-inbound speed deltas are
// normalized to; it MUST match the dashboard's TRAFFIC_POLL_INTERVAL_S (5s),
// the fixed divisor the frontend applies to turn a delta into a rate.
nodeInboundSpeedWindowMs int64 = 5000
)
// inboundSample is a node inbound's last-seen cumulative up/down and the time
// (unix millis) its counter last changed, used to derive a normalized speed.
type inboundSample struct {
up, down, at int64
}
type nodePollState struct {
busy bool
cancel context.CancelFunc
lastIP, lastGlobals time.Time
}
type nodeClientSample struct {
at time.Time
emails []string
speed []*xray.ClientTraffic
}
type NodeTrafficSyncJob struct {
nodeService service.NodeService
inboundService service.InboundService
settingService service.SettingService
xrayService service.XrayService
ctx context.Context
cancel context.CancelFunc
dispatch sync.Mutex
closed bool
workers sync.WaitGroup
polls map[int]*nodePollState
inFlight, nextNode int
maintaining, publishing bool
hadNodes bool
structural atomicBool
noGuidIpEndpoint sync.Map
// Only the publisher touches the inbound speed baseline.
prevInboundTotals map[string]inboundSample
clientSpeedMu sync.Mutex
prevClientTotals map[int]map[string]inboundSample
clientSamples map[int]nodeClientSample
}
type atomicBool struct {
mu sync.Mutex
v bool
}
func (a *atomicBool) set() {
a.mu.Lock()
a.v = true
a.mu.Unlock()
}
func (a *atomicBool) takeAndReset() bool {
a.mu.Lock()
v := a.v
a.v = false
a.mu.Unlock()
return v
}
func NewNodeTrafficSyncJob() *NodeTrafficSyncJob {
ctx, cancel := context.WithCancel(context.Background())
return &NodeTrafficSyncJob{ctx: ctx, cancel: cancel, polls: make(map[int]*nodePollState)}
}
// Close drains polls and publication before the panel stops its traffic writer.
func (j *NodeTrafficSyncJob) Close() {
j.dispatch.Lock()
j.closed = true
j.cancel()
j.dispatch.Unlock()
j.workers.Wait()
}
func (j *NodeTrafficSyncJob) Run() {
if !j.dispatch.TryLock() {
return
}
defer j.dispatch.Unlock()
end, allowed := service.BeginDatabaseWork()
if !allowed {
return
}
defer end()
mgr := runtime.GetManager()
if j.closed || mgr == nil {
return
}
nodes, err := j.nodeService.ListOperational()
if err != nil {
logger.Warning("node traffic sync: load nodes failed:", err)
return
}
j.inboundService.RetainSyncedNodeOnlineClients(nodes)
present := make(map[int]*model.Node, len(nodes))
for _, node := range nodes {
present[node.Id] = node
}
for id, poll := range j.polls {
node := present[id]
if poll.busy && (node == nil || !node.Enable || node.Status != "online") {
poll.cancel()
}
if !poll.busy && node == nil {
delete(j.polls, id)
j.noGuidIpEndpoint.Delete(id)
}
}
j.clientSpeedMu.Lock()
j.pruneClientSpeedNodes(nodes)
j.clientSpeedMu.Unlock()
// Cache pruning waits on the traffic writer, so keep it off the dispatch path.
j.startPeriodicWorker("node-traffic-maintenance", &j.maintaining, func() {
j.maintainTraffic(nodes)
})
if len(nodes) == 0 {
if j.hadNodes && !j.publishing {
j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic)
j.hadNodes = false
} else if websocket.HasClients() && !j.inboundService.HasFreshXrayOnlineSample() {
// Standalone panels also need to refresh attribution while Xray is unpolled.
j.startPeriodicWorker("local-online-publish", &j.publishing, func() {
websocket.BroadcastTraffic(map[string]any{
"nodeTraffics": []*xray.Traffic{},
"onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
"activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
})
})
}
return
}
j.hadNodes = true
fetchTimeout, err := j.settingService.GetNodeTrafficFetchTimeout()
if err != nil || fetchTimeout < time.Second || fetchTimeout > 30*time.Second {
fetchTimeout = nodeTrafficSyncRequestTimeout
}
now := time.Now()
for remaining := len(nodes); remaining > 0 && j.inFlight < nodeTrafficSyncConcurrency; remaining-- {
j.nextNode %= len(nodes)
node := nodes[j.nextNode]
j.nextNode++
if !node.Enable || node.Status != "online" {
continue
}
state := j.polls[node.Id]
if state == nil {
state = &nodePollState{}
j.polls[node.Id] = state
}
if state.busy {
continue
}
doIPSync := now.Sub(state.lastIP) >= nodeClientIpSyncInterval
if doIPSync {
state.lastIP = now
}
pushGlobals := now.Sub(state.lastGlobals) >= nodeGlobalPushInterval
if pushGlobals {
state.lastGlobals = now
}
pollCtx, cancel := context.WithCancel(j.ctx)
state.busy = true
state.cancel = cancel
j.inFlight++
j.startWorker("node-traffic-sync:"+node.Name, func() {
defer func() {
cancel()
j.dispatch.Lock()
state.busy = false
state.cancel = nil
j.inFlight--
j.dispatch.Unlock()
}()
if end, allowed := service.BeginDatabaseWork(); allowed {
defer end()
j.syncOne(pollCtx, mgr, node, doIPSync, pushGlobals, fetchTimeout)
}
})
}
j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic)
}
// Worker admission is serialized with Close. The cron wrapper only sees dispatch.
func (j *NodeTrafficSyncJob) startWorker(name string, work func()) {
j.workers.Add(1)
common.GoRecover(name, func() {
defer j.workers.Done()
work()
})
}
func (j *NodeTrafficSyncJob) startPeriodicWorker(name string, busy *bool, work func()) {
if *busy {
return
}
*busy = true
j.startWorker(name, func() {
defer func() {
j.dispatch.Lock()
*busy = false
j.dispatch.Unlock()
}()
if end, allowed := service.BeginDatabaseWork(); allowed {
defer end()
work()
}
})
}
func (j *NodeTrafficSyncJob) maintainTraffic(nodes []*model.Node) {
if err := j.inboundService.RetainNodeSnapshotCaches(nodes); err != nil {
logger.Warning("node traffic sync: prune snapshot caches failed:", err)
}
if len(nodes) == 0 {
return
}
_, clientsDisabled, err := j.inboundService.AddTraffic(nil, nil)
if err != nil {
logger.Warning("node traffic sync: depletion check failed:", err)
}
if clientsDisabled {
j.xrayService.ApplyPendingDepletionRestart()
j.structural.set()
}
}
func (j *NodeTrafficSyncJob) publishTraffic() {
// Prune stale local-online entries (no local active emails or inbound tags
// to add here — only the local xray poll feeds those) so a stopped local
// xray's clients and inbounds still age out between traffic polls.
j.inboundService.RefreshLocalOnlineClients(nil, nil)
// Derive per-node-inbound speed every tick (keeps the baseline fresh even
// with no dashboard open); only broadcast it when someone is watching.
inboundSpeed := j.nodeInboundSpeed()
if !websocket.HasClients() {
return
}
activeEmails, clientSpeed := j.clientSpeedSnapshot(time.Now())
// Same snapshot-vs-delta split as the local traffic job: above the
// threshold a full snapshot would be dropped by the hub's payload cap, so
// send only the rows for clients online on the synced nodes this tick.
snapshot := true
if total, countErr := j.inboundService.CountClientTraffics(); countErr != nil {
logger.Warning("node traffic sync: count client traffics failed:", countErr)
} else if total > clientStatsSnapshotMaxClients {
snapshot = false
}
var stats []*xray.ClientTraffic
var statsErr error
if snapshot {
stats, statsErr = j.inboundService.GetAllClientTraffics()
} else {
stats, statsErr = j.inboundService.GetActiveClientTraffics(activeEmails)
}
if statsErr != nil {
logger.Warning("node traffic sync: get client traffics for websocket failed:", statsErr)
}
var lastOnline map[string]int64
if snapshot {
var loErr error
if lastOnline, loErr = j.inboundService.GetClientsLastOnline(); loErr != nil {
logger.Warning("node traffic sync: get last-online failed:", loErr)
}
} else {
lastOnline = make(map[string]int64, len(stats))
for _, ct := range stats {
if ct != nil {
lastOnline[ct.Email] = ct.LastOnline
}
}
}
if lastOnline == nil {
lastOnline = map[string]int64{}
}
online := j.inboundService.GetOnlineClients()
if online == nil {
online = []string{}
}
trafficPayload := map[string]any{
"onlineClients": online,
"onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
"activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
"lastOnlineMap": lastOnline,
}
// Always send the key so the dashboard clears node inbounds that went idle
// this tick. A nil result (query error) marshals to null and is skipped
// client-side, leaving the last shown value untouched; an empty (non-nil)
// slice marshals to [] and clears stale speeds.
trafficPayload["nodeTraffics"] = inboundSpeed
websocket.BroadcastTraffic(trafficPayload)
// Own source so the clients page adds it to local Xray/TUIC speed instead of
// overwriting it; sent even when empty so idle clients clear.
websocket.BroadcastTraffic(map[string]any{
"clientTraffics": clientSpeed,
"clientTrafficSource": "node",
"clientTrafficIntervalMs": nodeInboundSpeedWindowMs,
})
clientStats := map[string]any{"snapshot": snapshot}
if len(stats) > 0 {
clientStats["clients"] = stats
}
if summary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
logger.Warning("node traffic sync: get inbounds summary for websocket failed:", err)
} else if len(summary) > 0 {
clientStats["inbounds"] = summary
}
if len(clientStats) > 1 {
websocket.BroadcastClientStats(clientStats)
}
if j.structural.takeAndReset() {
websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
websocket.BroadcastInvalidate(websocket.MessageTypeClients)
}
}
// nodeInboundSpeed derives a per-node-inbound speed delta by diffing the current
// cumulative up/down against the previous poll's, keyed by the central tag the
// dashboard matches. The node's counter keeps climbing while the master can't
// reach it, so the first delta after a gap (node outage, skipped poll, slow
// node) spans more than one poll window; it is normalized to the fixed
// nodeInboundSpeedWindowMs using the real elapsed time so the dashboard's fixed
// divisor yields the true average rate over the gap instead of an impossible
// one-tick spike. The change timestamp only advances when the value actually
// moves, so an idle stretch is averaged correctly when traffic resumes. A reset
// rebaselines to the lower value; a first-seen tag yields no delta until the
// next poll.
func (j *NodeTrafficSyncJob) nodeInboundSpeed() []*xray.Traffic {
totals, err := j.inboundService.GetNodeInboundTrafficTotals()
if err != nil {
return nil
}
now := time.Now().UnixMilli()
deltas := make([]*xray.Traffic, 0, len(totals))
next := make(map[string]inboundSample, len(totals))
for tag, cur := range totals {
prev, ok := j.prevInboundTotals[tag]
sample, up, down := speedStep(prev, ok, cur, now)
next[tag] = sample
if up > 0 || down > 0 {
deltas = append(deltas, &xray.Traffic{Tag: tag, IsInbound: true, Up: up, Down: down})
}
}
j.prevInboundTotals = next
return deltas
}
// speedStep advances one counter's baseline and returns its delta normalized to
// nodeInboundSpeedWindowMs; see nodeInboundSpeed for the idle/gap/reset rules.
func speedStep(prev inboundSample, ok bool, cur [2]int64, now int64) (inboundSample, int64, int64) {
if !ok {
return inboundSample{up: cur[0], down: cur[1], at: now}, 0, 0
}
dUp := cur[0] - prev.up
dDown := cur[1] - prev.down
if dUp <= 0 && dDown <= 0 {
if cur[0] < prev.up || cur[1] < prev.down {
return inboundSample{up: cur[0], down: cur[1], at: now}, 0, 0
}
return prev, 0, 0
}
if dUp < 0 {
dUp = 0
}
if dDown < 0 {
dDown = 0
}
elapsed := max(now-prev.at, nodeInboundSpeedWindowMs)
return inboundSample{up: cur[0], down: cur[1], at: now},
dUp * nodeInboundSpeedWindowMs / elapsed,
dDown * nodeInboundSpeedWindowMs / elapsed
}
// A client on several inbounds of one node shares one counter row, so copies are
// never summed; divergent copies fold to the per-field max, as the merge does (#5274).
func nodeClientTotals(snap *runtime.TrafficSnapshot) map[string][2]int64 {
totals := make(map[string][2]int64)
if snap == nil {
return totals
}
for _, ib := range snap.Inbounds {
if ib == nil {
continue
}
for _, cs := range ib.ClientStats {
if cs.Email == "" {
continue
}
cur := totals[cs.Email]
totals[cs.Email] = [2]int64{max(cur[0], cs.Up), max(cur[1], cs.Down)}
}
}
return totals
}
func diffClientTotals(prev map[string]inboundSample, cur map[string][2]int64, now int64) (map[string]inboundSample, []*xray.ClientTraffic) {
next := make(map[string]inboundSample, len(cur))
var deltas []*xray.ClientTraffic
for email, c := range cur {
p, ok := prev[email]
sample, up, down := speedStep(p, ok, c, now)
next[email] = sample
if up > 0 || down > 0 {
deltas = append(deltas, &xray.ClientTraffic{Email: email, Up: up, Down: down})
}
}
return next, deltas
}
func (j *NodeTrafficSyncJob) recordNodeClientSpeed(ctx context.Context, nodeID int, snap *runtime.TrafficSnapshot, now time.Time) {
cur := nodeClientTotals(snap)
j.clientSpeedMu.Lock()
previous := j.prevClientTotals[nodeID]
j.clientSpeedMu.Unlock()
next, deltas := diffClientTotals(previous, cur, now.UnixMilli())
var emails []string
if snap != nil {
emails = append(emails, snap.OnlineEmails...)
for _, online := range snap.OnlineTree {
emails = append(emails, online...)
}
}
j.clientSpeedMu.Lock()
defer j.clientSpeedMu.Unlock()
if ctx.Err() != nil {
return
}
if j.prevClientTotals == nil {
j.prevClientTotals = make(map[int]map[string]inboundSample)
}
j.prevClientTotals[nodeID] = next
if j.clientSamples == nil {
j.clientSamples = make(map[int]nodeClientSample)
}
j.clientSamples[nodeID] = nodeClientSample{at: now, emails: emails, speed: deltas}
}
func (j *NodeTrafficSyncJob) clientSpeedSnapshot(now time.Time) ([]string, []*xray.ClientTraffic) {
j.clientSpeedMu.Lock()
for id, sample := range j.clientSamples {
if now.Sub(sample.at) >= nodeClientSampleTTL {
delete(j.clientSamples, id)
}
}
samples := maps.Clone(j.clientSamples)
j.clientSpeedMu.Unlock()
var activeEmails []string
byEmail := make(map[string]*xray.ClientTraffic)
for _, sample := range samples {
activeEmails = append(activeEmails, sample.emails...)
for _, delta := range sample.speed {
total := byEmail[delta.Email]
if total == nil {
total = &xray.ClientTraffic{Email: delta.Email}
byEmail[delta.Email] = total
}
total.Up += delta.Up
total.Down += delta.Down
}
}
speed := make([]*xray.ClientTraffic, 0, len(byEmail))
for _, row := range byEmail {
speed = append(speed, row)
}
return activeEmails, speed
}
// Keep the accounting baseline across temporary outages and presentation expiry.
// Caller holds clientSpeedMu.
func (j *NodeTrafficSyncJob) pruneClientSpeedNodes(nodes []*model.Node) {
alive := make(map[int]struct{}, len(nodes))
for _, n := range nodes {
if n != nil {
alive[n.Id] = struct{}{}
if !n.Enable || n.Status != "online" {
delete(j.clientSamples, n.Id)
}
}
}
for id := range j.prevClientTotals {
if _, ok := alive[id]; !ok {
delete(j.prevClientTotals, id)
delete(j.clientSamples, id)
}
}
}
func (j *NodeTrafficSyncJob) pushGlobals(pollCtx context.Context, node *model.Node, remote *runtime.Remote) {
masterGuid, err := j.settingService.GetPanelGuid()
if err != nil || masterGuid == "" {
return
}
traffics, err := j.inboundService.GetNodeClientTraffics(node.Id)
if err != nil {
logger.Warningf("node traffic sync: load globals for %s failed: %v", node.Name, err)
return
}
if len(traffics) == 0 {
return
}
ctx, cancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout)
defer cancel()
if err := remote.PushGlobalClientTraffics(ctx, masterGuid, traffics); err != nil {
if strings.Contains(err.Error(), "HTTP 404") {
logger.Debugf("node traffic sync: node %s has no global-traffic endpoint (old build)", node.Name)
} else {
logger.Warningf("node traffic sync: push globals to %s failed: %v", node.Name, err)
}
}
}
func (j *NodeTrafficSyncJob) syncOne(pollCtx context.Context, mgr *runtime.Manager, n *model.Node, doIpSync, pushGlobals bool, fetchTimeout time.Duration) {
rt, err := mgr.RemoteFor(n)
if err != nil {
logger.Warningf("node traffic sync: remote lookup failed for %s: %v", n.Name, err)
return
}
if pushGlobals {
defer func() {
if pollCtx.Err() == nil {
j.pushGlobals(pollCtx, n, rt)
}
}()
}
justPushed := false
if n.ConfigDirty {
reconcileCtx, reconcileCancel := context.WithTimeout(pollCtx, nodeReconcileTimeout)
reconcileErr := j.inboundService.ReconcileNode(reconcileCtx, rt, n)
reconcileCancel()
if pollCtx.Err() != nil {
return
}
if reconcileErr != nil {
// The dirty flag stays set so reconcile retries next tick, but traffic
// accounting must keep flowing: one rejected inbound used to starve the
// whole node's traffic/online sync forever (#5685).
logger.Warningf("node traffic sync: reconcile for %s failed, continuing with traffic pull: %v", n.Name, reconcileErr)
} else {
if clearErr := j.nodeService.ClearNodeDirty(n.Id, n.ConfigDirtyAt); clearErr != nil {
logger.Warningf("node traffic sync: clear dirty for %s failed: %v", n.Name, clearErr)
}
j.structural.set()
// The snapshot below may still predate the push we just made, so its
// lagging lifecycle values must not merge back this tick (#6228).
justPushed = true
}
}
// Before the snapshot, so counters a reset just zeroed are what gets merged.
resetCtx, resetCancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout)
if resetErr := j.inboundService.DeliverNodeResets(resetCtx, n.Id, rt); resetErr != nil {
logger.Warningf("node traffic sync: reset delivery to %s failed, retrying next tick: %v", n.Name, resetErr)
}
resetCancel()
if pollCtx.Err() != nil {
return
}
ctx, cancel := context.WithTimeout(pollCtx, fetchTimeout)
defer cancel()
fetchStarted := time.Now()
snap, err := rt.FetchTrafficSnapshot(ctx)
prepareStarted := time.Now()
if err != nil {
logger.Warningf("node traffic sync: fetch from %s failed after %dms: %v", n.Name, prepareStarted.Sub(fetchStarted).Milliseconds(), err)
j.inboundService.ClearNodeOnlineClients(n.Id)
return
}
snap.ManagedAliases = rt.AdoptedInboundAliases()
syncCanAdopt := syncCanAdoptInbounds(n, snap.ManagedAliases)
service.FilterNodeSnapshot(n, snap)
enabled, status, dirty, _, err := j.nodeService.NodeSyncState(n.Id)
if err != nil || !enabled || status != "online" {
j.inboundService.ClearNodeOnlineClients(n.Id)
return
}
if !dirty {
if pending, checkErr := j.inboundService.SnapshotHasUnadoptedInbounds(n.Id, snap); checkErr != nil {
logger.Warningf("node traffic sync: unadopted-inbound check for %s failed: %v", n.Name, checkErr)
} else if pending {
hostCtx, hostCancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout)
groups, hgErr := rt.FetchHostGroups(hostCtx)
hostCancel()
if hgErr != nil {
logger.Debugf("node traffic sync: fetch host groups from %s failed: %v", n.Name, hgErr)
} else {
snap.HostGroups = groups
}
}
}
mergeStarted := time.Now()
changed, err := j.inboundService.MergeOnlineNodeTraffic(pollCtx, n.Id, snap, dirty, justPushed)
logger.Debugf("node traffic sync timing: node_id=%d compact=%t fetch_ms=%d prepare_ms=%d merge_ms=%d",
n.Id, snap.StructuralRevision != "", prepareStarted.Sub(fetchStarted).Milliseconds(),
mergeStarted.Sub(prepareStarted).Milliseconds(), time.Since(mergeStarted).Milliseconds())
if err != nil {
logger.Warningf("node traffic sync: merge for %s failed: %v", n.Name, err)
return
}
if changed {
j.structural.set()
}
enabled, status, _, _, err = j.nodeService.NodeSyncState(n.Id)
if err != nil || !enabled || status != "online" || pollCtx.Err() != nil {
j.inboundService.ClearNodeOnlineClients(n.Id)
return
}
j.recordNodeClientSpeed(pollCtx, n.Id, snap, time.Now())
if !dirty && n.InboundsAdoptedAt == 0 && syncCanAdopt {
if markErr := j.nodeService.MarkNodeInboundsAdopted(n.Id); markErr != nil {
logger.Warningf("node traffic sync: mark inbounds adopted for %s failed: %v", n.Name, markErr)
}
}
if !doIpSync {
return
}
ipCtx, ipCancel := context.WithTimeout(pollCtx, nodeClientIpSyncTimeout)
defer ipCancel()
nodeIps, err := rt.FetchAllClientIps(ipCtx)
if err == nil && len(nodeIps) > 0 {
if err := j.inboundService.MergePolledNodeClientIps(ipCtx, n, nodeIps); err != nil {
if errors.Is(err, service.ErrIneligibleNodeIPReport) {
return
}
logger.Warningf("node traffic sync: merge client ips from %s failed: %v", n.Name, err)
}
} else if err != nil {
logger.Warningf("node traffic sync: fetch client ips from %s failed: %v", n.Name, err)
}
masterIps, err := j.inboundService.GetNodeInboundClientIps(n.Id)
if err != nil {
logger.Warningf("node traffic sync: load client ips for push to %s failed: %v", n.Name, err)
return
}
if len(masterIps) > 0 {
if err := rt.PushAllClientIps(ipCtx, masterIps); err != nil {
logger.Warningf("node traffic sync: push client ips to %s failed: %v", n.Name, err)
}
}
// Per-node IP attribution: pull the node's guid-keyed subtree (its own
// observations plus any descendants) so the master can tell which node each
// IP is on. Old nodes without the endpoint return HTTP 404 every cycle — note
// it once per node (re-armed on recovery) instead of flooding the log.
if guidTrees, err := rt.FetchClientIpsByGuid(ipCtx); err != nil {
if strings.Contains(err.Error(), "HTTP 404") {
if _, seen := j.noGuidIpEndpoint.LoadOrStore(n.Id, true); !seen {
logger.Debugf("node traffic sync: node %s has no client-IP attribution endpoint (old build)", n.Name)
}
} else {
logger.Debugf("node traffic sync: fetch client ip attribution from %s failed: %v", n.Name, err)
}
} else {
j.noGuidIpEndpoint.Delete(n.Id)
if len(guidTrees) > 0 {
if err := j.inboundService.MergePolledClientIpsByGuid(ipCtx, n, guidTrees); err != nil &&
!errors.Is(err, service.ErrIneligibleNodeIPReport) {
logger.Warningf("node traffic sync: merge client ip attribution from %s failed: %v", n.Name, err)
}
}
}
}
// Whether this sync can perform the "first clean adoption" that
// InboundsAdoptedAt records (#6283).
func syncCanAdoptInbounds(n *model.Node, adoptedAliases []string) bool {
if n == nil || n.InboundSyncMode != "selected" {
return true
}
return len(n.InboundTags) > 0 || len(adoptedAliases) > 0
}