1
0

node.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  231. // node so the UI can show per-node success/failure for a bulk request.
  232. type NodeUpdateResult struct {
  233. Id int `json:"id"`
  234. Name string `json:"name"`
  235. OK bool `json:"ok"`
  236. Error string `json:"error,omitempty"`
  237. }
  238. // UpdatePanels triggers the official self-updater on each given node. Only
  239. // enabled, online nodes are eligible — an offline node can't be reached, so it
  240. // is reported as skipped rather than silently dropped.
  241. func (s *NodeService) UpdatePanels(ids []int) ([]NodeUpdateResult, error) {
  242. mgr := runtime.GetManager()
  243. if mgr == nil {
  244. return nil, fmt.Errorf("runtime manager unavailable")
  245. }
  246. results := make([]NodeUpdateResult, 0, len(ids))
  247. for _, id := range ids {
  248. n, err := s.GetById(id)
  249. if err != nil || n == nil {
  250. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  251. continue
  252. }
  253. res := NodeUpdateResult{Id: id, Name: n.Name}
  254. switch {
  255. case !n.Enable:
  256. res.Error = "node is disabled"
  257. case n.Status != "online":
  258. res.Error = "node is offline"
  259. default:
  260. remote, remoteErr := mgr.RemoteFor(n)
  261. if remoteErr != nil {
  262. res.Error = remoteErr.Error()
  263. break
  264. }
  265. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  266. updErr := remote.UpdatePanel(ctx)
  267. cancel()
  268. if updErr != nil {
  269. res.Error = updErr.Error()
  270. } else {
  271. res.OK = true
  272. }
  273. }
  274. results = append(results, res)
  275. }
  276. return results, nil
  277. }
  278. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  279. db := database.GetDB()
  280. updates := map[string]any{
  281. "status": p.Status,
  282. "last_heartbeat": p.LastHeartbeat,
  283. "latency_ms": p.LatencyMs,
  284. "xray_version": p.XrayVersion,
  285. "panel_version": p.PanelVersion,
  286. "cpu_pct": p.CpuPct,
  287. "mem_pct": p.MemPct,
  288. "uptime_secs": p.UptimeSecs,
  289. "last_error": p.LastError,
  290. }
  291. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  292. return err
  293. }
  294. if p.Status == "online" {
  295. now := time.Unix(p.LastHeartbeat, 0)
  296. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  297. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  298. }
  299. return nil
  300. }
  301. func nodeMetricKey(id int, metric string) string {
  302. return "node:" + strconv.Itoa(id) + ":" + metric
  303. }
  304. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  305. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  306. }
  307. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  308. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  309. addr, err := netsafe.NormalizeHost(n.Address)
  310. if err != nil {
  311. patch.LastError = err.Error()
  312. return patch, err
  313. }
  314. scheme := n.Scheme
  315. if scheme != "http" && scheme != "https" {
  316. scheme = "https"
  317. }
  318. if n.Port <= 0 || n.Port > 65535 {
  319. patch.LastError = "node port must be 1-65535"
  320. return patch, errors.New(patch.LastError)
  321. }
  322. probeURL := &url.URL{
  323. Scheme: scheme,
  324. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  325. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  326. }
  327. req, err := http.NewRequestWithContext(
  328. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  329. http.MethodGet, probeURL.String(), nil)
  330. if err != nil {
  331. patch.LastError = err.Error()
  332. return patch, err
  333. }
  334. if n.ApiToken != "" {
  335. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  336. }
  337. req.Header.Set("Accept", "application/json")
  338. start := time.Now()
  339. resp, err := nodeHTTPClient.Do(req)
  340. if err != nil {
  341. patch.LastError = err.Error()
  342. return patch, err
  343. }
  344. defer resp.Body.Close()
  345. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  346. if resp.StatusCode != http.StatusOK {
  347. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  348. return patch, errors.New(patch.LastError)
  349. }
  350. var envelope struct {
  351. Success bool `json:"success"`
  352. Msg string `json:"msg"`
  353. Obj *struct {
  354. CpuPct float64 `json:"cpu"`
  355. Mem struct {
  356. Current uint64 `json:"current"`
  357. Total uint64 `json:"total"`
  358. } `json:"mem"`
  359. Xray struct {
  360. Version string `json:"version"`
  361. } `json:"xray"`
  362. PanelVersion string `json:"panelVersion"`
  363. Uptime uint64 `json:"uptime"`
  364. } `json:"obj"`
  365. }
  366. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  367. patch.LastError = "decode response: " + err.Error()
  368. return patch, err
  369. }
  370. if !envelope.Success || envelope.Obj == nil {
  371. patch.LastError = "remote returned success=false: " + envelope.Msg
  372. return patch, errors.New(patch.LastError)
  373. }
  374. o := envelope.Obj
  375. patch.CpuPct = o.CpuPct
  376. if o.Mem.Total > 0 {
  377. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  378. }
  379. patch.XrayVersion = o.Xray.Version
  380. patch.PanelVersion = o.PanelVersion
  381. patch.UptimeSecs = o.Uptime
  382. return patch, nil
  383. }
  384. type ProbeResultUI struct {
  385. Status string `json:"status"`
  386. LatencyMs int `json:"latencyMs"`
  387. XrayVersion string `json:"xrayVersion"`
  388. PanelVersion string `json:"panelVersion"`
  389. CpuPct float64 `json:"cpuPct"`
  390. MemPct float64 `json:"memPct"`
  391. UptimeSecs uint64 `json:"uptimeSecs"`
  392. Error string `json:"error"`
  393. }
  394. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  395. r := ProbeResultUI{
  396. LatencyMs: p.LatencyMs,
  397. XrayVersion: p.XrayVersion,
  398. PanelVersion: p.PanelVersion,
  399. CpuPct: p.CpuPct,
  400. MemPct: p.MemPct,
  401. UptimeSecs: p.UptimeSecs,
  402. Error: p.LastError,
  403. }
  404. if ok {
  405. r.Status = "online"
  406. } else {
  407. r.Status = "offline"
  408. }
  409. return r
  410. }