Merge pull request #1205 from mmorel-35/master

enable more linters, report coverage and cache mods
tags/v3.21.12 v3.21.12
shirou 3 years ago committed by GitHub
commit 2f8da0a394
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -13,6 +13,18 @@ jobs:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v2
- id: cache-paths
run: |
echo "::set-output name=cache::$(go env GOCACHE)"
echo "::set-output name=mod-cache::$(go env GOMODCACHE)"
- name: Cache go modules
uses: actions/cache@v2
with:
path: |
${{ steps.cache-paths.outputs.cache }}
${{ steps.cache-paths.outputs.mod-cache }}
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: Build Test v3 - name: Build Test v3
run: | run: |
make build_test make build_test

@ -14,6 +14,25 @@ jobs:
go-version: ${{ matrix.go-version }} go-version: ${{ matrix.go-version }}
- name: Checkout code - name: Checkout code
uses: actions/checkout@v2 uses: actions/checkout@v2
- id: go-env
run: |
echo "::set-output name=cache::$(go env GOCACHE)"
echo "::set-output name=mod-cache::$(go env GOMODCACHE)"
- name: Cache go modules
uses: actions/cache@v2
with:
path: |
${{ steps.go-env.outputs.cache }}
${{ steps.go-env.outputs.mod-cache }}
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: Test - name: Test
run: | run: |
go test ./... go test -coverprofile='coverage.out' -covermode=atomic ./...
- name: Upload Code Coverage
uses: codecov/codecov-action@v2
with:
fail_ci_if_error: true
files: coverage.out
flags: ${{ runner.os }},go-${{ matrix.go-version }}
token: ${{ secrets.CODECOV_TOKEN }}

@ -1,9 +1,35 @@
issues:
max-same-issues: 0
exclude-rules:
- linters:
- gosec
text: "G204"
- linters:
- revive
text: "var-naming"
- linters:
- revive
text: "exported"
linters: linters:
enable: enable:
- asciicheck
- durationcheck
- errorlint - errorlint
- gci - gci
- gofmt
- gofumpt
- goimports
- gosec
- gosimple - gosimple
- importas
- megacheck
- misspell
- nakedret
- nolintlint
- predeclared
- revive
- typecheck - typecheck
- unparam
disable: disable:
- deadcode - deadcode
- errcheck - errcheck

@ -103,5 +103,4 @@ func main() {
issueRemoveUnusedValue() issueRemoveUnusedValue()
} }
} }
} }

@ -51,8 +51,10 @@ type lastPercent struct {
lastPerCPUTimes []TimesStat lastPerCPUTimes []TimesStat
} }
var lastCPUPercent lastPercent var (
var invoke common.Invoker = common.Invoke{} lastCPUPercent lastPercent
invoke common.Invoker = common.Invoke{}
)
func init() { func init() {
lastCPUPercent.Lock() lastCPUPercent.Lock()

@ -1,3 +1,4 @@
//go:build aix
// +build aix // +build aix
package cpu package cpu
@ -56,11 +57,11 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
return nil, err return nil, err
} }
info := InfoStat{ info := InfoStat{
CPU: 0, CPU: 0,
Mhz: float64(c.ProcessorHz / 1000000), Mhz: float64(c.ProcessorHz / 1000000),
Cores: int32(c.NCpusCfg), Cores: int32(c.NCpusCfg),
} }
result := []InfoStat{info}; result := []InfoStat{info}
return result, nil return result, nil
} }
@ -71,4 +72,3 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) {
} }
return c.NCpusCfg, nil return c.NCpusCfg, nil
} }

@ -1,3 +1,4 @@
//go:build darwin
// +build darwin // +build darwin
package cpu package cpu

@ -1,5 +1,5 @@
// +build darwin //go:build darwin && cgo
// +build cgo // +build darwin,cgo
package cpu package cpu
@ -108,5 +108,4 @@ func allCPUTimes() ([]TimesStat, error) {
} }
return []TimesStat{c}, nil return []TimesStat{c}, nil
} }

@ -1,5 +1,5 @@
// +build darwin //go:build darwin && !cgo
// +build !cgo // +build darwin,!cgo
package cpu package cpu

