xray_traffic_job.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. // If no frontend client is connected, skip all WebSocket broadcasting
  62. // routines — including the active-client DB query and JSON marshaling.
  63. if !websocket.HasClients() {
  64. return
  65. }
  66. // Online presence + traffic deltas — small payload, always fits in WS.
  67. // Force non-nil slice/map so JSON marshalling produces [] / {} instead of
  68. // `null` when everyone is offline. The frontend's traffic handler treats
  69. // a missing/null onlineClients field as "no update", so without this the
  70. // "everyone went offline" transition was silently dropped — stale online
  71. // users lingered in the list and the online filter kept showing them.
  72. onlineClients := j.inboundService.GetOnlineClients()
  73. if onlineClients == nil {
  74. onlineClients = []string{}
  75. }
  76. lastOnlineMap, err := j.inboundService.GetClientsLastOnline()
  77. if err != nil {
  78. logger.Warning("get clients last online failed:", err)
  79. }
  80. if lastOnlineMap == nil {
  81. lastOnlineMap = make(map[string]int64)
  82. }
  83. websocket.BroadcastTraffic(map[string]any{
  84. "traffics": traffics,
  85. "clientTraffics": clientTraffics,
  86. "onlineClients": onlineClients,
  87. "lastOnlineMap": lastOnlineMap,
  88. })
  89. // Full snapshot every cycle: absolute per-client counters and inbound
  90. // totals. Frontend overwrites both in place. The previous delta path
  91. // (activeEmails -> GetActiveClientTraffics) silently omitted the
  92. // clients array whenever nobody moved bytes in the cycle, leaving the
  93. // client rows in the UI stuck at stale traffic/remained/all-time.
  94. clientStatsPayload := map[string]any{}
  95. if stats, err := j.inboundService.GetAllClientTraffics(); err != nil {
  96. logger.Warning("get all client traffics for websocket failed:", err)
  97. } else if len(stats) > 0 {
  98. clientStatsPayload["clients"] = stats
  99. }
  100. if inboundSummary, err := j.inboundService.GetInboundsTrafficSummary(); err != nil {
  101. logger.Warning("get inbounds traffic summary for websocket failed:", err)
  102. } else if len(inboundSummary) > 0 {
  103. clientStatsPayload["inbounds"] = inboundSummary
  104. }
  105. if len(clientStatsPayload) > 0 {
  106. websocket.BroadcastClientStats(clientStatsPayload)
  107. }
  108. // Outbounds list is small (one row per outbound, no per-client expansion)
  109. // so the full snapshot still fits comfortably in WS.
  110. if updatedOutbounds, err := j.outboundService.GetOutboundsTraffic(); err == nil && updatedOutbounds != nil {
  111. websocket.BroadcastOutbounds(updatedOutbounds)
  112. } else if err != nil {
  113. logger.Warning("get all outbounds for websocket failed:", err)
  114. }
  115. }
  116. func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
  117. informURL, err := j.settingService.GetExternalTrafficInformURI()
  118. if err != nil {
  119. logger.Warning("get ExternalTrafficInformURI failed:", err)
  120. return
  121. }
  122. informURL, err = service.SanitizePublicHTTPURL(informURL, false)
  123. if err != nil {
  124. logger.Warning("ExternalTrafficInformURI blocked:", err)
  125. return
  126. }
  127. requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
  128. if err != nil {
  129. logger.Warning("parse client/inbound traffic failed:", err)
  130. return
  131. }
  132. request := fasthttp.AcquireRequest()
  133. defer fasthttp.ReleaseRequest(request)
  134. request.Header.SetMethod("POST")
  135. request.Header.SetContentType("application/json; charset=UTF-8")
  136. request.SetBody([]byte(requestBody))
  137. request.SetRequestURI(informURL)
  138. response := fasthttp.AcquireResponse()
  139. defer fasthttp.ReleaseResponse(response)
  140. if err := fasthttp.Do(request, response); err != nil {
  141. logger.Warning("POST ExternalTrafficInformURI failed:", err)
  142. }
  143. }