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"
|
2020-07-01 12:47:56 +00:00
|
|
|
"fmt"
|
|
|
|
"unsafe"
|
2017-02-01 18:26:00 +00:00
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-07-01 12:47:56 +00:00
|
|
|
// xsw_usage in sys/sysctl.h
|
|
|
|
type swapUsage struct {
|
|
|
|
Total uint64
|
|
|
|
Avail uint64
|
|
|
|
Used uint64
|
|
|
|
Pagesize int32
|
|
|
|
Encrypted bool
|
|
|
|
}
|
|
|
|
|
2017-02-01 18:26:00 +00:00
|
|
|
// 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) {
|
2020-07-01 12:47:56 +00:00
|
|
|
// https://github.com/yanllearnn/go-osstat/blob/ae8a279d26f52ec946a03698c7f50a26cfb427e3/memory/memory_darwin.go
|
2017-02-01 18:26:00 +00:00
|
|
|
var ret *SwapMemoryStat
|
|
|
|
|
2020-07-01 12:47:56 +00:00
|
|
|
value, err := unix.SysctlRaw("vm.swapusage")
|
2017-02-01 18:26:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return ret, err
|
|
|
|
}
|
2020-07-01 12:47:56 +00:00
|
|
|
if len(value) != 32 {
|
|
|
|
return ret, fmt.Errorf("unexpected output of sysctl vm.swapusage: %v (len: %d)", value, len(value))
|
2017-02-01 18:26:00 +00:00
|
|
|
}
|
2020-07-01 12:47:56 +00:00
|
|
|
swap := (*swapUsage)(unsafe.Pointer(&value[0]))
|
2017-02-01 18:26:00 +00:00
|
|
|
|
|
|
|
u := float64(0)
|
2020-07-01 12:47:56 +00:00
|
|
|
if swap.Total != 0 {
|
|
|
|
u = ((float64(swap.Total) - float64(swap.Avail)) / float64(swap.Total)) * 100.0
|
2017-02-01 18:26:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ret = &SwapMemoryStat{
|
2020-07-01 12:47:56 +00:00
|
|
|
Total: swap.Total,
|
|
|
|
Used: swap.Used,
|
|
|
|
Free: swap.Avail,
|
2017-02-01 18:26:00 +00:00
|
|
|
UsedPercent: u,
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret, nil
|
|
|
|
}
|