xray_traffic_job.go 9.6 KB

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