Files
cmii-uav-watchdog-project/cmii-uav-watchdog-agent/host_info/mem_service.go
2025-12-06 11:26:05 +08:00

74 lines
1.5 KiB
Go

package host_info
import (
"cmii-uav-watchdog-common/models"
"cmii-uav-watchdog-common/wdd_log"
"os"
"strconv"
"strings"
)
// NewMemoryInfo creates a new MemoryInfo instance with default values.
func NewMemoryInfo() models.MemoryInfo {
return models.MemoryInfo{
Total: 0,
Free: 0,
Available: 0,
Used: 0,
Buffers: 0,
Cached: 0,
Shared: 0,
}
}
// GetMemoryInfo reads memory information from /proc/meminfo.
func GetMemoryInfo() models.MemoryInfo {
memInfo := NewMemoryInfo()
data, err := os.ReadFile("/proc/meminfo")
if err != nil {
wdd_log.Error("读取 /proc/meminfo 失败: %v", err)
return memInfo
}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
key := fields[0]
value, err := strconv.ParseUint(fields[1], 10, 64)
if err != nil {
wdd_log.Error("解析 %s 的值失败: %v", key, err)
continue
}
switch key {
case "MemTotal:":
memInfo.Total = value
case "MemFree:":
memInfo.Free = value
case "MemAvailable:":
memInfo.Available = value
case "Buffers:":
memInfo.Buffers = value // 存储 Buffers 值
case "Cached:":
memInfo.Cached = value // 存储 Cached 值
case "Shmem:":
memInfo.Shared = value // 存储 Shared 值
}
}
// 计算已用内存
memInfo.Used = memInfo.Total - memInfo.Free - memInfo.Buffers - memInfo.Cached - memInfo.Shared
return memInfo
}
/*
Total Memory: 16384228 kB
Free Memory: 1234567 kB
Available Memory: 2345678 kB
*/