1
0

node.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/util/common"
  16. "github.com/mhsanaei/3x-ui/v3/util/netsafe"
  17. "github.com/mhsanaei/3x-ui/v3/web/runtime"
  18. )
  19. type HeartbeatPatch struct {
  20. Status string
  21. LastHeartbeat int64
  22. LatencyMs int
  23. XrayVersion string
  24. PanelVersion string
  25. CpuPct float64
  26. MemPct float64
  27. UptimeSecs uint64
  28. LastError string
  29. }
  30. type NodeService struct{}
  31. var nodeHTTPClient = &http.Client{
  32. Transport: &http.Transport{
  33. MaxIdleConns: 64,
  34. MaxIdleConnsPerHost: 4,
  35. IdleConnTimeout: 60 * time.Second,
  36. DialContext: netsafe.SSRFGuardedDialContext,
  37. },
  38. }
  39. func (s *NodeService) GetAll() ([]*model.Node, error) {
  40. db := database.GetDB()
  41. var nodes []*model.Node
  42. err := db.Model(model.Node{}).Order("id asc").Find(&nodes).Error
  43. if err != nil || len(nodes) == 0 {
  44. return nodes, err
  45. }
  46. type inboundRow struct {
  47. Id int
  48. NodeID int `gorm:"column:node_id"`
  49. }
  50. var inboundRows []inboundRow
  51. if err := db.Table("inbounds").
  52. Select("id, node_id").
  53. Where("node_id IS NOT NULL").
  54. Scan(&inboundRows).Error; err != nil {
  55. return nodes, nil
  56. }
  57. if len(inboundRows) == 0 {
  58. return nodes, nil
  59. }
  60. inboundsByNode := make(map[int][]int, len(nodes))
  61. nodeByInbound := make(map[int]int, len(inboundRows))
  62. for _, row := range inboundRows {
  63. inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
  64. nodeByInbound[row.Id] = row.NodeID
  65. }
  66. type clientCountRow struct {
  67. NodeID int `gorm:"column:node_id"`
  68. Count int `gorm:"column:count"`
  69. }
  70. var clientCounts []clientCountRow
  71. if err := db.Raw(`
  72. SELECT inbounds.node_id AS node_id, COUNT(DISTINCT client_inbounds.client_id) AS count
  73. FROM inbounds
  74. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  75. WHERE inbounds.node_id IS NOT NULL
  76. GROUP BY inbounds.node_id
  77. `).Scan(&clientCounts).Error; err == nil {
  78. for _, row := range clientCounts {
  79. for _, n := range nodes {
  80. if n.Id == row.NodeID {
  81. n.ClientCount = row.Count
  82. break
  83. }
  84. }
  85. }
  86. }
  87. now := time.Now().UnixMilli()
  88. type trafficRow struct {
  89. InboundID int `gorm:"column:inbound_id"`
  90. Email string
  91. Enable bool
  92. Total int64
  93. Up int64
  94. Down int64
  95. ExpiryTime int64 `gorm:"column:expiry_time"`
  96. }
  97. var trafficRows []trafficRow
  98. inboundIDs := make([]int, 0, len(nodeByInbound))
  99. for id := range nodeByInbound {
  100. inboundIDs = append(inboundIDs, id)
  101. }
  102. if err := db.Table("client_traffics").
  103. Select("inbound_id, email, enable, total, up, down, expiry_time").
  104. Where("inbound_id IN ?", inboundIDs).
  105. Scan(&trafficRows).Error; err == nil {
  106. online := make(map[string]struct{})
  107. for _, email := range s.onlineEmails() {
  108. online[email] = struct{}{}
  109. }
  110. depletedByNode := make(map[int]int)
  111. onlineByNode := make(map[int]int)
  112. for _, row := range trafficRows {
  113. nodeID, ok := nodeByInbound[row.InboundID]
  114. if !ok {
  115. continue
  116. }
  117. expired := row.ExpiryTime > 0 && row.ExpiryTime <= now
  118. exhausted := row.Total > 0 && row.Up+row.Down >= row.Total
  119. if expired || exhausted || !row.Enable {
  120. depletedByNode[nodeID]++
  121. }
  122. if _, ok := online[row.Email]; ok {
  123. onlineByNode[nodeID]++
  124. }
  125. }
  126. for _, n := range nodes {
  127. n.InboundCount = len(inboundsByNode[n.Id])
  128. n.DepletedCount = depletedByNode[n.Id]
  129. n.OnlineCount = onlineByNode[n.Id]
  130. }
  131. }
  132. return nodes, nil
  133. }
  134. func (s *NodeService) onlineEmails() []string {
  135. svc := InboundService{}
  136. return svc.GetOnlineClients()
  137. }
  138. func (s *NodeService) GetById(id int) (*model.Node, error) {
  139. db := database.GetDB()
  140. n := &model.Node{}
  141. if err := db.Model(model.Node{}).Where("id = ?", id).First(n).Error; err != nil {
  142. return nil, err
  143. }
  144. return n, nil
  145. }
  146. func normalizeBasePath(p string) string {
  147. p = strings.TrimSpace(p)
  148. if p == "" {
  149. return "/"
  150. }
  151. if !strings.HasPrefix(p, "/") {
  152. p = "/" + p
  153. }
  154. if !strings.HasSuffix(p, "/") {
  155. p = p + "/"
  156. }
  157. return p
  158. }
  159. func (s *NodeService) normalize(n *model.Node) error {
  160. n.Name = strings.TrimSpace(n.Name)
  161. n.ApiToken = strings.TrimSpace(n.ApiToken)
  162. if n.Name == "" {
  163. return common.NewError("node name is required")
  164. }
  165. addr, err := netsafe.NormalizeHost(n.Address)
  166. if err != nil {
  167. return common.NewError(err.Error())
  168. }
  169. n.Address = addr
  170. if n.Port <= 0 || n.Port > 65535 {
  171. return common.NewError("node port must be 1-65535")
  172. }
  173. if n.Scheme != "http" && n.Scheme != "https" {
  174. n.Scheme = "https"
  175. }
  176. n.BasePath = normalizeBasePath(n.BasePath)
  177. return nil
  178. }
  179. func (s *NodeService) Create(n *model.Node) error {
  180. if err := s.normalize(n); err != nil {
  181. return err
  182. }
  183. db := database.GetDB()
  184. return db.Create(n).Error
  185. }
  186. func (s *NodeService) Update(id int, in *model.Node) error {
  187. if err := s.normalize(in); err != nil {
  188. return err
  189. }
  190. db := database.GetDB()
  191. existing := &model.Node{}
  192. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  193. return err
  194. }
  195. updates := map[string]any{
  196. "name": in.Name,
  197. "remark": in.Remark,
  198. "scheme": in.Scheme,
  199. "address": in.Address,
  200. "port": in.Port,
  201. "base_path": in.BasePath,
  202. "api_token": in.ApiToken,
  203. "enable": in.Enable,
  204. "allow_private_address": in.AllowPrivateAddress,
  205. }
  206. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  207. return err
  208. }
  209. if mgr := runtime.GetManager(); mgr != nil {
  210. mgr.InvalidateNode(id)
  211. }
  212. return nil
  213. }
  214. func (s *NodeService) Delete(id int) error {
  215. db := database.GetDB()
  216. if err := db.Where("id = ?", id).Delete(model.Node{}).Error; err != nil {
  217. return err
  218. }
  219. if mgr := runtime.GetManager(); mgr != nil {
  220. mgr.InvalidateNode(id)
  221. }
  222. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  223. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  224. return nil
  225. }
  226. func (s *NodeService) SetEnable(id int, enable bool) error {
  227. db := database.GetDB()
  228. return db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error
  229. }
  230. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  231. db := database.GetDB()
  232. updates := map[string]any{
  233. "status": p.Status,
  234. "last_heartbeat": p.LastHeartbeat,
  235. "latency_ms": p.LatencyMs,
  236. "xray_version": p.XrayVersion,
  237. "panel_version": p.PanelVersion,
  238. "cpu_pct": p.CpuPct,
  239. "mem_pct": p.MemPct,
  240. "uptime_secs": p.UptimeSecs,
  241. "last_error": p.LastError,
  242. }
  243. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  244. return err
  245. }
  246. if p.Status == "online" {
  247. now := time.Unix(p.LastHeartbeat, 0)
  248. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  249. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  250. }
  251. return nil
  252. }
  253. func nodeMetricKey(id int, metric string) string {
  254. return "node:" + strconv.Itoa(id) + ":" + metric
  255. }
  256. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  257. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  258. }
  259. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  260. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  261. addr, err := netsafe.NormalizeHost(n.Address)
  262. if err != nil {
  263. patch.LastError = err.Error()
  264. return patch, err
  265. }
  266. scheme := n.Scheme
  267. if scheme != "http" && scheme != "https" {
  268. scheme = "https"
  269. }
  270. if n.Port <= 0 || n.Port > 65535 {
  271. patch.LastError = "node port must be 1-65535"
  272. return patch, errors.New(patch.LastError)
  273. }
  274. probeURL := &url.URL{
  275. Scheme: scheme,
  276. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  277. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  278. }
  279. req, err := http.NewRequestWithContext(
  280. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  281. http.MethodGet, probeURL.String(), nil)
  282. if err != nil {
  283. patch.LastError = err.Error()
  284. return patch, err
  285. }
  286. if n.ApiToken != "" {
  287. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  288. }
  289. req.Header.Set("Accept", "application/json")
  290. start := time.Now()
  291. resp, err := nodeHTTPClient.Do(req)
  292. if err != nil {
  293. patch.LastError = err.Error()
  294. return patch, err
  295. }
  296. defer resp.Body.Close()
  297. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  298. if resp.StatusCode != http.StatusOK {
  299. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  300. return patch, errors.New(patch.LastError)
  301. }
  302. var envelope struct {
  303. Success bool `json:"success"`
  304. Msg string `json:"msg"`
  305. Obj *struct {
  306. CpuPct float64 `json:"cpu"`
  307. Mem struct {
  308. Current uint64 `json:"current"`
  309. Total uint64 `json:"total"`
  310. } `json:"mem"`
  311. Xray struct {
  312. Version string `json:"version"`
  313. } `json:"xray"`
  314. PanelVersion string `json:"panelVersion"`
  315. Uptime uint64 `json:"uptime"`
  316. } `json:"obj"`
  317. }
  318. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  319. patch.LastError = "decode response: " + err.Error()
  320. return patch, err
  321. }
  322. if !envelope.Success || envelope.Obj == nil {
  323. patch.LastError = "remote returned success=false: " + envelope.Msg
  324. return patch, errors.New(patch.LastError)
  325. }
  326. o := envelope.Obj
  327. patch.CpuPct = o.CpuPct
  328. if o.Mem.Total > 0 {
  329. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  330. }
  331. patch.XrayVersion = o.Xray.Version
  332. patch.PanelVersion = o.PanelVersion
  333. patch.UptimeSecs = o.Uptime
  334. return patch, nil
  335. }
  336. type ProbeResultUI struct {
  337. Status string `json:"status"`
  338. LatencyMs int `json:"latencyMs"`
  339. XrayVersion string `json:"xrayVersion"`
  340. PanelVersion string `json:"panelVersion"`
  341. CpuPct float64 `json:"cpuPct"`
  342. MemPct float64 `json:"memPct"`
  343. UptimeSecs uint64 `json:"uptimeSecs"`
  344. Error string `json:"error"`
  345. }
  346. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  347. r := ProbeResultUI{
  348. LatencyMs: p.LatencyMs,
  349. XrayVersion: p.XrayVersion,
  350. PanelVersion: p.PanelVersion,
  351. CpuPct: p.CpuPct,
  352. MemPct: p.MemPct,
  353. UptimeSecs: p.UptimeSecs,
  354. Error: p.LastError,
  355. }
  356. if ok {
  357. r.Status = "online"
  358. } else {
  359. r.Status = "offline"
  360. }
  361. return r
  362. }