xray_traffic_job.go 8.8 KB

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