|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io/ioutil" |
| 6 | + "strconv" |
| 7 | + "strings" |
| 8 | + |
| 9 | + psutil "github.com/shirou/gopsutil/mem" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + cgroupV2Path = "/sys/fs/cgroup/memory.max" |
| 14 | + cgroupV1Path = "/sys/fs/cgroup/memory/memory.limit_in_bytes" |
| 15 | + cgroupNoLimitV1 = 0x7FFFFFFFFFFFF000 |
| 16 | +) |
| 17 | + |
| 18 | +// Read file content and parse as uint64 |
| 19 | +func readUintFromFile(path string) (uint64, error) { |
| 20 | + data, err := ioutil.ReadFile(path) |
| 21 | + if err != nil { |
| 22 | + return 0, err |
| 23 | + } |
| 24 | + content := strings.TrimSpace(string(data)) |
| 25 | + return strconv.ParseUint(content, 10, 64) |
| 26 | +} |
| 27 | + |
| 28 | +// Check cgroup v2 memory limit |
| 29 | +func getCgroupV2Limit() (uint64, error) { |
| 30 | + data, err := ioutil.ReadFile(cgroupV2Path) |
| 31 | + if err != nil { |
| 32 | + return 0, err |
| 33 | + } |
| 34 | + content := strings.TrimSpace(string(data)) |
| 35 | + if content == "max" { |
| 36 | + return 0, fmt.Errorf("cgroup v2: no memory limit set") |
| 37 | + } |
| 38 | + limit, err := strconv.ParseUint(content, 10, 64) |
| 39 | + if err != nil || limit == 0 { |
| 40 | + return 0, fmt.Errorf("cgroup v2: invalid memory limit") |
| 41 | + } |
| 42 | + return limit, nil |
| 43 | +} |
| 44 | + |
| 45 | +// Check cgroup v1 memory limit |
| 46 | +func getCgroupV1Limit() (uint64, error) { |
| 47 | + limit, err := readUintFromFile(cgroupV1Path) |
| 48 | + if err != nil { |
| 49 | + return 0, err |
| 50 | + } |
| 51 | + // 0 or cgroup's "infinity" value means no limit |
| 52 | + if limit == 0 || limit >= cgroupNoLimitV1 { |
| 53 | + return 0, fmt.Errorf("cgroup v1: no memory limit set") |
| 54 | + } |
| 55 | + return limit, nil |
| 56 | +} |
| 57 | + |
| 58 | +// Get total memory, prefer cgroup v2 -> cgroup v1 -> host |
| 59 | +func getTotalMemory() (uint64, error) { |
| 60 | + if limit, err := getCgroupV2Limit(); err == nil { |
| 61 | + return limit, nil |
| 62 | + } |
| 63 | + if limit, err := getCgroupV1Limit(); err == nil { |
| 64 | + return limit, nil |
| 65 | + } |
| 66 | + mem, err := psutil.VirtualMemory() |
| 67 | + if err != nil { |
| 68 | + return 0, fmt.Errorf("failed to get system memory: %v", err) |
| 69 | + } |
| 70 | + return mem.Total, nil |
| 71 | +} |
0 commit comments