node_traffic_sync_job.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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/web/runtime"
  10. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  12. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  13. )
  14. const (
  15. nodeTrafficSyncConcurrency = 8
  16. nodeTrafficSyncRequestTimeout = 4 * time.Second
  17. nodeReconcileTimeout = 30 * time.Second
  18. nodeClientIpSyncInterval = 10 * time.Second
  19. nodeGlobalPushInterval = 30 * time.Second
  20. )
  21. type NodeTrafficSyncJob struct {
  22. nodeService service.NodeService
  23. inboundService service.InboundService
  24. settingService service.SettingService
  25. xrayService service.XrayService
  26. running sync.Mutex
  27. structural atomicBool
  28. ipSyncMu sync.Mutex
  29. lastIpSync int64
  30. globalPushMu sync.Mutex
  31. lastGlobalPush int64
  32. }
  33. type atomicBool struct {
  34. mu sync.Mutex
  35. v bool
  36. }
  37. func (a *atomicBool) set() {
  38. a.mu.Lock()
  39. a.v = true
  40. a.mu.Unlock()
  41. }
  42. func (a *atomicBool) takeAndReset() bool {
  43. a.mu.Lock()
  44. v := a.v
  45. a.v = false
  46. a.mu.Unlock()
  47. return v
  48. }
  49. func NewNodeTrafficSyncJob() *NodeTrafficSyncJob {
  50. return &NodeTrafficSyncJob{}
  51. }
  52. func (j *NodeTrafficSyncJob) Run() {
  53. if !j.running.TryLock() {
  54. return
  55. }
  56. defer j.running.Unlock()
  57. mgr := runtime.GetManager()
  58. if mgr == nil {
  59. return
  60. }
  61. nodes, err := j.nodeService.GetAll()
  62. if err != nil {
  63. logger.Warning("node traffic sync: load nodes failed:", err)
  64. return
  65. }
  66. if len(nodes) == 0 {
  67. return
  68. }
  69. // Decide once per tick whether this run also syncs client IPs, and stamp the
  70. // clock before the loop so two back-to-back 5s ticks can't both qualify.
  71. doIpSync := false
  72. j.ipSyncMu.Lock()
  73. if now := time.Now().Unix(); now-j.lastIpSync >= int64(nodeClientIpSyncInterval/time.Second) {
  74. doIpSync = true
  75. j.lastIpSync = now
  76. }
  77. j.ipSyncMu.Unlock()
  78. sem := make(chan struct{}, nodeTrafficSyncConcurrency)
  79. var wg sync.WaitGroup
  80. for _, n := range nodes {
  81. if !n.Enable || n.Status != "online" {
  82. continue
  83. }
  84. wg.Add(1)
  85. sem <- struct{}{}
  86. go func(n *model.Node) {
  87. defer wg.Done()
  88. defer func() { <-sem }()
  89. j.syncOne(mgr, n, doIpSync)
  90. }(n)
  91. }
  92. wg.Wait()
  93. _, clientsDisabled, err := j.inboundService.AddTraffic(nil, nil)
  94. if err != nil {
  95. logger.Warning("node traffic sync: depletion check failed:", err)
  96. }
  97. if clientsDisabled {
  98. if restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable(); settingErr == nil && restartOnDisable {
  99. if err := j.xrayService.RestartXray(true); err != nil {
  100. logger.Warning("node traffic sync: restart xray after disabling clients failed:", err)
  101. j.xrayService.SetToNeedRestart()
  102. }
  103. } else if settingErr != nil {
  104. logger.Warning("node traffic sync: get RestartXrayOnClientDisable failed:", settingErr)
  105. }
  106. j.structural.set()
  107. }
  108. j.maybePushGlobals(mgr, nodes)
  109. lastOnline, err := j.inboundService.GetClientsLastOnline()
  110. if err != nil {
  111. logger.Warning("node traffic sync: get last-online failed:", err)
  112. }
  113. if lastOnline == nil {
  114. lastOnline = map[string]int64{}
  115. }
  116. // Prune stale local-online entries (no local active emails or inbound tags
  117. // to add here — only the local xray poll feeds those) so a stopped local
  118. // xray's clients and inbounds still age out between traffic polls.
  119. j.inboundService.RefreshLocalOnlineClients(nil, nil)
  120. if !websocket.HasClients() {
  121. return
  122. }
  123. online := j.inboundService.GetOnlineClients()
  124. if online == nil {
  125. online = []string{}
  126. }
  127. websocket.BroadcastTraffic(map[string]any{
  128. "onlineClients": online,
  129. "onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
  130. "activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
  131. "lastOnlineMap": lastOnline,
  132. })
  133. clientStats := map[string]any{}
  134. if stats, err := j.inboundService.GetAllClientTraffics(); err != nil {
  135. logger.Warning("node traffic sync: get all client traffics for websocket failed:", err)
  136. } else if len(stats) > 0 {
  137. clientStats["clients"] = stats
  138. }
  139. if summary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  140. logger.Warning("node traffic sync: get inbounds summary for websocket failed:", err)
  141. } else if len(summary) > 0 {
  142. clientStats["inbounds"] = summary
  143. }
  144. if len(clientStats) > 0 {
  145. websocket.BroadcastClientStats(clientStats)
  146. }
  147. if j.structural.takeAndReset() {
  148. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  149. websocket.BroadcastInvalidate(websocket.MessageTypeClients)
  150. }
  151. }
  152. // maybePushGlobals broadcasts this panel's aggregated per-client usage to its
  153. // online nodes so each node can display the client's cross-panel total and
  154. // enforce its quota locally (see InboundService.AcceptGlobalTraffic). Scoped
  155. // per node to the clients that node actually hosts, and throttled — the
  156. // aggregates only need to reach nodes on a human timescale, not every poll.
  157. func (j *NodeTrafficSyncJob) maybePushGlobals(mgr *runtime.Manager, nodes []*model.Node) {
  158. j.globalPushMu.Lock()
  159. now := time.Now().Unix()
  160. if now-j.lastGlobalPush < int64(nodeGlobalPushInterval/time.Second) {
  161. j.globalPushMu.Unlock()
  162. return
  163. }
  164. j.lastGlobalPush = now
  165. j.globalPushMu.Unlock()
  166. masterGuid, err := j.settingService.GetPanelGuid()
  167. if err != nil || masterGuid == "" {
  168. return
  169. }
  170. sem := make(chan struct{}, nodeTrafficSyncConcurrency)
  171. var wg sync.WaitGroup
  172. for _, n := range nodes {
  173. if !n.Enable || n.Status != "online" {
  174. continue
  175. }
  176. remote, err := mgr.RemoteFor(n)
  177. if err != nil {
  178. continue
  179. }
  180. traffics, err := j.inboundService.GetNodeClientTraffics(n.Id)
  181. if err != nil {
  182. logger.Warning("node traffic sync: load globals for", n.Name, "failed:", err)
  183. continue
  184. }
  185. if len(traffics) == 0 {
  186. continue
  187. }
  188. wg.Add(1)
  189. sem <- struct{}{}
  190. go func(n *model.Node, remote *runtime.Remote, traffics []*xray.ClientTraffic) {
  191. defer wg.Done()
  192. defer func() { <-sem }()
  193. ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout)
  194. defer cancel()
  195. if err := remote.PushGlobalClientTraffics(ctx, masterGuid, traffics); err != nil {
  196. // An old-build node without the endpoint answers 404 — not worth a
  197. // warning every cycle.
  198. if strings.Contains(err.Error(), "HTTP 404") {
  199. logger.Debug("node traffic sync: node", n.Name, "has no global-traffic endpoint (old build)")
  200. } else {
  201. logger.Warning("node traffic sync: push globals to", n.Name, "failed:", err)
  202. }
  203. }
  204. }(n, remote, traffics)
  205. }
  206. wg.Wait()
  207. }
  208. func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSync bool) {
  209. rt, err := mgr.RemoteFor(n)
  210. if err != nil {
  211. logger.Warning("node traffic sync: remote lookup failed for", n.Name, ":", err)
  212. return
  213. }
  214. if n.ConfigDirty {
  215. reconcileCtx, reconcileCancel := context.WithTimeout(context.Background(), nodeReconcileTimeout)
  216. reconcileErr := j.inboundService.ReconcileNode(reconcileCtx, rt, n)
  217. reconcileCancel()
  218. if reconcileErr != nil {
  219. logger.Warning("node traffic sync: reconcile for", n.Name, "failed:", reconcileErr)
  220. return
  221. }
  222. if clearErr := j.nodeService.ClearNodeDirty(n.Id, n.ConfigDirtyAt); clearErr != nil {
  223. logger.Warning("node traffic sync: clear dirty for", n.Name, "failed:", clearErr)
  224. }
  225. j.structural.set()
  226. }
  227. ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout)
  228. defer cancel()
  229. snap, err := rt.FetchTrafficSnapshot(ctx)
  230. if err != nil {
  231. logger.Warning("node traffic sync: fetch from", n.Name, "failed:", err)
  232. j.inboundService.ClearNodeOnlineClients(n.Id)
  233. return
  234. }
  235. service.FilterNodeSnapshot(n, snap)
  236. _, _, dirty, _, _ := j.nodeService.NodeSyncState(n.Id)
  237. changed, err := j.inboundService.SetRemoteTraffic(n.Id, snap, dirty)
  238. if err != nil {
  239. logger.Warning("node traffic sync: merge for", n.Name, "failed:", err)
  240. return
  241. }
  242. if changed {
  243. j.structural.set()
  244. }
  245. if !doIpSync {
  246. return
  247. }
  248. nodeIps, err := rt.FetchAllClientIps(ctx)
  249. if err == nil && len(nodeIps) > 0 {
  250. if err := j.inboundService.MergeInboundClientIps(nodeIps); err != nil {
  251. logger.Warning("node traffic sync: merge client ips from", n.Name, "failed:", err)
  252. }
  253. } else if err != nil {
  254. logger.Warning("node traffic sync: fetch client ips from", n.Name, "failed:", err)
  255. }
  256. masterIps, err := j.inboundService.GetAllInboundClientIps()
  257. if err != nil {
  258. logger.Warning("node traffic sync: load client ips for push to", n.Name, "failed:", err)
  259. return
  260. }
  261. if len(masterIps) > 0 {
  262. if err := rt.PushAllClientIps(ctx, masterIps); err != nil {
  263. logger.Warning("node traffic sync: push client ips to", n.Name, "failed:", err)
  264. }
  265. }
  266. }