u_resource.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. package util
  2. import (
  3. "fmt"
  4. "github.com/shirou/gopsutil/cpu"
  5. "github.com/shirou/gopsutil/disk"
  6. "github.com/shirou/gopsutil/mem"
  7. "github.com/shirou/gopsutil/process"
  8. "os/exec"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. type ProcessInfo struct {
  15. Pid int32 `json:"pid"`
  16. Name string `json:"name"`
  17. CpuUsage float64 `json:"cpuUsage"`
  18. MemUsage float32 `json:"memUsage"`
  19. }
  20. func GetTop10CpuAndMem() ([]ProcessInfo, []ProcessInfo) {
  21. // 获取所有进程的CPU占用率
  22. processes, err := process.Processes()
  23. if err != nil {
  24. //fmt.Println("Error:", err)
  25. return nil, nil
  26. }
  27. // 创建一个用于存储进程CPU占用率的映射
  28. cpuPercent := make(map[int32]float64)
  29. memPercent := make(map[int32]float32)
  30. // 获取每个进程的CPU占用率
  31. for _, p := range processes {
  32. pid := p.Pid
  33. cpuPercent[pid], err = p.CPUPercent()
  34. memPercent[pid], err = p.MemoryPercent()
  35. }
  36. // 根据CPU占用率对进程进行排序
  37. sortedPidsCpu := make([]int32, 0, len(cpuPercent))
  38. sortedPidsMem := make([]int32, 0, len(cpuPercent))
  39. for pid := range cpuPercent {
  40. sortedPidsCpu = append(sortedPidsCpu, pid)
  41. }
  42. sort.Slice(sortedPidsCpu, func(i, j int) bool {
  43. return cpuPercent[sortedPidsCpu[i]] > cpuPercent[sortedPidsCpu[j]]
  44. })
  45. // 输出前10个CPU占用率最高的进程名称
  46. var top10Cpu []ProcessInfo
  47. for i, pid := range sortedPidsCpu {
  48. if i >= 10 {
  49. break
  50. }
  51. p, err := process.NewProcess(pid)
  52. if err != nil {
  53. continue
  54. }
  55. name, _ := p.Name()
  56. top10Cpu = append(top10Cpu, ProcessInfo{
  57. Pid: pid,
  58. Name: name,
  59. CpuUsage: cpuPercent[pid],
  60. MemUsage: memPercent[pid],
  61. })
  62. }
  63. // --------------------- 内存
  64. var top10Mem []ProcessInfo
  65. for pid := range memPercent {
  66. sortedPidsMem = append(sortedPidsMem, pid)
  67. }
  68. sort.Slice(sortedPidsMem, func(i, j int) bool {
  69. return memPercent[sortedPidsMem[i]] > memPercent[sortedPidsMem[j]]
  70. })
  71. for i, pid := range sortedPidsMem {
  72. if i >= 10 {
  73. break
  74. }
  75. p, err := process.NewProcess(pid)
  76. if err != nil {
  77. continue
  78. }
  79. name, _ := p.Name()
  80. top10Mem = append(top10Mem, ProcessInfo{
  81. Pid: pid,
  82. Name: name,
  83. CpuUsage: cpuPercent[pid],
  84. MemUsage: memPercent[pid],
  85. })
  86. }
  87. return top10Cpu, top10Mem
  88. }
  89. // cpu总占用率
  90. func GetCpuPercent() float64 {
  91. percent, _ := cpu.Percent(time.Second, false)
  92. return percent[0]
  93. }
  94. // 内存总占用率
  95. func GetMemoryPercent() float64 {
  96. memory, _ := mem.VirtualMemory()
  97. return memory.UsedPercent
  98. }
  99. // 磁盘总占用率
  100. func GetDiskPercent() float64 {
  101. parts, _ := disk.Partitions(true)
  102. diskInfo, _ := disk.Usage(parts[0].Mountpoint)
  103. return diskInfo.UsedPercent
  104. }
  105. // GetDiskUsed 解析 df 命令的输出
  106. // df -B1 /dev/vdb
  107. // Filesystem 1B-blocks Used Available Use% Mounted on
  108. // /dev/vdb 527371075584 16390344704 484120408064 4% /mnt/disk001
  109. func GetDiskUsed(filesystem string) (uint64, error) {
  110. cmd := exec.Command("df", "-B1", filesystem)
  111. output, err := cmd.CombinedOutput()
  112. if err != nil {
  113. return 0, err
  114. }
  115. lines := strings.Split(string(output), "\n")
  116. fields := strings.Fields(lines[1])
  117. parseUint, err := strconv.ParseUint(fields[2], 10, 64)
  118. if err != nil {
  119. return 0, err
  120. }
  121. return parseUint, nil
  122. }
  123. // GetDirectoryDiskUsed 获取目录列表的总大小
  124. func GetDirectoryDiskUsed(directories []string) (uint64, error) {
  125. cmd := exec.Command("du", "-s")
  126. cmd.Args = append(cmd.Args, directories...)
  127. output, err := cmd.CombinedOutput()
  128. if err != nil {
  129. fmt.Println(err)
  130. return 0, err
  131. }
  132. lines := strings.Split(string(output), "\n")
  133. sum := uint64(0)
  134. for _, line := range lines {
  135. if len(line) > 0 {
  136. fmt.Println(line)
  137. fields := strings.Fields(line)
  138. parseUint, err := strconv.ParseUint(fields[0], 10, 64)
  139. fmt.Println("parseUint", parseUint)
  140. if err != nil {
  141. fmt.Println(err)
  142. return 0, err
  143. }
  144. sum += parseUint
  145. }
  146. }
  147. return sum, nil
  148. }
  149. // GetDiskUsagePercent 获取磁盘使用率
  150. func GetDiskUsagePercent() (float64, error) {
  151. // 执行 df 命令获取磁盘使用情况
  152. cmd := exec.Command("df", "--total")
  153. output, err := cmd.Output()
  154. if err != nil {
  155. return 0.0, err
  156. }
  157. // 解析 df 命令输出,计算磁盘占比
  158. lines := strings.Split(string(output), "\n")
  159. for _, line := range lines[1:] {
  160. fields := strings.Fields(line)
  161. if len(fields) >= 6 && fields[0] == "total" {
  162. //filesystem := fields[0]
  163. total, _ := strconv.ParseFloat(strings.TrimSuffix(fields[1], "G"), 64)
  164. used, _ := strconv.ParseFloat(strings.TrimSuffix(fields[2], "G"), 64)
  165. usedPercent := (used / total) * 100
  166. //fmt.Printf("文件系统 %s 已使用 %.2f%%\n", filesystem, usedPercent)
  167. return usedPercent, err
  168. }
  169. }
  170. return 0.0, nil
  171. }