package fs import ( "bufio" "os" "path/filepath" "linkfog.com/public/lib/cgroup/fscommon" "linkfog.com/public/lib/l" ) var ( defaultMem = "9223372036854771712" ) func MemorySubSystemName() string { return "memory" } func GetMemoryLimit(cgroupDir string, defaultLimit float64) float64 { contents, err := fscommon.GetCgroupParamString(filepath.Join(cgroupDir, "memory.limit_in_bytes")) if err != nil { l.Errorf("read memory.limit_in_bytes error:%v, use default value", err) return defaultLimit } if contents == defaultMem { l.Warn("memory.limit_in_bytes is defaultMem, use default value") return defaultLimit } memLimit, err := fscommon.ParseUint(contents, 10, 64) if err != nil { l.Errorf("parse memory.limit_in_bytes error:%v, contents:%s, use default value", err, contents) return defaultLimit } if memLimit == 0 { l.Warn("memory.limit_in_bytes 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 = ParseMemoryStat(filepath.Join(cgroupDir, "memory.stat")) if err != nil { return } usage, err = fscommon.GetCgroupParamUint(filepath.Join(cgroupDir, "memory.usage_in_bytes")) if err != nil { return } workingSet = usage if v, ok := stats["total_inactive_file"]; ok { if workingSet < v { workingSet = 0 } else { workingSet -= v } } return } func ParseMemoryStat(statPath string) (map[string]uint64, error) { statFile, err := os.Open(statPath) if err != nil { return nil, err } defer statFile.Close() stats := make(map[string]uint64) sc := bufio.NewScanner(statFile) for sc.Scan() { t, v, err := fscommon.ParseKeyValue(sc.Text()) if err != nil { return nil, err } stats[t] = v } if err = sc.Err(); err != nil { return nil, err } return stats, nil } func GetKernelMemoryUsage(cgroupDir string) (usage uint64, err error) { return fscommon.GetCgroupParamUint(filepath.Join(cgroupDir, "memory.kmem.usage_in_bytes")) } func GetKernelMemorySlabInfo(cgroupDir string) (slabInfo SlabInfo, err error) { return ParseSlabInfo(filepath.Join(cgroupDir, "memory.kmem.slabinfo")) }