@ -15,14 +15,16 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
var ClocksPerSec = float64(128) var (
var cpuMatch = regexp.MustCompile(`^CPU:`) ClocksPerSec = float64(128)
var originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) cpuMatch = regexp.MustCompile(`^CPU:`)
var featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`)
var featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`)
var cpuEnd = regexp.MustCompile(`^Trying to mount root`) featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`)
var cpuTimesSize int cpuEnd = regexp.MustCompile(`^Trying to mount root`)
var emptyTimes cpuTimes cpuTimesSize int
emptyTimes cpuTimes
)
func init() { func init() {
clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK)

@ -1,3 +1,4 @@
//go:build !darwin && !linux && !freebsd && !openbsd && !solaris && !windows && !dragonfly && !plan9 && !aix
// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!dragonfly,!plan9,!aix // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!dragonfly,!plan9,!aix
package cpu package cpu

@ -15,15 +15,17 @@ import (
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
var ClocksPerSec = float64(128) var (
var cpuMatch = regexp.MustCompile(`^CPU:`) ClocksPerSec = float64(128)
var originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Family\s*=\s*(.+)\s+Model\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`) cpuMatch = regexp.MustCompile(`^CPU:`)
var featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`) originMatch = regexp.MustCompile(`Origin\s*=\s*"(.+)"\s+Id\s*=\s*(.+)\s+Family\s*=\s*(.+)\s+Model\s*=\s*(.+)\s+Stepping\s*=\s*(.+)`)
var featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`) featuresMatch = regexp.MustCompile(`Features=.+<(.+)>`)
var cpuEnd = regexp.MustCompile(`^Trying to mount root`) featuresMatch2 = regexp.MustCompile(`Features2=[a-f\dx]+<(.+)>`)
var cpuCores = regexp.MustCompile(`FreeBSD/SMP: (\d*) package\(s\) x (\d*) core\(s\)`) cpuEnd = regexp.MustCompile(`^Trying to mount root`)
var cpuTimesSize int cpuCores = regexp.MustCompile(`FreeBSD/SMP: (\d*) package\(s\) x (\d*) core\(s\)`)
var emptyTimes cpuTimes cpuTimesSize int
emptyTimes cpuTimes
)
func init() { func init() {
clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK) clkTck, err := sysconf.Sysconf(sysconf.SC_CLK_TCK)

@ -13,7 +13,7 @@ func TestParseDmesgBoot(t *testing.T) {
t.SkipNow() t.SkipNow()
} }
var cpuTests = []struct { cpuTests := []struct {
file string file string
cpuNum int cpuNum int
cores int32 cores int32

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package cpu package cpu
@ -30,7 +31,7 @@ func Times(percpu bool) ([]TimesStat, error) {
func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) { func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) {
filename := common.HostProc("stat") filename := common.HostProc("stat")
var lines = []string{} lines := []string{}
if percpu { if percpu {
statlines, err := common.ReadLines(filename) statlines, err := common.ReadLines(filename)
if err != nil || len(statlines) < 2 { if err != nil || len(statlines) < 2 {
@ -63,7 +64,7 @@ func sysCPUPath(cpu int32, relPath string) string {
return common.HostSys(fmt.Sprintf("devices/system/cpu/cpu%d", cpu), relPath) return common.HostSys(fmt.Sprintf("devices/system/cpu/cpu%d", cpu), relPath)
} }
func finishCPUInfo(c *InfoStat) error { func finishCPUInfo(c *InfoStat) {
var lines []string var lines []string
var err error var err error
var value float64 var value float64
@ -82,17 +83,16 @@ func finishCPUInfo(c *InfoStat) error {
// if we encounter errors below such as there are no cpuinfo_max_freq file, // if we encounter errors below such as there are no cpuinfo_max_freq file,
// we just ignore. so let Mhz is 0. // we just ignore. so let Mhz is 0.
if err != nil || len(lines) == 0 { if err != nil || len(lines) == 0 {
return nil return
} }
value, err = strconv.ParseFloat(lines[0], 64) value, err = strconv.ParseFloat(lines[0], 64)
if err != nil { if err != nil {
return nil return
} }
c.Mhz = value / 1000.0 // value is in kHz c.Mhz = value / 1000.0 // value is in kHz
if c.Mhz > 9999 { if c.Mhz > 9999 {
c.Mhz = c.Mhz / 1000.0 // value in Hz c.Mhz = c.Mhz / 1000.0 // value in Hz
} }
return nil
} }
// CPUInfo on linux will return 1 item per physical thread. // CPUInfo on linux will return 1 item per physical thread.
@ -127,10 +127,7 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
processorName = value processorName = value
case "processor": case "processor":
if c.CPU >= 0 { if c.CPU >= 0 {
err := finishCPUInfo(&c) finishCPUInfo(&c)
if err != nil {
return ret, err
}
ret = append(ret, c) ret = append(ret, c)
} }
c = InfoStat{Cores: 1, ModelName: processorName} c = InfoStat{Cores: 1, ModelName: processorName}
@ -224,10 +221,7 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
} }
} }
if c.CPU >= 0 { if c.CPU >= 0 {
err := finishCPUInfo(&c) finishCPUInfo(&c)
if err != nil {
return ret, err
}
ret = append(ret, c) ret = append(ret, c)
} }
return ret, nil return ret, nil
@ -345,7 +339,7 @@ func CountsWithContext(ctx context.Context, logical bool) (int, error) {
} }
// physical cores // physical cores
// https://github.com/giampaolo/psutil/blob/8415355c8badc9c94418b19bdf26e622f06f0cce/psutil/_pslinux.py#L615-L628 // https://github.com/giampaolo/psutil/blob/8415355c8badc9c94418b19bdf26e622f06f0cce/psutil/_pslinux.py#L615-L628
var threadSiblingsLists = make(map[string]bool) threadSiblingsLists := make(map[string]bool)
// These 2 files are the same but */core_cpus_list is newer while */thread_siblings_list is deprecated and may disappear in the future. // These 2 files are the same but */core_cpus_list is newer while */thread_siblings_list is deprecated and may disappear in the future.
// https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst // https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst
// https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964 // https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964

@ -1,3 +1,4 @@
//go:build openbsd
// +build openbsd // +build openbsd
package cpu package cpu
@ -108,7 +109,7 @@ func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) {
j *= 2 j *= 2
} }
var cpuTimes = make([]int32, cpUStates) cpuTimes := make([]int32, cpUStates)
var mib []int32 var mib []int32
if percpu { if percpu {
mib = []int32{ctlKern, kernCptime2, int32(j)} mib = []int32{ctlKern, kernCptime2, int32(j)}

@ -1,3 +1,4 @@
//go:build plan9
// +build plan9 // +build plan9
package cpu package cpu

@ -1,3 +1,4 @@
//go:build plan9
// +build plan9 // +build plan9
package cpu package cpu

@ -24,7 +24,7 @@ func init() {
} }
} }
//sum all values in a float64 map with float64 keys // sum all values in a float64 map with float64 keys
func msum(x map[float64]float64) float64 { func msum(x map[float64]float64) float64 {
total := 0.0 total := 0.0
for _, y := range x { for _, y := range x {
@ -47,7 +47,7 @@ func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) {
user := make(map[float64]float64) user := make(map[float64]float64)
kern := make(map[float64]float64) kern := make(map[float64]float64)
iowt := make(map[float64]float64) iowt := make(map[float64]float64)
//swap := make(map[float64]float64) // swap := make(map[float64]float64)
kstatSysOut, err := invoke.CommandWithContext(ctx, kstatSys, "-p", "cpu_stat:*:*:/^idle$|^user$|^kernel$|^iowait$|^swap$/") kstatSysOut, err := invoke.CommandWithContext(ctx, kstatSys, "-p", "cpu_stat:*:*:/^idle$|^user$|^kernel$|^iowait$|^swap$/")
if err != nil { if err != nil {
return nil, fmt.Errorf("cannot execute kstat: %s", err) return nil, fmt.Errorf("cannot execute kstat: %s", err)

@ -15,28 +15,36 @@ func TestParseISAInfo(t *testing.T) {
}{ }{
{ {
"1cpu_1core_isainfo.txt", "1cpu_1core_isainfo.txt",
[]string{"rdseed", "adx", "avx2", "fma", "bmi2", "bmi1", "rdrand", "f16c", "vmx", []string{
"rdseed", "adx", "avx2", "fma", "bmi2", "bmi1", "rdrand", "f16c", "vmx",
"avx", "xsave", "pclmulqdq", "aes", "movbe", "sse4.2", "sse4.1", "ssse3", "popcnt", "avx", "xsave", "pclmulqdq", "aes", "movbe", "sse4.2", "sse4.1", "ssse3", "popcnt",
"tscp", "cx16", "sse3", "sse2", "sse", "fxsr", "mmx", "cmov", "amd_sysc", "cx8", "tscp", "cx16", "sse3", "sse2", "sse", "fxsr", "mmx", "cmov", "amd_sysc", "cx8",
"tsc", "fpu"}, "tsc", "fpu",
},
}, },
{ {
"2cpu_1core_isainfo.txt", "2cpu_1core_isainfo.txt",
[]string{"rdseed", "adx", "avx2", "fma", "bmi2", "bmi1", "rdrand", "f16c", "vmx", []string{
"rdseed", "adx", "avx2", "fma", "bmi2", "bmi1", "rdrand", "f16c", "vmx",
"avx", "xsave", "pclmulqdq", "aes", "movbe", "sse4.2", "sse4.1", "ssse3", "popcnt", "avx", "xsave", "pclmulqdq", "aes", "movbe", "sse4.2", "sse4.1", "ssse3", "popcnt",
"tscp", "cx16", "sse3", "sse2", "sse", "fxsr", "mmx", "cmov", "amd_sysc", "cx8", "tscp", "cx16", "sse3", "sse2", "sse", "fxsr", "mmx", "cmov", "amd_sysc", "cx8",
"tsc", "fpu"}, "tsc", "fpu",
},
}, },
{ {
"2cpu_8core_isainfo.txt", "2cpu_8core_isainfo.txt",
[]string{"vmx", "avx", "xsave", "pclmulqdq", "aes", "sse4.2", "sse4.1", "ssse3", "popcnt", []string{
"vmx", "avx", "xsave", "pclmulqdq", "aes", "sse4.2", "sse4.1", "ssse3", "popcnt",
"tscp", "cx16", "sse3", "sse2", "sse", "fxsr", "mmx", "cmov", "amd_sysc", "cx8", "tscp", "cx16", "sse3", "sse2", "sse", "fxsr", "mmx", "cmov", "amd_sysc", "cx8",
"tsc", "fpu"}, "tsc", "fpu",
},
}, },
{ {
"2cpu_12core_isainfo.txt", "2cpu_12core_isainfo.txt",
[]string{"amd_svm", "amd_lzcnt", "popcnt", "amd_sse4a", "tscp", "ahf", "cx16", "sse3", "sse2", []string{
"sse", "fxsr", "amd_3dnowx", "amd_3dnow", "amd_mmx", "mmx", "cmov", "amd_sysc", "cx8", "tsc", "fpu"}, "amd_svm", "amd_lzcnt", "popcnt", "amd_sse4a", "tscp", "ahf", "cx16", "sse3", "sse2",
"sse", "fxsr", "amd_3dnowx", "amd_3dnow", "amd_mmx", "mmx", "cmov", "amd_sysc", "cx8", "tsc", "fpu",
},
}, },
} }

@ -74,7 +74,6 @@ func TestCpu_times(t *testing.T) {
if cpuTotal[0].Idle != 0 { if cpuTotal[0].Idle != 0 {
assert.InEpsilon(t, cpuTotal[0].Idle, perCPUIdleTimeSum, margin) assert.InEpsilon(t, cpuTotal[0].Idle, perCPUIdleTimeSum, margin)
} }
} }
func TestCpu_counts(t *testing.T) { func TestCpu_counts(t *testing.T) {
@ -162,7 +161,6 @@ func testCPUPercent(t *testing.T, percpu bool) {
} }
func testCPUPercentLastUsed(t *testing.T, percpu bool) { func testCPUPercentLastUsed(t *testing.T, percpu bool) {
numcpu := runtime.NumCPU() numcpu := runtime.NumCPU()
testCount := 10 testCount := 10
@ -194,7 +192,6 @@ func testCPUPercentLastUsed(t *testing.T, percpu bool) {
} }
} }
} }
} }
func TestCPUPercent(t *testing.T) { func TestCPUPercent(t *testing.T) {

@ -1,3 +1,4 @@
//go:build windows
// +build windows // +build windows
package cpu package cpu
@ -7,8 +8,8 @@ import (
"fmt" "fmt"
"unsafe" "unsafe"
"github.com/yusufpapurcu/wmi"
"github.com/shirou/gopsutil/v3/internal/common" "github.com/shirou/gopsutil/v3/internal/common"
"github.com/yusufpapurcu/wmi"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
) )

@ -1,86 +1,89 @@
//go:build aix
// +build aix // +build aix
package disk package disk
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/power-devops/perfstat" "github.com/power-devops/perfstat"
"github.com/shirou/gopsutil/v3/internal/common" "github.com/shirou/gopsutil/v3/internal/common"
) )
var FSType map[int]string var FSType map[int]string
func init() { func init() {
FSType = map[int]string{0: "jfs2", 1: "namefs", 2: "nfs", 3: "jfs", 5: "cdrom", 6: "proc", FSType = map[int]string{
16: "special-fs", 17: "cache-fs", 18: "nfs3", 19: "automount-fs", 20: "pool-fs", 32: "vxfs", 0: "jfs2", 1: "namefs", 2: "nfs", 3: "jfs", 5: "cdrom", 6: "proc",
33: "veritas-fs", 34: "udfs", 35: "nfs4", 36: "nfs4-pseudo", 37: "smbfs", 38: "mcr-pseudofs", 16: "special-fs", 17: "cache-fs", 18: "nfs3", 19: "automount-fs", 20: "pool-fs", 32: "vxfs",
39: "ahafs", 40: "sterm-nfs", 41: "asmfs" } 33: "veritas-fs", 34: "udfs", 35: "nfs4", 36: "nfs4-pseudo", 37: "smbfs", 38: "mcr-pseudofs",
39: "ahafs", 40: "sterm-nfs", 41: "asmfs",
}
} }
func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) {
f, err := perfstat.FileSystemStat() f, err := perfstat.FileSystemStat()
if err != nil { if err != nil {
return nil, err return nil, err
} }
ret := make([]PartitionStat, len(f)) ret := make([]PartitionStat, len(f))
for _, fs := range f { for _, fs := range f {
fstyp, exists := FSType[fs.FSType] fstyp, exists := FSType[fs.FSType]
if ! exists { if !exists {
fstyp = "unknown" fstyp = "unknown"
} }
info := PartitionStat{ info := PartitionStat{
Device: fs.Device, Device: fs.Device,
Mountpoint: fs.MountPoint, Mountpoint: fs.MountPoint,
Fstype: fstyp, Fstype: fstyp,
} }
ret = append(ret,info) ret = append(ret, info)
} }
return ret, err return ret, err
} }
func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) { func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOCountersStat, error) {
return nil, common.ErrNotImplementedError return nil, common.ErrNotImplementedError
} }
func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
f, err := perfstat.FileSystemStat() f, err := perfstat.FileSystemStat()
if err != nil { if err != nil {
return nil, err return nil, err
} }
blocksize := uint64(512) blocksize := uint64(512)
for _, fs := range f { for _, fs := range f {
if path == fs.MountPoint { if path == fs.MountPoint {
fstyp, exists := FSType[fs.FSType] fstyp, exists := FSType[fs.FSType]
if ! exists { if !exists {
fstyp = "unknown" fstyp = "unknown"
} }
info := UsageStat{ info := UsageStat{
Path: path, Path: path,
Fstype: fstyp, Fstype: fstyp,
Total: uint64(fs.TotalBlocks) * blocksize, Total: uint64(fs.TotalBlocks) * blocksize,
Free: uint64(fs.FreeBlocks) * blocksize, Free: uint64(fs.FreeBlocks) * blocksize,
Used: uint64(fs.TotalBlocks - fs.FreeBlocks) * blocksize, Used: uint64(fs.TotalBlocks-fs.FreeBlocks) * blocksize,
InodesTotal: uint64(fs.TotalInodes), InodesTotal: uint64(fs.TotalInodes),
InodesFree: uint64(fs.FreeInodes), InodesFree: uint64(fs.FreeInodes),
InodesUsed: uint64(fs.TotalInodes - fs.FreeInodes), InodesUsed: uint64(fs.TotalInodes - fs.FreeInodes),
} }
info.UsedPercent = (float64(info.Used) / float64(info.Total)) * 100.0 info.UsedPercent = (float64(info.Used) / float64(info.Total)) * 100.0
info.InodesUsedPercent = (float64(info.InodesUsed) / float64(info.InodesTotal)) * 100.0 info.InodesUsedPercent = (float64(info.InodesUsed) / float64(info.InodesTotal)) * 100.0
return &info, nil return &info, nil
} }
} }
return nil, fmt.Errorf("mountpoint %s not found", path) return nil, fmt.Errorf("mountpoint %s not found", path)
} }
func SerialNumberWithContext(ctx context.Context, name string) (string, error) { func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
return "", common.ErrNotImplementedError return "", common.ErrNotImplementedError
} }
func LabelWithContext(ctx context.Context, name string) (string, error) { func LabelWithContext(ctx context.Context, name string) (string, error) {
return "", common.ErrNotImplementedError return "", common.ErrNotImplementedError
} }

