diff --git a/mem/mem_linux.go b/mem/mem_linux.go index 82d1259..66ccca9 100644 --- a/mem/mem_linux.go +++ b/mem/mem_linux.go @@ -4,6 +4,7 @@ package mem import ( "context" + "encoding/json" "math" "os" "strconv" @@ -21,11 +22,36 @@ type VirtualMemoryExStat struct { Unevictable uint64 `json:"unevictable"` } +func (v VirtualMemoryExStat) String() string { + s, _ := json.Marshal(v) + return string(s) +} + func VirtualMemory() (*VirtualMemoryStat, error) { return VirtualMemoryWithContext(context.Background()) } func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { + vm, _, err := fillFromMeminfoWithContext(ctx) + if err != nil { + return nil, err + } + return vm, nil +} + +func VirtualMemoryEx() (*VirtualMemoryExStat, error) { + return VirtualMemoryExWithContext(context.Background()) +} + +func VirtualMemoryExWithContext(ctx context.Context) (*VirtualMemoryExStat, error) { + _, vmEx, err := fillFromMeminfoWithContext(ctx) + if err != nil { + return nil, err + } + return vmEx, nil +} + +func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *VirtualMemoryExStat, error) { filename := common.HostProc("meminfo") lines, _ := common.ReadLines(filename) @@ -49,7 +75,7 @@ func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { t, err := strconv.ParseUint(value, 10, 64) if err != nil { - return ret, err + return ret, retEx,err } switch key { case "MemTotal": @@ -144,7 +170,7 @@ func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { ret.Used = ret.Total - ret.Free - ret.Buffers - ret.Cached ret.UsedPercent = float64(ret.Used) / float64(ret.Total) * 100.0 - return ret, nil + return ret, retEx, nil } func SwapMemory() (*SwapMemoryStat, error) {