node.go 12 KB

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