2021-12-23 05:54:41 +08:00
|
|
|
//go:build darwin && !cgo
|
2021-08-18 21:52:13 +08:00
|
|
|
// +build darwin,!cgo
|
2016-02-21 03:37:17 +08:00
|
|
|
|
|
|
|
package mem
|
|
|
|
|
|
|
|
import (
|
2017-12-31 14:25:49 +08:00
|
|
|
"context"
|
2016-02-21 03:37:17 +08:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2017-06-03 04:51:00 +08:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2016-02-21 03:37:17 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Runs vm_stat and returns Free and inactive pages
|
|
|
|
func getVMStat(vms *VirtualMemoryStat) error {
|
2022-03-05 00:18:03 +08:00
|
|
|
out, err := invoke.Command("vm_stat")
|
2016-02-21 03:37:17 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return parseVMStat(string(out), vms)
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseVMStat(out string, vms *VirtualMemoryStat) error {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
lines := strings.Split(out, "\n")
|
2017-06-03 04:51:00 +08:00
|
|
|
pagesize := uint64(unix.Getpagesize())
|
2016-02-21 03:37:17 +08:00
|
|
|
for _, line := range lines {
|
|
|
|
fields := strings.Split(line, ":")
|
|
|
|
if len(fields) < 2 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
key := strings.TrimSpace(fields[0])
|
|
|
|
value := strings.Trim(fields[1], " .")
|
|
|
|
switch key {
|
|
|
|
case "Pages free":
|
|
|
|
free, e := strconv.ParseUint(value, 10, 64)
|
|
|
|
if e != nil {
|
|
|
|
err = e
|
|
|
|
}
|
|
|
|
vms.Free = free * pagesize
|
|
|
|
case "Pages inactive":
|
|
|
|
inactive, e := strconv.ParseUint(value, 10, 64)
|
|
|
|
if e != nil {
|
|
|
|
err = e
|
|
|
|
}
|
|
|
|
vms.Inactive = inactive * pagesize
|
|
|
|
case "Pages active":
|
|
|
|
active, e := strconv.ParseUint(value, 10, 64)
|
|
|
|
if e != nil {
|
|
|
|
err = e
|
|
|
|
}
|
|
|
|
vms.Active = active * pagesize
|
|
|
|
case "Pages wired down":
|
|
|
|
wired, e := strconv.ParseUint(value, 10, 64)
|
|
|
|
if e != nil {
|
|
|
|
err = e
|
|
|
|
}
|
|
|
|
vms.Wired = wired * pagesize
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// VirtualMemory returns VirtualmemoryStat.
|
|
|
|
func VirtualMemory() (*VirtualMemoryStat, error) {
|
2017-12-31 14:25:49 +08:00
|
|
|
return VirtualMemoryWithContext(context.Background())
|
|
|
|
}
|
|
|
|
|
|
|
|
func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) {
|
2016-02-21 03:37:17 +08:00
|
|
|
ret := &VirtualMemoryStat{}
|
|
|
|
|
2016-02-22 14:24:07 +08:00
|
|
|
total, err := getHwMemsize()
|
2016-02-21 03:37:17 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
err = getVMStat(ret)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ret.Available = ret.Free + ret.Inactive
|
|
|
|
ret.Total = total
|
|
|
|
|
2016-02-22 14:24:07 +08:00
|
|
|
ret.Used = ret.Total - ret.Available
|
|
|
|
ret.UsedPercent = 100 * float64(ret.Used) / float64(ret.Total)
|
2016-02-21 03:37:17 +08:00
|
|
|
|
|
|
|
return ret, nil
|
|
|
|
}
|