node.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. package service
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/subtle"
  6. "crypto/tls"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "net"
  13. "net/http"
  14. "net/url"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "github.com/mhsanaei/3x-ui/v3/database"
  19. "github.com/mhsanaei/3x-ui/v3/database/model"
  20. "github.com/mhsanaei/3x-ui/v3/util/common"
  21. "github.com/mhsanaei/3x-ui/v3/util/netsafe"
  22. "github.com/mhsanaei/3x-ui/v3/web/runtime"
  23. )
  24. type HeartbeatPatch struct {
  25. Status string
  26. LastHeartbeat int64
  27. LatencyMs int
  28. XrayVersion string
  29. PanelVersion string
  30. Guid string
  31. CpuPct float64
  32. MemPct float64
  33. UptimeSecs uint64
  34. LastError string
  35. // XrayState and XrayError come from the remote /panel/api/server/status when the
  36. // panel API is reachable. They allow distinguishing panel connectivity from
  37. // Xray core health on the node.
  38. XrayState string
  39. XrayError string
  40. }
  41. type NodeService struct{}
  42. var nodeHTTPClient = &http.Client{
  43. Transport: &http.Transport{
  44. MaxIdleConns: 64,
  45. MaxIdleConnsPerHost: 4,
  46. IdleConnTimeout: 60 * time.Second,
  47. DialContext: netsafe.SSRFGuardedDialContext,
  48. },
  49. }
  50. // nodeHTTPClientFor returns the HTTP client used to reach a node, honoring its
  51. // per-node TLS verification mode. "verify" (or any http node) uses the shared
  52. // client with default certificate validation. "skip" disables validation.
  53. // "pin" disables the default chain check but verifies the leaf certificate's
  54. // SHA-256 against the stored pin, keeping MITM protection for self-signed certs.
  55. func nodeHTTPClientFor(n *model.Node) (*http.Client, error) {
  56. mode := n.TlsVerifyMode
  57. if mode == "" {
  58. mode = "verify"
  59. }
  60. if mode == "verify" || n.Scheme == "http" {
  61. return nodeHTTPClient, nil
  62. }
  63. tlsCfg := &tls.Config{InsecureSkipVerify: true}
  64. if mode == "pin" {
  65. want, err := decodeCertPin(n.PinnedCertSha256)
  66. if err != nil {
  67. return nil, err
  68. }
  69. tlsCfg.VerifyConnection = func(cs tls.ConnectionState) error {
  70. if len(cs.PeerCertificates) == 0 {
  71. return common.NewError("node presented no certificate")
  72. }
  73. sum := sha256.Sum256(cs.PeerCertificates[0].Raw)
  74. if subtle.ConstantTimeCompare(sum[:], want) != 1 {
  75. return common.NewError("node certificate does not match pinned SHA-256")
  76. }
  77. return nil
  78. }
  79. }
  80. return &http.Client{
  81. Transport: &http.Transport{
  82. MaxIdleConns: 64,
  83. MaxIdleConnsPerHost: 4,
  84. IdleConnTimeout: 60 * time.Second,
  85. DialContext: netsafe.SSRFGuardedDialContext,
  86. TLSClientConfig: tlsCfg,
  87. },
  88. }, nil
  89. }
  90. // decodeCertPin accepts a SHA-256 certificate hash as base64 (the format used
  91. // by Xray's pinnedPeerCertSha256) or hex with optional colons (the openssl
  92. // -fingerprint style) and returns the 32 raw bytes.
  93. func decodeCertPin(s string) ([]byte, error) {
  94. s = strings.TrimSpace(s)
  95. if s == "" {
  96. return nil, common.NewError("certificate pin is empty")
  97. }
  98. if b, err := hex.DecodeString(strings.ReplaceAll(s, ":", "")); err == nil && len(b) == sha256.Size {
  99. return b, nil
  100. }
  101. for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding} {
  102. if b, err := enc.DecodeString(s); err == nil && len(b) == sha256.Size {
  103. return b, nil
  104. }
  105. }
  106. return nil, common.NewError("certificate pin must be a SHA-256 hash (base64 or hex)")
  107. }
  108. // FetchCertFingerprint connects to the node over HTTPS without verifying the
  109. // certificate and returns the leaf certificate's SHA-256 as base64, so the UI
  110. // can offer a "fetch and pin current certificate" action.
  111. func (s *NodeService) FetchCertFingerprint(ctx context.Context, n *model.Node) (string, error) {
  112. addr, err := netsafe.NormalizeHost(n.Address)
  113. if err != nil {
  114. return "", err
  115. }
  116. scheme := n.Scheme
  117. if scheme != "http" && scheme != "https" {
  118. scheme = "https"
  119. }
  120. if scheme != "https" {
  121. return "", common.NewError("certificate pinning is only available for https nodes")
  122. }
  123. if n.Port <= 0 || n.Port > 65535 {
  124. return "", common.NewError("node port must be 1-65535")
  125. }
  126. probeURL := &url.URL{
  127. Scheme: scheme,
  128. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  129. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  130. }
  131. req, err := http.NewRequestWithContext(
  132. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  133. http.MethodGet, probeURL.String(), nil)
  134. if err != nil {
  135. return "", err
  136. }
  137. client := &http.Client{
  138. Transport: &http.Transport{
  139. DialContext: netsafe.SSRFGuardedDialContext,
  140. TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // lgtm[go/disabled-certificate-check]
  141. },
  142. }
  143. resp, err := client.Do(req)
  144. if err != nil {
  145. return "", err
  146. }
  147. defer resp.Body.Close()
  148. if resp.TLS == nil || len(resp.TLS.PeerCertificates) == 0 {
  149. return "", common.NewError("node did not present a TLS certificate")
  150. }
  151. sum := sha256.Sum256(resp.TLS.PeerCertificates[0].Raw)
  152. return base64.StdEncoding.EncodeToString(sum[:]), nil
  153. }
  154. func (s *NodeService) GetAll() ([]*model.Node, error) {
  155. db := database.GetDB()
  156. var nodes []*model.Node
  157. err := db.Model(model.Node{}).Order("id asc").Find(&nodes).Error
  158. if err != nil || len(nodes) == 0 {
  159. return nodes, err
  160. }
  161. type inboundRow struct {
  162. Id int
  163. NodeID int `gorm:"column:node_id"`
  164. }
  165. var inboundRows []inboundRow
  166. if err := db.Table("inbounds").
  167. Select("id, node_id").
  168. Where("node_id IS NOT NULL").
  169. Scan(&inboundRows).Error; err != nil {
  170. return nodes, nil
  171. }
  172. if len(inboundRows) == 0 {
  173. return nodes, nil
  174. }
  175. inboundsByNode := make(map[int][]int, len(nodes))
  176. nodeByInbound := make(map[int]int, len(inboundRows))
  177. for _, row := range inboundRows {
  178. inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
  179. nodeByInbound[row.Id] = row.NodeID
  180. }
  181. type clientCountRow struct {
  182. NodeID int `gorm:"column:node_id"`
  183. Count int `gorm:"column:count"`
  184. }
  185. var clientCounts []clientCountRow
  186. if err := db.Raw(`
  187. SELECT inbounds.node_id AS node_id, COUNT(DISTINCT client_inbounds.client_id) AS count
  188. FROM inbounds
  189. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  190. WHERE inbounds.node_id IS NOT NULL
  191. GROUP BY inbounds.node_id
  192. `).Scan(&clientCounts).Error; err == nil {
  193. for _, row := range clientCounts {
  194. for _, n := range nodes {
  195. if n.Id == row.NodeID {
  196. n.ClientCount = row.Count
  197. break
  198. }
  199. }
  200. }
  201. }
  202. now := time.Now().UnixMilli()
  203. type trafficRow struct {
  204. InboundID int `gorm:"column:inbound_id"`
  205. Email string
  206. Enable bool
  207. Total int64
  208. Up int64
  209. Down int64
  210. ExpiryTime int64 `gorm:"column:expiry_time"`
  211. }
  212. var trafficRows []trafficRow
  213. inboundIDs := make([]int, 0, len(nodeByInbound))
  214. for id := range nodeByInbound {
  215. inboundIDs = append(inboundIDs, id)
  216. }
  217. if err := db.Table("client_traffics").
  218. Select("inbound_id, email, enable, total, up, down, expiry_time").
  219. Where("inbound_id IN ?", inboundIDs).
  220. Scan(&trafficRows).Error; err == nil {
  221. depletedByNode := make(map[int]int)
  222. for _, row := range trafficRows {
  223. nodeID, ok := nodeByInbound[row.InboundID]
  224. if !ok {
  225. continue
  226. }
  227. expired := row.ExpiryTime > 0 && row.ExpiryTime <= now
  228. exhausted := row.Total > 0 && row.Up+row.Down >= row.Total
  229. if expired || exhausted || !row.Enable {
  230. depletedByNode[nodeID]++
  231. }
  232. }
  233. onlineByGuid := s.onlineEmailsByGuid()
  234. for _, n := range nodes {
  235. n.InboundCount = len(inboundsByNode[n.Id])
  236. n.DepletedCount = depletedByNode[n.Id]
  237. // Online is attributed to the node that physically hosts the client
  238. // (by GUID): a client on a sub-node counts under the sub-node, not
  239. // the intermediate node it syncs through (#4983).
  240. n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n)])
  241. }
  242. }
  243. return nodes, nil
  244. }
  245. func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
  246. svc := InboundService{}
  247. byGuid := svc.GetOnlineClientsByGuid()
  248. out := make(map[string]map[string]struct{}, len(byGuid))
  249. for guid, emails := range byGuid {
  250. set := make(map[string]struct{}, len(emails))
  251. for _, email := range emails {
  252. set[email] = struct{}{}
  253. }
  254. out[guid] = set
  255. }
  256. return out
  257. }
  258. // effectiveNodeGuid is a node's stable online-attribution key: its reported
  259. // panelGuid, or a master-local synthetic id when the node is an old build that
  260. // hasn't reported one yet (#4983).
  261. func effectiveNodeGuid(n *model.Node) string {
  262. if n.Guid != "" {
  263. return n.Guid
  264. }
  265. return synthNodeGuid(n.Id)
  266. }
  267. func (s *NodeService) GetById(id int) (*model.Node, error) {
  268. db := database.GetDB()
  269. n := &model.Node{}
  270. if err := db.Model(model.Node{}).Where("id = ?", id).First(n).Error; err != nil {
  271. return nil, err
  272. }
  273. return n, nil
  274. }
  275. func normalizeBasePath(p string) string {
  276. p = strings.TrimSpace(p)
  277. if p == "" {
  278. return "/"
  279. }
  280. if !strings.HasPrefix(p, "/") {
  281. p = "/" + p
  282. }
  283. if !strings.HasSuffix(p, "/") {
  284. p = p + "/"
  285. }
  286. return p
  287. }
  288. func (s *NodeService) normalize(n *model.Node) error {
  289. n.Name = strings.TrimSpace(n.Name)
  290. n.ApiToken = strings.TrimSpace(n.ApiToken)
  291. if n.Name == "" {
  292. return common.NewError("node name is required")
  293. }
  294. addr, err := netsafe.NormalizeHost(n.Address)
  295. if err != nil {
  296. return common.NewError(err.Error())
  297. }
  298. n.Address = addr
  299. if n.Port <= 0 || n.Port > 65535 {
  300. return common.NewError("node port must be 1-65535")
  301. }
  302. if n.Scheme != "http" && n.Scheme != "https" {
  303. n.Scheme = "https"
  304. }
  305. if n.TlsVerifyMode != "skip" && n.TlsVerifyMode != "pin" {
  306. n.TlsVerifyMode = "verify"
  307. }
  308. n.PinnedCertSha256 = strings.TrimSpace(n.PinnedCertSha256)
  309. if n.TlsVerifyMode == "pin" {
  310. if _, err := decodeCertPin(n.PinnedCertSha256); err != nil {
  311. return common.NewError(err.Error())
  312. }
  313. }
  314. n.BasePath = normalizeBasePath(n.BasePath)
  315. return nil
  316. }
  317. func (s *NodeService) Create(n *model.Node) error {
  318. if err := s.normalize(n); err != nil {
  319. return err
  320. }
  321. db := database.GetDB()
  322. return db.Create(n).Error
  323. }
  324. func (s *NodeService) Update(id int, in *model.Node) error {
  325. if err := s.normalize(in); err != nil {
  326. return err
  327. }
  328. db := database.GetDB()
  329. existing := &model.Node{}
  330. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  331. return err
  332. }
  333. updates := map[string]any{
  334. "name": in.Name,
  335. "remark": in.Remark,
  336. "scheme": in.Scheme,
  337. "address": in.Address,
  338. "port": in.Port,
  339. "base_path": in.BasePath,
  340. "api_token": in.ApiToken,
  341. "enable": in.Enable,
  342. "allow_private_address": in.AllowPrivateAddress,
  343. "tls_verify_mode": in.TlsVerifyMode,
  344. "pinned_cert_sha256": in.PinnedCertSha256,
  345. }
  346. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  347. return err
  348. }
  349. if mgr := runtime.GetManager(); mgr != nil {
  350. mgr.InvalidateNode(id)
  351. }
  352. return nil
  353. }
  354. func (s *NodeService) Delete(id int) error {
  355. db := database.GetDB()
  356. if err := db.Where("id = ?", id).Delete(model.Node{}).Error; err != nil {
  357. return err
  358. }
  359. if err := db.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  360. return err
  361. }
  362. if mgr := runtime.GetManager(); mgr != nil {
  363. mgr.InvalidateNode(id)
  364. }
  365. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  366. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  367. return nil
  368. }
  369. func (s *NodeService) SetEnable(id int, enable bool) error {
  370. db := database.GetDB()
  371. return db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error
  372. }
  373. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  374. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  375. // exist on the node rather than the central panel. See issue #4854.
  376. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  377. n, err := s.GetById(id)
  378. if err != nil || n == nil {
  379. return nil, fmt.Errorf("node not found")
  380. }
  381. if !n.Enable {
  382. return nil, fmt.Errorf("node is disabled")
  383. }
  384. mgr := runtime.GetManager()
  385. if mgr == nil {
  386. return nil, fmt.Errorf("runtime manager unavailable")
  387. }
  388. remote, err := mgr.RemoteFor(n)
  389. if err != nil {
  390. return nil, err
  391. }
  392. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  393. defer cancel()
  394. return remote.GetWebCertFiles(ctx)
  395. }
  396. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  397. // node so the UI can show per-node success/failure for a bulk request.
  398. type NodeUpdateResult struct {
  399. Id int `json:"id"`
  400. Name string `json:"name"`
  401. OK bool `json:"ok"`
  402. Error string `json:"error,omitempty"`
  403. }
  404. // UpdatePanels triggers the official self-updater on each given node. Only
  405. // enabled, online nodes are eligible — an offline node can't be reached, so it
  406. // is reported as skipped rather than silently dropped.
  407. func (s *NodeService) UpdatePanels(ids []int) ([]NodeUpdateResult, error) {
  408. mgr := runtime.GetManager()
  409. if mgr == nil {
  410. return nil, fmt.Errorf("runtime manager unavailable")
  411. }
  412. results := make([]NodeUpdateResult, 0, len(ids))
  413. for _, id := range ids {
  414. n, err := s.GetById(id)
  415. if err != nil || n == nil {
  416. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  417. continue
  418. }
  419. res := NodeUpdateResult{Id: id, Name: n.Name}
  420. switch {
  421. case !n.Enable:
  422. res.Error = "node is disabled"
  423. case n.Status != "online":
  424. res.Error = "node is offline"
  425. default:
  426. remote, remoteErr := mgr.RemoteFor(n)
  427. if remoteErr != nil {
  428. res.Error = remoteErr.Error()
  429. break
  430. }
  431. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  432. updErr := remote.UpdatePanel(ctx)
  433. cancel()
  434. if updErr != nil {
  435. res.Error = updErr.Error()
  436. } else {
  437. res.OK = true
  438. }
  439. }
  440. results = append(results, res)
  441. }
  442. return results, nil
  443. }
  444. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  445. db := database.GetDB()
  446. updates := map[string]any{
  447. "status": p.Status,
  448. "last_heartbeat": p.LastHeartbeat,
  449. "latency_ms": p.LatencyMs,
  450. "xray_version": p.XrayVersion,
  451. "panel_version": p.PanelVersion,
  452. "cpu_pct": p.CpuPct,
  453. "mem_pct": p.MemPct,
  454. "uptime_secs": p.UptimeSecs,
  455. "last_error": p.LastError,
  456. "xray_state": p.XrayState,
  457. "xray_error": p.XrayError,
  458. }
  459. // Only learn the GUID; never clear a known one if an old-build node (or a
  460. // failed probe) reports none, so the stable identity survives blips.
  461. if p.Guid != "" {
  462. updates["guid"] = p.Guid
  463. }
  464. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  465. return err
  466. }
  467. if p.Status == "online" {
  468. now := time.Unix(p.LastHeartbeat, 0)
  469. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  470. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  471. }
  472. return nil
  473. }
  474. func (s *NodeService) MarkNodeDirty(id int) error {
  475. if id <= 0 {
  476. return nil
  477. }
  478. return database.GetDB().Model(model.Node{}).
  479. Where("id = ?", id).
  480. Updates(map[string]any{
  481. "config_dirty": true,
  482. "config_dirty_at": time.Now().UnixMilli(),
  483. }).Error
  484. }
  485. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  486. if id <= 0 {
  487. return nil
  488. }
  489. return database.GetDB().Model(model.Node{}).
  490. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  491. Update("config_dirty", false).Error
  492. }
  493. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  494. if id <= 0 {
  495. return false, "", false, 0, errors.New("invalid node id")
  496. }
  497. var row model.Node
  498. err = database.GetDB().Model(model.Node{}).
  499. Select("enable", "status", "config_dirty", "config_dirty_at").
  500. Where("id = ?", id).
  501. First(&row).Error
  502. if err != nil {
  503. return false, "", false, 0, err
  504. }
  505. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  506. }
  507. func (s *NodeService) IsNodePending(id int) bool {
  508. enabled, status, dirty, _, err := s.NodeSyncState(id)
  509. if err != nil {
  510. return false
  511. }
  512. return !enabled || status != "online" || dirty
  513. }
  514. func nodeMetricKey(id int, metric string) string {
  515. return "node:" + strconv.Itoa(id) + ":" + metric
  516. }
  517. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  518. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  519. }
  520. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  521. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  522. addr, err := netsafe.NormalizeHost(n.Address)
  523. if err != nil {
  524. patch.LastError = err.Error()
  525. return patch, err
  526. }
  527. scheme := n.Scheme
  528. if scheme != "http" && scheme != "https" {
  529. scheme = "https"
  530. }
  531. if n.Port <= 0 || n.Port > 65535 {
  532. patch.LastError = "node port must be 1-65535"
  533. return patch, errors.New(patch.LastError)
  534. }
  535. probeURL := &url.URL{
  536. Scheme: scheme,
  537. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  538. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  539. }
  540. req, err := http.NewRequestWithContext(
  541. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  542. http.MethodGet, probeURL.String(), nil)
  543. if err != nil {
  544. patch.LastError = err.Error()
  545. return patch, err
  546. }
  547. if n.ApiToken != "" {
  548. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  549. }
  550. req.Header.Set("Accept", "application/json")
  551. client, err := nodeHTTPClientFor(n)
  552. if err != nil {
  553. patch.LastError = err.Error()
  554. return patch, err
  555. }
  556. start := time.Now()
  557. resp, err := client.Do(req)
  558. if err != nil {
  559. patch.LastError = err.Error()
  560. return patch, err
  561. }
  562. defer resp.Body.Close()
  563. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  564. if resp.StatusCode != http.StatusOK {
  565. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  566. return patch, errors.New(patch.LastError)
  567. }
  568. var envelope struct {
  569. Success bool `json:"success"`
  570. Msg string `json:"msg"`
  571. Obj *struct {
  572. CpuPct float64 `json:"cpu"`
  573. Mem struct {
  574. Current uint64 `json:"current"`
  575. Total uint64 `json:"total"`
  576. } `json:"mem"`
  577. Xray struct {
  578. Version string `json:"version"`
  579. State string `json:"state"`
  580. ErrorMsg string `json:"errorMsg"`
  581. } `json:"xray"`
  582. PanelVersion string `json:"panelVersion"`
  583. PanelGuid string `json:"panelGuid"`
  584. Uptime uint64 `json:"uptime"`
  585. } `json:"obj"`
  586. }
  587. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  588. patch.LastError = "decode response: " + err.Error()
  589. return patch, err
  590. }
  591. if !envelope.Success || envelope.Obj == nil {
  592. patch.LastError = "remote returned success=false: " + envelope.Msg
  593. return patch, errors.New(patch.LastError)
  594. }
  595. o := envelope.Obj
  596. patch.CpuPct = o.CpuPct
  597. if o.Mem.Total > 0 {
  598. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  599. }
  600. patch.XrayVersion = o.Xray.Version
  601. patch.XrayState = o.Xray.State
  602. patch.XrayError = o.Xray.ErrorMsg
  603. patch.PanelVersion = o.PanelVersion
  604. patch.Guid = o.PanelGuid
  605. patch.UptimeSecs = o.Uptime
  606. return patch, nil
  607. }
  608. type ProbeResultUI struct {
  609. Status string `json:"status" example:"online"`
  610. LatencyMs int `json:"latencyMs" example:"42"`
  611. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  612. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  613. CpuPct float64 `json:"cpuPct" example:"12.5"`
  614. MemPct float64 `json:"memPct" example:"45.2"`
  615. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  616. Error string `json:"error"`
  617. // XrayState/XrayError are populated on successful probes even when the node's
  618. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  619. XrayState string `json:"xrayState"`
  620. XrayError string `json:"xrayError"`
  621. }
  622. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  623. r := ProbeResultUI{
  624. LatencyMs: p.LatencyMs,
  625. XrayVersion: p.XrayVersion,
  626. PanelVersion: p.PanelVersion,
  627. CpuPct: p.CpuPct,
  628. MemPct: p.MemPct,
  629. UptimeSecs: p.UptimeSecs,
  630. Error: FriendlyProbeError(p.LastError),
  631. XrayState: p.XrayState,
  632. XrayError: p.XrayError,
  633. }
  634. if ok {
  635. r.Status = "online"
  636. } else {
  637. r.Status = "offline"
  638. }
  639. return r
  640. }
  641. func FriendlyProbeError(msg string) string {
  642. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  643. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  644. }
  645. return msg
  646. }