xray_traffic_job.go 5.8 KB

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