node.go 19 KB

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