memory.go 1.64 KB
Newer Older
“李磊”'s avatar
“李磊” committed
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
package fs2

import (
	"errors"
	"path/filepath"

	"linkfog.com/public/lib/cgroup/fs"
	"linkfog.com/public/lib/cgroup/fscommon"
	"linkfog.com/public/lib/l"
)

func GetMemoryLimit(cgroupDir string, defaultLimit float64) float64 {
	contents, err := fscommon.GetCgroupParamString(filepath.Join(cgroupDir, "memory.max"))
	if err != nil {
		l.Errorf("read memory.max error:%v, use default value", err)
		return defaultLimit
	}
	if contents == "max" {
		l.Warn("memory.max is max, use default value")
		return defaultLimit
	}

	memLimit, err := fscommon.ParseUint(contents, 10, 64)
	if err != nil {
		l.Errorf("parse memory.max error:%v, contents:%s, use default value", err, contents)
		return defaultLimit
	}
	if memLimit == 0 {
		l.Warn("memory.max is 0, use default value")
		return defaultLimit
	}

	return float64(memLimit)
}

func GetMemoryUsage(cgroupDir string) (usage uint64, workingSet uint64, err error) {
	var stats map[string]uint64
	stats, err = fs.ParseMemoryStat(filepath.Join(cgroupDir, "memory.stat"))
	if err != nil {
		return
	}

	usage, err = fscommon.GetCgroupParamUint(filepath.Join(cgroupDir, "memory.current"))
	if err != nil {
		return
	}

	workingSet = usage
	if v, ok := stats["inactive_file"]; ok {
		if workingSet < v {
			workingSet = 0
		} else {
			workingSet -= v
		}
	}

	return
}

func GetKernelMemoryUsage(cgroupDir string) (usage uint64, err error) {
	return 0, errors.New("cgroup2: get kmem usage not implemented")
}

func GetKernelMemorySlabInfo(cgroupDir string) (slabInfo fs.SlabInfo, err error) {
	return fs.SlabInfo{}, errors.New("cgroup2: get kmem slabinfo not implemented")
}