...

Source file src/github.com/shirou/gopsutil/load/load_darwin.go

Documentation: github.com/shirou/gopsutil/load

     1  // +build darwin
     2  
     3  package load
     4  
     5  import (
     6  	"context"
     7  	"os/exec"
     8  	"strings"
     9  	"unsafe"
    10  
    11  	"golang.org/x/sys/unix"
    12  )
    13  
    14  func Avg() (*AvgStat, error) {
    15  	return AvgWithContext(context.Background())
    16  }
    17  
    18  func AvgWithContext(ctx context.Context) (*AvgStat, error) {
    19  	// This SysctlRaw method borrowed from
    20  	// https://github.com/prometheus/node_exporter/blob/master/collector/loadavg_freebsd.go
    21  	// this implementation is common with BSDs
    22  	type loadavg struct {
    23  		load  [3]uint32
    24  		scale int
    25  	}
    26  	b, err := unix.SysctlRaw("vm.loadavg")
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	load := *(*loadavg)(unsafe.Pointer((&b[0])))
    31  	scale := float64(load.scale)
    32  	ret := &AvgStat{
    33  		Load1:  float64(load.load[0]) / scale,
    34  		Load5:  float64(load.load[1]) / scale,
    35  		Load15: float64(load.load[2]) / scale,
    36  	}
    37  
    38  	return ret, nil
    39  }
    40  
    41  // Misc returnes miscellaneous host-wide statistics.
    42  // darwin use ps command to get process running/blocked count.
    43  // Almost same as FreeBSD implementation, but state is different.
    44  // U means 'Uninterruptible Sleep'.
    45  func Misc() (*MiscStat, error) {
    46  	return MiscWithContext(context.Background())
    47  }
    48  
    49  func MiscWithContext(ctx context.Context) (*MiscStat, error) {
    50  	bin, err := exec.LookPath("ps")
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  	out, err := invoke.CommandWithContext(ctx, bin, "axo", "state")
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	lines := strings.Split(string(out), "\n")
    59  
    60  	ret := MiscStat{}
    61  	for _, l := range lines {
    62  		if strings.Contains(l, "R") {
    63  			ret.ProcsRunning++
    64  		} else if strings.Contains(l, "U") {
    65  			// uninterruptible sleep == blocked
    66  			ret.ProcsBlocked++
    67  		}
    68  	}
    69  
    70  	return &ret, nil
    71  }
    72  

View as plain text