node_traffic_sync_job.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package job
  2. import (
  3. "context"
  4. "strings"
  5. "sync"
  6. "time"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  9. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  10. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  12. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. )
  15. const (
  16. nodeTrafficSyncConcurrency = 8
  17. nodeTrafficSyncRequestTimeout = 4 * time.Second
  18. nodeReconcileTimeout = 30 * time.Second
  19. nodeClientIpSyncInterval = 10 * time.Second
  20. nodeClientIpSyncTimeout = 6 * time.Second
  21. nodeGlobalPushInterval = 30 * time.Second
  22. // nodeInboundSpeedWindowMs is the poll window node-inbound speed deltas are
  23. // normalized to; it MUST match the dashboard's TRAFFIC_POLL_INTERVAL_S (5s),
  24. // the fixed divisor the frontend applies to turn a delta into a rate.
  25. nodeInboundSpeedWindowMs int64 = 5000
  26. )
  27. // inboundSample is a node inbound's last-seen cumulative up/down and the time
  28. // (unix millis) its counter last changed, used to derive a normalized speed.
  29. type inboundSample struct {
  30. up, down, at int64
  31. }
  32. type NodeTrafficSyncJob struct {
  33. nodeService service.NodeService
  34. inboundService service.InboundService
  35. settingService service.SettingService
  36. xrayService service.XrayService
  37. running sync.Mutex
  38. structural atomicBool
  39. ipSyncMu sync.Mutex
  40. lastIpSync int64
  41. globalPushMu sync.Mutex
  42. lastGlobalPush int64
  43. // noGuidIpEndpoint tracks nodes (by id) whose client-IP attribution endpoint
  44. // returned 404, so an old-build node is noted once instead of every cycle.
  45. noGuidIpEndpoint sync.Map
  46. // prevInboundTotals holds the previous poll's cumulative up/down (and the time
  47. // the counter last changed) per node inbound tag, so the next poll can derive
  48. // a per-inbound speed delta — node inbounds have no local Xray poll. Touched
  49. // only from Run (serialized).
  50. prevInboundTotals map[string]inboundSample
  51. }
  52. type atomicBool struct {
  53. mu sync.Mutex
  54. v bool
  55. }
  56. func (a *atomicBool) set() {
  57. a.mu.Lock()
  58. a.v = true
  59. a.mu.Unlock()
  60. }
  61. func (a *atomicBool) takeAndReset() bool {
  62. a.mu.Lock()
  63. v := a.v
  64. a.v = false
  65. a.mu.Unlock()
  66. return v
  67. }
  68. func NewNodeTrafficSyncJob() *NodeTrafficSyncJob {
  69. return &NodeTrafficSyncJob{}
  70. }
  71. func (j *NodeTrafficSyncJob) Run() {
  72. if !j.running.TryLock() {
  73. return
  74. }
  75. defer j.running.Unlock()
  76. mgr := runtime.GetManager()
  77. if mgr == nil {
  78. return
  79. }
  80. nodes, err := j.nodeService.GetAll()
  81. if err != nil {
  82. logger.Warning("node traffic sync: load nodes failed:", err)
  83. return
  84. }
  85. j.inboundService.RetainSyncedNodeOnlineClients(nodes)
  86. if len(nodes) == 0 {
  87. return
  88. }
  89. // Decide once per tick whether this run also syncs client IPs, and stamp the
  90. // clock before the loop so two back-to-back 5s ticks can't both qualify.
  91. doIpSync := false
  92. j.ipSyncMu.Lock()
  93. if now := time.Now().Unix(); now-j.lastIpSync >= int64(nodeClientIpSyncInterval/time.Second) {
  94. doIpSync = true
  95. j.lastIpSync = now
  96. }
  97. j.ipSyncMu.Unlock()
  98. sem := make(chan struct{}, nodeTrafficSyncConcurrency)
  99. var wg sync.WaitGroup
  100. var activeMu sync.Mutex
  101. var activeEmails []string
  102. for _, n := range nodes {
  103. if !n.Enable || n.Status != "online" {
  104. continue
  105. }
  106. wg.Add(1)
  107. sem <- struct{}{}
  108. n := n
  109. common.GoRecover("node-traffic-sync:"+n.Name, func() {
  110. defer wg.Done()
  111. defer func() { <-sem }()
  112. if emails := j.syncOne(mgr, n, doIpSync); len(emails) > 0 {
  113. activeMu.Lock()
  114. activeEmails = append(activeEmails, emails...)
  115. activeMu.Unlock()
  116. }
  117. })
  118. }
  119. wg.Wait()
  120. _, clientsDisabled, err := j.inboundService.AddTraffic(nil, nil)
  121. if err != nil {
  122. logger.Warning("node traffic sync: depletion check failed:", err)
  123. }
  124. if clientsDisabled {
  125. if restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable(); settingErr == nil && restartOnDisable {
  126. if err := j.xrayService.RestartXray(true); err != nil {
  127. logger.Warning("node traffic sync: restart xray after disabling clients failed:", err)
  128. j.xrayService.SetToNeedRestart()
  129. }
  130. } else if settingErr != nil {
  131. logger.Warning("node traffic sync: get RestartXrayOnClientDisable failed:", settingErr)
  132. }
  133. j.structural.set()
  134. }
  135. j.maybePushGlobals(mgr, nodes)
  136. // Prune stale local-online entries (no local active emails or inbound tags
  137. // to add here — only the local xray poll feeds those) so a stopped local
  138. // xray's clients and inbounds still age out between traffic polls.
  139. j.inboundService.RefreshLocalOnlineClients(nil, nil)
  140. // Derive per-node-inbound speed every tick (keeps the baseline fresh even
  141. // with no dashboard open); only broadcast it when someone is watching.
  142. inboundSpeed := j.nodeInboundSpeed()
  143. if !websocket.HasClients() {
  144. return
  145. }
  146. // Same snapshot-vs-delta split as the local traffic job: above the
  147. // threshold a full snapshot would be dropped by the hub's payload cap, so
  148. // send only the rows for clients online on the synced nodes this tick.
  149. snapshot := true
  150. if total, countErr := j.inboundService.CountClientTraffics(); countErr != nil {
  151. logger.Warning("node traffic sync: count client traffics failed:", countErr)
  152. } else if total > clientStatsSnapshotMaxClients {
  153. snapshot = false
  154. }
  155. var stats []*xray.ClientTraffic
  156. var statsErr error
  157. if snapshot {
  158. stats, statsErr = j.inboundService.GetAllClientTraffics()
  159. } else {
  160. stats, statsErr = j.inboundService.GetActiveClientTraffics(activeEmails)
  161. }
  162. if statsErr != nil {
  163. logger.Warning("node traffic sync: get client traffics for websocket failed:", statsErr)
  164. }
  165. var lastOnline map[string]int64
  166. if snapshot {
  167. var loErr error
  168. if lastOnline, loErr = j.inboundService.GetClientsLastOnline(); loErr != nil {
  169. logger.Warning("node traffic sync: get last-online failed:", loErr)
  170. }
  171. } else {
  172. lastOnline = make(map[string]int64, len(stats))
  173. for _, ct := range stats {
  174. if ct != nil {
  175. lastOnline[ct.Email] = ct.LastOnline
  176. }
  177. }
  178. }
  179. if lastOnline == nil {
  180. lastOnline = map[string]int64{}
  181. }
  182. online := j.inboundService.GetOnlineClients()
  183. if online == nil {
  184. online = []string{}
  185. }
  186. trafficPayload := map[string]any{
  187. "onlineClients": online,
  188. "onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
  189. "activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
  190. "lastOnlineMap": lastOnline,
  191. }
  192. // Always send the key so the dashboard clears node inbounds that went idle
  193. // this tick. A nil result (query error) marshals to null and is skipped
  194. // client-side, leaving the last shown value untouched; an empty (non-nil)
  195. // slice marshals to [] and clears stale speeds.
  196. trafficPayload["nodeTraffics"] = inboundSpeed
  197. websocket.BroadcastTraffic(trafficPayload)
  198. clientStats := map[string]any{"snapshot": snapshot}
  199. if len(stats) > 0 {
  200. clientStats["clients"] = stats
  201. }
  202. if summary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  203. logger.Warning("node traffic sync: get inbounds summary for websocket failed:", err)
  204. } else if len(summary) > 0 {
  205. clientStats["inbounds"] = summary
  206. }
  207. if len(clientStats) > 1 {
  208. websocket.BroadcastClientStats(clientStats)
  209. }
  210. if j.structural.takeAndReset() {
  211. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  212. websocket.BroadcastInvalidate(websocket.MessageTypeClients)
  213. }
  214. }
  215. // nodeInboundSpeed derives a per-node-inbound speed delta by diffing the current
  216. // cumulative up/down against the previous poll's, keyed by the central tag the
  217. // dashboard matches. The node's counter keeps climbing while the master can't
  218. // reach it, so the first delta after a gap (node outage, skipped poll, slow
  219. // node) spans more than one poll window; it is normalized to the fixed
  220. // nodeInboundSpeedWindowMs using the real elapsed time so the dashboard's fixed
  221. // divisor yields the true average rate over the gap instead of an impossible
  222. // one-tick spike. The change timestamp only advances when the value actually
  223. // moves, so an idle stretch is averaged correctly when traffic resumes. A reset
  224. // rebaselines to the lower value; a first-seen tag yields no delta until the
  225. // next poll.
  226. func (j *NodeTrafficSyncJob) nodeInboundSpeed() []*xray.Traffic {
  227. totals, err := j.inboundService.GetNodeInboundTrafficTotals()
  228. if err != nil {
  229. return nil
  230. }
  231. now := time.Now().UnixMilli()
  232. deltas := make([]*xray.Traffic, 0, len(totals))
  233. next := make(map[string]inboundSample, len(totals))
  234. for tag, cur := range totals {
  235. prev, ok := j.prevInboundTotals[tag]
  236. if !ok {
  237. next[tag] = inboundSample{up: cur[0], down: cur[1], at: now}
  238. continue
  239. }
  240. dUp := cur[0] - prev.up
  241. dDown := cur[1] - prev.down
  242. if dUp <= 0 && dDown <= 0 {
  243. // No movement, or a counter reset: hold the change timestamp so a
  244. // later jump is averaged over the real elapsed window, not shown as a
  245. // spike. Adopt the lower value on a reset.
  246. if cur[0] < prev.up || cur[1] < prev.down {
  247. next[tag] = inboundSample{up: cur[0], down: cur[1], at: now}
  248. } else {
  249. next[tag] = prev
  250. }
  251. continue
  252. }
  253. if dUp < 0 {
  254. dUp = 0
  255. }
  256. if dDown < 0 {
  257. dDown = 0
  258. }
  259. elapsed := max(now-prev.at, nodeInboundSpeedWindowMs)
  260. up := dUp * nodeInboundSpeedWindowMs / elapsed
  261. down := dDown * nodeInboundSpeedWindowMs / elapsed
  262. if up > 0 || down > 0 {
  263. deltas = append(deltas, &xray.Traffic{Tag: tag, IsInbound: true, Up: up, Down: down})
  264. }
  265. next[tag] = inboundSample{up: cur[0], down: cur[1], at: now}
  266. }
  267. j.prevInboundTotals = next
  268. return deltas
  269. }
  270. // maybePushGlobals broadcasts this panel's aggregated per-client usage to its
  271. // online nodes so each node can display the client's cross-panel total and
  272. // enforce its quota locally (see InboundService.AcceptGlobalTraffic). Scoped
  273. // per node to the clients that node actually hosts, and throttled — the
  274. // aggregates only need to reach nodes on a human timescale, not every poll.
  275. func (j *NodeTrafficSyncJob) maybePushGlobals(mgr *runtime.Manager, nodes []*model.Node) {
  276. j.globalPushMu.Lock()
  277. now := time.Now().Unix()
  278. if now-j.lastGlobalPush < int64(nodeGlobalPushInterval/time.Second) {
  279. j.globalPushMu.Unlock()
  280. return
  281. }
  282. j.lastGlobalPush = now
  283. j.globalPushMu.Unlock()
  284. masterGuid, err := j.settingService.GetPanelGuid()
  285. if err != nil || masterGuid == "" {
  286. return
  287. }
  288. sem := make(chan struct{}, nodeTrafficSyncConcurrency)
  289. var wg sync.WaitGroup
  290. for _, n := range nodes {
  291. if !n.Enable || n.Status != "online" {
  292. continue
  293. }
  294. remote, err := mgr.RemoteFor(n)
  295. if err != nil {
  296. continue
  297. }
  298. traffics, err := j.inboundService.GetNodeClientTraffics(n.Id)
  299. if err != nil {
  300. logger.Warningf("node traffic sync: load globals for %s failed: %v", n.Name, err)
  301. continue
  302. }
  303. if len(traffics) == 0 {
  304. continue
  305. }
  306. wg.Add(1)
  307. sem <- struct{}{}
  308. n, remote, traffics := n, remote, traffics
  309. common.GoRecover("node-global-push:"+n.Name, func() {
  310. defer wg.Done()
  311. defer func() { <-sem }()
  312. ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout)
  313. defer cancel()
  314. if err := remote.PushGlobalClientTraffics(ctx, masterGuid, traffics); err != nil {
  315. // An old-build node without the endpoint answers 404 — not worth a
  316. // warning every cycle.
  317. if strings.Contains(err.Error(), "HTTP 404") {
  318. logger.Debugf("node traffic sync: node %s has no global-traffic endpoint (old build)", n.Name)
  319. } else {
  320. logger.Warningf("node traffic sync: push globals to %s failed: %v", n.Name, err)
  321. }
  322. }
  323. })
  324. }
  325. wg.Wait()
  326. }
  327. // syncOne pulls one node's traffic snapshot and merges it. It returns the
  328. // emails online on that node this tick, feeding the delta broadcast above the
  329. // snapshot threshold; nil on any failure path.
  330. func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSync bool) []string {
  331. rt, err := mgr.RemoteFor(n)
  332. if err != nil {
  333. logger.Warningf("node traffic sync: remote lookup failed for %s: %v", n.Name, err)
  334. return nil
  335. }
  336. justPushed := false
  337. if n.ConfigDirty {
  338. reconcileCtx, reconcileCancel := context.WithTimeout(context.Background(), nodeReconcileTimeout)
  339. reconcileErr := j.inboundService.ReconcileNode(reconcileCtx, rt, n)
  340. reconcileCancel()
  341. if reconcileErr != nil {
  342. // The dirty flag stays set so reconcile retries next tick, but traffic
  343. // accounting must keep flowing: one rejected inbound used to starve the
  344. // whole node's traffic/online sync forever (#5685).
  345. logger.Warningf("node traffic sync: reconcile for %s failed, continuing with traffic pull: %v", n.Name, reconcileErr)
  346. } else {
  347. if clearErr := j.nodeService.ClearNodeDirty(n.Id, n.ConfigDirtyAt); clearErr != nil {
  348. logger.Warningf("node traffic sync: clear dirty for %s failed: %v", n.Name, clearErr)
  349. }
  350. j.structural.set()
  351. // The snapshot below may still predate the push we just made, so its
  352. // lagging lifecycle values must not merge back this tick (#6228).
  353. justPushed = true
  354. }
  355. }
  356. ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout)
  357. defer cancel()
  358. snap, err := rt.FetchTrafficSnapshot(ctx)
  359. if err != nil {
  360. logger.Warningf("node traffic sync: fetch from %s failed: %v", n.Name, err)
  361. j.inboundService.ClearNodeOnlineClients(n.Id)
  362. return nil
  363. }
  364. snap.ManagedAliases = rt.AdoptedInboundAliases()
  365. syncCanAdopt := syncCanAdoptInbounds(n, snap.ManagedAliases)
  366. service.FilterNodeSnapshot(n, snap)
  367. _, _, dirty, _, _ := j.nodeService.NodeSyncState(n.Id)
  368. if !dirty {
  369. if pending, checkErr := j.inboundService.SnapshotHasUnadoptedInbounds(n.Id, snap); checkErr != nil {
  370. logger.Warningf("node traffic sync: unadopted-inbound check for %s failed: %v", n.Name, checkErr)
  371. } else if pending {
  372. hostCtx, hostCancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout)
  373. groups, hgErr := rt.FetchHostGroups(hostCtx)
  374. hostCancel()
  375. if hgErr != nil {
  376. logger.Debugf("node traffic sync: fetch host groups from %s failed: %v", n.Name, hgErr)
  377. } else {
  378. snap.HostGroups = groups
  379. }
  380. }
  381. }
  382. changed, err := j.inboundService.SetRemoteTraffic(n.Id, snap, dirty, justPushed)
  383. if err != nil {
  384. logger.Warningf("node traffic sync: merge for %s failed: %v", n.Name, err)
  385. return nil
  386. }
  387. if changed {
  388. j.structural.set()
  389. }
  390. if !dirty && n.InboundsAdoptedAt == 0 && syncCanAdopt {
  391. if markErr := j.nodeService.MarkNodeInboundsAdopted(n.Id); markErr != nil {
  392. logger.Warningf("node traffic sync: mark inbounds adopted for %s failed: %v", n.Name, markErr)
  393. }
  394. }
  395. active := make([]string, 0, len(snap.OnlineEmails))
  396. active = append(active, snap.OnlineEmails...)
  397. for _, emails := range snap.OnlineTree {
  398. active = append(active, emails...)
  399. }
  400. if !doIpSync {
  401. return active
  402. }
  403. ipCtx, ipCancel := context.WithTimeout(context.Background(), nodeClientIpSyncTimeout)
  404. defer ipCancel()
  405. nodeIps, err := rt.FetchAllClientIps(ipCtx)
  406. if err == nil && len(nodeIps) > 0 {
  407. if err := j.inboundService.MergeInboundClientIps(nodeIps); err != nil {
  408. logger.Warningf("node traffic sync: merge client ips from %s failed: %v", n.Name, err)
  409. }
  410. } else if err != nil {
  411. logger.Warningf("node traffic sync: fetch client ips from %s failed: %v", n.Name, err)
  412. }
  413. masterIps, err := j.inboundService.GetNodeInboundClientIps(n.Id)
  414. if err != nil {
  415. logger.Warningf("node traffic sync: load client ips for push to %s failed: %v", n.Name, err)
  416. return active
  417. }
  418. if len(masterIps) > 0 {
  419. if err := rt.PushAllClientIps(ipCtx, masterIps); err != nil {
  420. logger.Warningf("node traffic sync: push client ips to %s failed: %v", n.Name, err)
  421. }
  422. }
  423. // Per-node IP attribution: pull the node's guid-keyed subtree (its own
  424. // observations plus any descendants) so the master can tell which node each
  425. // IP is on. Old nodes without the endpoint return HTTP 404 every cycle — note
  426. // it once per node (re-armed on recovery) instead of flooding the log.
  427. if guidTrees, err := rt.FetchClientIpsByGuid(ipCtx); err != nil {
  428. if strings.Contains(err.Error(), "HTTP 404") {
  429. if _, seen := j.noGuidIpEndpoint.LoadOrStore(n.Id, true); !seen {
  430. logger.Debugf("node traffic sync: node %s has no client-IP attribution endpoint (old build)", n.Name)
  431. }
  432. } else {
  433. logger.Debugf("node traffic sync: fetch client ip attribution from %s failed: %v", n.Name, err)
  434. }
  435. } else {
  436. j.noGuidIpEndpoint.Delete(n.Id)
  437. if len(guidTrees) > 0 {
  438. if err := j.inboundService.MergeClientIpsByGuid(n, guidTrees); err != nil {
  439. logger.Warningf("node traffic sync: merge client ip attribution from %s failed: %v", n.Name, err)
  440. }
  441. }
  442. }
  443. return active
  444. }
  445. // Whether this sync can perform the "first clean adoption" that
  446. // InboundsAdoptedAt records (#6283).
  447. func syncCanAdoptInbounds(n *model.Node, adoptedAliases []string) bool {
  448. if n == nil || n.InboundSyncMode != "selected" {
  449. return true
  450. }
  451. return len(n.InboundTags) > 0 || len(adoptedAliases) > 0
  452. }