[mem][darwin] Remove calls to sysctl binary in mem/mem_darwin.go #639

pull/644/head
Lomanic 6 years ago
parent d110536e10
commit e3c878cc43

@ -5,10 +5,9 @@ package mem
import ( import (
"context" "context"
"encoding/binary" "encoding/binary"
"strconv" "fmt"
"strings" "unsafe"
"github.com/shirou/gopsutil/internal/common"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -27,46 +26,42 @@ func getHwMemsize() (uint64, error) {
return total, nil return total, nil
} }
// xsw_usage in sys/sysctl.h
type swapUsage struct {
Total uint64
Avail uint64
Used uint64
Pagesize int32
Encrypted bool
}
// SwapMemory returns swapinfo. // SwapMemory returns swapinfo.
func SwapMemory() (*SwapMemoryStat, error) { func SwapMemory() (*SwapMemoryStat, error) {
return SwapMemoryWithContext(context.Background()) return SwapMemoryWithContext(context.Background())
} }
func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) { func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
// https://github.com/yanllearnn/go-osstat/blob/ae8a279d26f52ec946a03698c7f50a26cfb427e3/memory/memory_darwin.go
var ret *SwapMemoryStat var ret *SwapMemoryStat
swapUsage, err := common.DoSysctrlWithContext(ctx, "vm.swapusage") value, err := unix.SysctlRaw("vm.swapusage")
if err != nil { if err != nil {
return ret, err return ret, err
} }
if len(value) != 32 {
total := strings.Replace(swapUsage[2], "M", "", 1) return ret, fmt.Errorf("unexpected output of sysctl vm.swapusage: %v (len: %d)", value, len(value))
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
} }
swap := (*swapUsage)(unsafe.Pointer(&value[0]))
u := float64(0) u := float64(0)
if total_v != 0 { if swap.Total != 0 {
u = ((total_v - free_v) / total_v) * 100.0 u = ((float64(swap.Total) - float64(swap.Avail)) / float64(swap.Total)) * 100.0
} }
// vm.swapusage shows "M", multiply 1024 * 1024 to convert bytes.
ret = &SwapMemoryStat{ ret = &SwapMemoryStat{
Total: uint64(total_v * 1024 * 1024), Total: swap.Total,
Used: uint64(used_v * 1024 * 1024), Used: swap.Used,
Free: uint64(free_v * 1024 * 1024), Free: swap.Avail,
UsedPercent: u, UsedPercent: u,
} }

Loading…
Cancel
Save