zhangzengfei
2023-11-28 3a706d3378aa3626501370352963883fd2783558
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package sys
 
import (
    "fmt"
    "os"
    "os/exec"
    "sort"
    "time"
    "vamicro/extend/util"
 
    "basic.com/valib/gogpu.git"
 
    "github.com/shirou/gopsutil/cpu"
    "github.com/shirou/gopsutil/disk"
    "github.com/shirou/gopsutil/host"
    "github.com/shirou/gopsutil/mem"
)
 
type SummaryInfo struct {
    Cpu  []float64             `json:"cpu" example:"cpu使用率"`
    Gpu  []gogpu.GpuUnitInfo   `json:"gpu" example:"gpu使用率"`
    Mem  mem.VirtualMemoryStat `json:"mem" example:"内存使用率"`
    Disk disk.UsageStat        `json:"disk" example:"磁盘空间"`
}
 
const Interval time.Duration = time.Second * 60
 
var Stat = &SummaryInfo{}
 
func GatherStat() {
    for range time.Tick(Interval) {
        // Cpu
        if cpuUsedPercent, err := cpu.Percent(time.Second, true); err == nil {
            Stat.Cpu = Stat.Cpu[0:0]
            for _, v := range cpuUsedPercent {
                Stat.Cpu = append(Stat.Cpu, v)
            }
        }
 
        // Memory
        if meminfo, err := mem.VirtualMemory(); err == nil {
            Stat.Mem = *meminfo
        }
 
        // Disk
        if disk, err := disk.Usage("/"); err == nil {
            Stat.Disk = *disk
        }
 
        // Gpu
        agxGpuProcIface := "/sys/devices/gpu.0/load"
 
        if util.Exists(agxGpuProcIface) {
            fd, err1 := os.Open(agxGpuProcIface)
            if err1 == nil {
                var load int64
                fmt.Fscanf(fd, "%d", &load)
                // 模拟nvidia库的输出
                Stat.Gpu = append(Stat.Gpu, gogpu.GpuUnitInfo{
                    GpuMemoryTotal: 1000,
                    GpuMemoryUsed:  load,
                })
                fd.Close()
            }
        } else {
            if gpuInfo, err := gogpu.Info(); err == nil {
                sort.Sort(gogpu.GPURank(gpuInfo.Info))
                Stat.Gpu = Stat.Gpu[0:0]
                for _, v := range gpuInfo.Info {
                    Stat.Gpu = append(Stat.Gpu, v)
                }
            }
        }
    }
}
 
func GetSysInfo() map[string]interface{} {
    return util.Struct2Map(Stat)
}
 
func GetDeviceInfo() map[string]interface{} {
    cmd := exec.Command("/bin/sh", "-c", "lsblk -d | grep -v part | grep -v SWAP | grep -v M | grep disk | awk '{printf $4\" \"}'")
    disks, _ := cmd.Output()
    cpu, _ := cpu.Info()
    mem, _ := mem.VirtualMemory()
    host, _ := host.Info()
 
    return util.Struct2Map(map[string]interface{}{
        "cpu":  cpu,
        "mem":  mem,
        "host": host,
        "disk": string(disks),
    })
}