xray_traffic_job.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package job
  2. import (
  3. "encoding/json"
  4. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  5. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  6. "github.com/mhsanaei/3x-ui/v3/internal/web/service/outbound"
  7. "github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. "github.com/valyala/fasthttp"
  10. )
  11. // XrayTrafficJob collects and processes traffic statistics from Xray, updating the database and optionally informing external APIs.
  12. type XrayTrafficJob struct {
  13. settingService service.SettingService
  14. xrayService service.XrayService
  15. inboundService service.InboundService
  16. outboundService outbound.OutboundService
  17. }
  18. // NewXrayTrafficJob creates a new traffic collection job instance.
  19. func NewXrayTrafficJob() *XrayTrafficJob {
  20. return new(XrayTrafficJob)
  21. }
  22. // Run collects traffic statistics from Xray, updates the database, and pushes
  23. // real-time updates over WebSocket using compact delta payloads — no REST
  24. // fallback, scales to 10k–20k+ clients per inbound.
  25. func (j *XrayTrafficJob) Run() {
  26. if !j.xrayService.IsXrayRunning() {
  27. return
  28. }
  29. traffics, clientTraffics, err := j.xrayService.GetXrayTraffic()
  30. if err != nil {
  31. return
  32. }
  33. needRestart0, clientsDisabled, err := j.inboundService.AddTraffic(traffics, clientTraffics)
  34. if err != nil {
  35. logger.Warning("add inbound traffic failed:", err)
  36. }
  37. err, needRestart1 := j.outboundService.AddTraffic(traffics, clientTraffics)
  38. if err != nil {
  39. logger.Warning("add outbound traffic failed:", err)
  40. }
  41. if clientsDisabled {
  42. restartOnDisable, settingErr := j.settingService.GetRestartXrayOnClientDisable()
  43. if settingErr != nil {
  44. logger.Warning("get RestartXrayOnClientDisable failed:", settingErr)
  45. }
  46. if restartOnDisable {
  47. if err := j.xrayService.RestartXray(true); err != nil {
  48. logger.Warning("restart xray after disabling clients failed:", err)
  49. j.xrayService.SetToNeedRestart()
  50. }
  51. }
  52. websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
  53. }
  54. if ExternalTrafficInformEnable, err := j.settingService.GetExternalTrafficInformEnable(); ExternalTrafficInformEnable {
  55. j.informTrafficToExternalAPI(traffics, clientTraffics)
  56. } else if err != nil {
  57. logger.Warning("get ExternalTrafficInformEnable failed:", err)
  58. }
  59. if needRestart0 || needRestart1 {
  60. j.xrayService.SetToNeedRestart()
  61. }
  62. // Derive the local online set from this poll's per-email deltas rather
  63. // than the shared last_online column, which remote-node syncs also bump
  64. // and would otherwise make a client active only on a remote node appear
  65. // online on local inbounds.
  66. activeEmails := make([]string, 0, len(clientTraffics))
  67. deltaActive := make(map[string]bool, len(clientTraffics))
  68. for _, ct := range clientTraffics {
  69. if ct != nil && ct.Up+ct.Down > 0 {
  70. activeEmails = append(activeEmails, ct.Email)
  71. deltaActive[ct.Email] = true
  72. }
  73. }
  74. // When the core supports the online-stats API, union in connection-based
  75. // onlines. Neither signal alone covers everything: an idle-but-connected
  76. // client moves no bytes between polls (the delta heuristic's blind spot),
  77. // while a short-lived connection can close before this poll yet still show
  78. // in the delta. Older cores fall back to deltas alone.
  79. if onlineUsers, apiMode, ouErr := j.xrayService.GetOnlineUsers(); ouErr != nil {
  80. logger.Debug("get online users from xray api failed:", ouErr)
  81. } else if apiMode {
  82. idleOnline := make([]string, 0, len(onlineUsers))
  83. for _, u := range onlineUsers {
  84. if !deltaActive[u.Email] {
  85. activeEmails = append(activeEmails, u.Email)
  86. idleOnline = append(idleOnline, u.Email)
  87. }
  88. }
  89. // The traffic path only bumps last_online on a non-zero delta; keep the
  90. // column fresh for clients kept online purely by a live connection.
  91. if err := j.inboundService.BumpClientsLastOnline(idleOnline); err != nil {
  92. logger.Warning("bump last online for connected clients failed:", err)
  93. }
  94. }
  95. // Pair the email signal with the inbound tags that moved bytes this poll.
  96. // Xray's user>>>email counter aggregates across every inbound a client is
  97. // attached to, so an online email alone can't say which inbound it used —
  98. // gating the per-inbound view on these tags keeps a multi-inbound client
  99. // off inbounds that saw no traffic. See issue #4859.
  100. activeInboundTags := make([]string, 0, len(traffics))
  101. for _, tr := range traffics {
  102. if tr != nil && tr.IsInbound && tr.Up+tr.Down > 0 {
  103. activeInboundTags = append(activeInboundTags, tr.Tag)
  104. }
  105. }
  106. j.inboundService.RefreshLocalOnlineClients(activeEmails, activeInboundTags)
  107. if !websocket.HasClients() {
  108. return
  109. }
  110. lastOnlineMap, err := j.inboundService.GetClientsLastOnline()
  111. if err != nil {
  112. logger.Warning("get clients last online failed:", err)
  113. }
  114. if lastOnlineMap == nil {
  115. lastOnlineMap = make(map[string]int64)
  116. }
  117. onlineClients := j.inboundService.GetOnlineClients()
  118. if onlineClients == nil {
  119. onlineClients = []string{}
  120. }
  121. websocket.BroadcastTraffic(map[string]any{
  122. "traffics": traffics,
  123. "clientTraffics": clientTraffics,
  124. "onlineClients": onlineClients,
  125. "onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
  126. "activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
  127. "lastOnlineMap": lastOnlineMap,
  128. })
  129. clientStatsPayload := map[string]any{}
  130. if stats, err := j.inboundService.GetAllClientTraffics(); err != nil {
  131. logger.Warning("get all client traffics for websocket failed:", err)
  132. } else if len(stats) > 0 {
  133. clientStatsPayload["clients"] = stats
  134. }
  135. if inboundSummary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  136. logger.Warning("get inbounds traffic summary for websocket failed:", err)
  137. } else if len(inboundSummary) > 0 {
  138. clientStatsPayload["inbounds"] = inboundSummary
  139. }
  140. if len(clientStatsPayload) > 0 {
  141. websocket.BroadcastClientStats(clientStatsPayload)
  142. }
  143. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil {
  144. websocket.BroadcastOutbounds(updatedOutbounds)
  145. } else if err != nil {
  146. logger.Warning("get all outbounds for websocket failed:", err)
  147. }
  148. }
  149. func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
  150. informURL, err := j.settingService.GetExternalTrafficInformURI()
  151. if err != nil {
  152. logger.Warning("get ExternalTrafficInformURI failed:", err)
  153. return
  154. }
  155. informURL, err = service.SanitizePublicHTTPURL(informURL, false)
  156. if err != nil {
  157. logger.Warning("ExternalTrafficInformURI blocked:", err)
  158. return
  159. }
  160. requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
  161. if err != nil {
  162. logger.Warning("parse client/inbound traffic failed:", err)
  163. return
  164. }
  165. request := fasthttp.AcquireRequest()
  166. defer fasthttp.ReleaseRequest(request)
  167. request.Header.SetMethod("POST")
  168. request.Header.SetContentType("application/json; charset=UTF-8")
  169. request.SetBody([]byte(requestBody))
  170. request.SetRequestURI(informURL)
  171. response := fasthttp.AcquireResponse()
  172. defer fasthttp.ReleaseResponse(response)
  173. if err := fasthttp.Do(request, response); err != nil {
  174. logger.Warning("POST ExternalTrafficInformURI failed:", err)
  175. }
  176. }