node.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. // Chunk the IN clause to avoid "too many SQL variables" on SQLite
  218. // when there are many node-owned inbounds (common with many nodes).
  219. // sqliteMaxVars is defined in this package (inbound.go).
  220. for _, batch := range chunkInts(inboundIDs, sqliteMaxVars) {
  221. var page []trafficRow
  222. if err := db.Table("client_traffics").
  223. Select("inbound_id, email, enable, total, up, down, expiry_time").
  224. Where("inbound_id IN ?", batch).
  225. Scan(&page).Error; err == nil {
  226. trafficRows = append(trafficRows, page...)
  227. }
  228. }
  229. depletedByNode := make(map[int]int)
  230. if len(trafficRows) > 0 {
  231. for _, row := range trafficRows {
  232. nodeID, ok := nodeByInbound[row.InboundID]
  233. if !ok {
  234. continue
  235. }
  236. expired := row.ExpiryTime > 0 && row.ExpiryTime <= now
  237. exhausted := row.Total > 0 && row.Up+row.Down >= row.Total
  238. if expired || exhausted || !row.Enable {
  239. depletedByNode[nodeID]++
  240. }
  241. }
  242. }
  243. onlineByGuid := s.onlineEmailsByGuid()
  244. for _, n := range nodes {
  245. n.InboundCount = len(inboundsByNode[n.Id])
  246. n.DepletedCount = depletedByNode[n.Id]
  247. // Online is attributed to the node that physically hosts the client
  248. // (by GUID): a client on a sub-node counts under the sub-node, not
  249. // the intermediate node it syncs through (#4983).
  250. n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n)])
  251. }
  252. return nodes, nil
  253. }
  254. func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
  255. svc := InboundService{}
  256. byGuid := svc.GetOnlineClientsByGuid()
  257. out := make(map[string]map[string]struct{}, len(byGuid))
  258. for guid, emails := range byGuid {
  259. set := make(map[string]struct{}, len(emails))
  260. for _, email := range emails {
  261. set[email] = struct{}{}
  262. }
  263. out[guid] = set
  264. }
  265. return out
  266. }
  267. // effectiveNodeGuid is a node's stable online-attribution key: its reported
  268. // panelGuid, or a master-local synthetic id when the node is an old build that
  269. // hasn't reported one yet (#4983).
  270. func effectiveNodeGuid(n *model.Node) string {
  271. if n.Guid != "" {
  272. return n.Guid
  273. }
  274. return synthNodeGuid(n.Id)
  275. }
  276. func (s *NodeService) GetById(id int) (*model.Node, error) {
  277. db := database.GetDB()
  278. n := &model.Node{}
  279. if err := db.Model(model.Node{}).Where("id = ?", id).First(n).Error; err != nil {
  280. return nil, err
  281. }
  282. return n, nil
  283. }
  284. func normalizeBasePath(p string) string {
  285. p = strings.TrimSpace(p)
  286. if p == "" {
  287. return "/"
  288. }
  289. if !strings.HasPrefix(p, "/") {
  290. p = "/" + p
  291. }
  292. if !strings.HasSuffix(p, "/") {
  293. p = p + "/"
  294. }
  295. return p
  296. }
  297. func (s *NodeService) normalize(n *model.Node) error {
  298. n.Name = strings.TrimSpace(n.Name)
  299. n.ApiToken = strings.TrimSpace(n.ApiToken)
  300. if n.Name == "" {
  301. return common.NewError("node name is required")
  302. }
  303. addr, err := netsafe.NormalizeHost(n.Address)
  304. if err != nil {
  305. return common.NewError(err.Error())
  306. }
  307. n.Address = addr
  308. if n.Port <= 0 || n.Port > 65535 {
  309. return common.NewError("node port must be 1-65535")
  310. }
  311. if n.Scheme != "http" && n.Scheme != "https" {
  312. n.Scheme = "https"
  313. }
  314. if n.TlsVerifyMode != "skip" && n.TlsVerifyMode != "pin" {
  315. n.TlsVerifyMode = "verify"
  316. }
  317. n.PinnedCertSha256 = strings.TrimSpace(n.PinnedCertSha256)
  318. if n.TlsVerifyMode == "pin" {
  319. if _, err := decodeCertPin(n.PinnedCertSha256); err != nil {
  320. return common.NewError(err.Error())
  321. }
  322. }
  323. n.BasePath = normalizeBasePath(n.BasePath)
  324. return nil
  325. }
  326. func (s *NodeService) Create(n *model.Node) error {
  327. if err := s.normalize(n); err != nil {
  328. return err
  329. }
  330. db := database.GetDB()
  331. return db.Create(n).Error
  332. }
  333. func (s *NodeService) Update(id int, in *model.Node) error {
  334. if err := s.normalize(in); err != nil {
  335. return err
  336. }
  337. db := database.GetDB()
  338. existing := &model.Node{}
  339. if err := db.Where("id = ?", id).First(existing).Error; err != nil {
  340. return err
  341. }
  342. updates := map[string]any{
  343. "name": in.Name,
  344. "remark": in.Remark,
  345. "scheme": in.Scheme,
  346. "address": in.Address,
  347. "port": in.Port,
  348. "base_path": in.BasePath,
  349. "api_token": in.ApiToken,
  350. "enable": in.Enable,
  351. "allow_private_address": in.AllowPrivateAddress,
  352. "tls_verify_mode": in.TlsVerifyMode,
  353. "pinned_cert_sha256": in.PinnedCertSha256,
  354. }
  355. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  356. return err
  357. }
  358. if mgr := runtime.GetManager(); mgr != nil {
  359. mgr.InvalidateNode(id)
  360. }
  361. return nil
  362. }
  363. func (s *NodeService) Delete(id int) error {
  364. db := database.GetDB()
  365. if err := db.Where("id = ?", id).Delete(model.Node{}).Error; err != nil {
  366. return err
  367. }
  368. if err := db.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  369. return err
  370. }
  371. if mgr := runtime.GetManager(); mgr != nil {
  372. mgr.InvalidateNode(id)
  373. }
  374. nodeMetrics.drop(nodeMetricKey(id, "cpu"))
  375. nodeMetrics.drop(nodeMetricKey(id, "mem"))
  376. return nil
  377. }
  378. func (s *NodeService) SetEnable(id int, enable bool) error {
  379. db := database.GetDB()
  380. return db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error
  381. }
  382. // GetWebCertFiles asks a node for its own web TLS certificate/key file paths,
  383. // used by "Set Cert from Panel" so a node-assigned inbound gets paths that
  384. // exist on the node rather than the central panel. See issue #4854.
  385. func (s *NodeService) GetWebCertFiles(id int) (*runtime.WebCertFiles, error) {
  386. n, err := s.GetById(id)
  387. if err != nil || n == nil {
  388. return nil, fmt.Errorf("node not found")
  389. }
  390. if !n.Enable {
  391. return nil, fmt.Errorf("node is disabled")
  392. }
  393. mgr := runtime.GetManager()
  394. if mgr == nil {
  395. return nil, fmt.Errorf("runtime manager unavailable")
  396. }
  397. remote, err := mgr.RemoteFor(n)
  398. if err != nil {
  399. return nil, err
  400. }
  401. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  402. defer cancel()
  403. return remote.GetWebCertFiles(ctx)
  404. }
  405. // NodeUpdateResult reports the outcome of triggering a panel self-update on one
  406. // node so the UI can show per-node success/failure for a bulk request.
  407. type NodeUpdateResult struct {
  408. Id int `json:"id"`
  409. Name string `json:"name"`
  410. OK bool `json:"ok"`
  411. Error string `json:"error,omitempty"`
  412. }
  413. // UpdatePanels triggers the official self-updater on each given node. Only
  414. // enabled, online nodes are eligible — an offline node can't be reached, so it
  415. // is reported as skipped rather than silently dropped.
  416. func (s *NodeService) UpdatePanels(ids []int) ([]NodeUpdateResult, error) {
  417. mgr := runtime.GetManager()
  418. if mgr == nil {
  419. return nil, fmt.Errorf("runtime manager unavailable")
  420. }
  421. results := make([]NodeUpdateResult, 0, len(ids))
  422. for _, id := range ids {
  423. n, err := s.GetById(id)
  424. if err != nil || n == nil {
  425. results = append(results, NodeUpdateResult{Id: id, OK: false, Error: "node not found"})
  426. continue
  427. }
  428. res := NodeUpdateResult{Id: id, Name: n.Name}
  429. switch {
  430. case !n.Enable:
  431. res.Error = "node is disabled"
  432. case n.Status != "online":
  433. res.Error = "node is offline"
  434. default:
  435. remote, remoteErr := mgr.RemoteFor(n)
  436. if remoteErr != nil {
  437. res.Error = remoteErr.Error()
  438. break
  439. }
  440. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  441. updErr := remote.UpdatePanel(ctx)
  442. cancel()
  443. if updErr != nil {
  444. res.Error = updErr.Error()
  445. } else {
  446. res.OK = true
  447. }
  448. }
  449. results = append(results, res)
  450. }
  451. return results, nil
  452. }
  453. func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
  454. db := database.GetDB()
  455. updates := map[string]any{
  456. "status": p.Status,
  457. "last_heartbeat": p.LastHeartbeat,
  458. "latency_ms": p.LatencyMs,
  459. "xray_version": p.XrayVersion,
  460. "panel_version": p.PanelVersion,
  461. "cpu_pct": p.CpuPct,
  462. "mem_pct": p.MemPct,
  463. "uptime_secs": p.UptimeSecs,
  464. "last_error": p.LastError,
  465. "xray_state": p.XrayState,
  466. "xray_error": p.XrayError,
  467. }
  468. // Only learn the GUID; never clear a known one if an old-build node (or a
  469. // failed probe) reports none, so the stable identity survives blips.
  470. if p.Guid != "" {
  471. updates["guid"] = p.Guid
  472. }
  473. if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
  474. return err
  475. }
  476. if p.Status == "online" {
  477. now := time.Unix(p.LastHeartbeat, 0)
  478. nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
  479. nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
  480. }
  481. return nil
  482. }
  483. func (s *NodeService) MarkNodeDirty(id int) error {
  484. if id <= 0 {
  485. return nil
  486. }
  487. return database.GetDB().Model(model.Node{}).
  488. Where("id = ?", id).
  489. Updates(map[string]any{
  490. "config_dirty": true,
  491. "config_dirty_at": time.Now().UnixMilli(),
  492. }).Error
  493. }
  494. func (s *NodeService) ClearNodeDirty(id int, dirtyAt int64) error {
  495. if id <= 0 {
  496. return nil
  497. }
  498. return database.GetDB().Model(model.Node{}).
  499. Where("id = ? AND config_dirty_at = ?", id, dirtyAt).
  500. Update("config_dirty", false).Error
  501. }
  502. func (s *NodeService) NodeSyncState(id int) (enabled bool, status string, dirty bool, dirtyAt int64, err error) {
  503. if id <= 0 {
  504. return false, "", false, 0, errors.New("invalid node id")
  505. }
  506. var row model.Node
  507. err = database.GetDB().Model(model.Node{}).
  508. Select("enable", "status", "config_dirty", "config_dirty_at").
  509. Where("id = ?", id).
  510. First(&row).Error
  511. if err != nil {
  512. return false, "", false, 0, err
  513. }
  514. return row.Enable, row.Status, row.ConfigDirty, row.ConfigDirtyAt, nil
  515. }
  516. func (s *NodeService) IsNodePending(id int) bool {
  517. enabled, status, dirty, _, err := s.NodeSyncState(id)
  518. if err != nil {
  519. return false
  520. }
  521. return !enabled || status != "online" || dirty
  522. }
  523. func nodeMetricKey(id int, metric string) string {
  524. return "node:" + strconv.Itoa(id) + ":" + metric
  525. }
  526. func (s *NodeService) AggregateNodeMetric(id int, metric string, bucketSeconds int, maxPoints int) []map[string]any {
  527. return nodeMetrics.aggregate(nodeMetricKey(id, metric), bucketSeconds, maxPoints)
  528. }
  529. func (s *NodeService) Probe(ctx context.Context, n *model.Node) (HeartbeatPatch, error) {
  530. patch := HeartbeatPatch{LastHeartbeat: time.Now().Unix()}
  531. addr, err := netsafe.NormalizeHost(n.Address)
  532. if err != nil {
  533. patch.LastError = err.Error()
  534. return patch, err
  535. }
  536. scheme := n.Scheme
  537. if scheme != "http" && scheme != "https" {
  538. scheme = "https"
  539. }
  540. if n.Port <= 0 || n.Port > 65535 {
  541. patch.LastError = "node port must be 1-65535"
  542. return patch, errors.New(patch.LastError)
  543. }
  544. probeURL := &url.URL{
  545. Scheme: scheme,
  546. Host: net.JoinHostPort(addr, strconv.Itoa(n.Port)),
  547. Path: normalizeBasePath(n.BasePath) + "panel/api/server/status",
  548. }
  549. req, err := http.NewRequestWithContext(
  550. netsafe.ContextWithAllowPrivate(ctx, n.AllowPrivateAddress),
  551. http.MethodGet, probeURL.String(), nil)
  552. if err != nil {
  553. patch.LastError = err.Error()
  554. return patch, err
  555. }
  556. if n.ApiToken != "" {
  557. req.Header.Set("Authorization", "Bearer "+n.ApiToken)
  558. }
  559. req.Header.Set("Accept", "application/json")
  560. client, err := nodeHTTPClientFor(n)
  561. if err != nil {
  562. patch.LastError = err.Error()
  563. return patch, err
  564. }
  565. start := time.Now()
  566. resp, err := client.Do(req)
  567. if err != nil {
  568. patch.LastError = err.Error()
  569. return patch, err
  570. }
  571. defer resp.Body.Close()
  572. patch.LatencyMs = int(time.Since(start) / time.Millisecond)
  573. if resp.StatusCode != http.StatusOK {
  574. patch.LastError = fmt.Sprintf("HTTP %d from remote panel", resp.StatusCode)
  575. return patch, errors.New(patch.LastError)
  576. }
  577. var envelope struct {
  578. Success bool `json:"success"`
  579. Msg string `json:"msg"`
  580. Obj *struct {
  581. CpuPct float64 `json:"cpu"`
  582. Mem struct {
  583. Current uint64 `json:"current"`
  584. Total uint64 `json:"total"`
  585. } `json:"mem"`
  586. Xray struct {
  587. Version string `json:"version"`
  588. State string `json:"state"`
  589. ErrorMsg string `json:"errorMsg"`
  590. } `json:"xray"`
  591. PanelVersion string `json:"panelVersion"`
  592. PanelGuid string `json:"panelGuid"`
  593. Uptime uint64 `json:"uptime"`
  594. } `json:"obj"`
  595. }
  596. if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
  597. patch.LastError = "decode response: " + err.Error()
  598. return patch, err
  599. }
  600. if !envelope.Success || envelope.Obj == nil {
  601. patch.LastError = "remote returned success=false: " + envelope.Msg
  602. return patch, errors.New(patch.LastError)
  603. }
  604. o := envelope.Obj
  605. patch.CpuPct = o.CpuPct
  606. if o.Mem.Total > 0 {
  607. patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
  608. }
  609. patch.XrayVersion = o.Xray.Version
  610. patch.XrayState = o.Xray.State
  611. patch.XrayError = o.Xray.ErrorMsg
  612. patch.PanelVersion = o.PanelVersion
  613. patch.Guid = o.PanelGuid
  614. patch.UptimeSecs = o.Uptime
  615. return patch, nil
  616. }
  617. type ProbeResultUI struct {
  618. Status string `json:"status" example:"online"`
  619. LatencyMs int `json:"latencyMs" example:"42"`
  620. XrayVersion string `json:"xrayVersion" example:"25.10.31"`
  621. PanelVersion string `json:"panelVersion" example:"v3.x.x"`
  622. CpuPct float64 `json:"cpuPct" example:"12.5"`
  623. MemPct float64 `json:"memPct" example:"45.2"`
  624. UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
  625. Error string `json:"error"`
  626. // XrayState/XrayError are populated on successful probes even when the node's
  627. // Xray core is not healthy. The UI uses them for a distinct "panel ok, xray failed" indicator.
  628. XrayState string `json:"xrayState"`
  629. XrayError string `json:"xrayError"`
  630. }
  631. func (p HeartbeatPatch) ToUI(ok bool) ProbeResultUI {
  632. r := ProbeResultUI{
  633. LatencyMs: p.LatencyMs,
  634. XrayVersion: p.XrayVersion,
  635. PanelVersion: p.PanelVersion,
  636. CpuPct: p.CpuPct,
  637. MemPct: p.MemPct,
  638. UptimeSecs: p.UptimeSecs,
  639. Error: FriendlyProbeError(p.LastError),
  640. XrayState: p.XrayState,
  641. XrayError: p.XrayError,
  642. }
  643. if ok {
  644. r.Status = "online"
  645. } else {
  646. r.Status = "offline"
  647. }
  648. return r
  649. }
  650. func FriendlyProbeError(msg string) string {
  651. if strings.Contains(msg, "server gave HTTP response to HTTPS client") {
  652. return "the server speaks HTTP, not HTTPS; set the node scheme to http"
  653. }
  654. return msg
  655. }