diff --git a/.golangci.yml b/.golangci.yml index 2c0436b..8f827ac 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -41,6 +41,13 @@ linters: gocritic: disabled-checks: - captLocal + - commentedOutCode + - deferInLoop + - hexLiteral + - hugeParam + - tooManyResultsChecker + - unnamedResult + enable-all: true gomodguard: blocked: modules: diff --git a/cpu/cpu_linux.go b/cpu/cpu_linux.go index a3c60ff..c6ec17e 100644 --- a/cpu/cpu_linux.go +++ b/cpu/cpu_linux.go @@ -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] diff --git a/cpu/cpu_plan9_test.go b/cpu/cpu_plan9_test.go index ebbf948..237b0a3 100644 --- a/cpu/cpu_plan9_test.go +++ b/cpu/cpu_plan9_test.go @@ -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) diff --git a/cpu/cpu_solaris.go b/cpu/cpu_solaris.go index 3dcea89..9494e3c 100644 --- a/cpu/cpu_solaris.go +++ b/cpu/cpu_solaris.go @@ -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) diff --git a/cpu/cpu_test.go b/cpu/cpu_test.go index 9295dcd..ccba2b6 100644 --- a/cpu/cpu_test.go +++ b/cpu/cpu_test.go @@ -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) { diff --git a/disk/disk_darwin.go b/disk/disk_darwin.go index 41187d2..975eb10 100644 --- a/disk/disk_darwin.go +++ b/disk/disk_darwin.go @@ -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) } } diff --git a/disk/disk_freebsd.go b/disk/disk_freebsd.go index bd5eeea..d920993 100644 --- a/disk/disk_freebsd.go +++ b/disk/disk_freebsd.go @@ -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 diff --git a/disk/disk_linux.go b/disk/disk_linux.go index 8a0a5b1..54fdf05 100644 --- a/disk/disk_linux.go +++ b/disk/disk_linux.go @@ -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() diff --git a/disk/disk_netbsd.go b/disk/disk_netbsd.go index 9d9e56f..1859405 100644 --- a/disk/disk_netbsd.go +++ b/disk/disk_netbsd.go @@ -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"} diff --git a/disk/disk_openbsd.go b/disk/disk_openbsd.go index 2b0ce10..65d16b5 100644 --- a/disk/disk_openbsd.go +++ b/disk/disk_openbsd.go @@ -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"} diff --git a/disk/disk_test.go b/disk/disk_test.go index 1e665d7..aea50d9 100644 --- a/disk/disk_test.go +++ b/disk/disk_test.go @@ -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) } diff --git a/disk/disk_windows.go b/disk/disk_windows.go index 4e605e2..0abc844 100644 --- a/disk/disk_windows.go +++ b/disk/disk_windows.go @@ -192,40 +192,41 @@ func IOCountersWithContext(_ context.Context, names ...string) (map[string]IOCou return drivemap, err } for _, v := range lpBuffer[:lpBufferLen] { - if 'A' <= v && v <= 'Z' { - path := string(rune(v)) + ":" - typepath, _ := windows.UTF16PtrFromString(path) - typeret := windows.GetDriveType(typepath) - if typeret != windows.DRIVE_FIXED { + if 'A' > v || v > 'Z' { + continue + } + path := string(rune(v)) + ":" + typepath, _ := windows.UTF16PtrFromString(path) + typeret := windows.GetDriveType(typepath) + if typeret != windows.DRIVE_FIXED { + continue + } + szDevice := `\\.\` + path + const IOCTL_DISK_PERFORMANCE = 0x70020 + h, err := windows.CreateFile(syscall.StringToUTF16Ptr(szDevice), 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0) + if err != nil { + if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { continue } - szDevice := `\\.\` + path - const IOCTL_DISK_PERFORMANCE = 0x70020 - h, err := windows.CreateFile(syscall.StringToUTF16Ptr(szDevice), 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0) - if err != nil { - if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) { - continue - } - return drivemap, err - } - defer windows.CloseHandle(h) + return drivemap, err + } + defer windows.CloseHandle(h) - var diskPerformanceSize uint32 - err = windows.DeviceIoControl(h, IOCTL_DISK_PERFORMANCE, nil, 0, (*byte)(unsafe.Pointer(&diskPerformance)), uint32(unsafe.Sizeof(diskPerformance)), &diskPerformanceSize, nil) - if err != nil { - return drivemap, err - } + var diskPerformanceSize uint32 + err = windows.DeviceIoControl(h, IOCTL_DISK_PERFORMANCE, nil, 0, (*byte)(unsafe.Pointer(&diskPerformance)), uint32(unsafe.Sizeof(diskPerformance)), &diskPerformanceSize, nil) + if err != nil { + return drivemap, err + } - if len(names) == 0 || common.StringsHas(names, path) { - drivemap[path] = IOCountersStat{ - ReadBytes: uint64(diskPerformance.BytesRead), - WriteBytes: uint64(diskPerformance.BytesWritten), - ReadCount: uint64(diskPerformance.ReadCount), - WriteCount: uint64(diskPerformance.WriteCount), - ReadTime: uint64(diskPerformance.ReadTime / 10000 / 1000), // convert to ms: https://github.com/giampaolo/psutil/issues/1012 - WriteTime: uint64(diskPerformance.WriteTime / 10000 / 1000), - Name: path, - } + if len(names) == 0 || common.StringsHas(names, path) { + drivemap[path] = IOCountersStat{ + ReadBytes: uint64(diskPerformance.BytesRead), + WriteBytes: uint64(diskPerformance.BytesWritten), + ReadCount: uint64(diskPerformance.ReadCount), + WriteCount: uint64(diskPerformance.WriteCount), + ReadTime: uint64(diskPerformance.ReadTime / 10000 / 1000), // convert to ms: https://github.com/giampaolo/psutil/issues/1012 + WriteTime: uint64(diskPerformance.WriteTime / 10000 / 1000), + Name: path, } } } diff --git a/docker/docker_linux.go b/docker/docker_linux.go index 4002136..1221900 100644 --- a/docker/docker_linux.go +++ b/docker/docker_linux.go @@ -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-.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-.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) diff --git a/docker/docker_notlinux.go b/docker/docker_notlinux.go index 18605af..d293e90 100644 --- a/docker/docker_notlinux.go +++ b/docker/docker_notlinux.go @@ -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-.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 } diff --git a/host/host_aix.go b/host/host_aix.go index 54382a5..2e8fb55 100644 --- a/host/host_aix.go +++ b/host/host_aix.go @@ -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 { diff --git a/host/host_linux.go b/host/host_linux.go index ee9b2af..3e7d725 100644 --- a/host/host_linux.go +++ b/host/host_linux.go @@ -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{} diff --git a/host/host_solaris.go b/host/host_solaris.go index d5350bf..77cd1ab 100644 --- a/host/host_solaris.go +++ b/host/host_solaris.go @@ -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") diff --git a/host/host_test.go b/host/host_test.go index 5432f71..1751025 100644 --- a/host/host_test.go +++ b/host/host_test.go @@ -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) { diff --git a/host/host_windows.go b/host/host_windows.go index 5eb9661..21a7661 100644 --- a/host/host_windows.go +++ b/host/host_windows.go @@ -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 diff --git a/internal/common/common.go b/internal/common/common.go index 4f9b2f7..d48b41e 100644 --- a/internal/common/common.go +++ b/internal/common/common.go @@ -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 diff --git a/internal/common/common_linux.go b/internal/common/common_linux.go index 04ec171..ffaae42 100644 --- a/internal/common/common_linux.go +++ b/internal/common/common_linux.go @@ -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 diff --git a/internal/common/common_unix.go b/internal/common/common_unix.go index c9f91b1..2ccb376 100644 --- a/internal/common/common_unix.go +++ b/internal/common/common_unix.go @@ -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) diff --git a/load/load_aix_nocgo.go b/load/load_aix_nocgo.go index cfb4117..5e4ba6d 100644 --- a/load/load_aix_nocgo.go +++ b/load/load_aix_nocgo.go @@ -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 } diff --git a/load/load_solaris.go b/load/load_solaris.go index 3713f4a..479c110 100644 --- a/load/load_solaris.go +++ b/load/load_solaris.go @@ -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 } diff --git a/load/load_test.go b/load/load_test.go index c69094c..24e80c1 100644 --- a/load/load_test.go +++ b/load/load_test.go @@ -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) } diff --git a/mem/mem_linux_test.go b/mem/mem_linux_test.go index f0b12a0..18e27c5 100644 --- a/mem/mem_linux_test.go +++ b/mem/mem_linux_test.go @@ -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) diff --git a/mem/mem_test.go b/mem/mem_test.go index cf0c268..20417ff 100644 --- a/mem/mem_test.go +++ b/mem/mem_test.go @@ -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) { diff --git a/net/net.go b/net/net.go index 78798c5..bb5ef43 100644 --- a/net/net.go +++ b/net/net.go @@ -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, diff --git a/net/net_aix.go b/net/net_aix.go index a5fa881..d5a93f4 100644 --- a/net/net_aix.go +++ b/net/net_aix.go @@ -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") diff --git a/net/net_linux.go b/net/net_linux.go index 9697526..ed279a3 100644 --- a/net/net_linux.go +++ b/net/net_linux.go @@ -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 { diff --git a/net/net_openbsd.go b/net/net_openbsd.go index 481a276..55087ce 100644 --- a/net/net_openbsd.go +++ b/net/net_openbsd.go @@ -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") diff --git a/net/net_test.go b/net/net_test.go index a369446..fb1ef5b 100644 --- a/net/net_test.go +++ b/net/net_test.go @@ -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) } diff --git a/net/net_unix.go b/net/net_unix.go index ae7e9d8..7c5153d 100644 --- a/net/net_unix.go +++ b/net/net_unix.go @@ -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 { diff --git a/process/process_darwin.go b/process/process_darwin.go index 5afafd8..91f3932 100644 --- a/process/process_darwin.go +++ b/process/process_darwin.go @@ -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-- diff --git a/process/process_linux.go b/process/process_linux.go index bf96fd3..f8ddbb6 100644 --- a/process/process_linux.go +++ b/process/process_linux.go @@ -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) diff --git a/process/process_openbsd.go b/process/process_openbsd.go index 5a6d361..063ff20 100644 --- a/process/process_openbsd.go +++ b/process/process_openbsd.go @@ -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)) diff --git a/process/process_posix.go b/process/process_posix.go index 12d5fe2..9fe55b4 100644 --- a/process/process_posix.go +++ b/process/process_posix.go @@ -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) diff --git a/process/process_test.go b/process/process_test.go index bffe6b9..7f75140 100644 --- a/process/process_test.go +++ b/process/process_test.go @@ -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++ } diff --git a/process/process_windows.go b/process/process_windows.go index 6142abc..b4748d3 100644 --- a/process/process_windows.go +++ b/process/process_windows.go @@ -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 { diff --git a/sensors/sensors_test.go b/sensors/sensors_test.go index 9c6ac24..1b6069e 100644 --- a/sensors/sensors_test.go +++ b/sensors/sensors_test.go @@ -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) {