2017-02-01 18:26:00 +00:00
|
|
|
// +build darwin
|
|
|
|
|
|
|
|
package mem
|
|
|
|
|
|
|
|
import (
|
2018-10-19 18:33:23 +00:00
|
|
|
"context"
|
2017-02-01 18:26:00 +00:00
|
|
|
"encoding/binary"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/shirou/gopsutil/internal/common"
|
2018-10-19 18:33:23 +00:00
|
|
|
"golang.org/x/sys/unix"
|
2017-02-01 18:26:00 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func getHwMemsize() (uint64, error) {
|
2018-10-19 18:33:23 +00:00
|
|
|
totalString, err := unix.Sysctl("hw.memsize")
|
2017-02-01 18:26:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2018-10-19 18:33:23 +00:00
|
|
|
// unix.sysctl() helpfully assumes the result is a null-terminated string and
|
2017-02-01 18:26:00 +00:00
|
|
|
// removes the last byte of the result if it's 0 :/
|
|
|
|
totalString += "\x00"
|
|
|
|
|
|
|
|
total := uint64(binary.LittleEndian.Uint64([]byte(totalString)))
|
|
|
|
|
|
|
|
return total, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// SwapMemory returns swapinfo.
|
|
|
|
func SwapMemory() (*SwapMemoryStat, error) {
|
2018-10-19 18:33:23 +00:00
|
|
|
return SwapMemoryWithContext(context.Background())
|
|
|
|
}
|
|
|
|
|
|
|
|
func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
|
2017-02-01 18:26:00 +00:00
|
|
|
var ret *SwapMemoryStat
|
|
|
|
|
2018-10-19 18:33:23 +00:00
|
|
|
swapUsage, err := common.DoSysctrlWithContext(ctx, "vm.swapusage")
|
2017-02-01 18:26:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return ret, err
|
|
|
|
}
|
|
|
|
|
|
|
|
total := strings.Replace(swapUsage[2], "M", "", 1)
|
|
|
|
used := strings.Replace(swapUsage[5], "M", "", 1)
|
|
|
|
free := strings.Replace(swapUsage[8], "M", "", 1)
|
|
|
|
|
|
|
|
total_v, err := strconv.ParseFloat(total, 64)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
used_v, err := strconv.ParseFloat(used, 64)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
free_v, err := strconv.ParseFloat(free, 64)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
u := float64(0)
|
|
|
|
if total_v != 0 {
|
|
|
|
u = ((total_v - free_v) / total_v) * 100.0
|
|
|
|
}
|
|
|
|
|
|
|
|
// vm.swapusage shows "M", multiply 1024 * 1024 to convert bytes.
|
|
|
|
ret = &SwapMemoryStat{
|
|
|
|
Total: uint64(total_v * 1024 * 1024),
|
|
|
|
Used: uint64(used_v * 1024 * 1024),
|
|
|
|
Free: uint64(free_v * 1024 * 1024),
|
|
|
|
UsedPercent: u,
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret, nil
|
|
|
|
}
|