mem: Add VirtualMemoryEx() and VirtualMemoryExWithContext()

This commit is contained in:
Xuewei Zhang 2020-01-30 18:46:47 -08:00
parent 3695635d09
commit 929068ccd5
1 changed files with 28 additions and 2 deletions

View File

@ -4,6 +4,7 @@ package mem
import ( import (
"context" "context"
"encoding/json"
"math" "math"
"os" "os"
"strconv" "strconv"
@ -21,11 +22,36 @@ type VirtualMemoryExStat struct {
Unevictable uint64 `json:"unevictable"` Unevictable uint64 `json:"unevictable"`
} }
func (v VirtualMemoryExStat) String() string {
s, _ := json.Marshal(v)
return string(s)
}
func VirtualMemory() (*VirtualMemoryStat, error) { func VirtualMemory() (*VirtualMemoryStat, error) {
return VirtualMemoryWithContext(context.Background()) return VirtualMemoryWithContext(context.Background())
} }
func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { 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") filename := common.HostProc("meminfo")
lines, _ := common.ReadLines(filename) lines, _ := common.ReadLines(filename)
@ -49,7 +75,7 @@ func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) {
t, err := strconv.ParseUint(value, 10, 64) t, err := strconv.ParseUint(value, 10, 64)
if err != nil { if err != nil {
return ret, err return ret, retEx,err
} }
switch key { switch key {
case "MemTotal": case "MemTotal":
@ -144,7 +170,7 @@ func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) {
ret.Used = ret.Total - ret.Free - ret.Buffers - ret.Cached ret.Used = ret.Total - ret.Free - ret.Buffers - ret.Cached
ret.UsedPercent = float64(ret.Used) / float64(ret.Total) * 100.0 ret.UsedPercent = float64(ret.Used) / float64(ret.Total) * 100.0
return ret, nil return ret, retEx, nil
} }
func SwapMemory() (*SwapMemoryStat, error) { func SwapMemory() (*SwapMemoryStat, error) {