node_stat.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package analytic
  2. import (
  3. "github.com/shirou/gopsutil/v4/cpu"
  4. "github.com/shirou/gopsutil/v4/load"
  5. "github.com/shirou/gopsutil/v4/net"
  6. "github.com/uozi-tech/cosy/logger"
  7. "math"
  8. "runtime"
  9. "time"
  10. )
  11. func GetNodeStat() (data NodeStat) {
  12. memory, err := GetMemoryStat()
  13. if err != nil {
  14. logger.Error(err)
  15. return
  16. }
  17. cpuTimesBefore, _ := cpu.Times(false)
  18. time.Sleep(1000 * time.Millisecond)
  19. cpuTimesAfter, _ := cpu.Times(false)
  20. threadNum := runtime.GOMAXPROCS(0)
  21. cpuUserUsage := (cpuTimesAfter[0].User - cpuTimesBefore[0].User) / (float64(1000*threadNum) / 1000)
  22. cpuSystemUsage := (cpuTimesAfter[0].System - cpuTimesBefore[0].System) / (float64(1000*threadNum) / 1000)
  23. loadAvg, err := load.Avg()
  24. if err != nil {
  25. logger.Error(err)
  26. return
  27. }
  28. diskStat, err := GetDiskStat()
  29. if err != nil {
  30. logger.Error(err)
  31. return
  32. }
  33. netIO, err := net.IOCounters(false)
  34. if err != nil {
  35. logger.Error(err)
  36. return
  37. }
  38. var network net.IOCountersStat
  39. if len(netIO) > 0 {
  40. network = netIO[0]
  41. }
  42. return NodeStat{
  43. AvgLoad: loadAvg,
  44. CPUPercent: math.Min((cpuUserUsage+cpuSystemUsage)*100, 100),
  45. MemoryPercent: memory.Pressure,
  46. DiskPercent: diskStat.Percentage,
  47. Network: network,
  48. }
  49. }