node.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package analytic
  2. import (
  3. "encoding/json"
  4. "github.com/0xJacky/Nginx-UI/internal/transport"
  5. "github.com/0xJacky/Nginx-UI/internal/upgrader"
  6. "github.com/0xJacky/Nginx-UI/model"
  7. "github.com/shirou/gopsutil/v4/load"
  8. "github.com/shirou/gopsutil/v4/net"
  9. "github.com/uozi-tech/cosy/logger"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "sync"
  14. "time"
  15. )
  16. type NodeInfo struct {
  17. NodeRuntimeInfo upgrader.RuntimeInfo `json:"node_runtime_info"`
  18. Version string `json:"version"`
  19. CPUNum int `json:"cpu_num"`
  20. MemoryTotal string `json:"memory_total"`
  21. DiskTotal string `json:"disk_total"`
  22. }
  23. type NodeStat struct {
  24. AvgLoad *load.AvgStat `json:"avg_load"`
  25. CPUPercent float64 `json:"cpu_percent"`
  26. MemoryPercent float64 `json:"memory_percent"`
  27. DiskPercent float64 `json:"disk_percent"`
  28. Network net.IOCountersStat `json:"network"`
  29. Status bool `json:"status"`
  30. ResponseAt time.Time `json:"response_at"`
  31. }
  32. type Node struct {
  33. EnvironmentID int `json:"environment_id,omitempty"`
  34. *model.Environment
  35. NodeStat
  36. NodeInfo
  37. }
  38. var mutex sync.Mutex
  39. type TNodeMap map[uint64]*Node
  40. var NodeMap TNodeMap
  41. func init() {
  42. NodeMap = make(TNodeMap)
  43. }
  44. func GetNode(env *model.Environment) (n *Node) {
  45. if env == nil {
  46. // this should never happen
  47. logger.Error("env is nil")
  48. return
  49. }
  50. if !env.Enabled {
  51. return &Node{
  52. Environment: env,
  53. }
  54. }
  55. n, ok := NodeMap[env.ID]
  56. if !ok {
  57. n = &Node{}
  58. }
  59. n.Environment = env
  60. return n
  61. }
  62. func InitNode(env *model.Environment) (n *Node) {
  63. n = &Node{
  64. Environment: env,
  65. }
  66. u, err := url.JoinPath(env.URL, "/api/node")
  67. if err != nil {
  68. logger.Error(err)
  69. return
  70. }
  71. t, err := transport.NewTransport()
  72. if err != nil {
  73. return
  74. }
  75. client := http.Client{
  76. Transport: t,
  77. }
  78. req, err := http.NewRequest("GET", u, nil)
  79. if err != nil {
  80. logger.Error(err)
  81. return
  82. }
  83. req.Header.Set("X-Node-Secret", env.Token)
  84. resp, err := client.Do(req)
  85. if err != nil {
  86. logger.Error(err)
  87. return
  88. }
  89. defer resp.Body.Close()
  90. bytes, _ := io.ReadAll(resp.Body)
  91. if resp.StatusCode != http.StatusOK {
  92. logger.Error(string(bytes))
  93. return
  94. }
  95. err = json.Unmarshal(bytes, &n.NodeInfo)
  96. if err != nil {
  97. logger.Error(err)
  98. return
  99. }
  100. return
  101. }