You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.0 KiB

  1. package utils
  2. import (
  3. "github.com/shirou/gopsutil/cpu"
  4. "github.com/shirou/gopsutil/disk"
  5. "github.com/shirou/gopsutil/mem"
  6. "runtime"
  7. "time"
  8. )
  9. const (
  10. B = 1
  11. KB = 1024 * B
  12. MB = 1024 * KB
  13. GB = 1024 * MB
  14. )
  15. type Server struct {
  16. Os Os `json:"os"`
  17. Cpu Cpu `json:"cpu"`
  18. Rrm Rrm `json:"ram"`
  19. Disk Disk `json:"disk"`
  20. }
  21. type Os struct {
  22. GOOS string `json:"goos"`
  23. NumCPU int `json:"numCpu"`
  24. Compiler string `json:"compiler"`
  25. GoVersion string `json:"goVersion"`
  26. NumGoroutine int `json:"numGoroutine"`
  27. }
  28. type Cpu struct {
  29. Cpus []float64 `json:"cpus"`
  30. Cores int `json:"cores"`
  31. }
  32. type Rrm struct {
  33. UsedMB int `json:"usedMb"`
  34. TotalMB int `json:"totalMb"`
  35. UsedPercent int `json:"usedPercent"`
  36. }
  37. type Disk struct {
  38. UsedMB int `json:"usedMb"`
  39. UsedGB int `json:"usedGb"`
  40. TotalMB int `json:"totalMb"`
  41. TotalGB int `json:"totalGb"`
  42. UsedPercent int `json:"usedPercent"`
  43. }
  44. // InitOS OS信息
  45. func InitOS() (o Os) {
  46. o.GOOS = runtime.GOOS
  47. o.NumCPU = runtime.NumCPU()
  48. o.Compiler = runtime.Compiler
  49. o.GoVersion = runtime.Version()
  50. o.NumGoroutine = runtime.NumGoroutine()
  51. return o
  52. }
  53. // InitCPU CPU信息
  54. func InitCPU() (c Cpu, err error) {
  55. if cores, err := cpu.Counts(false); err != nil {
  56. return c, err
  57. } else {
  58. c.Cores = cores
  59. }
  60. if cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true); err != nil {
  61. return c, err
  62. } else {
  63. c.Cpus = cpus
  64. }
  65. return c, nil
  66. }
  67. // InitRAM ARM信息
  68. func InitRAM() (r Rrm, err error) {
  69. if u, err := mem.VirtualMemory(); err != nil{
  70. return r, err
  71. }else {
  72. r.UsedMB = int(u.Used) / MB
  73. r.TotalMB = int(u.Total) / MB
  74. r.UsedPercent = int(u.UsedPercent)
  75. }
  76. return r, nil
  77. }
  78. // InitDisk 硬盘信息
  79. func InitDisk() (d Disk, err error) {
  80. if u, err := disk.Usage("/"); err != nil{
  81. return d, err
  82. } else {
  83. d.UsedMB = int(u.Used) / MB
  84. d.UsedGB = int(u.Used) / GB
  85. d.TotalMB = int(u.Total) / MB
  86. d.TotalGB = int(u.Total) / GB
  87. d.UsedPercent = int(u.UsedPercent)
  88. }
  89. return d, nil
  90. }