node.go 21 KB

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