enable all go-critic

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
pull/1856/head
Matthieu MOREL 2 months ago
parent 2c7ae10ae6
commit 431dd63e80

@ -41,6 +41,13 @@ linters:
gocritic:
disabled-checks:
- captLocal
- commentedOutCode
- deferInLoop
- hexLiteral
- hugeParam
- tooManyResultsChecker
- unnamedResult
enable-all: true
gomodguard:
blocked:
modules:

@ -135,7 +135,7 @@ func finishCPUInfo(ctx context.Context, c *InfoStat) {
var err error
var value float64
if len(c.CoreID) == 0 {
if c.CoreID == "" {
lines, err = common.ReadLines(sysCPUPath(ctx, c.CPU, "topology/core_id"))
if err == nil {
c.CoreID = lines[0]

@ -35,7 +35,7 @@ var timesTests = []struct {
func TestTimesPlan9(t *testing.T) {
for _, tt := range timesTests {
t.Run(tt.mockedRootFS, func(t *testing.T) {
t.Setenv("HOST_ROOT", filepath.Join("testdata/plan9", tt.mockedRootFS))
t.Setenv("HOST_ROOT", filepath.Join("testdata", "plan9", tt.mockedRootFS))
stats, err := Times(false)
common.SkipIfNotImplementedErr(t, err)
require.NoError(t, err)

@ -140,8 +140,8 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
}
result := make([]InfoStat, 0, len(flags))
for _, proc := range procs {
procWithFlags := proc
for i := range procs {
procWithFlags := procs[i]
procWithFlags.Flags = flags
result = append(result, procWithFlags)
}
@ -149,7 +149,7 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
return result, nil
}
var flagsMatch = regexp.MustCompile(`[\w\.]+`)
var flagsMatch = regexp.MustCompile(`[\w.]+`)
func parseISAInfo(cmdOutput string) ([]string, error) {
words := flagsMatch.FindAllString(cmdOutput, -1)

@ -2,7 +2,6 @@
package cpu
import (
"fmt"
"os"
"runtime"
"testing"
@ -80,7 +79,7 @@ func TestTimeStat_String(t *testing.T) {
Idle: 300.1,
}
e := `{"cpu":"cpu0","user":100.1,"system":200.1,"idle":300.1,"nice":0.0,"iowait":0.0,"irq":0.0,"softirq":0.0,"steal":0.0,"guest":0.0,"guestNice":0.0}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "CPUTimesStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "CPUTimesStat string is invalid: %v", v)
}
func TestInfo(t *testing.T) {

@ -35,7 +35,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
// to prevent accessing uninitialized entries.
// https://github.com/shirou/gopsutil/issues/1390
fs = fs[:count]
for _, stat := range fs {
for i := range fs {
stat := &fs[i]
opts := []string{"rw"}
if stat.Flags&unix.MNT_RDONLY != 0 {
opts = []string{"ro"}
@ -131,8 +132,10 @@ func SerialNumberWithContext(ctx context.Context, _ string) (string, error) {
// Extract all serial numbers into a single string
var serialNumbers []string
for _, spnvmeData := range data.SPNVMeDataType {
for _, item := range spnvmeData.Items {
for i := range data.SPNVMeDataType {
spnvmeData := &data.SPNVMeDataType[i]
for j := range spnvmeData.Items {
item := &spnvmeData.Items[j]
serialNumbers = append(serialNumbers, item.DeviceSerial)
}
}

@ -33,7 +33,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
return ret, err
}
for _, stat := range fs {
for i := range fs {
stat := &fs[i]
opts := []string{"rw"}
if stat.Flags&unix.MNT_RDONLY != 0 {
opts = []string{"ro"}
@ -182,7 +183,8 @@ func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
break
}
}
if err = s.Err(); err != nil {
err = s.Err()
if err != nil {
return "", err
}
return serial, nil

@ -486,7 +486,7 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC
return ret, nil
}
func udevData(ctx context.Context, major uint32, minor uint32, name string) (string, error) {
func udevData(ctx context.Context, major, minor uint32, name string) (string, error) {
udevDataPath := common.HostRunWithContext(ctx, fmt.Sprintf("udev/data/b%d:%d", major, minor))
if f, err := os.Open(udevDataPath); err == nil {
defer f.Close()

@ -57,7 +57,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
return ret, err
}
for _, stat := range buf {
for i := range buf {
stat := &buf[i]
opts := []string{"rw"}
if stat.Flag&MNT_RDONLY != 0 {
opts = []string{"rw"}

@ -27,7 +27,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
return ret, err
}
for _, stat := range fs {
for i := range fs {
stat := &fs[i]
opts := []string{"rw"}
if stat.F_flags&unix.MNT_RDONLY != 0 {
opts = []string{"rw"}

@ -2,7 +2,6 @@
package disk
import (
"fmt"
"runtime"
"sync"
"testing"
@ -81,7 +80,7 @@ func TestUsageStat_String(t *testing.T) {
Fstype: "ext4",
}
e := `{"path":"/","fstype":"ext4","total":1000,"free":2000,"used":3000,"usedPercent":50.1,"inodesTotal":4000,"inodesUsed":5000,"inodesFree":6000,"inodesUsedPercent":49.1}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "DiskUsageStat string is invalid: %v", v)
}
func TestPartitionStat_String(t *testing.T) {
@ -92,7 +91,7 @@ func TestPartitionStat_String(t *testing.T) {
Opts: []string{"ro"},
}
e := `{"device":"sd01","mountpoint":"/","fstype":"ext4","opts":["ro"]}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "DiskUsageStat string is invalid: %v", v)
}
func TestIOCountersStat_String(t *testing.T) {
@ -105,5 +104,5 @@ func TestIOCountersStat_String(t *testing.T) {
SerialNumber: "SERIAL",
}
e := `{"readCount":100,"mergedReadCount":0,"writeCount":200,"mergedWriteCount":0,"readBytes":300,"writeBytes":400,"readTime":0,"writeTime":0,"iopsInProgress":0,"ioTime":0,"weightedIO":0,"name":"sd01","serialNumber":"SERIAL","label":""}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "DiskUsageStat string is invalid: %v", v)
}

@ -192,7 +192,9 @@ func IOCountersWithContext(_ context.Context, names ...string) (map[string]IOCou
return drivemap, err
}
for _, v := range lpBuffer[:lpBufferLen] {
if 'A' <= v && v <= 'Z' {
if 'A' > v || v > 'Z' {
continue
}
path := string(rune(v)) + ":"
typepath, _ := windows.UTF16PtrFromString(path)
typeret := windows.GetDriveType(typepath)
@ -228,7 +230,6 @@ func IOCountersWithContext(_ context.Context, names ...string) (map[string]IOCou
}
}
}
}
return drivemap, nil
}

@ -87,7 +87,7 @@ func GetDockerIDListWithContext(ctx context.Context) ([]string, error) {
// containerID is same as docker id if you use docker.
// If you use container via systemd.slice, you could use
// containerID = docker-<container id>.scope and base=/sys/fs/cgroup/cpuacct/system.slice/
func CgroupCPU(containerID string, base string) (*CgroupCPUStat, error) {
func CgroupCPU(containerID, base string) (*CgroupCPUStat, error) {
return CgroupCPUWithContext(context.Background(), containerID, base)
}
@ -95,18 +95,18 @@ func CgroupCPU(containerID string, base string) (*CgroupCPUStat, error) {
// containerID is same as docker id if you use docker.
// If you use container via systemd.slice, you could use
// containerID = docker-<container id>.scope and base=/sys/fs/cgroup/cpuacct/system.slice/
func CgroupCPUUsage(containerID string, base string) (float64, error) {
func CgroupCPUUsage(containerID, base string) (float64, error) {
return CgroupCPUUsageWithContext(context.Background(), containerID, base)
}
func CgroupCPUWithContext(ctx context.Context, containerID string, base string) (*CgroupCPUStat, error) {
func CgroupCPUWithContext(ctx context.Context, containerID, base string) (*CgroupCPUStat, error) {
statfile := getCgroupFilePath(ctx, containerID, base, "cpuacct", "cpuacct.stat")
lines, err := common.ReadLines(statfile)
if err != nil {
return nil, err
}
// empty containerID means all cgroup
if len(containerID) == 0 {
if containerID == "" {
containerID = "all"
}
@ -166,15 +166,15 @@ func CgroupCPUDockerUsageWithContext(ctx context.Context, containerID string) (f
return CgroupCPUUsageWithContext(ctx, containerID, common.HostSysWithContext(ctx, "fs/cgroup/cpuacct/docker"))
}
func CgroupMem(containerID string, base string) (*CgroupMemStat, error) {
func CgroupMem(containerID, base string) (*CgroupMemStat, error) {
return CgroupMemWithContext(context.Background(), containerID, base)
}
func CgroupMemWithContext(ctx context.Context, containerID string, base string) (*CgroupMemStat, error) {
func CgroupMemWithContext(ctx context.Context, containerID, base string) (*CgroupMemStat, error) {
statfile := getCgroupFilePath(ctx, containerID, base, "memory", "memory.stat")
// empty containerID means all cgroup
if len(containerID) == 0 {
if containerID == "" {
containerID = "all"
}
lines, err := common.ReadLines(statfile)
@ -276,7 +276,7 @@ func CgroupMemDockerWithContext(ctx context.Context, containerID string) (*Cgrou
// getCgroupFilePath constructs file path to get targeted stats file.
func getCgroupFilePath(ctx context.Context, containerID, base, target, file string) string {
if len(base) == 0 {
if base == "" {
base = common.HostSysWithContext(ctx, fmt.Sprintf("fs/cgroup/%s/docker", target))
}
statfile := path.Join(base, containerID, file)

@ -33,11 +33,11 @@ func GetDockerIDListWithContext(_ context.Context) ([]string, error) {
// containerID is same as docker id if you use docker.
// If you use container via systemd.slice, you could use
// containerID = docker-<container id>.scope and base=/sys/fs/cgroup/cpuacct/system.slice/
func CgroupCPU(containerID string, base string) (*CgroupCPUStat, error) {
func CgroupCPU(containerID, base string) (*CgroupCPUStat, error) {
return CgroupCPUWithContext(context.Background(), containerID, base)
}
func CgroupCPUWithContext(_ context.Context, _ string, _ string) (*CgroupCPUStat, error) {
func CgroupCPUWithContext(_ context.Context, _, _ string) (*CgroupCPUStat, error) {
return nil, ErrCgroupNotAvailable
}
@ -49,11 +49,11 @@ func CgroupCPUDockerWithContext(ctx context.Context, containerID string) (*Cgrou
return CgroupCPUWithContext(ctx, containerID, common.HostSysWithContext(ctx, "fs/cgroup/cpuacct/docker"))
}
func CgroupMem(containerID string, base string) (*CgroupMemStat, error) {
func CgroupMem(containerID, base string) (*CgroupMemStat, error) {
return CgroupMemWithContext(context.Background(), containerID, base)
}
func CgroupMemWithContext(_ context.Context, _ string, _ string) (*CgroupMemStat, error) {
func CgroupMemWithContext(_ context.Context, _, _ string) (*CgroupMemStat, error) {
return nil, ErrCgroupNotAvailable
}

@ -160,7 +160,7 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) {
}
// Much of this function could be static. However, to be future proofed, I've made it call the OS for the information in all instances.
func PlatformInformationWithContext(ctx context.Context) (platform string, family string, version string, err error) {
func PlatformInformationWithContext(ctx context.Context) (platform, family, version string, err error) {
// Set the platform (which should always, and only be, "AIX") from `uname -s`
out, err := invoke.CommandWithContext(ctx, "uname", "-s")
if err != nil {

@ -170,7 +170,7 @@ func getlsbStruct(ctx context.Context) (*lsbStruct, error) {
return ret, nil
}
func PlatformInformationWithContext(ctx context.Context) (platform string, family string, version string, err error) {
func PlatformInformationWithContext(ctx context.Context) (platform, family, version string, err error) {
lsb, err := getlsbStruct(ctx)
if err != nil {
lsb = &lsbStruct{}

@ -67,7 +67,7 @@ func numProcs(_ context.Context) (uint64, error) {
return uint64(len(dirs)), nil
}
var kstatMatch = regexp.MustCompile(`([^\s]+)[\s]+([^\s]*)`)
var kstatMatch = regexp.MustCompile(`(\S+)\s+(\S*)`)
func BootTimeWithContext(ctx context.Context) (uint64, error) {
out, err := invoke.CommandWithContext(ctx, "kstat", "-p", "unix:0:system_misc:boot_time")

@ -2,7 +2,6 @@
package host
import (
"fmt"
"os"
"sync"
"testing"
@ -86,7 +85,7 @@ func TestInfoStat_String(t *testing.T) {
KernelArch: "x86_64",
}
e := `{"hostname":"test","uptime":3000,"bootTime":1447040000,"procs":100,"os":"linux","platform":"ubuntu","platformFamily":"","platformVersion":"","kernelVersion":"","kernelArch":"x86_64","virtualizationSystem":"","virtualizationRole":"","hostId":"edfd25ff-3c9c-b1a4-e660-bd826495ad35"}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "HostInfoStat string is invalid:\ngot %v\nwant %v", v, e)
assert.JSONEqf(t, e, v.String(), "HostInfoStat string is invalid:\ngot %v\nwant %v", v, e)
}
func TestUserStat_String(t *testing.T) {
@ -97,7 +96,7 @@ func TestUserStat_String(t *testing.T) {
Started: 100,
}
e := `{"user":"user","terminal":"term","host":"host","started":100}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "UserStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "UserStat string is invalid: %v", v)
}
func TestGuid(t *testing.T) {

@ -136,7 +136,7 @@ func BootTimeWithContext(_ context.Context) (uint64, error) {
return t, nil
}
func PlatformInformationWithContext(_ context.Context) (platform string, family string, version string, err error) {
func PlatformInformationWithContext(_ context.Context) (platform, family, version string, err error) {
platform, family, _, displayVersion, err := platformInformation()
if err != nil {
return "", "", "", err

@ -115,7 +115,7 @@ func ReadLines(filename string) ([]string, error) {
}
// ReadLine reads a file and returns the first occurrence of a line that is prefixed with prefix.
func ReadLine(filename string, prefix string) (string, error) {
func ReadLine(filename, prefix string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", err
@ -156,7 +156,7 @@ func ReadLinesOffsetN(filename string, offset uint, n int) ([]string, error) {
for i := uint(0); i < uint(n)+offset || n < 0; i++ {
line, err := r.ReadString('\n')
if err != nil {
if err == io.EOF && len(line) > 0 {
if err == io.EOF && line != "" {
ret = append(ret, strings.Trim(line, "\n"))
}
break
@ -349,7 +349,7 @@ func PathExistsWithContents(filename string) bool {
// GetEnvWithContext retrieves the environment variable key. If it does not exist it returns the default.
// The context may optionally contain a map superseding os.EnvKey.
func GetEnvWithContext(ctx context.Context, key string, dfault string, combineWith ...string) string {
func GetEnvWithContext(ctx context.Context, key, dfault string, combineWith ...string) string {
var value string
if env, ok := ctx.Value(common.EnvKey).(common.EnvMap); ok {
value = env[common.EnvKeyType(key)]
@ -365,7 +365,7 @@ func GetEnvWithContext(ctx context.Context, key string, dfault string, combineWi
}
// 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, dfault string, combineWith ...string) string {
value := os.Getenv(key)
if value == "" {
value = dfault

@ -317,11 +317,11 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
return system, role, nil
}
func GetOSRelease() (platform string, version string, err error) {
func GetOSRelease() (platform, version string, err error) {
return GetOSReleaseWithContext(context.Background())
}
func GetOSReleaseWithContext(ctx context.Context) (platform string, version string, err error) {
func GetOSReleaseWithContext(ctx context.Context) (platform, version string, err error) {
contents, err := ReadLines(HostEtcWithContext(ctx, "os-release"))
if err != nil {
return "", "", nil // return empty

@ -33,7 +33,7 @@ func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ..
var ret []string
for _, l := range lines[1:] {
if len(l) == 0 {
if l == "" {
continue
}
ret = append(ret, l)

@ -4,6 +4,7 @@
package load
import (
"bytes"
"context"
"regexp"
"strconv"
@ -20,7 +21,7 @@ func AvgWithContext(ctx context.Context) (*AvgStat, error) {
return nil, err
}
idx := strings.Index(string(line), "load average:")
idx := bytes.Index(line, []byte("load average:"))
if idx < 0 {
return nil, common.ErrNotImplementedError
}

@ -45,7 +45,8 @@ func AvgWithContext(ctx context.Context) (*AvgStat, error) {
}
*tgt = float64(v) / (1 << 8)
}
if err = scanner.Err(); err != nil {
err = scanner.Err()
if err != nil {
return nil, err
}

@ -2,7 +2,6 @@
package load
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
@ -28,7 +27,7 @@ func TestAvgStat_String(t *testing.T) {
Load15: 30.1,
}
e := `{"load1":10.1,"load5":20.1,"load15":30.1}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "LoadAvgStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "LoadAvgStat string is invalid: %v", v)
t.Log(e)
}
@ -51,7 +50,7 @@ func TestMiscStatString(t *testing.T) {
Ctxt: 3,
}
e := `{"procsTotal":4,"procsCreated":5,"procsRunning":1,"procsBlocked":2,"ctxt":3}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "TestMiscString string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "TestMiscString string is invalid: %v", v)
t.Log(e)
}

@ -126,7 +126,7 @@ var virtualMemoryTests = []struct {
func TestVirtualMemoryLinux(t *testing.T) {
for _, tt := range virtualMemoryTests {
t.Run(tt.mockedRootFS, func(t *testing.T) {
t.Setenv("HOST_PROC", filepath.Join("testdata/linux/virtualmemory/", tt.mockedRootFS, "proc"))
t.Setenv("HOST_PROC", filepath.Join("testdata", "linux", "virtualmemory", tt.mockedRootFS, "proc"))
stat, err := VirtualMemory()
common.SkipIfNotImplementedErr(t, err)

@ -2,7 +2,6 @@
package mem
import (
"fmt"
"runtime"
"testing"
@ -77,7 +76,7 @@ func TestVirtualMemoryStat_String(t *testing.T) {
}
t.Log(v)
e := `{"total":10,"available":20,"used":30,"usedPercent":30.1,"free":40,"active":0,"inactive":0,"wired":0,"laundry":0,"buffers":0,"cached":0,"writeBack":0,"dirty":0,"writeBackTmp":0,"shared":0,"slab":0,"sreclaimable":0,"sunreclaim":0,"pageTables":0,"swapCached":0,"commitLimit":0,"committedAS":0,"highTotal":0,"highFree":0,"lowTotal":0,"lowFree":0,"swapTotal":0,"swapFree":0,"mapped":0,"vmallocTotal":0,"vmallocUsed":0,"vmallocChunk":0,"hugePagesTotal":0,"hugePagesFree":0,"hugePagesRsvd":0,"hugePagesSurp":0,"hugePageSize":0,"anonHugePages":0}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "VirtualMemoryStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "VirtualMemoryStat string is invalid: %v", v)
}
func TestSwapMemoryStat_String(t *testing.T) {
@ -94,7 +93,7 @@ func TestSwapMemoryStat_String(t *testing.T) {
PgMajFault: 6,
}
e := `{"total":10,"used":30,"free":40,"usedPercent":30.1,"sin":1,"sout":2,"pgIn":3,"pgOut":4,"pgFault":5,"pgMajFault":6}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "SwapMemoryStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "SwapMemoryStat string is invalid: %v", v)
}
func TestSwapDevices(t *testing.T) {

@ -94,7 +94,7 @@ type ConntrackStat struct {
SearchRestart uint32 `json:"searchRestart"` // Conntrack table lookups restarted due to hashtable resizes
}
func NewConntrackStat(e uint32, s uint32, f uint32, n uint32, inv uint32, ign uint32, del uint32, dlst uint32, ins uint32, insfail uint32, drop uint32, edrop uint32, ie uint32, en uint32, ec uint32, ed uint32, sr uint32) *ConntrackStat {
func NewConntrackStat(e, s, f, n, inv, ign, del, dlst, ins, insfail, drop, edrop, ie, en, ec, ed, sr uint32) *ConntrackStat {
return &ConntrackStat{
Entries: e,
Searched: s,

@ -83,7 +83,7 @@ var portMatch = regexp.MustCompile(`(.*)\.(\d+)$`)
// This function only works for netstat returning addresses with a "."
// before the port (0.0.0.0.22 instead of 0.0.0.0:22).
func parseNetstatAddr(local string, remote string, family uint32) (laddr Addr, raddr Addr, err error) {
func parseNetstatAddr(local, remote string, family uint32) (laddr, raddr Addr, err error) {
parse := func(l string) (Addr, error) {
matches := portMatch.FindStringSubmatch(l)
if matches == nil {
@ -183,7 +183,7 @@ func hasCorrectInetProto(kind, proto string) bool {
return false
}
func parseNetstatA(output string, kind string) ([]ConnectionStat, error) {
func parseNetstatA(output, kind string) ([]ConnectionStat, error) {
var ret []ConnectionStat
lines := strings.Split(string(output), "\n")

@ -793,7 +793,7 @@ func processUnix(file string, kind netConnectionKindType, inodes map[string][]in
return ret, nil
}
func updateMap(src map[string][]inodeMap, add map[string][]inodeMap) map[string][]inodeMap {
func updateMap(src, add map[string][]inodeMap) map[string][]inodeMap {
for key, value := range add {
a, exists := src[key]
if !exists {

@ -217,7 +217,7 @@ func parseNetstatLine(line string) (ConnectionStat, error) {
return n, nil
}
func parseNetstatAddr(local string, remote string, family uint32) (laddr Addr, raddr Addr, err error) {
func parseNetstatAddr(local, remote string, family uint32) (laddr, raddr Addr, err error) {
parse := func(l string) (Addr, error) {
matches := portMatch.FindStringSubmatch(l)
if matches == nil {
@ -260,11 +260,7 @@ func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat,
switch strings.ToLower(kind) {
default:
fallthrough
case "":
fallthrough
case "all":
fallthrough
case "inet":
case "", "all", "inet":
// nothing to add
case "inet4":
args = append(args, "-finet")

@ -16,7 +16,7 @@ import (
func TestAddrString(t *testing.T) {
v := Addr{IP: "192.168.0.1", Port: 8000}
s := fmt.Sprintf("%v", v)
s := v.String()
assert.JSONEqf(t, `{"ip":"192.168.0.1","port":8000}`, s, "Addr string is invalid: %v", v)
}
@ -26,7 +26,7 @@ func TestIOCountersStatString(t *testing.T) {
BytesSent: 100,
}
e := `{"name":"test","bytesSent":100,"bytesRecv":0,"packetsSent":0,"packetsRecv":0,"errin":0,"errout":0,"dropin":0,"dropout":0,"fifoin":0,"fifoout":0}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetIOCountersStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "NetIOCountersStat string is invalid: %v", v)
}
func TestProtoCountersStatString(t *testing.T) {
@ -39,7 +39,7 @@ func TestProtoCountersStatString(t *testing.T) {
},
}
e := `{"protocol":"tcp","stats":{"ActiveOpens":4000,"MaxConn":-1,"PassiveOpens":3000}}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetProtoCountersStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "NetProtoCountersStat string is invalid: %v", v)
}
func TestConnectionStatString(t *testing.T) {
@ -50,7 +50,7 @@ func TestConnectionStatString(t *testing.T) {
Uids: []int32{10, 10},
}
e := `{"fd":10,"family":10,"type":10,"localaddr":{"ip":"","port":0},"remoteaddr":{"ip":"","port":0},"status":"","uids":[10,10],"pid":0}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "NetConnectionStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "NetConnectionStat string is invalid: %v", v)
}
func TestIOCountersAll(t *testing.T) {
@ -194,10 +194,10 @@ func TestInterfaceStatString(t *testing.T) {
Addrs: InterfaceAddrList{{Addr: "1.2.3.4"}, {Addr: "5.6.7.8"}},
}
s := fmt.Sprintf("%v", v)
s := v.String()
assert.JSONEqf(t, `{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]}`, s, "InterfaceStat string is invalid: %v", s)
list := InterfaceStatList{v, v}
s = fmt.Sprintf("%v", list)
s = list.String()
assert.JSONEqf(t, `[{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]},{"index":0,"mtu":1500,"name":"eth0","hardwareAddr":"01:23:45:67:89:ab","flags":["up","down"],"addrs":[{"addr":"1.2.3.4"},{"addr":"5.6.7.8"}]}]`, s, "InterfaceStatList string is invalid: %v", s)
}

@ -29,11 +29,7 @@ func ConnectionsPidWithContext(ctx context.Context, kind string, pid int32) ([]C
switch strings.ToLower(kind) {
default:
fallthrough
case "":
fallthrough
case "all":
fallthrough
case "inet":
case "", "all", "inet":
args = append(args, "tcp", "-i", "udp")
case "inet4":
args = append(args, "4")
@ -135,7 +131,7 @@ func parseNetLine(line string) (ConnectionStat, error) {
return n, nil
}
func parseNetAddr(line string) (laddr Addr, raddr Addr, err error) {
func parseNetAddr(line string) (laddr, raddr Addr, err error) {
parse := func(l string) (Addr, error) {
host, port, err := net.SplitHostPort(l)
if err != nil {

@ -45,7 +45,8 @@ func pidsWithContext(_ context.Context) ([]int32, error) {
return ret, err
}
for _, proc := range kprocs {
for i := range kprocs {
proc := &kprocs[i]
ret = append(ret, int32(proc.Proc.P_pid))
}
@ -74,7 +75,7 @@ func (p *Process) NameWithContext(ctx context.Context) (string, error) {
if err != nil {
return "", err
}
if len(cmdName) > 0 {
if cmdName != "" {
extendedName := filepath.Base(cmdName)
if strings.HasPrefix(extendedName, p.name) {
name = extendedName
@ -238,7 +239,7 @@ func (p *Process) getKProc() (*unix.KinfoProc, error) {
// Return value deletes Header line(you must not input wrong arg).
// And splited by Space. Caller have responsibility to manage.
// If passed arg pid is 0, get information from all process.
func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption bool, nameOption bool) ([][]string, error) {
func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption, nameOption bool) ([][]string, error) {
var cmd []string
switch {
case pid == 0: // will get from all processes.
@ -396,7 +397,7 @@ func (p *Process) cmdlineSlice() ([]string, error) {
// of the process.
for _, arg := range args[1:] {
argStr = string(arg)
if len(argStr) > 0 {
if argStr != "" {
if nargs > 0 {
argSlice = append(argSlice, argStr)
nargs--

@ -358,7 +358,7 @@ func (p *Process) ChildrenWithContext(ctx context.Context) ([]*Process, error) {
if err != nil {
continue
}
if int32(ppid) == p.Pid {
if ppid == int64(p.Pid) {
np, err := NewProcessWithContext(ctx, int32(pid))
if err != nil {
continue
@ -639,7 +639,7 @@ func (p *Process) fillFromfdWithContext(ctx context.Context) (int32, []*OpenFile
var openfiles []*OpenFilesStat
for _, fd := range fnames {
fpath := filepath.Join(statPath, fd)
filepath, err := os.Readlink(fpath)
path, err := os.Readlink(fpath)
if err != nil {
continue
}
@ -648,7 +648,7 @@ func (p *Process) fillFromfdWithContext(ctx context.Context) (int32, []*OpenFile
return numFDs, openfiles, err
}
o := &OpenFilesStat{
Path: filepath,
Path: path,
Fd: t,
}
openfiles = append(openfiles, o)

@ -358,7 +358,7 @@ func (p *Process) getKProc() (*KinfoProc, error) {
return &k, nil
}
func callKernProcSyscall(op int32, arg int32) ([]byte, uint64, error) {
func callKernProcSyscall(op, arg int32) ([]byte, uint64, error) {
mib := []int32{CTLKern, KernProc, op, arg, sizeOfKinfoProc, 0}
mibptr := unsafe.Pointer(&mib[0])
miblen := uint64(len(mib))

@ -67,7 +67,8 @@ func getTerminalMap() (map[uint64]string, error) {
for _, name := range termfiles {
stat := unix.Stat_t{}
if err = unix.Stat(name, &stat); err != nil {
err = unix.Stat(name, &stat)
if err != nil {
return nil, err
}
rdev := uint64(stat.Rdev)

@ -446,7 +446,7 @@ func TestConnections(t *testing.T) {
serverConnections := 0
for _, connection := range c {
if connection.Laddr.IP == tcpServerAddrIP && connection.Laddr.Port == uint32(tcpServerAddrPort) && connection.Raddr.Port != 0 {
if connection.Laddr.IP == tcpServerAddrIP && uint64(connection.Laddr.Port) == tcpServerAddrPort && connection.Raddr.Port != 0 {
require.Equalf(t, "ESTABLISHED", connection.Status, "expected server connection to be ESTABLISHED, have %+v", connection)
serverConnections++
}
@ -454,7 +454,7 @@ func TestConnections(t *testing.T) {
clientConnections := 0
for _, connection := range c {
if connection.Raddr.IP == tcpServerAddrIP && connection.Raddr.Port == uint32(tcpServerAddrPort) {
if connection.Raddr.IP == tcpServerAddrIP && uint64(connection.Raddr.Port) == tcpServerAddrPort {
require.Equalf(t, "ESTABLISHED", connection.Status, "expected client connection to be ESTABLISHED, have %+v", connection)
clientConnections++
}

@ -882,7 +882,8 @@ func getFromSnapProcess(pid int32) (int32, int32, string, error) { //nolint:unpa
defer windows.CloseHandle(snap)
var pe32 windows.ProcessEntry32
pe32.Size = uint32(unsafe.Sizeof(pe32))
if err = windows.Process32First(snap, &pe32); err != nil {
err = windows.Process32First(snap, &pe32)
if err != nil {
return 0, 0, "", err
}
for {

@ -3,7 +3,6 @@
package sensors
import (
"fmt"
"os"
"testing"
@ -21,7 +20,7 @@ func TestTemperatureStat_String(t *testing.T) {
Critical: 0.1,
}
s := `{"sensorKey":"CPU","temperature":1.1,"sensorHigh":30.1,"sensorCritical":0.1}`
assert.Equalf(t, s, fmt.Sprintf("%v", v), "TemperatureStat string is invalid, %v", fmt.Sprintf("%v", v))
assert.Equalf(t, s, v.String(), "TemperatureStat string is invalid, %v", v.String())
}
func TestTemperatures(t *testing.T) {

Loading…
Cancel
Save