@ -1,3 +1,4 @@
//go:build darwin
// +build darwin // +build darwin
package disk package disk

@ -1,5 +1,5 @@
// +build darwin //go:build darwin && cgo
// +build cgo // +build darwin,cgo
package disk package disk

@ -1,5 +1,5 @@
// +build darwin //go:build darwin && !cgo
// +build !cgo // +build darwin,!cgo
package disk package disk

@ -1,3 +1,4 @@
//go:build !darwin && !linux && !freebsd && !openbsd && !windows && !solaris && !aix
// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris,!aix // +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris,!aix
package disk package disk

@ -1,3 +1,4 @@
//go:build freebsd
// +build freebsd // +build freebsd
package disk package disk

@ -52,6 +52,7 @@ type devstat struct {
Id *byte Id *byte
Sequence1 uint32 Sequence1 uint32
} }
type bintime struct { type bintime struct {
Sec int32 Sec int32
Frac uint64 Frac uint64

@ -55,6 +55,7 @@ type devstat struct {
Sequence1 uint32 Sequence1 uint32
Pad_cgo_2 [4]byte Pad_cgo_2 [4]byte
} }
type bintime struct { type bintime struct {
Sec int64 Sec int64
Frac uint64 Frac uint64

@ -52,6 +52,7 @@ type devstat struct {
Id *byte Id *byte
Sequence1 uint32 Sequence1 uint32
} }
type bintime struct { type bintime struct {
Sec int32 Sec int32
Frac uint64 Frac uint64

@ -1,5 +1,6 @@
// +build freebsd //go:build freebsd && arm64
// +build arm64 // +build freebsd,arm64
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs disk/types_freebsd.go // cgo -godefs disk/types_freebsd.go

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package disk package disk
@ -21,6 +22,7 @@ import (
const ( const (
sectorSize = 512 sectorSize = 512
) )
const ( const (
// man statfs // man statfs
ADFS_SUPER_MAGIC = 0xadf5 ADFS_SUPER_MAGIC = 0xadf5
@ -484,9 +486,8 @@ func LabelWithContext(ctx context.Context, name string) (string, error) {
dmname, err := ioutil.ReadFile(dmname_filename) dmname, err := ioutil.ReadFile(dmname_filename)
if err != nil { if err != nil {
return "", err return "", err
} else {
return strings.TrimSpace(string(dmname)), nil
} }
return strings.TrimSpace(string(dmname)), nil
} }
func getFsType(stat unix.Statfs_t) string { func getFsType(stat unix.Statfs_t) string {

@ -1,3 +1,4 @@
//go:build openbsd
// +build openbsd // +build openbsd
package disk package disk

@ -1,5 +1,6 @@
// +build openbsd //go:build openbsd && 386
// +build 386 // +build openbsd,386
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs disk/types_openbsd.go // cgo -godefs disk/types_openbsd.go

@ -1,5 +1,6 @@
// +build openbsd //go:build openbsd && arm64
// +build arm64 // +build openbsd,arm64
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs disk/types_openbsd.go // cgo -godefs disk/types_openbsd.go

@ -1,3 +1,4 @@
//go:build solaris
// +build solaris // +build solaris
package disk package disk
@ -23,20 +24,18 @@ const (
_MNTTAB = "/etc/mnttab" _MNTTAB = "/etc/mnttab"
) )
var ( // A blacklist of read-only virtual filesystems. Writable filesystems are of
// A blacklist of read-only virtual filesystems. Writable filesystems are of // operational concern and must not be included in this list.
// operational concern and must not be included in this list. var fsTypeBlacklist = map[string]struct{}{
fsTypeBlacklist = map[string]struct{}{ "ctfs": {},
"ctfs": struct{}{}, "dev": {},
"dev": struct{}{}, "fd": {},
"fd": struct{}{}, "lofs": {},
"lofs": struct{}{}, "lxproc": {},
"lxproc": struct{}{}, "mntfs": {},
"mntfs": struct{}{}, "objfs": {},
"objfs": struct{}{}, "proc": {},
"proc": struct{}{}, }
}
)
func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) { func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, error) {
ret := make([]PartitionStat, 0, _DEFAULT_NUM_MOUNTS) ret := make([]PartitionStat, 0, _DEFAULT_NUM_MOUNTS)
@ -113,6 +112,7 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return usageStat, nil return usageStat, nil
} }
func SerialNumberWithContext(ctx context.Context, name string) (string, error) { func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
return "", common.ErrNotImplementedError return "", common.ErrNotImplementedError
} }

@ -1,3 +1,4 @@
//go:build freebsd || linux || darwin
// +build freebsd linux darwin // +build freebsd linux darwin
package disk package disk

@ -1,3 +1,4 @@
//go:build windows
// +build windows // +build windows
package disk package disk
@ -106,7 +107,7 @@ func PartitionsWithContext(ctx context.Context, all bool) ([]PartitionStat, erro
uintptr(len(lpFileSystemNameBuffer))) uintptr(len(lpFileSystemNameBuffer)))
if driveret == 0 { if driveret == 0 {
if typeret == 5 || typeret == 2 { if typeret == 5 || typeret == 2 {
continue //device is not ready will happen if there is no disk in the drive continue // device is not ready will happen if there is no disk in the drive
} }
return ret, err return ret, err
} }

@ -1,4 +1,6 @@
//go:build ignore
// +build ignore // +build ignore
// Hand writing: _Ctype_struct___0 // Hand writing: _Ctype_struct___0
/* /*
@ -58,5 +60,7 @@ type (
_C_long_double C.longlong _C_long_double C.longlong
) )
type devstat C.struct_devstat type (
type bintime C.struct_bintime devstat C.struct_devstat
bintime C.struct_bintime
)

@ -1,4 +1,6 @@
//go:build ignore
// +build ignore // +build ignore
// Hand writing: _Ctype_struct___0 // Hand writing: _Ctype_struct___0
/* /*
@ -25,8 +27,12 @@ const (
sizeOfDiskstats = C.sizeof_struct_diskstats sizeOfDiskstats = C.sizeof_struct_diskstats
) )
type Diskstats C.struct_diskstats type (
type Timeval C.struct_timeval Diskstats C.struct_diskstats
Timeval C.struct_timeval
)
type Diskstat C.struct_diskstat type (
type bintime C.struct_bintime Diskstat C.struct_diskstat
bintime C.struct_bintime
)

@ -8,8 +8,10 @@ import (
"github.com/shirou/gopsutil/v3/internal/common" "github.com/shirou/gopsutil/v3/internal/common"
) )
var ErrDockerNotAvailable = errors.New("docker not available") var (
var ErrCgroupNotAvailable = errors.New("cgroup not available") ErrDockerNotAvailable = errors.New("docker not available")
ErrCgroupNotAvailable = errors.New("cgroup not available")
)
var invoke common.Invoker = common.Invoke{} var invoke common.Invoker = common.Invoke{}

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package docker package docker

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package docker package docker

@ -1,3 +1,4 @@
//go:build !linux
// +build !linux // +build !linux
package docker package docker

@ -1,3 +1,4 @@
//go:build darwin || freebsd || openbsd
// +build darwin freebsd openbsd // +build darwin freebsd openbsd
package host package host

@ -1,3 +1,4 @@
//go:build darwin
// +build darwin // +build darwin
package host package host
@ -94,7 +95,6 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) {
} }
return ret, nil return ret, nil
} }
func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) { func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) {

@ -14,6 +14,7 @@ type Utmpx struct {
Host [256]int8 Host [256]int8
Pad [16]uint32 Pad [16]uint32
} }
type Timeval struct { type Timeval struct {
Sec int32 Sec int32
} }

@ -14,6 +14,7 @@ type Utmpx struct {
Host [256]int8 Host [256]int8
Pad [16]uint32 Pad [16]uint32
} }
type Timeval struct { type Timeval struct {
Sec int32 Sec int32
} }

@ -1,5 +1,6 @@
// +build darwin //go:build darwin && arm64
// +build arm64 // +build darwin,arm64
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs host/types_darwin.go // cgo -godefs host/types_darwin.go

@ -1,5 +1,5 @@
// +build darwin //go:build darwin && cgo
// +build cgo // +build darwin,cgo
package host package host

@ -1,5 +1,5 @@
// +build darwin //go:build darwin && !cgo
// +build !cgo // +build darwin,!cgo
package host package host

@ -1,3 +1,4 @@
//go:build !darwin && !linux && !freebsd && !openbsd && !solaris && !windows
// +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows
package host package host

@ -1,3 +1,4 @@
//go:build freebsd
// +build freebsd // +build freebsd
package host package host
@ -81,7 +82,6 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) {
} }
return ret, nil return ret, nil
} }
func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) { func PlatformInformationWithContext(ctx context.Context) (string, string, string, error) {

@ -1,24 +1,25 @@
// +build freebsd //go:build freebsd && arm64
// +build arm64 // +build freebsd,arm64
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs host/types_freebsd.go // cgo -godefs host/types_freebsd.go
package host package host
const ( const (
sizeofPtr = 0x8 sizeofPtr = 0x8
sizeofShort = 0x2 sizeofShort = 0x2
sizeofInt = 0x4 sizeofInt = 0x4
sizeofLong = 0x8 sizeofLong = 0x8
sizeofLongLong = 0x8 sizeofLongLong = 0x8
sizeOfUtmpx = 0xc5 sizeOfUtmpx = 0xc5
) )
type ( type (
_C_short int16 _C_short int16
_C_int int32 _C_int int32
_C_long int64 _C_long int64
_C_long_long int64 _C_long_long int64
) )
type Utmp struct { type Utmp struct {

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package host package host
@ -121,7 +122,6 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) {
} }
return ret, nil return ret, nil
} }
func getlsbStruct() (*lsbStruct, error) { func getlsbStruct() (*lsbStruct, error) {
@ -304,7 +304,6 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil
} }
return platform, family, version, nil return platform, family, version, nil
} }
func KernelVersionWithContext(ctx context.Context) (version string, err error) { func KernelVersionWithContext(ctx context.Context) (version string, err error) {

@ -35,10 +35,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__unused [20]int8 X__unused [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type UtTv struct { type UtTv struct {
Sec int32 Sec int32
Usec int32 Usec int32

@ -33,10 +33,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__glibc_reserved [20]int8 X__glibc_reserved [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int64 Sec int64
Usec int64 Usec int64

@ -33,10 +33,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__glibc_reserved [20]int8 X__glibc_reserved [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int32 Sec int32
Usec int32 Usec int32

@ -33,10 +33,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__glibc_reserved [20]int8 X__glibc_reserved [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int64 Sec int64
Usec int64 Usec int64

@ -33,10 +33,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__unused [20]int8 X__unused [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int32 Sec int32
Usec int32 Usec int32

@ -33,10 +33,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__unused [20]int8 X__unused [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int32 Sec int32
Usec int32 Usec int32

@ -33,10 +33,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__unused [20]int8 X__unused [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int32 Sec int32
Usec int32 Usec int32

@ -33,10 +33,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__unused [20]int8 X__unused [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int32 Sec int32
Usec int32 Usec int32

@ -1,5 +1,6 @@
// +build linux //go:build linux && ppc64le
// +build ppc64le // +build linux,ppc64le
// Created by cgo -godefs - DO NOT EDIT // Created by cgo -godefs - DO NOT EDIT
// cgo -godefs types_linux.go // cgo -godefs types_linux.go
@ -35,10 +36,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__glibc_reserved [20]int8 X__glibc_reserved [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int64 Sec int64
Usec int64 Usec int64

@ -32,10 +32,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__glibc_reserved [20]uint8 X__glibc_reserved [20]uint8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int64 Sec int64
Usec int64 Usec int64

@ -1,5 +1,6 @@
// +build linux //go:build linux && s390x
// +build s390x // +build linux,s390x
// Created by cgo -godefs - DO NOT EDIT // Created by cgo -godefs - DO NOT EDIT
// cgo -godefs types_linux.go // cgo -godefs types_linux.go
@ -35,10 +36,12 @@ type utmp struct {
Addr_v6 [4]int32 Addr_v6 [4]int32
X__glibc_reserved [20]int8 X__glibc_reserved [20]int8
} }
type exit_status struct { type exit_status struct {
Termination int16 Termination int16
Exit int16 Exit int16
} }
type timeval struct { type timeval struct {
Sec int64 Sec int64
Usec int64 Usec int64

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package host package host

@ -1,3 +1,4 @@
//go:build openbsd
// +build openbsd // +build openbsd
package host package host

@ -1,5 +1,6 @@
// +build openbsd //go:build openbsd && 386
// +build 386 // +build openbsd,386
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs host/types_openbsd.go // cgo -godefs host/types_openbsd.go

@ -25,6 +25,7 @@ type Utmp struct {
Host [256]int8 Host [256]int8
Time int64 Time int64
} }
type Timeval struct { type Timeval struct {
Sec int64 Sec int64
Usec int64 Usec int64

@ -1,5 +1,6 @@
// +build openbsd //go:build openbsd && arm64
// +build arm64 // +build openbsd,arm64
// Code generated by cmd/cgo -godefs; DO NOT EDIT. // Code generated by cmd/cgo -godefs; DO NOT EDIT.
// cgo -godefs host/types_openbsd.go // cgo -godefs host/types_openbsd.go

@ -1,3 +1,4 @@
//go:build linux || freebsd || openbsd || darwin || solaris
// +build linux freebsd openbsd darwin solaris // +build linux freebsd openbsd darwin solaris
package host package host

@ -1,3 +1,4 @@
//go:build windows
// +build windows // +build windows
package host package host
@ -13,9 +14,9 @@ import (
"time" "time"
"unsafe" "unsafe"
"github.com/yusufpapurcu/wmi"
"github.com/shirou/gopsutil/v3/internal/common" "github.com/shirou/gopsutil/v3/internal/common"
"github.com/shirou/gopsutil/v3/process" "github.com/shirou/gopsutil/v3/process"
"github.com/yusufpapurcu/wmi"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
) )

@ -15,9 +15,8 @@ func (w *Warnings) Add(err error) {
func (w *Warnings) Reference() error { func (w *Warnings) Reference() error {
if len(w.List) > 0 { if len(w.List) > 0 {
return w return w
} else {
return nil
} }
return nil
} }
func (w *Warnings) Error() string { func (w *Warnings) Error() string {

@ -1,4 +1,6 @@
//go:build ignore
// +build ignore // +build ignore
// plus hand editing about timeval // plus hand editing about timeval
/* /*
@ -13,5 +15,7 @@ package host
*/ */
import "C" import "C"
type Utmpx C.struct_utmpx type (
type Timeval C.struct_timeval Utmpx C.struct_utmpx
Timeval C.struct_timeval
)

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
/* /*
@ -40,5 +41,7 @@ type (
_C_long_long C.longlong _C_long_long C.longlong
) )
type Utmp C.struct_utmp // for FreeBSD 9.0 compatibility type (
type Utmpx C.struct_futx Utmp C.struct_utmp // for FreeBSD 9.0 compatibility
Utmpx C.struct_futx
)

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
/* /*
@ -37,6 +38,8 @@ type (
_C_long_long C.longlong _C_long_long C.longlong
) )
type utmp C.struct_utmp type (
type exit_status C.struct_exit_status utmp C.struct_utmp
type timeval C.struct_timeval exit_status C.struct_exit_status
timeval C.struct_timeval
)

@ -1,3 +1,4 @@
//go:build ignore
// +build ignore // +build ignore
/* /*
@ -39,5 +40,7 @@ type (
_C_long_long C.longlong _C_long_long C.longlong
) )
type Utmp C.struct_utmp type (
type Timeval C.struct_timeval Utmp C.struct_utmp
Timeval C.struct_timeval
)

@ -388,8 +388,10 @@ type coder struct {
buf []byte buf []byte
} }
type decoder coder type (
type encoder coder decoder coder
encoder coder
)
func (d *decoder) uint8() uint8 { func (d *decoder) uint8() uint8 {
x := d.buf[0] x := d.buf[0]

@ -98,7 +98,6 @@ var ErrNotImplementedError = errors.New("not implemented yet")
// ReadFile reads contents from a file // ReadFile reads contents from a file
func ReadFile(filename string) (string, error) { func ReadFile(filename string) (string, error) {
content, err := ioutil.ReadFile(filename) content, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -312,7 +311,7 @@ func PathExists(filename string) bool {
return false return false
} }
//GetEnv retrieves the environment variable key. If it does not exist it returns the default. // GetEnv retrieves the environment variable key. If it does not exist it returns the default.
func GetEnv(key string, dfault string, combineWith ...string) string { func GetEnv(key string, dfault string, combineWith ...string) string {
value := os.Getenv(key) value := os.Getenv(key)
if value == "" { if value == "" {

@ -1,3 +1,4 @@
//go:build darwin
// +build darwin // +build darwin
package common package common

@ -1,3 +1,4 @@
//go:build freebsd || openbsd
// +build freebsd openbsd // +build freebsd openbsd
package common package common

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package common package common
@ -55,7 +56,6 @@ func NumProcs() (uint64, error) {
} }
func BootTimeWithContext(ctx context.Context) (uint64, error) { func BootTimeWithContext(ctx context.Context) (uint64, error) {
system, role, err := Virtualization() system, role, err := Virtualization()
if err != nil { if err != nil {
return 0, err return 0, err
@ -201,7 +201,6 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "status")) { if PathExists(filepath.Join(filename, "self", "status")) {
contents, err := ReadLines(filepath.Join(filename, "self", "status")) contents, err := ReadLines(filepath.Join(filename, "self", "status"))
if err == nil { if err == nil {
if StringsContains(contents, "s_context:") || if StringsContains(contents, "s_context:") ||
StringsContains(contents, "VxID:") { StringsContains(contents, "VxID:") {
system = "linux-vserver" system = "linux-vserver"

@ -1,3 +1,4 @@
//go:build openbsd
// +build openbsd // +build openbsd
package common package common

@ -37,6 +37,7 @@ func TestIntToString(t *testing.T) {
t.Error("could not convert") t.Error("could not convert")
} }
} }
func TestByteToString(t *testing.T) { func TestByteToString(t *testing.T) {
src := []byte{65, 66, 67} src := []byte{65, 66, 67}
dst := ByteToString(src) dst := ByteToString(src)
@ -63,12 +64,14 @@ func TestMustParseInt32(t *testing.T) {
t.Error("could not parse") t.Error("could not parse")
} }
} }
func TestMustParseUint64(t *testing.T) { func TestMustParseUint64(t *testing.T) {
ret := mustParseUint64("11111") ret := mustParseUint64("11111")
if ret != uint64(11111) { if ret != uint64(11111) {
t.Error("could not parse") t.Error("could not parse")
} }
} }
func TestMustParseFloat64(t *testing.T) { func TestMustParseFloat64(t *testing.T) {
ret := mustParseFloat64("11111.11") ret := mustParseFloat64("11111.11")
if ret != float64(11111.11) { if ret != float64(11111.11) {
@ -79,6 +82,7 @@ func TestMustParseFloat64(t *testing.T) {
t.Error("could not parse") t.Error("could not parse")
} }
} }
func TestStringsContains(t *testing.T) { func TestStringsContains(t *testing.T) {
target, err := ReadLines("common_test.go") target, err := ReadLines("common_test.go")
if err != nil { if err != nil {

@ -1,3 +1,4 @@
//go:build linux || freebsd || darwin || openbsd
// +build linux freebsd darwin openbsd // +build linux freebsd darwin openbsd
package common package common
@ -56,7 +57,7 @@ func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int
if len(l) == 0 { if len(l) == 0 {
continue continue
} }
i, err := strconv.Atoi(l) i, err := strconv.ParseInt(l, 10, 32)
if err != nil { if err != nil {
continue continue
} }

@ -1,3 +1,4 @@
//go:build windows
// +build windows // +build windows
package common package common
@ -162,7 +163,7 @@ func NewWin32PerformanceCounter(postName, counterName string) (*Win32Performance
if err != nil { if err != nil {
return nil, err return nil, err
} }
var counter = Win32PerformanceCounter{ counter := Win32PerformanceCounter{
Query: query, Query: query,
PostName: postName, PostName: postName,
CounterName: counterName, CounterName: counterName,

@ -8,7 +8,7 @@ import (
// Sleep awaits for provided interval. // Sleep awaits for provided interval.
// Can be interrupted by context cancelation. // Can be interrupted by context cancelation.
func Sleep(ctx context.Context, interval time.Duration) error { func Sleep(ctx context.Context, interval time.Duration) error {
var timer = time.NewTimer(interval) timer := time.NewTimer(interval)
select { select {
case <-ctx.Done(): case <-ctx.Done():
return ctx.Err() return ctx.Err()

@ -11,17 +11,17 @@ import (
func TestSleep(test *testing.T) { func TestSleep(test *testing.T) {
const dt = 50 * time.Millisecond const dt = 50 * time.Millisecond
var t = func(name string, ctx context.Context, expected error) { t := func(name string, ctx context.Context, expected error) {
test.Run(name, func(test *testing.T) { test.Run(name, func(test *testing.T) {
var err = common.Sleep(ctx, dt) err := common.Sleep(ctx, dt)
if !errors.Is(err, expected) { if !errors.Is(err, expected) {
test.Errorf("expected %v, got %v", expected, err) test.Errorf("expected %v, got %v", expected, err)
} }
}) })
} }
var ctx = context.Background() ctx := context.Background()
var canceled, cancel = context.WithCancel(ctx) canceled, cancel := context.WithCancel(ctx)
cancel() cancel()
t("background context", ctx, nil) t("background context", ctx, nil)

@ -1,3 +1,4 @@
//go:build aix
// +build aix // +build aix
package load package load
@ -11,61 +12,60 @@ package load
import "C" import "C"
import ( import (
"context" "context"
"unsafe" "unsafe"
"github.com/power-devops/perfstat" "github.com/power-devops/perfstat"
) )
func Avg() (*AvgStat, error) { func Avg() (*AvgStat, error) {
return AvgWithContext(context.Background()) return AvgWithContext(context.Background())
} }
func AvgWithContext(ctx context.Context) (*AvgStat, error) { func AvgWithContext(ctx context.Context) (*AvgStat, error) {
c, err := perfstat.CpuTotalStat() c, err := perfstat.CpuTotalStat()
if err != nil { if err != nil {
return nil, err return nil, err
} }
ret := &AvgStat{ ret := &AvgStat{
Load1: float64(c.LoadAvg1), Load1: float64(c.LoadAvg1),
Load5: float64(c.LoadAvg5), Load5: float64(c.LoadAvg5),
Load15: float64(c.LoadAvg15), Load15: float64(c.LoadAvg15),
} }
return ret, nil return ret, nil
} }
// Misc returns miscellaneous host-wide statistics. // Misc returns miscellaneous host-wide statistics.
// darwin use ps command to get process running/blocked count. // darwin use ps command to get process running/blocked count.
// Almost same as Darwin implementation, but state is different. // Almost same as Darwin implementation, but state is different.
func Misc() (*MiscStat, error) { func Misc() (*MiscStat, error) {
return MiscWithContext(context.Background()) return MiscWithContext(context.Background())
} }
func MiscWithContext(ctx context.Context) (*MiscStat, error) { func MiscWithContext(ctx context.Context) (*MiscStat, error) {
info := C.struct_procentry64{} info := C.struct_procentry64{}
cpid := C.pid_t(0) cpid := C.pid_t(0)
ret := MiscStat{} ret := MiscStat{}
for { for {
// getprocs first argument is a void* // getprocs first argument is a void*
num, err := C.getprocs64(unsafe.Pointer(&info), C.sizeof_struct_procentry64, nil, 0, &cpid, 1) num, err := C.getprocs64(unsafe.Pointer(&info), C.sizeof_struct_procentry64, nil, 0, &cpid, 1)
if err != nil { if err != nil {
return nil, err return nil, err
} }
ret.ProcsTotal++ ret.ProcsTotal++
switch info.pi_state { switch info.pi_state {
case C.SACTIVE: case C.SACTIVE:
ret.ProcsRunning++ ret.ProcsRunning++
case C.SSTOP: case C.SSTOP:
ret.ProcsBlocked++ ret.ProcsBlocked++
} }
if num == 0 { if num == 0 {
break break
}
} }
return &ret, nil }
return &ret, nil
} }

@ -1,3 +1,4 @@
//go:build darwin
// +build darwin // +build darwin
package load package load

@ -1,3 +1,4 @@
//go:build !darwin && !linux && !freebsd && !openbsd && !windows && !solaris && !aix
// +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris,!aix // +build !darwin,!linux,!freebsd,!openbsd,!windows,!solaris,!aix
package load package load

@ -1,3 +1,4 @@
//go:build freebsd
// +build freebsd // +build freebsd
package load package load

@ -1,3 +1,4 @@
//go:build linux
// +build linux // +build linux
package load package load
@ -17,14 +18,14 @@ func Avg() (*AvgStat, error) {
} }
func AvgWithContext(ctx context.Context) (*AvgStat, error) { func AvgWithContext(ctx context.Context) (*AvgStat, error) {
stat, err := fileAvgWithContext(ctx) stat, err := fileAvgWithContext()
if err != nil { if err != nil {
stat, err = sysinfoAvgWithContext(ctx) stat, err = sysinfoAvgWithContext()
} }
return stat, err return stat, err
} }
func sysinfoAvgWithContext(ctx context.Context) (*AvgStat, error) { func sysinfoAvgWithContext() (*AvgStat, error) {
var info syscall.Sysinfo_t var info syscall.Sysinfo_t
err := syscall.Sysinfo(&info) err := syscall.Sysinfo(&info)
if err != nil { if err != nil {
@ -39,7 +40,7 @@ func sysinfoAvgWithContext(ctx context.Context) (*AvgStat, error) {
}, nil }, nil
} }
func fileAvgWithContext(ctx context.Context) (*AvgStat, error) { func fileAvgWithContext() (*AvgStat, error) {
values, err := readLoadAvgFromFile() values, err := readLoadAvgFromFile()
if err != nil { if err != nil {
return nil, err return nil, err

@ -1,3 +1,4 @@
//go:build openbsd
// +build openbsd // +build openbsd
package load package load

@ -1,3 +1,4 @@
//go:build solaris
// +build solaris // +build solaris
package load package load

@ -71,7 +71,6 @@ func TestMiscStatString(t *testing.T) {
} }
func BenchmarkLoad(b *testing.B) { func BenchmarkLoad(b *testing.B) {
loadAvg := func(t testing.TB) { loadAvg := func(t testing.TB) {
v, err := Avg() v, err := Avg()
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)

@ -1,3 +1,4 @@
//go:build windows
// +build windows // +build windows
package load package load

@ -91,7 +91,7 @@ type SwapMemoryStat struct {
// Linux specific numbers // Linux specific numbers
// https://www.kernel.org/doc/Documentation/cgroup-v2.txt // https://www.kernel.org/doc/Documentation/cgroup-v2.txt
PgMajFault uint64 `json:"pgMajFault"` PgMajFault uint64 `json:"pgMajFault"`
} }
func (m VirtualMemoryStat) String() string { func (m VirtualMemoryStat) String() string {

@ -1,58 +1,59 @@
//go:build aix
// +build aix // +build aix
package mem package mem
import ( import (
"context" "context"
"github.com/power-devops/perfstat" "github.com/power-devops/perfstat"
) )
func VirtualMemory() (*VirtualMemoryStat, error) { func VirtualMemory() (*VirtualMemoryStat, error) {
return VirtualMemoryWithContext(context.Background()) return VirtualMemoryWithContext(context.Background())
} }
func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) {
m, err := perfstat.MemoryTotalStat() m, err := perfstat.MemoryTotalStat()
if err != nil { if err != nil {
return nil, err return nil, err
} }
pagesize := uint64(4096) pagesize := uint64(4096)
ret := VirtualMemoryStat{ ret := VirtualMemoryStat{
Total: uint64(m.RealTotal) * pagesize, Total: uint64(m.RealTotal) * pagesize,
Available: uint64(m.RealAvailable) * pagesize, Available: uint64(m.RealAvailable) * pagesize,
Free: uint64(m.RealFree) * pagesize, Free: uint64(m.RealFree) * pagesize,
Used: uint64(m.RealInUse) * pagesize, Used: uint64(m.RealInUse) * pagesize,
UsedPercent: 100 * float64(m.RealInUse) / float64(m.RealTotal), UsedPercent: 100 * float64(m.RealInUse) / float64(m.RealTotal),
Active: uint64(m.VirtualActive) * pagesize, Active: uint64(m.VirtualActive) * pagesize,
SwapTotal: uint64(m.PgSpTotal) * pagesize, SwapTotal: uint64(m.PgSpTotal) * pagesize,
SwapFree: uint64(m.PgSpFree) * pagesize, SwapFree: uint64(m.PgSpFree) * pagesize,
} }
return &ret, nil return &ret, nil
} }
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) {
m, err := perfstat.MemoryTotalStat() m, err := perfstat.MemoryTotalStat()
if err != nil { if err != nil {
return nil, err return nil, err
} }
pagesize := uint64(4096) pagesize := uint64(4096)
swapUsed := uint64(m.PgSpTotal - m.PgSpFree - m.PgSpRsvd) * pagesize swapUsed := uint64(m.PgSpTotal-m.PgSpFree-m.PgSpRsvd) * pagesize
swapTotal := uint64(m.PgSpTotal) * pagesize swapTotal := uint64(m.PgSpTotal) * pagesize
ret := SwapMemoryStat{ ret := SwapMemoryStat{
Total: swapTotal, Total: swapTotal,
Free: uint64(m.PgSpFree) * pagesize, Free: uint64(m.PgSpFree) * pagesize,
Used: swapUsed, Used: swapUsed,
UsedPercent: float64(100 * swapUsed) / float64(swapTotal), UsedPercent: float64(100*swapUsed) / float64(swapTotal),
Sin: uint64(m.PgSpIn), Sin: uint64(m.PgSpIn),
Sout: uint64(m.PgSpOut), Sout: uint64(m.PgSpOut),
PgIn: uint64(m.PageIn), PgIn: uint64(m.PageIn),
PgOut: uint64(m.PageOut), PgOut: uint64(m.PageOut),
PgFault: uint64(m.PageFaults), PgFault: uint64(m.PageFaults),
} }
return &ret, nil return &ret, nil
} }

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save