node.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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 FilterNodeSnapshot(n *model.Node, snap *runtime.TrafficSnapshot) {
  622. if n == nil || snap == nil || n.InboundSyncMode != "selected" {
  623. return
  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. filtered := make([]*model.Inbound, 0, len(snap.Inbounds))
  638. for _, inbound := range snap.Inbounds {
  639. if inbound == nil {
  640. continue
  641. }
  642. if _, ok := allowed[inbound.Tag]; ok {
  643. filtered = append(filtered, inbound)
  644. }
  645. }
  646. snap.Inbounds = filtered
  647. }
  648. func (s *NodeService) Delete(id int) error {
  649. db := database.GetDB()
  650. // Refuse to delete a node that still owns inbounds: dropping the node row
  651. // while inbounds keep its node_id leaves orphaned, dangling references that
  652. // confuse node sync, subscriptions and cleanup. The operator must detach or
  653. // remove those inbounds first. (DB-002)
  654. var attached int64
  655. if err := db.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil {
  656. return err
  657. }
  658. if attached > 0 {
  659. return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached))
  660. }
  661. // Capture the node's guid before deleting the row so we can drop its per-node
  662. // IP attribution. NodeClientIp is keyed by the node's attribution key, which
  663. // is its guid normally but its node-unique key for a cloned/ambiguous-guid
  664. // node (see effectiveNodeKey) — so we purge both below.
  665. var guid string
  666. var n model.Node
  667. if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil {
  668. guid = n.Guid
  669. }
  670. // Delete the node row and its per-node child rows atomically. Remove the
  671. // children (traffic baselines, IP attribution) before the parent node row so
  672. // the ordering already matches a future ON DELETE constraint. Delete stays
  673. // tolerant of a missing node row so it can still clean up orphaned baselines.
  674. if err := db.Transaction(func(tx *gorm.DB) error {
  675. if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  676. return err
  677. }
  678. guids := []string{synthNodeGuid(id)}
  679. if guid != "" {
  680. guids = append(guids, guid)
  681. }
  682. if err := tx.Where("node_guid IN ?", guids).Delete(&model.NodeClientIp{}).Error; err != nil {
  683. return err
  684. }
  685. return tx.Where("id = ?", id).Delete(&model.Node{}).Error
  686. }); err != nil {
  687. return err
  688. }
  689. if mgr := runtime.GetManager(); mgr != nil {
  690. mgr.InvalidateNode(id)
  691. }
  692. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  693. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  694. return nil
  695. }
  696. func (s *NodeService) SetEnable(id int, enable bool) error {
  697. db := database.GetDB()
  698. if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil {
  699. return err
  700. }
  701. if mgr := runtime.GetManager(); mgr != nil {
  702. mgr.InvalidateNode(id)
  703. }
  704. return nil
  705. }
  706. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  707. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  708. // exist on the node rather than the central panel. See issue #4854.
  709. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  710. n, err := s.GetById(id)
  711. if err != nil || n == nil {
  712. return nil, fmt.Errorf("node not found")
  713. }
  714. if !n.Enable {
  715. return nil, fmt.Errorf("node is disabled")
  716. }
  717. mgr := runtime.GetManager()
  718. if mgr == nil {
  719. return nil, fmt.Errorf("runtime manager unavailable")
  720. }
  721. remote, err := mgr.RemoteFor(n)
  722. if err != nil {
  723. return nil, err
  724. }
  725. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  726. defer cancel()
  727. return remote.GetWebCertFiles(ctx)
  728. }
  729. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  730. // node so the UI can show per-node success/failure for a bulk request.
  731. type NodeUpdateResult struct {
  732. Id int `json:"id"`
  733. Name string `json:"name"`
  734. OK bool `json:"ok"`
  735. Error string `json:"error,omitempty"`
  736. }
  737. // UpdatePanels triggers the official self-updater on each given node. Only
  738. // enabled, online nodes are eligible — an offline node can't be reached, so it
  739. // is reported as skipped rather than silently dropped.
  740. func (s *NodeService) UpdatePanels(ids []int, dev bool) ([]NodeUpdateResult, error) {
  741. mgr := runtime.GetManager()
  742. if mgr == nil {
  743. return nil, fmt.Errorf("runtime manager unavailable")
  744. }
  745. results := make([]NodeUpdateResult, 0, len(ids))
  746. for _, id := range ids {
  747. n, err := s.GetById(id)
  748. if err != nil || n == nil {
  749. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  750. continue
  751. }
  752. res := NodeUpdateResult{Id: id, Name: n.Name}
  753. switch {
  754. case !n.Enable:
  755. res.Error = "node is disabled"
  756. case n.Status != "online":
  757. res.Error = "node is offline"
  758. default:
  759. remote, remoteErr := mgr.RemoteFor(n)
  760. if remoteErr != nil {
  761. res.Error = remoteErr.Error()
  762. break
  763. }
  764. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  765. updErr := remote.UpdatePanel(ctx, dev)
  766. cancel()
  767. if updErr != nil {
  768. res.Error = updErr.Error()
  769. } else {
  770. res.OK = true
  771. }
  772. }
  773. results = append(results, res)
  774. }
  775. return results, nil
  776. }
  777. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  778. db := database.GetDB()
  779. updates := map[string]any{
  780. "status": p.Status,
  781. "last_heartbeat": p.LastHeartbeat,
  782. "latency_ms": p.LatencyMs,
  783. "xray_version": p.XrayVersion,
  784. "panel_version": p.PanelVersion,
  785. "cpu_pct": p.CpuPct,
  786. "mem_pct": p.MemPct,
  787. "uptime_secs": p.UptimeSecs,
  788. "net_up": p.NetUp,
  789. "net_down": p.NetDown,
  790. "last_error": p.LastError,
  791. "xray_state": p.XrayState,
  792. "xray_error": p.XrayError,
  793. }
  794. // Only learn the GUID; never clear a known one if an old-build node (or a
  795. // failed probe) reports none, so the stable identity survives blips.
  796. if p.Guid != "" {
  797. updates["guid"] = p.Guid
  798. s.warnOnDuplicateGuid(id, p.Guid)
  799. }
  800. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  801. return err
  802. }
  803. if p.Status == "online" {
  804. now := time.Unix(p.LastHeartbeat, 0)
  805. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  806. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  807. nodeMetrics.append(nodeMetricKey(id, "netUp"), now, float64(p.NetUp))
  808. nodeMetrics.append(nodeMetricKey(id, "netDown"), now, float64(p.NetDown))
  809. }
  810. return nil
  811. }
  812. // warnedDupGuid remembers the (nodeID -> guid) pairs already warned about so a
  813. // cloned-server collision is logged once, not every heartbeat.
  814. var warnedDupGuid sync.Map
  815. // warnOnDuplicateGuid logs once when a node reports a panelGuid already held by
  816. // another node or by the master itself (the cloned-server footgun). Attribution
  817. // still works — it falls back to node-unique keys — but the operator should
  818. // regenerate the duplicate panelGuid to restore real identity and per-node IP
  819. // attribution. Re-arms if the collision later clears.
  820. func (s *NodeService) warnOnDuplicateGuid(id int, guid string) {
  821. var clash int64
  822. database.GetDB().Model(&model.Node{}).Where("guid = ? AND id <> ?", guid, id).Count(&clash)
  823. masterGuid, _ := (&SettingService{}).GetPanelGuid()
  824. if clash == 0 && guid != masterGuid {
  825. warnedDupGuid.Delete(id)
  826. return
  827. }
  828. if prev, ok := warnedDupGuid.Load(id); ok && prev == guid {
  829. return
  830. }
  831. warnedDupGuid.Store(id, guid)
  832. 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)
  833. }
  834. func (s *NodeService) MarkNodeDirty(id int) error {
  835. return s.MarkNodeDirtyTx(database.GetDB(), id)
  836. }
  837. func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error {
  838. if id <= 0 {
  839. return nil
  840. }
  841. if tx == nil {
  842. return errors.New("nil db transaction")
  843. }
  844. return tx.Model(model.Node{}).
  845. Where("id = ?", id).
  846. Updates(map[string]any{
  847. "config_dirty": true,
  848. "config_dirty_at": time.Now().UnixMilli(),
  849. }).Error
  850. }
  851. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  852. if id <= 0 {
  853. return nil
  854. }
  855. return database.GetDB().Model(model.Node{}).
  856. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  857. Update("config_dirty", false).Error
  858. }
  859. func (s *NodeService) MarkNodeInboundsAdopted(id int) error {
  860. if id <= 0 {
  861. return nil
  862. }
  863. return database.GetDB().Model(model.Node{}).
  864. Where("id = ? AND inbounds_adopted_at = 0", id).
  865. Update("inbounds_adopted_at", time.Now().Unix()).Error
  866. }
  867. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  868. if id <= 0 {
  869. return false, "", false, 0, errors.New("invalid node id")
  870. }
  871. var row model.Node
  872. err = database.GetDB().Model(model.Node{}).
  873. Select("enable", "status", "config_dirty", "config_dirty_at").
  874. Where("id = ?", id).
  875. First(&row).Error
  876. if err != nil {
  877. return false, "", false, 0, err
  878. }
  879. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  880. }
  881. // IsNodePending reports whether a save targeting this node was deferred because
  882. // the node is unreachable right now — offline or disabled — so the edit only
  883. // reaches it on the next reconcile. It deliberately ignores config_dirty: that
  884. // flag is set on EVERY node-backed edit as the reconcile self-heal marker,
  885. // including edits pushed live to an online node, so keying the user-facing
  886. // "saved, node offline, will sync" toast off it fired the warning on every save
  887. // to a perfectly healthy online node.
  888. func (s *NodeService) IsNodePending(id int) bool {
  889. enabled, status, _, _, err := s.NodeSyncState(id)
  890. if err != nil {
  891. return false
  892. }
  893. return !enabled || status != "online"
  894. }
  895. func nodeMetricKey(id int, metric string) string {
  896. return "node:" + strconv.Itoa(id) + ":" + metric
  897. }
  898. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  899. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  900. }
  901. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  902. proxyURL := ""
  903. if n.OutboundTag != "" {
  904. if mgr := runtime.GetManager(); mgr != nil {
  905. proxyURL = mgr.NodeEgressProxyURL(n.Id)
  906. }
  907. }
  908. return s.probe(ctx, n, proxyURL)
  909. }
  910. func (s *NodeService) ProbeWithOutbound(ctx context.Context, n *model.Node, outboundTag string) (HeartbeatPatch, error) {
  911. if outboundTag == "" {
  912. return s.Probe(ctx, n)
  913. }
  914. var patch HeartbeatPatch
  915. var err error
  916. s.withOutboundBridge(n.Id, outboundTag, func(proxyURL string) {
  917. if proxyURL == "" {
  918. patch, err = s.Probe(ctx, n)
  919. return
  920. }
  921. patch, err = s.probe(ctx, n, proxyURL)
  922. })
  923. return patch, err
  924. }
  925. // withOutboundBridge stands up a temporary loopback SOCKS5 inbound in the
  926. // running Xray, routes it through outboundTag, and runs fn with the bridge's
  927. // proxy URL before tearing it down. It is used to reach a node through its
  928. // connection outbound before the persistent egress bridge has been injected
  929. // into the config (e.g. while the node is still being added or edited). When
  930. // Xray isn't running or the bridge can't be built, fn runs with an empty
  931. // proxyURL so callers fall back to a direct connection.
  932. func (s *NodeService) withOutboundBridge(nodeID int, outboundTag string, fn func(proxyURL string)) {
  933. proc := XrayProcess()
  934. if proc == nil || !proc.IsRunning() {
  935. fn("")
  936. return
  937. }
  938. apiPort := proc.GetAPIPort()
  939. if apiPort <= 0 {
  940. fn("")
  941. return
  942. }
  943. listener, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0")
  944. if err != nil {
  945. fn("")
  946. return
  947. }
  948. port := listener.Addr().(*net.TCPAddr).Port
  949. listener.Close()
  950. tag := fmt.Sprintf("node-test-%d-%d", nodeID, time.Now().UnixNano())
  951. proxyURL := fmt.Sprintf("socks5://127.0.0.1:%d", port)
  952. inboundJSON, err := json.Marshal(xray.InboundConfig{
  953. Listen: json_util.RawMessage(`"127.0.0.1"`),
  954. Port: port,
  955. Protocol: "socks",
  956. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  957. Tag: tag,
  958. })
  959. if err != nil {
  960. fn("")
  961. return
  962. }
  963. cfg := proc.GetConfig()
  964. routing := map[string]any{}
  965. if len(cfg.RouterConfig) > 0 {
  966. _ = json.Unmarshal(cfg.RouterConfig, &routing)
  967. }
  968. rules, _ := routing["rules"].([]any)
  969. rule := map[string]any{
  970. "type": "field",
  971. "inboundTag": []any{tag},
  972. }
  973. if routingTagIsBalancer(routing, outboundTag) {
  974. rule["balancerTag"] = outboundTag
  975. } else {
  976. rule["outboundTag"] = outboundTag
  977. }
  978. routing["rules"] = append([]any{rule}, rules...)
  979. routingJSON, err := json.Marshal(routing)
  980. if err != nil {
  981. fn("")
  982. return
  983. }
  984. originalRoutingJSON := cfg.RouterConfig
  985. api := xray.XrayAPI{}
  986. if err := api.Init(apiPort); err != nil {
  987. fn("")
  988. return
  989. }
  990. defer api.Close()
  991. if err := api.AddInbound(inboundJSON); err != nil {
  992. fn("")
  993. return
  994. }
  995. defer func() {
  996. if err := api.DelInbound(tag); err != nil {
  997. logger.Warning("remove temp node bridge inbound failed:", err)
  998. }
  999. }()
  1000. if err := api.ApplyRoutingConfig(routingJSON); err != nil {
  1001. fn("")
  1002. return
  1003. }
  1004. defer func() {
  1005. restore := originalRoutingJSON
  1006. if len(restore) == 0 {
  1007. restore = []byte("{}")
  1008. }
  1009. if err := api.ApplyRoutingConfig(restore); err != nil {
  1010. logger.Warning("restore routing after node bridge failed:", err)
  1011. }
  1012. }()
  1013. fn(proxyURL)
  1014. }
  1015. func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string) (HeartbeatPatch, error) {
  1016. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  1017. addr, err := netsafe.NormalizeHost(n.Address)
  1018. if err != nil {
  1019. patch.LastError = err.Error()
  1020. return patch, err
  1021. }
  1022. scheme := n.Scheme
  1023. if scheme != "http" && scheme != "https" {
  1024. scheme = "https"
  1025. }
  1026. if n.Port <= 0 || n.Port > 65535 {
  1027. patch.LastError = "node port must be 1-65535"
  1028. return patch, errors.New(patch.LastError)
  1029. }
  1030. probeURL := &url.URL{
  1031. Scheme: scheme,
  1032. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  1033. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  1034. }
  1035. req, err := http.NewRequestWithContext(
  1036. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  1037. http.MethodGet, probeURL.String(), nil)
  1038. if err != nil {
  1039. patch.LastError = err.Error()
  1040. return patch, err
  1041. }
  1042. if n.ApiToken != "" {
  1043. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  1044. }
  1045. req.Header.Set("Accept", "application/json")
  1046. client, err := runtime.HTTPClientForNode(n, proxyURL)
  1047. if err != nil {
  1048. patch.LastError = err.Error()
  1049. return patch, err
  1050. }
  1051. start := time.Now()
  1052. resp, err := client.Do(req)
  1053. if err != nil {
  1054. patch.LastError = err.Error()
  1055. return patch, err
  1056. }
  1057. defer resp.Body.Close()
  1058. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  1059. if resp.StatusCode != http.StatusOK {
  1060. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  1061. return patch, errors.New(patch.LastError)
  1062. }
  1063. var envelope struct {
  1064. Success bool `json:"success"`
  1065. Msg string `json:"msg"`
  1066. Obj *struct {
  1067. CpuPct float64 `json:"cpu"`
  1068. Mem struct {
  1069. Current uint64 `json:"current"`
  1070. Total uint64 `json:"total"`
  1071. } `json:"mem"`
  1072. Xray struct {
  1073. Version string `json:"version"`
  1074. State string `json:"state"`
  1075. ErrorMsg string `json:"errorMsg"`
  1076. } `json:"xray"`
  1077. PanelVersion string `json:"panelVersion"`
  1078. PanelGuid string `json:"panelGuid"`
  1079. Uptime uint64 `json:"uptime"`
  1080. NetIO struct {
  1081. Up uint64 `json:"up"`
  1082. Down uint64 `json:"down"`
  1083. } `json:"netIO"`
  1084. } `json:"obj"`
  1085. }
  1086. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  1087. patch.LastError = "decode response: " + err.Error()
  1088. return patch, err
  1089. }
  1090. if !envelope.Success || envelope.Obj == nil {
  1091. patch.LastError = "remote returned success=false: " + envelope.Msg
  1092. return patch, errors.New(patch.LastError)
  1093. }
  1094. o := envelope.Obj
  1095. patch.CpuPct = o.CpuPct
  1096. if o.Mem.Total > 0 {
  1097. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  1098. }
  1099. patch.XrayVersion = o.Xray.Version
  1100. patch.XrayState = o.Xray.State
  1101. patch.XrayError = o.Xray.ErrorMsg
  1102. patch.PanelVersion = o.PanelVersion
  1103. patch.Guid = o.PanelGuid
  1104. patch.UptimeSecs = o.Uptime
  1105. patch.NetUp = o.NetIO.Up
  1106. patch.NetDown = o.NetIO.Down
  1107. return patch, nil
  1108. }
  1109. type ProbeResultUI struct {
  1110. Status string `json:"status" example:"online"`
  1111. LatencyMs int `json:"latencyMs" example:"42"`
  1112. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  1113. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  1114. CpuPct float64 `json:"cpuPct" example:"12.5"`
  1115. MemPct float64 `json:"memPct" example:"45.2"`
  1116. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  1117. Error string `json:"error"`
  1118. // XrayState/XrayError are populated on successful probes even when the node's
  1119. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  1120. XrayState string `json:"xrayState"`
  1121. XrayError string `json:"xrayError"`
  1122. }
  1123. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  1124. r := ProbeResultUI{
  1125. LatencyMs: p.LatencyMs,
  1126. XrayVersion: p.XrayVersion,
  1127. PanelVersion: p.PanelVersion,
  1128. CpuPct: p.CpuPct,
  1129. MemPct: p.MemPct,
  1130. UptimeSecs: p.UptimeSecs,
  1131. Error: FriendlyProbeError(p.LastError),
  1132. XrayState: p.XrayState,
  1133. XrayError: p.XrayError,
  1134. }
  1135. if ok {
  1136. r.Status = "online"
  1137. } else {
  1138. r.Status = "offline"
  1139. }
  1140. return r
  1141. }
  1142. func FriendlyProbeError(msg string) string {
  1143. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  1144. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  1145. }
  1146. return msg
  1147. }