node.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. package service
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/tls"
  6. "encoding/base64"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "slices"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/mhsanaei/3x-ui/v3/internal/database"
  19. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  20. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  21. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  22. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  23. "github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
  24. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  25. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  26. "gorm.io/gorm"
  27. )
  28. type HeartbeatPatch struct {
  29. Status string
  30. LastHeartbeat int64
  31. LatencyMs int
  32. XrayVersion string
  33. PanelVersion string
  34. Guid string
  35. CpuPct float64
  36. MemPct float64
  37. UptimeSecs uint64
  38. // NetUp/NetDown are the node's current interface throughput (bytes/sec),
  39. // summed over non-virtual interfaces, read from its status response.
  40. NetUp uint64
  41. NetDown uint64
  42. LastError string
  43. // XrayState and XrayError come from the remote /panel/api/server/status when the
  44. // panel API is reachable. They allow distinguishing panel connectivity from
  45. // Xray core health on the node.
  46. XrayState string
  47. XrayError string
  48. }
  49. type NodeService struct{}
  50. // FetchCertFingerprint connects to the node over HTTPS without verifying the
  51. // certificate and returns the leaf certificate's SHA-256 as base64, so the UI
  52. // can offer a "fetch and pin current certificate" action.
  53. func (s *NodeService) FetchCertFingerprint(ctx context.Context, n *model.Node) (string, error) {
  54. addr, err := netsafe.NormalizeHost(n.Address)
  55. if err != nil {
  56. return "", err
  57. }
  58. scheme := n.Scheme
  59. if scheme != "http" && scheme != "https" {
  60. scheme = "https"
  61. }
  62. if scheme != "https" {
  63. return "", common.NewError("certificate pinning is only available for https nodes")
  64. }
  65. if n.Port <= 0 || n.Port > 65535 {
  66. return "", common.NewError("node port must be 1-65535")
  67. }
  68. probeURL := &url.URL{
  69. Scheme: scheme,
  70. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  71. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  72. }
  73. req, err := http.NewRequestWithContext(
  74. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  75. http.MethodGet, probeURL.String(), nil)
  76. if err != nil {
  77. return "", err
  78. }
  79. client := &http.Client{
  80. Transport: &http.Transport{
  81. DialContext: netsafe.SSRFGuardedDialContext,
  82. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // lgtm[go/disabled-certificate-check]
  83. },
  84. }
  85. resp, err := client.Do(req)
  86. if err != nil {
  87. return "", err
  88. }
  89. defer resp.Body.Close()
  90. if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
  91. return "", common.NewError("node did not present a TLS certificate")
  92. }
  93. sum := sha256.Sum256(resp.TLS.PeerCertificates[0].Raw)
  94. return base64.StdEncoding.EncodeToString(sum[:]), nil
  95. }
  96. func (s *NodeService) GetAll() ([]*model.Node, error) {
  97. db := database.GetDB()
  98. var nodes []*model.Node
  99. err := db.Model(model.Node{}).Order("id asc").Find(&nodes).Error
  100. if err != nil || len(nodes) == 0 {
  101. return nodes, err
  102. }
  103. type inboundRow struct {
  104. Id int
  105. NodeID int `gorm:"column:node_id"`
  106. }
  107. var inboundRows []inboundRow
  108. if err := db.Table("inbounds").
  109. Select("id, node_id").
  110. Where("node_id IS NOT NULL").
  111. Scan(&inboundRows).Error; err != nil {
  112. return nodes, nil
  113. }
  114. if len(inboundRows) == 0 {
  115. return nodes, nil
  116. }
  117. inboundsByNode := make(map[int][]int, len(nodes))
  118. for _, row := range inboundRows {
  119. inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
  120. }
  121. type clientCountRow struct {
  122. NodeID int `gorm:"column:node_id"`
  123. Count int `gorm:"column:count"`
  124. }
  125. var clientCounts []clientCountRow
  126. if err := db.Raw(`
  127. SELECT inbounds.node_id AS node_id, COUNT(DISTINCT client_inbounds.client_id) AS count
  128. FROM inbounds
  129. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  130. WHERE inbounds.node_id IS NOT NULL
  131. GROUP BY inbounds.node_id
  132. `).Scan(&clientCounts).Error; err == nil {
  133. for _, row := range clientCounts {
  134. for _, n := range nodes {
  135. if n.Id == row.NodeID {
  136. n.ClientCount = row.Count
  137. break
  138. }
  139. }
  140. }
  141. }
  142. depletedByNode := make(map[int]int)
  143. disabledByNode := make(map[int]int)
  144. activeByNode := make(map[int]int)
  145. statuses, _ := s.nodeClientStatuses()
  146. seen := make(map[int]map[int]struct{}, len(nodes))
  147. for _, st := range statuses {
  148. clientsSeen := seen[st.NodeID]
  149. if clientsSeen == nil {
  150. clientsSeen = make(map[int]struct{})
  151. seen[st.NodeID] = clientsSeen
  152. }
  153. if _, dup := clientsSeen[st.ClientID]; dup {
  154. // A client attached to several inbounds of one node counts once,
  155. // matching the distinct ClientCount above.
  156. continue
  157. }
  158. clientsSeen[st.ClientID] = struct{}{}
  159. switch {
  160. case st.Depleted:
  161. depletedByNode[st.NodeID]++
  162. case st.Disabled:
  163. disabledByNode[st.NodeID]++
  164. default:
  165. activeByNode[st.NodeID]++
  166. }
  167. }
  168. onlineByGuid := s.onlineEmailsByGuid()
  169. selfGuid, _ := (&SettingService{}).GetPanelGuid()
  170. ambiguous := ambiguousNodeGuids(nodes, selfGuid)
  171. for _, n := range nodes {
  172. n.InboundCount = len(inboundsByNode[n.Id])
  173. n.DepletedCount = depletedByNode[n.Id]
  174. n.DisabledCount = disabledByNode[n.Id]
  175. n.ActiveCount = activeByNode[n.Id]
  176. // Online is attributed to the node that physically hosts the client
  177. // (by GUID): a client on a sub-node counts under the sub-node, not
  178. // the intermediate node it syncs through (#4983).
  179. n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n, ambiguous)])
  180. }
  181. return nodes, nil
  182. }
  183. // nodeClientStatus is one node-hosted client's classification, carrying enough
  184. // identity for callers to bucket it by node id or by attribution GUID.
  185. type nodeClientStatus struct {
  186. InboundID int
  187. NodeID int
  188. ClientID int
  189. Depleted bool
  190. Disabled bool
  191. }
  192. // nodeClientStatuses classifies every client attached to a node-hosted inbound as
  193. // depleted / disabled / active, matching client_traffics by EMAIL rather than by
  194. // inbound_id. client_traffics.inbound_id goes stale after an inbound is
  195. // delete+recreated, so filtering by it silently drops most rows; the
  196. // client_inbounds -> clients join is the reliable client set and the email join
  197. // pulls each client's live counters. Precedence matches the inbound page:
  198. // depleted (expired/exhausted) wins over disabled.
  199. func (s *NodeService) nodeClientStatuses() ([]nodeClientStatus, error) {
  200. type row struct {
  201. InboundID int `gorm:"column:inbound_id"`
  202. NodeID int `gorm:"column:node_id"`
  203. ClientID int `gorm:"column:client_id"`
  204. Enable bool `gorm:"column:enable"`
  205. Total int64 `gorm:"column:total"`
  206. Up int64 `gorm:"column:up"`
  207. Down int64 `gorm:"column:down"`
  208. ExpiryTime int64 `gorm:"column:expiry_time"`
  209. }
  210. var rows []row
  211. if err := database.GetDB().Table("inbounds").
  212. Select("inbounds.id AS inbound_id, inbounds.node_id AS node_id, clients.id AS client_id, " +
  213. "clients.enable AS enable, ct.total AS total, ct.up AS up, ct.down AS down, ct.expiry_time AS expiry_time").
  214. Joins("JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id").
  215. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  216. Joins("LEFT JOIN client_traffics ct ON ct.email = clients.email").
  217. Where("inbounds.node_id IS NOT NULL").
  218. Scan(&rows).Error; err != nil {
  219. return nil, err
  220. }
  221. now := time.Now().UnixMilli()
  222. out := make([]nodeClientStatus, 0, len(rows))
  223. for _, r := range rows {
  224. st := nodeClientStatus{InboundID: r.InboundID, NodeID: r.NodeID, ClientID: r.ClientID}
  225. expired := r.ExpiryTime > 0 && r.ExpiryTime <= now
  226. exhausted := r.Total > 0 && r.Up+r.Down >= r.Total
  227. switch {
  228. case expired || exhausted:
  229. st.Depleted = true
  230. case !r.Enable:
  231. st.Disabled = true
  232. }
  233. out = append(out, st)
  234. }
  235. return out, nil
  236. }
  237. func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
  238. svc := InboundService{}
  239. byGuid := svc.GetOnlineClientsByGuid()
  240. out := make(map[string]map[string]struct{}, len(byGuid))
  241. for guid, emails := range byGuid {
  242. set := make(map[string]struct{}, len(emails))
  243. for _, email := range emails {
  244. set[email] = struct{}{}
  245. }
  246. out[guid] = set
  247. }
  248. return out
  249. }
  250. // effectiveNodeGuid is a node's stable online/inbound attribution key: its
  251. // reported panelGuid, or a master-local synthetic node-id fallback when the node
  252. // has no GUID yet (old build) or its GUID is ambiguous. ambiguous comes from
  253. // ambiguousNodeGuids.
  254. func effectiveNodeGuid(n *model.Node, ambiguous map[string]struct{}) string {
  255. if n.Guid == "" {
  256. return synthNodeGuid(n.Id)
  257. }
  258. if n.Id > 0 {
  259. if _, bad := ambiguous[n.Guid]; bad {
  260. return synthNodeGuid(n.Id)
  261. }
  262. }
  263. return n.Guid
  264. }
  265. // ambiguousNodeGuids returns the panelGuids a node must not be attributed under
  266. // directly, because doing so would merge two distinct identities: a GUID
  267. // reported by more than one of this master's direct nodes (cloned node servers
  268. // ship the same panelGuid in their copied settings), or a GUID equal to the
  269. // master's own panelGuid (a node cloned from the master). A node holding such a
  270. // GUID falls back to its node-unique synthNodeGuid. Transitive sub-nodes (Id 0)
  271. // carry distinct descendant GUIDs by construction and are excluded.
  272. func ambiguousNodeGuids(nodes []*model.Node, selfGuid string) map[string]struct{} {
  273. counts := make(map[string]int, len(nodes))
  274. for _, n := range nodes {
  275. if n.Id > 0 && n.Guid != "" {
  276. counts[n.Guid]++
  277. }
  278. }
  279. ambiguous := make(map[string]struct{})
  280. for guid, c := range counts {
  281. if c > 1 {
  282. ambiguous[guid] = struct{}{}
  283. }
  284. }
  285. if selfGuid != "" {
  286. if _, ok := counts[selfGuid]; ok {
  287. ambiguous[selfGuid] = struct{}{}
  288. }
  289. }
  290. return ambiguous
  291. }
  292. // effectiveNodeKey returns one node's attribution key without a preloaded node
  293. // list — its panelGuid when that GUID uniquely identifies it among the master's
  294. // nodes and differs from the master's own, otherwise its node-unique
  295. // synthNodeGuid. Same rule as effectiveNodeGuid + ambiguousNodeGuids, for the
  296. // write paths that handle a single node (online tree, IP attribution).
  297. func effectiveNodeKey(node *model.Node) string {
  298. if node == nil {
  299. return ""
  300. }
  301. if node.Guid == "" {
  302. return synthNodeGuid(node.Id)
  303. }
  304. var sameGuid int64
  305. database.GetDB().Model(&model.Node{}).Where("guid = ?", node.Guid).Count(&sameGuid)
  306. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  307. if sameGuid > 1 || node.Guid == masterGuid {
  308. return synthNodeGuid(node.Id)
  309. }
  310. return node.Guid
  311. }
  312. func (s *NodeService) GetById(id int) (*model.Node, error) {
  313. db := database.GetDB()
  314. n := &model.Node{}
  315. if err := db.Model(model.Node{}).Where("id = ?", id).First(n).Error; err != nil {
  316. return nil, err
  317. }
  318. return n, nil
  319. }
  320. func (s *NodeService) GetViewById(id int) (*NodeView, error) {
  321. n, err := s.GetById(id)
  322. if err != nil {
  323. return nil, err
  324. }
  325. return toNodeView(n), nil
  326. }
  327. // NodeExists reports whether a node with the given id exists on this panel.
  328. // Used to drop stale, cross-panel node references on inbound import. A Count
  329. // query distinguishes "no such node" (count 0, no error) from a real DB error.
  330. func (s *NodeService) NodeExists(id int) (bool, error) {
  331. if id <= 0 {
  332. return false, nil
  333. }
  334. var count int64
  335. if err := database.GetDB().Model(model.Node{}).Where("id = ?", id).Count(&count).Error; err != nil {
  336. return false, err
  337. }
  338. return count > 0, nil
  339. }
  340. func normalizeBasePath(p string) string {
  341. p = strings.TrimSpace(p)
  342. if p == "" {
  343. return "/"
  344. }
  345. if !strings.HasPrefix(p, "/") {
  346. p = "/" + p
  347. }
  348. if !strings.HasSuffix(p, "/") {
  349. p = p + "/"
  350. }
  351. return p
  352. }
  353. func (s *NodeService) normalize(n *model.Node) error {
  354. n.Name = strings.TrimSpace(n.Name)
  355. n.ApiToken = strings.TrimSpace(n.ApiToken)
  356. if n.Name == "" {
  357. return common.NewError("node name is required")
  358. }
  359. addr, err := netsafe.NormalizeHost(n.Address)
  360. if err != nil {
  361. return common.NewError(err.Error())
  362. }
  363. n.Address = addr
  364. if n.Port <= 0 || n.Port > 65535 {
  365. return common.NewError("node port must be 1-65535")
  366. }
  367. if n.Scheme != "http" && n.Scheme != "https" {
  368. n.Scheme = "https"
  369. }
  370. if n.TlsVerifyMode != "skip" && n.TlsVerifyMode != "pin" && n.TlsVerifyMode != "mtls" {
  371. n.TlsVerifyMode = "verify"
  372. }
  373. if n.TlsVerifyMode == "mtls" && n.Scheme != "https" {
  374. return common.NewError("mtls requires the node scheme to be https")
  375. }
  376. n.PinnedCertSha256 = strings.TrimSpace(n.PinnedCertSha256)
  377. if n.InboundSyncMode != "selected" {
  378. n.InboundSyncMode = "all"
  379. n.InboundTags = nil
  380. } else {
  381. seen := make(map[string]struct{}, len(n.InboundTags))
  382. tags := make([]string, 0, len(n.InboundTags))
  383. for _, tag := range n.InboundTags {
  384. tag = strings.TrimSpace(tag)
  385. if tag == "" {
  386. continue
  387. }
  388. if _, ok := seen[tag]; ok {
  389. continue
  390. }
  391. seen[tag] = struct{}{}
  392. tags = append(tags, tag)
  393. }
  394. n.InboundTags = tags
  395. }
  396. if n.TlsVerifyMode == "pin" {
  397. if _, err := runtime.DecodeCertPin(n.PinnedCertSha256); err != nil {
  398. return common.NewError(err.Error())
  399. }
  400. }
  401. n.BasePath = normalizeBasePath(n.BasePath)
  402. return nil
  403. }
  404. func (s *NodeService) Create(n *model.Node) error {
  405. if err := s.normalize(n); err != nil {
  406. return err
  407. }
  408. db := database.GetDB()
  409. return db.Create(n).Error
  410. }
  411. func (s *NodeService) CreateFromRequest(req *NodeMutationRequest) (*NodeView, error) {
  412. if err := req.validateCredentials(true); err != nil {
  413. return nil, err
  414. }
  415. n := req.toNode()
  416. if err := s.Create(n); err != nil {
  417. return nil, err
  418. }
  419. return toNodeView(n), nil
  420. }
  421. func (s *NodeService) Update(id int, in *model.Node) error {
  422. if err := s.normalize(in); err != nil {
  423. return err
  424. }
  425. inboundTagsJSON, err := json.Marshal(in.InboundTags)
  426. if err != nil {
  427. return err
  428. }
  429. db := database.GetDB()
  430. existing := &model.Node{}
  431. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  432. return err
  433. }
  434. updates := map[string]any{
  435. "name": in.Name,
  436. "remark": in.Remark,
  437. "scheme": in.Scheme,
  438. "address": in.Address,
  439. "port": in.Port,
  440. "base_path": in.BasePath,
  441. "api_token": in.ApiToken,
  442. "enable": in.Enable,
  443. "allow_private_address": in.AllowPrivateAddress,
  444. "tls_verify_mode": in.TlsVerifyMode,
  445. "pinned_cert_sha256": in.PinnedCertSha256,
  446. "inbound_sync_mode": in.InboundSyncMode,
  447. "inbound_tags": string(inboundTagsJSON),
  448. "outbound_tag": in.OutboundTag,
  449. }
  450. if err := db.Transaction(func(tx *gorm.DB) error {
  451. if err := tx.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  452. return err
  453. }
  454. return s.MarkNodeDirtyTx(tx, id)
  455. }); err != nil {
  456. return err
  457. }
  458. if mgr := runtime.GetManager(); mgr != nil {
  459. mgr.InvalidateNode(id)
  460. }
  461. return nil
  462. }
  463. func (s *NodeService) UpdateFromRequest(id int, req *NodeMutationRequest) error {
  464. if err := req.validateCredentials(false); err != nil {
  465. return err
  466. }
  467. in := req.toNode()
  468. if err := s.normalize(in); err != nil {
  469. return err
  470. }
  471. inboundTagsJSON, err := json.Marshal(in.InboundTags)
  472. if err != nil {
  473. return err
  474. }
  475. db := database.GetDB()
  476. existing := &model.Node{}
  477. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  478. return err
  479. }
  480. apiToken := existing.ApiToken
  481. switch {
  482. case req.ClearApiToken:
  483. apiToken = ""
  484. case req.ApiToken != nil:
  485. apiToken = *req.ApiToken
  486. }
  487. if apiToken == "" && in.Enable && in.TlsVerifyMode != "mtls" {
  488. return common.NewError("apiToken is required unless mtls is enabled")
  489. }
  490. updates := map[string]any{
  491. "name": in.Name,
  492. "remark": in.Remark,
  493. "scheme": in.Scheme,
  494. "address": in.Address,
  495. "port": in.Port,
  496. "base_path": in.BasePath,
  497. "api_token": apiToken,
  498. "enable": in.Enable,
  499. "allow_private_address": in.AllowPrivateAddress,
  500. "tls_verify_mode": in.TlsVerifyMode,
  501. "pinned_cert_sha256": in.PinnedCertSha256,
  502. "inbound_sync_mode": in.InboundSyncMode,
  503. "inbound_tags": string(inboundTagsJSON),
  504. "outbound_tag": in.OutboundTag,
  505. }
  506. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  507. return err
  508. }
  509. if dErr := s.MarkNodeDirty(id); dErr != nil {
  510. logger.Warning("mark node dirty after update failed:", dErr)
  511. }
  512. if mgr := runtime.GetManager(); mgr != nil {
  513. mgr.InvalidateNode(id)
  514. }
  515. return nil
  516. }
  517. func (s *NodeService) RuntimeNodeFromRequest(id int, req *NodeMutationRequest) (*model.Node, error) {
  518. if err := req.validateCredentials(id == 0); err != nil {
  519. return nil, err
  520. }
  521. var n *model.Node
  522. if id > 0 {
  523. existing, err := s.GetById(id)
  524. if err != nil {
  525. return nil, err
  526. }
  527. n = existing
  528. } else {
  529. n = &model.Node{}
  530. }
  531. overlay := req.toNode()
  532. overlay.Id = id
  533. if req.ApiToken == nil {
  534. overlay.ApiToken = n.ApiToken
  535. }
  536. if req.ClearApiToken {
  537. overlay.ApiToken = ""
  538. }
  539. *n = *overlay
  540. if err := s.normalize(n); err != nil {
  541. return nil, err
  542. }
  543. if n.ApiToken == "" && n.Enable && n.TlsVerifyMode != "mtls" {
  544. return nil, common.NewError("apiToken is required unless mtls is enabled")
  545. }
  546. return n, nil
  547. }
  548. func (s *NodeService) NodeFromRequestForCertificate(req *NodeMutationRequest) (*model.Node, error) {
  549. if req == nil {
  550. return nil, common.NewError("node request is required")
  551. }
  552. n := req.toNode()
  553. if n.Scheme == "" {
  554. n.Scheme = "https"
  555. }
  556. if n.BasePath == "" {
  557. n.BasePath = "/"
  558. }
  559. if err := s.normalize(n); err != nil {
  560. return nil, err
  561. }
  562. return n, nil
  563. }
  564. func (s *NodeService) GetRemoteInboundOptions(ctx context.Context, n *model.Node) ([]runtime.RemoteInboundOption, error) {
  565. if err := s.normalize(n); err != nil {
  566. return nil, err
  567. }
  568. if n.OutboundTag == "" {
  569. return runtime.NewRemote(n, nil).ListInboundOptions(ctx)
  570. }
  571. // Mirror ProbeWithOutbound: a node being added/edited has no persistent
  572. // egress bridge yet, so route the list call through a temporary one or the
  573. // remote panel stays unreachable and the request times out.
  574. var options []runtime.RemoteInboundOption
  575. var err error
  576. s.withOutboundBridge(n.Id, n.OutboundTag, func(proxyURL string) {
  577. options, err = runtime.NewRemote(n, staticEgressResolver(proxyURL)).ListInboundOptions(ctx)
  578. })
  579. return options, err
  580. }
  581. // staticEgressResolver hands a fixed proxy URL to runtime.NewRemote. An empty
  582. // string yields a direct connection, so it doubles as the graceful fallback
  583. // when a temporary bridge can't be built.
  584. type staticEgressResolver string
  585. func (r staticEgressResolver) NodeEgressProxyURL(int) string { return string(r) }
  586. // EnsureInboundTagAllowed adds a panel-managed inbound's tag to the node's
  587. // selection when the node syncs in "selected" mode. Without it, the next
  588. // traffic sync would filter the tag out of the snapshot and the orphan sweep
  589. // would silently delete the central row the panel just created or renamed.
  590. // Tags are only ever added (never removed): on a rename the node may keep
  591. // reporting the old tag until the remote update lands, and a leftover entry
  592. // that matches nothing is harmless.
  593. func (s *NodeService) EnsureInboundTagAllowed(nodeID int, tag string) error {
  594. return s.EnsureInboundTagAllowedTx(database.GetDB(), nodeID, tag)
  595. }
  596. func (s *NodeService) EnsureInboundTagAllowedTx(tx *gorm.DB, nodeID int, tag string) error {
  597. tag = strings.TrimSpace(tag)
  598. if nodeID <= 0 || tag == "" {
  599. return nil
  600. }
  601. if tx == nil {
  602. tx = database.GetDB()
  603. }
  604. node := &model.Node{}
  605. if err := tx.Where("id = ?", nodeID).First(node).Error; err != nil {
  606. return err
  607. }
  608. if node.InboundSyncMode != "selected" {
  609. return nil
  610. }
  611. if slices.Contains(node.InboundTags, tag) {
  612. return nil
  613. }
  614. buf, err := json.Marshal(append(node.InboundTags, tag))
  615. if err != nil {
  616. return err
  617. }
  618. return tx.Model(model.Node{}).Where("id = ?", nodeID).
  619. Updates(map[string]any{"inbound_tags": string(buf)}).Error
  620. }
  621. func nodeSelectedTagSet(n *model.Node) map[string]struct{} {
  622. if n == nil || n.InboundSyncMode != "selected" {
  623. return nil
  624. }
  625. prefix := nodeTagPrefix(&n.Id)
  626. allowed := make(map[string]struct{}, len(n.InboundTags)*2)
  627. for _, tag := range n.InboundTags {
  628. allowed[tag] = struct{}{}
  629. if prefix != "" {
  630. if stripped, found := strings.CutPrefix(tag, prefix); found {
  631. allowed[stripped] = struct{}{}
  632. } else {
  633. allowed[prefix+tag] = struct{}{}
  634. }
  635. }
  636. }
  637. return allowed
  638. }
  639. // A deselected tag is still served by the node — FilterNodeSnapshot just stops
  640. // reporting it — so its absence must never be read as "the node deleted it".
  641. func unmanagedTagPredicate(n *model.Node) func(string) bool {
  642. managed := nodeSelectedTagSet(n)
  643. if managed == nil {
  644. return func(string) bool { return false }
  645. }
  646. return func(tag string) bool {
  647. _, ok := managed[tag]
  648. return !ok
  649. }
  650. }
  651. func FilterNodeSnapshot(n *model.Node, snap *runtime.TrafficSnapshot) {
  652. if n == nil || snap == nil || n.InboundSyncMode != "selected" {
  653. return
  654. }
  655. allowed := nodeSelectedTagSet(n)
  656. filtered := make([]*model.Inbound, 0, len(snap.Inbounds))
  657. for _, inbound := range snap.Inbounds {
  658. if inbound == nil {
  659. continue
  660. }
  661. if _, ok := allowed[inbound.Tag]; ok {
  662. filtered = append(filtered, inbound)
  663. }
  664. }
  665. snap.Inbounds = filtered
  666. }
  667. func (s *NodeService) Delete(id int) error {
  668. db := database.GetDB()
  669. // Refuse to delete a node that still owns inbounds: dropping the node row
  670. // while inbounds keep its node_id leaves orphaned, dangling references that
  671. // confuse node sync, subscriptions and cleanup. The operator must detach or
  672. // remove those inbounds first. (DB-002)
  673. var attached int64
  674. if err := db.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil {
  675. return err
  676. }
  677. if attached > 0 {
  678. return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached))
  679. }
  680. // Capture the node's guid before deleting the row so we can drop its per-node
  681. // IP attribution. NodeClientIp is keyed by the node's attribution key, which
  682. // is its guid normally but its node-unique key for a cloned/ambiguous-guid
  683. // node (see effectiveNodeKey) — so we purge both below.
  684. var guid string
  685. var n model.Node
  686. if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil {
  687. guid = n.Guid
  688. }
  689. // Delete the node row and its per-node child rows atomically. Remove the
  690. // children (traffic baselines, IP attribution) before the parent node row so
  691. // the ordering already matches a future ON DELETE constraint. Delete stays
  692. // tolerant of a missing node row so it can still clean up orphaned baselines.
  693. if err := db.Transaction(func(tx *gorm.DB) error {
  694. if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  695. return err
  696. }
  697. guids := []string{synthNodeGuid(id)}
  698. if guid != "" {
  699. guids = append(guids, guid)
  700. }
  701. if err := tx.Where("node_guid IN ?", guids).Delete(&model.NodeClientIp{}).Error; err != nil {
  702. return err
  703. }
  704. return tx.Where("id = ?", id).Delete(&model.Node{}).Error
  705. }); err != nil {
  706. return err
  707. }
  708. if mgr := runtime.GetManager(); mgr != nil {
  709. mgr.InvalidateNode(id)
  710. }
  711. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  712. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  713. return nil
  714. }
  715. func (s *NodeService) SetEnable(id int, enable bool) error {
  716. db := database.GetDB()
  717. if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil {
  718. return err
  719. }
  720. if mgr := runtime.GetManager(); mgr != nil {
  721. mgr.InvalidateNode(id)
  722. }
  723. return nil
  724. }
  725. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  726. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  727. // exist on the node rather than the central panel. See issue #4854.
  728. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  729. n, err := s.GetById(id)
  730. if err != nil || n == nil {
  731. return nil, fmt.Errorf("node not found")
  732. }
  733. if !n.Enable {
  734. return nil, fmt.Errorf("node is disabled")
  735. }
  736. mgr := runtime.GetManager()
  737. if mgr == nil {
  738. return nil, fmt.Errorf("runtime manager unavailable")
  739. }
  740. remote, err := mgr.RemoteFor(n)
  741. if err != nil {
  742. return nil, err
  743. }
  744. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  745. defer cancel()
  746. return remote.GetWebCertFiles(ctx)
  747. }
  748. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  749. // node so the UI can show per-node success/failure for a bulk request.
  750. type NodeUpdateResult struct {
  751. Id int `json:"id"`
  752. Name string `json:"name"`
  753. OK bool `json:"ok"`
  754. Error string `json:"error,omitempty"`
  755. }
  756. // UpdatePanels triggers the official self-updater on each given node. Only
  757. // enabled, online nodes are eligible — an offline node can't be reached, so it
  758. // is reported as skipped rather than silently dropped.
  759. func (s *NodeService) UpdatePanels(ids []int, dev bool) ([]NodeUpdateResult, error) {
  760. mgr := runtime.GetManager()
  761. if mgr == nil {
  762. return nil, fmt.Errorf("runtime manager unavailable")
  763. }
  764. results := make([]NodeUpdateResult, 0, len(ids))
  765. for _, id := range ids {
  766. n, err := s.GetById(id)
  767. if err != nil || n == nil {
  768. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  769. continue
  770. }
  771. res := NodeUpdateResult{Id: id, Name: n.Name}
  772. switch {
  773. case !n.Enable:
  774. res.Error = "node is disabled"
  775. case n.Status != "online":
  776. res.Error = "node is offline"
  777. default:
  778. remote, remoteErr := mgr.RemoteFor(n)
  779. if remoteErr != nil {
  780. res.Error = remoteErr.Error()
  781. break
  782. }
  783. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  784. updErr := remote.UpdatePanel(ctx, dev)
  785. cancel()
  786. if updErr != nil {
  787. res.Error = updErr.Error()
  788. } else {
  789. res.OK = true
  790. }
  791. }
  792. results = append(results, res)
  793. }
  794. return results, nil
  795. }
  796. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  797. db := database.GetDB()
  798. updates := map[string]any{
  799. "status": p.Status,
  800. "last_heartbeat": p.LastHeartbeat,
  801. "latency_ms": p.LatencyMs,
  802. "xray_version": p.XrayVersion,
  803. "panel_version": p.PanelVersion,
  804. "cpu_pct": p.CpuPct,
  805. "mem_pct": p.MemPct,
  806. "uptime_secs": p.UptimeSecs,
  807. "net_up": p.NetUp,
  808. "net_down": p.NetDown,
  809. "last_error": p.LastError,
  810. "xray_state": p.XrayState,
  811. "xray_error": p.XrayError,
  812. }
  813. // Only learn the GUID; never clear a known one if an old-build node (or a
  814. // failed probe) reports none, so the stable identity survives blips.
  815. if p.Guid != "" {
  816. updates["guid"] = p.Guid
  817. s.warnOnDuplicateGuid(id, p.Guid)
  818. }
  819. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  820. return err
  821. }
  822. if p.Status == "online" {
  823. now := time.Unix(p.LastHeartbeat, 0)
  824. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  825. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  826. nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
  827. nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
  828. }
  829. return nil
  830. }
  831. // warnedDupGuid remembers the (nodeID -> guid) pairs already warned about so a
  832. // cloned-server collision is logged once, not every heartbeat.
  833. var warnedDupGuid sync.Map
  834. // warnOnDuplicateGuid logs once when a node reports a panelGuid already held by
  835. // another node or by the master itself (the cloned-server footgun). Attribution
  836. // still works — it falls back to node-unique keys — but the operator should
  837. // regenerate the duplicate panelGuid to restore real identity and per-node IP
  838. // attribution. Re-arms if the collision later clears.
  839. func (s *NodeService) warnOnDuplicateGuid(id int, guid string) {
  840. var clash int64
  841. database.GetDB().Model(&model.Node{}).Where("guid = ? AND id <> ?", guid, id).Count(&clash)
  842. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  843. if clash == 0 && guid != masterGuid {
  844. warnedDupGuid.Delete(id)
  845. return
  846. }
  847. if prev, ok := warnedDupGuid.Load(id); ok && prev == guid {
  848. return
  849. }
  850. warnedDupGuid.Store(id, guid)
  851. logger.Warningf("node %d reports panelGuid %s already used by another node or the master (cloned server?) — regenerate it on that node so online and IP attribution stay per-node", id, guid)
  852. }
  853. func (s *NodeService) MarkNodeDirty(id int) error {
  854. return s.MarkNodeDirtyTx(database.GetDB(), id)
  855. }
  856. func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error {
  857. if id <= 0 {
  858. return nil
  859. }
  860. if tx == nil {
  861. return errors.New("nil db transaction")
  862. }
  863. return tx.Model(model.Node{}).
  864. Where("id = ?", id).
  865. Updates(map[string]any{
  866. "config_dirty": true,
  867. "config_dirty_at": time.Now().UnixMilli(),
  868. }).Error
  869. }
  870. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  871. if id <= 0 {
  872. return nil
  873. }
  874. return database.GetDB().Model(model.Node{}).
  875. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  876. Update("config_dirty", false).Error
  877. }
  878. func (s *NodeService) MarkNodeInboundsAdopted(id int) error {
  879. if id <= 0 {
  880. return nil
  881. }
  882. return database.GetDB().Model(model.Node{}).
  883. Where("id = ? AND inbounds_adopted_at = 0", id).
  884. Update("inbounds_adopted_at", time.Now().Unix()).Error
  885. }
  886. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  887. if id <= 0 {
  888. return false, "", false, 0, errors.New("invalid node id")
  889. }
  890. var row model.Node
  891. err = database.GetDB().Model(model.Node{}).
  892. Select("enable", "status", "config_dirty", "config_dirty_at").
  893. Where("id = ?", id).
  894. First(&row).Error
  895. if err != nil {
  896. return false, "", false, 0, err
  897. }
  898. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  899. }
  900. // IsNodePending reports whether a save targeting this node was deferred because
  901. // the node is unreachable right now — offline or disabled — so the edit only
  902. // reaches it on the next reconcile. It deliberately ignores config_dirty: that
  903. // flag is set on EVERY node-backed edit as the reconcile self-heal marker,
  904. // including edits pushed live to an online node, so keying the user-facing
  905. // "saved, node offline, will sync" toast off it fired the warning on every save
  906. // to a perfectly healthy online node.
  907. func (s *NodeService) IsNodePending(id int) bool {
  908. enabled, status, _, _, err := s.NodeSyncState(id)
  909. if err != nil {
  910. return false
  911. }
  912. return !enabled || status != "online"
  913. }
  914. func nodeMetricKey(id int, metric string) string {
  915. return "node:" + strconv.Itoa(id) + ":" + metric
  916. }
  917. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  918. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  919. }
  920. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  921. proxyURL := ""
  922. if n.OutboundTag != "" {
  923. if mgr := runtime.GetManager(); mgr != nil {
  924. proxyURL = mgr.NodeEgressProxyURL(n.Id)
  925. }
  926. }
  927. return s.probe(ctx, n, proxyURL)
  928. }
  929. func (s *NodeService) ProbeWithOutbound(ctx context.Context, n *model.Node, outboundTag string) (HeartbeatPatch, error) {
  930. if outboundTag == "" {
  931. return s.Probe(ctx, n)
  932. }
  933. var patch HeartbeatPatch
  934. var err error
  935. s.withOutboundBridge(n.Id, outboundTag, func(proxyURL string) {
  936. if proxyURL == "" {
  937. patch, err = s.Probe(ctx, n)
  938. return
  939. }
  940. patch, err = s.probe(ctx, n, proxyURL)
  941. })
  942. return patch, err
  943. }
  944. // withOutboundBridge stands up a temporary loopback SOCKS5 inbound in the
  945. // running Xray, routes it through outboundTag, and runs fn with the bridge's
  946. // proxy URL before tearing it down. It is used to reach a node through its
  947. // connection outbound before the persistent egress bridge has been injected
  948. // into the config (e.g. while the node is still being added or edited). When
  949. // Xray isn't running or the bridge can't be built, fn runs with an empty
  950. // proxyURL so callers fall back to a direct connection.
  951. func (s *NodeService) withOutboundBridge(nodeID int, outboundTag string, fn func(proxyURL string)) {
  952. proc := XrayProcess()
  953. if proc == nil || !proc.IsRunning() {
  954. fn("")
  955. return
  956. }
  957. apiPort := proc.GetAPIPort()
  958. if apiPort <= 0 {
  959. fn("")
  960. return
  961. }
  962. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  963. if err != nil {
  964. fn("")
  965. return
  966. }
  967. port := listener.Addr().(*net.TCPAddr).Port
  968. listener.Close()
  969. tag := fmt.Sprintf("node-test-%d-%d", nodeID, time.Now().UnixNano())
  970. proxyURL := fmt.Sprintf("socks5://127.0.0.1:%d", port)
  971. inboundJSON, err := json.Marshal(xray.InboundConfig{
  972. Listen: json_util.RawMessage(`"127.0.0.1"`),
  973. Port: port,
  974. Protocol: "socks",
  975. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  976. Tag: tag,
  977. })
  978. if err != nil {
  979. fn("")
  980. return
  981. }
  982. cfg := proc.GetConfig()
  983. routing := map[string]any{}
  984. if len(cfg.RouterConfig) > 0 {
  985. _ = json.Unmarshal(cfg.RouterConfig, &routing)
  986. }
  987. rules, _ := routing["rules"].([]any)
  988. rule := map[string]any{
  989. "type": "field",
  990. "inboundTag": []any{tag},
  991. }
  992. if routingTagIsBalancer(routing, outboundTag) {
  993. rule["balancerTag"] = outboundTag
  994. } else {
  995. rule["outboundTag"] = outboundTag
  996. }
  997. routing["rules"] = append([]any{rule}, rules...)
  998. routingJSON, err := json.Marshal(routing)
  999. if err != nil {
  1000. fn("")
  1001. return
  1002. }
  1003. originalRoutingJSON := cfg.RouterConfig
  1004. api := xray.XrayAPI{}
  1005. if err := api.Init(apiPort); err != nil {
  1006. fn("")
  1007. return
  1008. }
  1009. defer api.Close()
  1010. if err := api.AddInbound(inboundJSON); err != nil {
  1011. fn("")
  1012. return
  1013. }
  1014. defer func() {
  1015. if err := api.DelInbound(tag); err != nil {
  1016. logger.Warning("remove temp node bridge inbound failed:", err)
  1017. }
  1018. }()
  1019. if err := api.ApplyRoutingConfig(routingJSON); err != nil {
  1020. fn("")
  1021. return
  1022. }
  1023. defer func() {
  1024. restore := originalRoutingJSON
  1025. if len(restore) == 0 {
  1026. restore = []byte("{}")
  1027. }
  1028. if err := api.ApplyRoutingConfig(restore); err != nil {
  1029. logger.Warning("restore routing after node bridge failed:", err)
  1030. }
  1031. }()
  1032. fn(proxyURL)
  1033. }
  1034. func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string) (HeartbeatPatch, error) {
  1035. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  1036. addr, err := netsafe.NormalizeHost(n.Address)
  1037. if err != nil {
  1038. patch.LastError = err.Error()
  1039. return patch, err
  1040. }
  1041. scheme := n.Scheme
  1042. if scheme != "http" && scheme != "https" {
  1043. scheme = "https"
  1044. }
  1045. if n.Port <= 0 || n.Port > 65535 {
  1046. patch.LastError = "node port must be 1-65535"
  1047. return patch, errors.New(patch.LastError)
  1048. }
  1049. probeURL := &url.URL{
  1050. Scheme: scheme,
  1051. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  1052. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  1053. }
  1054. req, err := http.NewRequestWithContext(
  1055. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  1056. http.MethodGet, probeURL.String(), nil)
  1057. if err != nil {
  1058. patch.LastError = err.Error()
  1059. return patch, err
  1060. }
  1061. if n.ApiToken != "" {
  1062. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  1063. }
  1064. req.Header.Set("Accept", "application/json")
  1065. client, err := runtime.HTTPClientForNode(n, proxyURL)
  1066. if err != nil {
  1067. patch.LastError = err.Error()
  1068. return patch, err
  1069. }
  1070. start := time.Now()
  1071. resp, err := client.Do(req)
  1072. if err != nil {
  1073. patch.LastError = err.Error()
  1074. return patch, err
  1075. }
  1076. defer resp.Body.Close()
  1077. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  1078. if resp.StatusCode != http.StatusOK {
  1079. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  1080. return patch, errors.New(patch.LastError)
  1081. }
  1082. var envelope struct {
  1083. Success bool `json:"success"`
  1084. Msg string `json:"msg"`
  1085. Obj *struct {
  1086. CpuPct float64 `json:"cpu"`
  1087. Mem struct {
  1088. Current uint64 `json:"current"`
  1089. Total uint64 `json:"total"`
  1090. } `json:"mem"`
  1091. Xray struct {
  1092. Version string `json:"version"`
  1093. State string `json:"state"`
  1094. ErrorMsg string `json:"errorMsg"`
  1095. } `json:"xray"`
  1096. PanelVersion string `json:"panelVersion"`
  1097. PanelGuid string `json:"panelGuid"`
  1098. Uptime uint64 `json:"uptime"`
  1099. NetIO struct {
  1100. Up uint64 `json:"up"`
  1101. Down uint64 `json:"down"`
  1102. } `json:"netIO"`
  1103. } `json:"obj"`
  1104. }
  1105. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  1106. patch.LastError = "decode response: " + err.Error()
  1107. return patch, err
  1108. }
  1109. if !envelope.Success || envelope.Obj == nil {
  1110. patch.LastError = "remote returned success=false: " + envelope.Msg
  1111. return patch, errors.New(patch.LastError)
  1112. }
  1113. o := envelope.Obj
  1114. patch.CpuPct = o.CpuPct
  1115. if o.Mem.Total > 0 {
  1116. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  1117. }
  1118. patch.XrayVersion = o.Xray.Version
  1119. patch.XrayState = o.Xray.State
  1120. patch.XrayError = o.Xray.ErrorMsg
  1121. patch.PanelVersion = o.PanelVersion
  1122. patch.Guid = o.PanelGuid
  1123. patch.UptimeSecs = o.Uptime
  1124. patch.NetUp = o.NetIO.Up
  1125. patch.NetDown = o.NetIO.Down
  1126. return patch, nil
  1127. }
  1128. type ProbeResultUI struct {
  1129. Status string `json:"status" example:"online"`
  1130. LatencyMs int `json:"latencyMs" example:"42"`
  1131. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  1132. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  1133. CpuPct float64 `json:"cpuPct" example:"12.5"`
  1134. MemPct float64 `json:"memPct" example:"45.2"`
  1135. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  1136. Error string `json:"error"`
  1137. // XrayState/XrayError are populated on successful probes even when the node's
  1138. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  1139. XrayState string `json:"xrayState"`
  1140. XrayError string `json:"xrayError"`
  1141. }
  1142. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  1143. r := ProbeResultUI{
  1144. LatencyMs: p.LatencyMs,
  1145. XrayVersion: p.XrayVersion,
  1146. PanelVersion: p.PanelVersion,
  1147. CpuPct: p.CpuPct,
  1148. MemPct: p.MemPct,
  1149. UptimeSecs: p.UptimeSecs,
  1150. Error: FriendlyProbeError(p.LastError),
  1151. XrayState: p.XrayState,
  1152. XrayError: p.XrayError,
  1153. }
  1154. if ok {
  1155. r.Status = "online"
  1156. } else {
  1157. r.Status = "offline"
  1158. }
  1159. return r
  1160. }
  1161. func FriendlyProbeError(msg string) string {
  1162. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  1163. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  1164. }
  1165. return msg
  1166. }