u_resource.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package util
  2. import (
  3. "github.com/shirou/gopsutil/cpu"
  4. "github.com/shirou/gopsutil/disk"
  5. "github.com/shirou/gopsutil/mem"
  6. "os/exec"
  7. "strconv"
  8. "strings"
  9. "time"
  10. )
  11. // GetCpuPercent cpu总占用率
  12. func GetCpuPercent() float64 {
  13. percent, _ := cpu.Percent(time.Second, false)
  14. return percent[0]
  15. }
  16. // GetMemoryPercent 内存总占用率
  17. func GetMemoryPercent() float64 {
  18. memory, _ := mem.SwapMemory()
  19. return memory.UsedPercent
  20. }
  21. // GetDiskPercent 磁盘总占用率
  22. func GetDiskPercent() float64 {
  23. parts, _ := disk.Partitions(true)
  24. diskInfo, _ := disk.Usage(parts[0].Mountpoint)
  25. return diskInfo.UsedPercent
  26. }
  27. // GetDiskUsed 解析 df 命令的输出
  28. // df -B1 /dev/vdb
  29. // Filesystem 1B-blocks Used Available Use% Mounted on
  30. // /dev/vdb 527371075584 16390344704 484120408064 4% /mnt/disk001
  31. func GetDiskUsed(filesystem string) (uint64, error) {
  32. cmd := exec.Command("df", "-B1", filesystem)
  33. output, err := cmd.CombinedOutput()
  34. if err != nil {
  35. return 0, err
  36. }
  37. lines := strings.Split(string(output), "\n")
  38. fields := strings.Fields(lines[1])
  39. parseUint, err := strconv.ParseUint(fields[2], 10, 64)
  40. if err != nil {
  41. return 0, err
  42. }
  43. return parseUint, nil
  44. }
  45. // GetDiskUsagePercent 获取磁盘使用率
  46. func GetDiskUsagePercent() (float64, error) {
  47. // 执行 df 命令获取磁盘使用情况
  48. cmd := exec.Command("df", "--total")
  49. output, err := cmd.Output()
  50. if err != nil {
  51. return 0.0, err
  52. }
  53. // 解析 df 命令输出,计算磁盘占比
  54. lines := strings.Split(string(output), "\n")
  55. for _, line := range lines[1:] {
  56. fields := strings.Fields(line)
  57. if len(fields) >= 6 && fields[0] == "total" {
  58. //filesystem := fields[0]
  59. total, _ := strconv.ParseFloat(strings.TrimSuffix(fields[1], "G"), 64)
  60. used, _ := strconv.ParseFloat(strings.TrimSuffix(fields[2], "G"), 64)
  61. usedPercent := (used / total) * 100
  62. //fmt.Printf("文件系统 %s 已使用 %.2f%%\n", filesystem, usedPercent)
  63. return usedPercent, err
  64. }
  65. }
  66. return 0.0, nil
  67. }