xray_traffic_job.go 9.8 KB

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