node_stat.go 1.1 KB

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