xray_traffic_job.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. lastOnlineMap, err := j.inboundService.GetClientsLastOnline()
  63. if err != nil {
  64. logger.Warning("get clients last online failed:", err)
  65. }
  66. if lastOnlineMap == nil {
  67. lastOnlineMap = make(map[string]int64)
  68. }
  69. // Derive the local online set from this poll's per-email deltas rather
  70. // than the shared last_online column, which remote-node syncs also bump
  71. // and would otherwise make a client active only on a remote node appear
  72. // online on local inbounds.
  73. activeEmails := make([]string, 0, len(clientTraffics))
  74. for _, ct := range clientTraffics {
  75. if ct != nil && ct.Up+ct.Down > 0 {
  76. activeEmails = append(activeEmails, ct.Email)
  77. }
  78. }
  79. // Pair the email signal with the inbound tags that moved bytes this poll.
  80. // Xray's user>>>email counter aggregates across every inbound a client is
  81. // attached to, so an online email alone can't say which inbound it used —
  82. // gating the per-inbound view on these tags keeps a multi-inbound client
  83. // off inbounds that saw no traffic. See issue #4859.
  84. activeInboundTags := make([]string, 0, len(traffics))
  85. for _, tr := range traffics {
  86. if tr != nil && tr.IsInbound && tr.Up+tr.Down > 0 {
  87. activeInboundTags = append(activeInboundTags, tr.Tag)
  88. }
  89. }
  90. j.inboundService.RefreshLocalOnlineClients(activeEmails, activeInboundTags)
  91. if !websocket.HasClients() {
  92. return
  93. }
  94. onlineClients := j.inboundService.GetOnlineClients()
  95. if onlineClients == nil {
  96. onlineClients = []string{}
  97. }
  98. websocket.BroadcastTraffic(map[string]any{
  99. "traffics": traffics,
  100. "clientTraffics": clientTraffics,
  101. "onlineClients": onlineClients,
  102. "onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
  103. "activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
  104. "lastOnlineMap": lastOnlineMap,
  105. })
  106. clientStatsPayload := map[string]any{}
  107. if stats, err := j.inboundService.GetAllClientTraffics(); err != nil {
  108. logger.Warning("get all client traffics for websocket failed:", err)
  109. } else if len(stats) > 0 {
  110. clientStatsPayload["clients"] = stats
  111. }
  112. if inboundSummary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  113. logger.Warning("get inbounds traffic summary for websocket failed:", err)
  114. } else if len(inboundSummary) > 0 {
  115. clientStatsPayload["inbounds"] = inboundSummary
  116. }
  117. if len(clientStatsPayload) > 0 {
  118. websocket.BroadcastClientStats(clientStatsPayload)
  119. }
  120. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil {
  121. websocket.BroadcastOutbounds(updatedOutbounds)
  122. } else if err != nil {
  123. logger.Warning("get all outbounds for websocket failed:", err)
  124. }
  125. }
  126. func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
  127. informURL, err := j.settingService.GetExternalTrafficInformURI()
  128. if err != nil {
  129. logger.Warning("get ExternalTrafficInformURI failed:", err)
  130. return
  131. }
  132. informURL, err = service.SanitizePublicHTTPURL(informURL, false)
  133. if err != nil {
  134. logger.Warning("ExternalTrafficInformURI blocked:", err)
  135. return
  136. }
  137. requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
  138. if err != nil {
  139. logger.Warning("parse client/inbound traffic failed:", err)
  140. return
  141. }
  142. request := fasthttp.AcquireRequest()
  143. defer fasthttp.ReleaseRequest(request)
  144. request.Header.SetMethod("POST")
  145. request.Header.SetContentType("application/json; charset=UTF-8")
  146. request.SetBody([]byte(requestBody))
  147. request.SetRequestURI(informURL)
  148. response := fasthttp.AcquireResponse()
  149. defer fasthttp.ReleaseResponse(response)
  150. if err := fasthttp.Do(request, response); err != nil {
  151. logger.Warning("POST ExternalTrafficInformURI failed:", err)
  152. }
  153. }