diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index e99161fb8..882bead77 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -24,7 +24,7 @@ jobs: - uses: actions/setup-go@v6 with: go-version-file: go.mod - - run: go run github.com/onsi/ginkgo/v2/ginkgo run -r --race --keep-going ./... + - run: go run github.com/onsi/ginkgo/v2/ginkgo run -r -p --race --keep-going --output-interceptor-mode=none ./... if: ${{ ! startsWith(matrix.os, 'windows') }} - - run: go run github.com/onsi/ginkgo/v2/ginkgo run -r --race --keep-going --output-interceptor-mode=none --skip-package=psnotify -v ./... + - run: go run github.com/onsi/ginkgo/v2/ginkgo run -r -p --race --keep-going --output-interceptor-mode=none --skip-package=psnotify ./... if: ${{ startsWith(matrix.os, 'windows') }} diff --git a/bin/test-unit b/bin/test-unit index f8d5df055..10fe0cfd2 100755 --- a/bin/test-unit +++ b/bin/test-unit @@ -19,7 +19,7 @@ main() { set -x fi - go run github.com/onsi/ginkgo/v2/ginkgo -p -r --randomize-all --randomize-suites --keep-going --race --skip-package=$skip_packages + go run github.com/onsi/ginkgo/v2/ginkgo run -p -r --randomize-all --randomize-suites --keep-going --race --skip-package=$skip_packages } main "$@" diff --git a/concrete_sigar_test.go b/concrete_sigar_test.go index ad297b883..51b866a4f 100644 --- a/concrete_sigar_test.go +++ b/concrete_sigar_test.go @@ -1,6 +1,7 @@ package sigar_test import ( + "errors" "runtime" "time" @@ -53,7 +54,7 @@ var _ = Describe("ConcreteSigar", func() { It("GetLoadAverage", func() { avg, err := concreteSigar.GetLoadAverage() - if err == sigar.ErrNotImplemented { + if errors.Is(err, sigar.ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(avg.One).ToNot(BeNil()) @@ -81,12 +82,12 @@ var _ = Describe("ConcreteSigar", func() { }) It("GetSwap", func() { - fsusage, err := concreteSigar.GetFileSystemUsage("/") + fsUsage, err := concreteSigar.GetFileSystemUsage("/") Expect(err).ToNot(HaveOccurred()) - Expect(fsusage.Total).ToNot(BeNil()) + Expect(fsUsage.Total).ToNot(BeNil()) - fsusage, err = concreteSigar.GetFileSystemUsage("T O T A L L Y B O G U S") + fsUsage, err = concreteSigar.GetFileSystemUsage("T O T A L L Y B O G U S") Expect(err).To(HaveOccurred()) - Expect(fsusage.Total).To(Equal(uint64(0))) + Expect(fsUsage.Total).To(Equal(uint64(0))) }) }) diff --git a/examples/df/df.go b/examples/df/df.go index a5d73a56c..86bc414ab 100644 --- a/examples/df/df.go +++ b/examples/df/df.go @@ -3,12 +3,11 @@ package main import ( "flag" "fmt" - "os" sigar "github.com/cloudfoundry/gosigar" ) -const output_format = "%-15s %4s %4s %5s %4s %-15s\n" +const outputFormat = "%-15s %4s %4s %5s %4s %-15s\n" func formatSize(size uint64) string { return sigar.FormatSize(size * 1024) @@ -18,16 +17,15 @@ func main() { var fileSystemFilter string flag.StringVar(&fileSystemFilter, "t", "", "Filesystem to filter on") flag.Parse() - fslist := sigar.FileSystemList{} - fslist.Get() //nolint:errcheck + fsList := sigar.FileSystemList{} + fsList.Get() //nolint:errcheck - fmt.Fprintf(os.Stdout, output_format, //nolint:errcheck - "Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on") + fmt.Printf(outputFormat, "Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on") - for _, fs := range fslist.List { - dir_name := fs.DirName + for _, fs := range fsList.List { + dirName := fs.DirName usage := sigar.FileSystemUsage{} - usage.Get(dir_name) //nolint:errcheck + usage.Get(dirName) //nolint:errcheck if fileSystemFilter != "" { if fs.SysTypeName != fileSystemFilter { @@ -35,12 +33,12 @@ func main() { } } - fmt.Fprintf(os.Stdout, output_format, //nolint:errcheck + fmt.Printf(outputFormat, fs.DevName, formatSize(usage.Total), formatSize(usage.Used), formatSize(usage.Avail), sigar.FormatPercent(usage.UsePercent()), - dir_name) + dirName) } } diff --git a/examples/free/free.go b/examples/free/free.go index 2809e444b..3314d32d3 100644 --- a/examples/free/free.go +++ b/examples/free/free.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "os" sigar "github.com/cloudfoundry/gosigar" ) @@ -18,15 +17,8 @@ func main() { mem.Get() //nolint:errcheck swap.Get() //nolint:errcheck - fmt.Fprintf(os.Stdout, "%18s %10s %10s\n", //nolint:errcheck - "total", "used", "free") - - fmt.Fprintf(os.Stdout, "Mem: %10d %10d %10d\n", //nolint:errcheck - format(mem.Total), format(mem.Used), format(mem.Free)) - - fmt.Fprintf(os.Stdout, "-/+ buffers/cache: %10d %10d\n", //nolint:errcheck - format(mem.ActualUsed), format(mem.ActualFree)) - - fmt.Fprintf(os.Stdout, "Swap: %10d %10d %10d\n", //nolint:errcheck - format(swap.Total), format(swap.Used), format(swap.Free)) + fmt.Printf("%18s %10s %10s\n", "total", "used", "free") + fmt.Printf("Mem: %10d %10d %10d\n", format(mem.Total), format(mem.Used), format(mem.Free)) + fmt.Printf("-/+ buffers/cache: %10d %10d\n", format(mem.ActualUsed), format(mem.ActualFree)) + fmt.Printf("Swap: %10d %10d %10d\n", format(swap.Total), format(swap.Used), format(swap.Free)) } diff --git a/examples/uptime/uptime.go b/examples/uptime/uptime.go index 3fa038f4d..08cc166a5 100644 --- a/examples/uptime/uptime.go +++ b/examples/uptime/uptime.go @@ -2,7 +2,6 @@ package main import ( "fmt" - "os" "time" sigar "github.com/cloudfoundry/gosigar" @@ -19,7 +18,7 @@ func main() { return } - fmt.Fprintf(os.Stdout, " %s up %s load average: %.2f, %.2f, %.2f\n", //nolint:errcheck + fmt.Printf(" %s up %s load average: %.2f, %.2f, %.2f\n", time.Now().Format("15:04:05"), uptime.Format(), avg.One, avg.Five, avg.Fifteen) diff --git a/go.mod b/go.mod index e80e1cdc3..dbeafb95c 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,6 @@ go 1.23.0 require ( github.com/onsi/ginkgo/v2 v2.27.2 github.com/onsi/gomega v1.38.2 - github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.8.4 golang.org/x/sys v0.35.0 ) diff --git a/go.sum b/go.sum index 35af6bae3..a854a5116 100644 --- a/go.sum +++ b/go.sum @@ -35,8 +35,6 @@ github.com/onsi/ginkgo/v2 v2.27.2 h1:LzwLj0b89qtIy6SSASkzlNvX6WktqurSHwkk2ipF/Ns github.com/onsi/ginkgo/v2 v2.27.2/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= diff --git a/psnotify/psnotify_bsd.go b/psnotify/psnotify_bsd.go index 2bde081da..f9805acd2 100644 --- a/psnotify/psnotify_bsd.go +++ b/psnotify/psnotify_bsd.go @@ -1,8 +1,9 @@ //go:build darwin || freebsd || netbsd || openbsd -// Go interface to BSD kqueue process events. package psnotify +// Go interface to BSD kqueue process events. + import ( "syscall" ) diff --git a/psnotify/psnotify_test.go b/psnotify/psnotify_test.go index cb33408d9..bdaa79d98 100644 --- a/psnotify/psnotify_test.go +++ b/psnotify/psnotify_test.go @@ -185,7 +185,7 @@ func TestWatchFork(t *testing.T) { tw := newTestWatcher(t) - // no watches added yet, so this fork event will no be captured + // no watches added yet, so this fork event will not be captured runCommand(t, "date") // watch fork events for this process diff --git a/sigar_darwin.go b/sigar_darwin.go index d8c7d34d1..48abd1372 100644 --- a/sigar_darwin.go +++ b/sigar_darwin.go @@ -27,34 +27,34 @@ import ( "golang.org/x/sys/unix" ) -func (self *LoadAverage) Get() error { //nolint:staticcheck +func (la *LoadAverage) Get() error { //nolint:staticcheck avg := []C.double{0, 0, 0} C.getloadavg(&avg[0], C.int(len(avg))) - self.One = float64(avg[0]) - self.Five = float64(avg[1]) - self.Fifteen = float64(avg[2]) + la.One = float64(avg[0]) + la.Five = float64(avg[1]) + la.Fifteen = float64(avg[2]) return nil } -func (self *Uptime) Get() error { //nolint:staticcheck +func (u *Uptime) Get() error { //nolint:staticcheck tv := syscall.Timeval32{} if err := sysctlbyname("kern.boottime", &tv); err != nil { return err } - self.Length = time.Since(time.Unix(int64(tv.Sec), int64(tv.Usec)*1000)).Seconds() + u.Length = time.Since(time.Unix(int64(tv.Sec), int64(tv.Usec)*1000)).Seconds() return nil } -func (self *Mem) Get() error { //nolint:staticcheck +func (m *Mem) Get() error { //nolint:staticcheck var vmstat C.vm_statistics_data_t - if err := sysctlbyname("hw.memsize", &self.Total); err != nil { + if err := sysctlbyname("hw.memsize", &m.Total); err != nil { return err } @@ -63,38 +63,38 @@ func (self *Mem) Get() error { //nolint:staticcheck } kern := uint64(vmstat.inactive_count) << 12 - self.Free = uint64(vmstat.free_count) << 12 + m.Free = uint64(vmstat.free_count) << 12 - self.Used = self.Total - self.Free - self.ActualFree = self.Free + kern - self.ActualUsed = self.Used - kern + m.Used = m.Total - m.Free + m.ActualFree = m.Free + kern + m.ActualUsed = m.Used - kern return nil } -func (self *Mem) GetIgnoringCGroups() error { //nolint:staticcheck - return self.Get() +func (m *Mem) GetIgnoringCGroups() error { //nolint:staticcheck + return m.Get() } type xsw_usage struct { Total, Avail, Used uint64 } -func (self *Swap) Get() error { //nolint:staticcheck +func (s *Swap) Get() error { //nolint:staticcheck sw_usage := xsw_usage{} if err := sysctlbyname("vm.swapusage", &sw_usage); err != nil { return err } - self.Total = sw_usage.Total - self.Used = sw_usage.Used - self.Free = sw_usage.Avail + s.Total = sw_usage.Total + s.Used = sw_usage.Used + s.Free = sw_usage.Avail return nil } -func (self *Cpu) Get() error { //nolint:staticcheck +func (c *Cpu) Get() error { //nolint:staticcheck var count C.mach_msg_type_number_t = C.HOST_CPU_LOAD_INFO_COUNT var cpuload C.host_cpu_load_info_data_t @@ -104,18 +104,18 @@ func (self *Cpu) Get() error { //nolint:staticcheck &count) if status != C.KERN_SUCCESS { - return fmt.Errorf("host_statistics error=%d", status) + return fmt.Errorf("host_statistics error=%d", int64(status)) } - self.User = uint64(cpuload.cpu_ticks[C.CPU_STATE_USER]) - self.Sys = uint64(cpuload.cpu_ticks[C.CPU_STATE_SYSTEM]) - self.Idle = uint64(cpuload.cpu_ticks[C.CPU_STATE_IDLE]) - self.Nice = uint64(cpuload.cpu_ticks[C.CPU_STATE_NICE]) + c.User = uint64(cpuload.cpu_ticks[C.CPU_STATE_USER]) + c.Sys = uint64(cpuload.cpu_ticks[C.CPU_STATE_SYSTEM]) + c.Idle = uint64(cpuload.cpu_ticks[C.CPU_STATE_IDLE]) + c.Nice = uint64(cpuload.cpu_ticks[C.CPU_STATE_NICE]) return nil } -func (self *CpuList) Get() error { //nolint:staticcheck +func (cl *CpuList) Get() error { //nolint:staticcheck var count C.mach_msg_type_number_t var cpuload *C.processor_cpu_load_info_data_t var ncpu C.natural_t @@ -127,7 +127,7 @@ func (self *CpuList) Get() error { //nolint:staticcheck &count) if status != C.KERN_SUCCESS { - return fmt.Errorf("host_processor_info error=%d", status) + return fmt.Errorf("host_processor_info error=%d", int64(status)) } // jump through some cgo casting hoops and ensure we properly free @@ -147,7 +147,7 @@ func (self *CpuList) Get() error { //nolint:staticcheck bbuf := bytes.NewBuffer(buf) - self.List = make([]Cpu, 0, ncpu) + cl.List = make([]Cpu, 0, ncpu) for i := 0; i < int(ncpu); i++ { cpu := Cpu{} @@ -162,13 +162,13 @@ func (self *CpuList) Get() error { //nolint:staticcheck cpu.Idle = uint64(cpu_ticks[C.CPU_STATE_IDLE]) cpu.Nice = uint64(cpu_ticks[C.CPU_STATE_NICE]) - self.List = append(self.List, cpu) + cl.List = append(cl.List, cpu) } return nil } -func (self *FileSystemList) Get() error { //nolint:staticcheck +func (fsl *FileSystemList) Get() error { //nolint:staticcheck num, err := getfsstat(nil, C.MNT_NOWAIT) if num < 0 { return err @@ -193,12 +193,12 @@ func (self *FileSystemList) Get() error { //nolint:staticcheck fslist = append(fslist, fs) } - self.List = fslist + fsl.List = fslist return err } -func (self *ProcList) Get() error { //nolint:staticcheck +func (pl *ProcList) Get() error { //nolint:staticcheck n := C.proc_listpids(C.PROC_ALL_PIDS, 0, nil, 0) if n <= 0 { return syscall.EINVAL @@ -225,82 +225,82 @@ func (self *ProcList) Get() error { //nolint:staticcheck list = append(list, int(pid)) } - self.List = list + pl.List = list return nil } -func (self *ProcState) Get(pid int) error { //nolint:staticcheck +func (ps *ProcState) Get(pid int) error { //nolint:staticcheck info := C.struct_proc_taskallinfo{} if err := task_info(pid, &info); err != nil { return err } - self.Name = C.GoString(&info.pbsd.pbi_comm[0]) + ps.Name = C.GoString(&info.pbsd.pbi_comm[0]) switch info.pbsd.pbi_status { case C.SIDL: - self.State = RunStateIdle + ps.State = RunStateIdle case C.SRUN: - self.State = RunStateRun + ps.State = RunStateRun case C.SSLEEP: - self.State = RunStateSleep + ps.State = RunStateSleep case C.SSTOP: - self.State = RunStateStop + ps.State = RunStateStop case C.SZOMB: - self.State = RunStateZombie + ps.State = RunStateZombie default: - self.State = RunStateUnknown + ps.State = RunStateUnknown } - self.Ppid = int(info.pbsd.pbi_ppid) + ps.Ppid = int(info.pbsd.pbi_ppid) - self.Tty = int(info.pbsd.e_tdev) + ps.Tty = int(info.pbsd.e_tdev) - self.Priority = int(info.ptinfo.pti_priority) + ps.Priority = int(info.ptinfo.pti_priority) - self.Nice = int(info.pbsd.pbi_nice) + ps.Nice = int(info.pbsd.pbi_nice) return nil } -func (self *ProcMem) Get(pid int) error { //nolint:staticcheck +func (pm *ProcMem) Get(pid int) error { //nolint:staticcheck info := C.struct_proc_taskallinfo{} if err := task_info(pid, &info); err != nil { return err } - self.Size = uint64(info.ptinfo.pti_virtual_size) - self.Resident = uint64(info.ptinfo.pti_resident_size) - self.PageFaults = uint64(info.ptinfo.pti_faults) + pm.Size = uint64(info.ptinfo.pti_virtual_size) + pm.Resident = uint64(info.ptinfo.pti_resident_size) + pm.PageFaults = uint64(info.ptinfo.pti_faults) return nil } -func (self *ProcTime) Get(pid int) error { //nolint:staticcheck +func (pt *ProcTime) Get(pid int) error { //nolint:staticcheck info := C.struct_proc_taskallinfo{} if err := task_info(pid, &info); err != nil { return err } - self.User = + pt.User = uint64(info.ptinfo.pti_total_user) / uint64(time.Millisecond) - self.Sys = + pt.Sys = uint64(info.ptinfo.pti_total_system) / uint64(time.Millisecond) - self.Total = self.User + self.Sys + pt.Total = pt.User + pt.Sys - self.StartTime = (uint64(info.pbsd.pbi_start_tvsec) * 1000) + + pt.StartTime = (uint64(info.pbsd.pbi_start_tvsec) * 1000) + (uint64(info.pbsd.pbi_start_tvusec) / 1000) return nil } -func (self *ProcArgs) Get(pid int) error { //nolint:staticcheck +func (pa *ProcArgs) Get(pid int) error { //nolint:staticcheck var args []string argv := func(arg string) { @@ -309,14 +309,14 @@ func (self *ProcArgs) Get(pid int) error { //nolint:staticcheck err := kern_procargs(pid, nil, argv, nil) - self.List = args + pa.List = args return err } -func (self *ProcExe) Get(pid int) error { //nolint:staticcheck +func (pe *ProcExe) Get(pid int) error { //nolint:staticcheck exe := func(arg string) { - self.Name = arg + pe.Name = arg } return kern_procargs(pid, exe, nil, nil) @@ -394,7 +394,7 @@ func sysctl(mib []C.int, old *byte, oldlen *uintptr, _, _, e1 := syscall.Syscall6(syscall.SYS___SYSCTL, uintptr(p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), - uintptr(unsafe.Pointer(new)), uintptr(newlen)) + uintptr(unsafe.Pointer(new)), newlen) if e1 != 0 { err = e1 } @@ -411,7 +411,7 @@ func vm_info(vmstat *C.vm_statistics_data_t) error { &count) if status != C.KERN_SUCCESS { - return fmt.Errorf("host_statistics=%d", status) + return fmt.Errorf("host_statistics=%d", int64(status)) } return nil diff --git a/sigar_format.go b/sigar_format.go index 86aeb45b9..9f840685a 100644 --- a/sigar_format.go +++ b/sigar_format.go @@ -8,7 +8,7 @@ import ( "time" ) -// Go version of apr_strfsize +// FormatSize Go version of apr_strfsize func FormatSize(size uint64) string { ord := []string{"K", "M", "G", "T", "P", "E"} o := 0 @@ -57,16 +57,16 @@ func FormatPercent(percent float64) string { return strconv.FormatFloat(percent, 'f', -1, 64) + "%" } -func (self *FileSystemUsage) UsePercent() float64 { //nolint:staticcheck - b_used := (self.Total - self.Free) / 1024 - b_avail := self.Avail / 1024 - utotal := b_used + b_avail - used := b_used +func (fs *FileSystemUsage) UsePercent() float64 { //nolint:staticcheck + bUsed := (fs.Total - fs.Free) / 1024 + bAvail := fs.Avail / 1024 + uTotal := bUsed + bAvail + used := bUsed - if utotal != 0 { + if uTotal != 0 { u100 := used * 100 - pct := u100 / utotal - if u100%utotal != 0 { + pct := u100 / uTotal + if u100%uTotal != 0 { pct += 1 } return (float64(pct) / float64(100)) * 100.0 @@ -75,10 +75,10 @@ func (self *FileSystemUsage) UsePercent() float64 { //nolint:staticcheck return 0.0 } -func (self *Uptime) Format() string { //nolint:staticcheck +func (u *Uptime) Format() string { //nolint:staticcheck buf := new(bytes.Buffer) w := bufio.NewWriter(buf) - uptime := uint64(self.Length) + uptime := uint64(u.Length) days := uptime / (60 * 60 * 24) @@ -101,11 +101,11 @@ func (self *Uptime) Format() string { //nolint:staticcheck return buf.String() } -func (self *ProcTime) FormatStartTime() string { //nolint:staticcheck - if self.StartTime == 0 { +func (pt *ProcTime) FormatStartTime() string { //nolint:staticcheck + if pt.StartTime == 0 { return "00:00" } - start := time.Unix(int64(self.StartTime)/1000, 0) + start := time.Unix(int64(pt.StartTime)/1000, 0) format := "Jan02" if time.Since(start).Seconds() < (60 * 60 * 24) { format = "15:04" @@ -113,8 +113,8 @@ func (self *ProcTime) FormatStartTime() string { //nolint:staticcheck return start.Format(format) } -func (self *ProcTime) FormatTotal() string { //nolint:staticcheck - t := self.Total / 1000 +func (pt *ProcTime) FormatTotal() string { //nolint:staticcheck + t := pt.Total / 1000 ss := t % 60 t /= 60 mm := t % 60 diff --git a/sigar_freebsd.go b/sigar_freebsd.go index 1578fc824..43c99b6a1 100644 --- a/sigar_freebsd.go +++ b/sigar_freebsd.go @@ -159,18 +159,18 @@ func readProcFile(pid int, name string) ([]byte, error) { return contents, err } -func (self *Uptime) Get() error { +func (u *Uptime) Get() error { var tv unix.Timeval boottimeRaw, err := unix.SysctlRaw("kern.boottime") if err != nil { return err } tv = *(*unix.Timeval)(unsafe.Pointer(&boottimeRaw[0])) - self.Length = time.Since(time.Unix(int64(tv.Sec), int64(tv.Usec)*1000)).Seconds() + u.Length = time.Since(time.Unix(int64(tv.Sec), int64(tv.Usec)*1000)).Seconds() return nil } -func (self *LoadAverage) Get() error { +func (la *LoadAverage) Get() error { avgRaw, err := unix.SysctlRaw("vm.loadavg") if err != nil { return err @@ -178,14 +178,14 @@ func (self *LoadAverage) Get() error { avg := *(*loadStruct)(unsafe.Pointer(&avgRaw[0])) fscale := float64(avg.Fscale) - self.One = float64(avg.Ldavg[0]) / fscale - self.Five = float64(avg.Ldavg[1]) / fscale - self.Fifteen = float64(avg.Ldavg[2]) / fscale + la.One = float64(avg.Ldavg[0]) / fscale + la.Five = float64(avg.Ldavg[1]) / fscale + la.Fifteen = float64(avg.Ldavg[2]) / fscale return nil } -func (self *ProcList) Get() error { +func (pl *ProcList) Get() error { dir, err := os.Open(Procd) if err != nil { return err @@ -212,37 +212,37 @@ func (self *ProcList) Get() error { } } - self.List = list + pl.List = list return nil } -func (self *ProcState) Get(pid int) error { +func (ps *ProcState) Get(pid int) error { pinfo, err := getProcInfo(pid) if err != nil { return err } - self.Name = string(bytes.Trim(pinfo.Comm[:], "\x00")) - self.Ppid = int(pinfo.Ppid) + ps.Name = string(bytes.Trim(pinfo.Comm[:], "\x00")) + ps.Ppid = int(pinfo.Ppid) switch pinfo.Stat { case procStateRun: - self.State = RunStateRun + ps.State = RunStateRun case procStateIdle: - self.State = RunStateIdle + ps.State = RunStateIdle case procStateSleep: - self.State = RunStateSleep + ps.State = RunStateSleep case procStateStop: - self.State = RunStateStop + ps.State = RunStateStop case procStateZombie: - self.State = RunStateZombie + ps.State = RunStateZombie default: - self.State = RunStateUnknown + ps.State = RunStateUnknown } return nil } -func (self *FileSystemList) Get() error { +func (fsl *FileSystemList) Get() error { n, err := unix.Getfsstat(nil, unix.MNT_NOWAIT) if err != nil { return err @@ -257,11 +257,11 @@ func (self *FileSystemList) Get() error { fs.SysTypeName = string(bytes.Trim(f.Fstypename[:], "\x00")) fslist = append(fslist, fs) } - self.List = fslist + fsl.List = fslist return nil } -func (self *FileSystemUsage) Get(path string) error { +func (fs *FileSystemUsage) Get(path string) error { stat := unix.Statfs_t{} err := unix.Statfs(path, &stat) if err != nil { @@ -270,22 +270,22 @@ func (self *FileSystemUsage) Get(path string) error { bsize := stat.Bsize / 512 - self.Total = (uint64(stat.Blocks) * uint64(bsize)) >> 1 - self.Free = (uint64(stat.Bfree) * uint64(bsize)) >> 1 - self.Avail = (uint64(stat.Bavail) * uint64(bsize)) >> 1 - self.Used = self.Total - self.Free - self.Files = stat.Files - self.FreeFiles = uint64(stat.Ffree) + fs.Total = (uint64(stat.Blocks) * uint64(bsize)) >> 1 + fs.Free = (uint64(stat.Bfree) * uint64(bsize)) >> 1 + fs.Avail = (uint64(stat.Bavail) * uint64(bsize)) >> 1 + fs.Used = fs.Total - fs.Free + fs.Files = stat.Files + fs.FreeFiles = uint64(stat.Ffree) return nil } -func (self *ProcTime) Get(pid int) error { +func (pt *ProcTime) Get(pid int) error { rusage := unix.Rusage{} unix.Getrusage(pid, &rusage) - self.User = uint64(rusage.Utime.Nano() / 1e6) - self.Sys = uint64(rusage.Stime.Nano() / 1e6) - self.Total = self.User + self.Sys + pt.User = uint64(rusage.Utime.Nano() / 1e6) + pt.Sys = uint64(rusage.Stime.Nano() / 1e6) + pt.Total = pt.User + pt.Sys var tv unix.Timeval pinfo, err := getProcInfo(pid) @@ -293,12 +293,12 @@ func (self *ProcTime) Get(pid int) error { return err } tv = *(*unix.Timeval)(unsafe.Pointer(&pinfo.Start[0])) - self.StartTime = (uint64(tv.Sec) * 1000) + (uint64(tv.Usec) / 1000) + pt.StartTime = (uint64(tv.Sec) * 1000) + (uint64(tv.Usec) / 1000) return nil } -func (self *Cpu) Get() error { +func (c *Cpu) Get() error { cpTime, err := unix.SysctlRaw("kern.cp_time") if err != nil { return err @@ -306,19 +306,19 @@ func (self *Cpu) Get() error { cpuRaw := *(*cpuStat)(unsafe.Pointer(&cpTime[0])) - self.User = uint64(cpuRaw.user) - self.Nice = uint64(cpuRaw.nice) - self.Sys = uint64(cpuRaw.sys) - self.Irq = uint64(cpuRaw.irq) - self.Idle = uint64(cpuRaw.idle) + c.User = uint64(cpuRaw.user) + c.Nice = uint64(cpuRaw.nice) + c.Sys = uint64(cpuRaw.sys) + c.Irq = uint64(cpuRaw.irq) + c.Idle = uint64(cpuRaw.idle) return nil } -func (self *Mem) Get() error { +func (m *Mem) Get() error { var err error - self.Total, err = unix.SysctlUint64("hw.physmem") + m.Total, err = unix.SysctlUint64("hw.physmem") if err != nil { return err } @@ -332,19 +332,19 @@ func (self *Mem) Get() error { if err != nil { return err } - self.Free = uint64(freePages) * uint64(pageSize) + m.Free = uint64(freePages) * uint64(pageSize) - self.Used = self.Total - self.Free + m.Used = m.Total - m.Free return nil } -func (self *Mem) GetIgnoringCGroups() error { - return self.Get() +func (m *Mem) GetIgnoringCGroups() error { + return m.Get() } -func (self *Swap) Get() error { +func (s *Swap) Get() error { var err error - self.Total, err = unix.SysctlUint64("vm.swap_total") + s.Total, err = unix.SysctlUint64("vm.swap_total") if err != nil { return err } @@ -360,7 +360,7 @@ type cpuStat struct { idle int64 } -func (self *CpuList) Get() error { +func (cl *CpuList) Get() error { cpTimes, err := unix.SysctlRaw("kern.cp_times") if err != nil { return err @@ -383,12 +383,12 @@ func (self *CpuList) Get() error { cpulist = append(cpulist, cpu) } - self.List = cpulist + cl.List = cpulist return nil } -func (self *ProcMem) Get(pid int) error { +func (pm *ProcMem) Get(pid int) error { pageSize, err := unix.SysctlUint32("hw.pagesize") if err != nil { return err @@ -397,17 +397,17 @@ func (self *ProcMem) Get(pid int) error { rusage := unix.Rusage{} unix.Getrusage(pid, &rusage) - self.Resident = (uint64(rusage.Ixrss) + uint64(rusage.Idrss)) * uint64(pageSize) - self.Share = uint64(rusage.Isrss) * uint64(pageSize) - self.Size = self.Resident + self.Share - self.MinorFaults = uint64(rusage.Minflt) - self.MajorFaults = uint64(rusage.Majflt) - self.PageFaults = self.MinorFaults + self.MajorFaults + pm.Resident = (uint64(rusage.Ixrss) + uint64(rusage.Idrss)) * uint64(pageSize) + pm.Share = uint64(rusage.Isrss) * uint64(pageSize) + pm.Size = pm.Resident + pm.Share + pm.MinorFaults = uint64(rusage.Minflt) + pm.MajorFaults = uint64(rusage.Majflt) + pm.PageFaults = pm.MinorFaults + pm.MajorFaults return nil } -func (self *ProcArgs) Get(pid int) error { +func (pa *ProcArgs) Get(pid int) error { contents, err := readProcFile(pid, "cmdline") if err != nil { return err @@ -425,14 +425,14 @@ func (self *ProcArgs) Get(pid int) error { args = append(args, string(chop(arg))) } - self.List = args + pa.List = args return nil } -func (self *ProcExe) Get(pid int) error { +func (pe *ProcExe) Get(pid int) error { var err error - self.Name, err = os.Readlink(procFileName(pid, "file")) + pe.Name, err = os.Readlink(procFileName(pid, "file")) if err != nil { return err } diff --git a/sigar_interface.go b/sigar_interface.go index 431e109c3..d1887d284 100644 --- a/sigar_interface.go +++ b/sigar_interface.go @@ -27,21 +27,21 @@ type Cpu struct { Stolen uint64 } -func (cpu *Cpu) Total() uint64 { - return cpu.User + cpu.Nice + cpu.Sys + cpu.Idle + - cpu.Wait + cpu.Irq + cpu.SoftIrq + cpu.Stolen +func (c *Cpu) Total() uint64 { + return c.User + c.Nice + c.Sys + c.Idle + + c.Wait + c.Irq + c.SoftIrq + c.Stolen } -func (cpu Cpu) Delta(other Cpu) Cpu { +func (c *Cpu) Delta(other Cpu) Cpu { return Cpu{ - User: cpu.User - other.User, - Nice: cpu.Nice - other.Nice, - Sys: cpu.Sys - other.Sys, - Idle: cpu.Idle - other.Idle, - Wait: cpu.Wait - other.Wait, - Irq: cpu.Irq - other.Irq, - SoftIrq: cpu.SoftIrq - other.SoftIrq, - Stolen: cpu.Stolen - other.Stolen, + User: c.User - other.User, + Nice: c.Nice - other.Nice, + Sys: c.Sys - other.Sys, + Idle: c.Idle - other.Idle, + Wait: c.Wait - other.Wait, + Irq: c.Irq - other.Irq, + SoftIrq: c.SoftIrq - other.SoftIrq, + Stolen: c.Stolen - other.Stolen, } } diff --git a/sigar_interface_test.go b/sigar_interface_test.go index c7f8755d2..16ead2ea5 100644 --- a/sigar_interface_test.go +++ b/sigar_interface_test.go @@ -1,6 +1,7 @@ package sigar import ( + "errors" "os" "path/filepath" "runtime" @@ -15,7 +16,7 @@ var _ = Describe("Sigar", func() { It("cpu", func() { cpu := Cpu{} err := cpu.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -24,7 +25,7 @@ var _ = Describe("Sigar", func() { It("load average", func() { avg := LoadAverage{} err := avg.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -33,7 +34,7 @@ var _ = Describe("Sigar", func() { It("uptime", func() { uptime := Uptime{} err := uptime.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -43,7 +44,7 @@ var _ = Describe("Sigar", func() { It("mem", func() { mem := Mem{} err := mem.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -54,7 +55,7 @@ var _ = Describe("Sigar", func() { It("swap", func() { swap := Swap{} err := swap.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -64,7 +65,7 @@ var _ = Describe("Sigar", func() { It("cpu list", func() { cpulist := CpuList{} err := cpulist.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -77,7 +78,7 @@ var _ = Describe("Sigar", func() { It("file system list", func() { fslist := FileSystemList{} err := fslist.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -88,7 +89,7 @@ var _ = Describe("Sigar", func() { It("file system usage", func() { fsusage := FileSystemUsage{} err := fsusage.Get("/") - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -100,7 +101,7 @@ var _ = Describe("Sigar", func() { It("proc list", func() { pids := ProcList{} err := pids.Get() - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -114,7 +115,7 @@ var _ = Describe("Sigar", func() { It("proc state", func() { state := ProcState{} err := state.Get(os.Getppid()) - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -129,7 +130,7 @@ var _ = Describe("Sigar", func() { It("proc cpu", func() { pCpu := ProcCpu{} err := pCpu.Get(os.Getppid()) - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -141,7 +142,7 @@ var _ = Describe("Sigar", func() { It("proc mem", func() { mem := ProcMem{} err := mem.Get(os.Getppid()) - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -153,7 +154,7 @@ var _ = Describe("Sigar", func() { It("proc time", func() { time := ProcTime{} err := time.Get(os.Getppid()) - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -165,7 +166,7 @@ var _ = Describe("Sigar", func() { It("proc args", func() { args := ProcArgs{} err := args.Get(os.Getppid()) - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) @@ -176,7 +177,7 @@ var _ = Describe("Sigar", func() { It("proc exe", func() { exe := ProcExe{} err := exe.Get(os.Getppid()) - if err == ErrNotImplemented { + if errors.Is(err, ErrNotImplemented) { Skip("Not implemented on " + runtime.GOOS) } Expect(err).ToNot(HaveOccurred()) diff --git a/sigar_linux.go b/sigar_linux.go index 5faaaf05a..45d1498e1 100644 --- a/sigar_linux.go +++ b/sigar_linux.go @@ -77,7 +77,7 @@ func init() { }) } -func (self *LoadAverage) Get() error { //nolint:staticcheck +func (la *LoadAverage) Get() error { //nolint:staticcheck line, err := os.ReadFile(Procd + "/loadavg") if err != nil { return nil @@ -85,39 +85,39 @@ func (self *LoadAverage) Get() error { //nolint:staticcheck fields := strings.Fields(string(line)) - self.One, _ = strconv.ParseFloat(fields[0], 64) //nolint:errcheck - self.Five, _ = strconv.ParseFloat(fields[1], 64) //nolint:errcheck - self.Fifteen, _ = strconv.ParseFloat(fields[2], 64) //nolint:errcheck + la.One, _ = strconv.ParseFloat(fields[0], 64) //nolint:errcheck + la.Five, _ = strconv.ParseFloat(fields[1], 64) //nolint:errcheck + la.Fifteen, _ = strconv.ParseFloat(fields[2], 64) //nolint:errcheck return nil } -func (self *Uptime) Get() error { //nolint:staticcheck +func (u *Uptime) Get() error { //nolint:staticcheck sysinfo := syscall.Sysinfo_t{} if err := syscall.Sysinfo(&sysinfo); err != nil { return err } - self.Length = float64(sysinfo.Uptime) + u.Length = float64(sysinfo.Uptime) return nil } -func (self *Mem) Get() error { //nolint:staticcheck - return self.get(false) +func (m *Mem) Get() error { //nolint:staticcheck + return m.get(false) } -func (self *Mem) GetIgnoringCGroups() error { //nolint:staticcheck - return self.get(true) +func (m *Mem) GetIgnoringCGroups() error { //nolint:staticcheck + return m.get(true) } -func (self *Mem) get(ignoreCGroups bool) error { //nolint:staticcheck +func (m *Mem) get(ignoreCGroups bool) error { //nolint:staticcheck var available = MaxUint64 var buffers, cached uint64 table := map[string]*uint64{ - "MemTotal": &self.Total, - "MemFree": &self.Free, + "MemTotal": &m.Total, + "MemFree": &m.Free, "MemAvailable": &available, "Buffers": &buffers, "Cached": &cached, @@ -128,13 +128,13 @@ func (self *Mem) get(ignoreCGroups bool) error { //nolint:staticcheck } if available == MaxUint64 { - self.ActualFree = self.Free + buffers + cached + m.ActualFree = m.Free + buffers + cached } else { - self.ActualFree = available + m.ActualFree = available } - self.Used = self.Total - self.Free - self.ActualUsed = self.Total - self.ActualFree + m.Used = m.Total - m.Free + m.ActualUsed = m.Total - m.ActualFree if ignoreCGroups { return nil @@ -159,7 +159,7 @@ func (self *Mem) get(ignoreCGroups bool) error { //nolint:staticcheck // // (*) There does not seem to be a truly reliable and portable // means of detecting execution inside a container vs - // outside. Between all the platforms (macos, linux, + // outside. Between all the platforms (macOS, linux, // windows), and container runtimes (docker, lxc, oci, ...). // // (**) The exact value actually is 2^63 - 4096, i.e @@ -175,11 +175,11 @@ func (self *Mem) get(ignoreCGroups bool) error { //nolint:staticcheck cgroupLimit, err := determineMemoryLimit(cgroup) // (x) If the limit is not available or bogus we keep the host data as limit. - if err == nil && cgroupLimit < self.Total { + if err == nil && cgroupLimit < m.Total { // See (2) above why only a cgroup limit less than the // host total is accepted as the new total available // memory in the cgroup. - self.Total = cgroupLimit + m.Total = cgroupLimit } rss, err := determineMemoryUsage(cgroup) @@ -198,42 +198,41 @@ func (self *Mem) get(ignoreCGroups bool) error { //nolint:staticcheck swap = 0 } - self.Used = rss + swap - self.Free = self.Total - self.Used + m.Used = rss + swap + m.Free = m.Total - m.Used - self.ActualUsed = self.Used - self.ActualFree = self.Free + m.ActualUsed = m.Used + m.ActualFree = m.Free return nil } -func (self *Swap) Get() error { //nolint:staticcheck +func (s *Swap) Get() error { //nolint:staticcheck table := map[string]*uint64{ - "SwapTotal": &self.Total, - "SwapFree": &self.Free, + "SwapTotal": &s.Total, + "SwapFree": &s.Free, } if err := parseMeminfo(table); err != nil { return err } - self.Used = self.Total - self.Free + s.Used = s.Total - s.Free return nil } -func (self *Cpu) Get() error { //nolint:staticcheck +func (c *Cpu) Get() error { //nolint:staticcheck return readFile(Procd+"/stat", func(line string) bool { if len(line) > 4 && line[0:4] == "cpu " { - parseCpuStat(self, line) //nolint:errcheck + parseCpuStat(c, line) //nolint:errcheck return false } return true - }) } -func (self *CpuList) Get() error { //nolint:staticcheck - capacity := len(self.List) +func (cl *CpuList) Get() error { //nolint:staticcheck + capacity := len(cl.List) if capacity == 0 { capacity = 4 } @@ -248,17 +247,17 @@ func (self *CpuList) Get() error { //nolint:staticcheck return true }) - self.List = list + cl.List = list return err } -func (self *FileSystemList) Get() error { //nolint:staticcheck +func (fsl *FileSystemList) Get() error { //nolint:staticcheck src := Etcd + "/mtab" if _, err := os.Stat(src); err != nil { src = Procd + "/mounts" } - capacity := len(self.List) + capacity := len(fsl.List) if capacity == 0 { capacity = 10 } @@ -278,12 +277,12 @@ func (self *FileSystemList) Get() error { //nolint:staticcheck return true }) - self.List = fslist + fsl.List = fslist return err } -func (self *ProcList) Get() error { //nolint:staticcheck +func (pl *ProcList) Get() error { //nolint:staticcheck dir, err := os.Open(Procd) if err != nil { return err @@ -310,12 +309,12 @@ func (self *ProcList) Get() error { //nolint:staticcheck } } - self.List = list + pl.List = list return nil } -func (self *ProcState) Get(pid int) error { //nolint:staticcheck +func (ps *ProcState) Get(pid int) error { //nolint:staticcheck contents, err := readProcFile(pid, "stat") if err != nil { return err @@ -323,24 +322,24 @@ func (self *ProcState) Get(pid int) error { //nolint:staticcheck fields := strings.Fields(string(contents)) - self.Name = fields[1][1 : len(fields[1])-1] // strip ()'s + ps.Name = fields[1][1 : len(fields[1])-1] // strip ()'s - self.State = RunState(fields[2][0]) + ps.State = RunState(fields[2][0]) - self.Ppid, _ = strconv.Atoi(fields[3]) //nolint:errcheck + ps.Ppid, _ = strconv.Atoi(fields[3]) //nolint:errcheck - self.Tty, _ = strconv.Atoi(fields[6]) //nolint:errcheck + ps.Tty, _ = strconv.Atoi(fields[6]) //nolint:errcheck - self.Priority, _ = strconv.Atoi(fields[17]) //nolint:errcheck + ps.Priority, _ = strconv.Atoi(fields[17]) //nolint:errcheck - self.Nice, _ = strconv.Atoi(fields[18]) //nolint:errcheck + ps.Nice, _ = strconv.Atoi(fields[18]) //nolint:errcheck - self.Processor, _ = strconv.Atoi(fields[38]) //nolint:errcheck + ps.Processor, _ = strconv.Atoi(fields[38]) //nolint:errcheck return nil } -func (self *ProcMem) Get(pid int) error { //nolint:staticcheck +func (pm *ProcMem) Get(pid int) error { //nolint:staticcheck contents, err := readProcFile(pid, "statm") if err != nil { return err @@ -349,13 +348,13 @@ func (self *ProcMem) Get(pid int) error { //nolint:staticcheck fields := strings.Fields(string(contents)) size, _ := strtoull(fields[0]) //nolint:errcheck - self.Size = size << 12 + pm.Size = size << 12 rss, _ := strtoull(fields[1]) //nolint:errcheck - self.Resident = rss << 12 + pm.Resident = rss << 12 share, _ := strtoull(fields[2]) //nolint:errcheck - self.Share = share << 12 + pm.Share = share << 12 contents, err = readProcFile(pid, "stat") if err != nil { @@ -364,14 +363,14 @@ func (self *ProcMem) Get(pid int) error { //nolint:staticcheck fields = strings.Fields(string(contents)) - self.MinorFaults, _ = strtoull(fields[10]) //nolint:errcheck - self.MajorFaults, _ = strtoull(fields[12]) //nolint:errcheck - self.PageFaults = self.MinorFaults + self.MajorFaults + pm.MinorFaults, _ = strtoull(fields[10]) //nolint:errcheck + pm.MajorFaults, _ = strtoull(fields[12]) //nolint:errcheck + pm.PageFaults = pm.MinorFaults + pm.MajorFaults return nil } -func (self *ProcTime) Get(pid int) error { //nolint:staticcheck +func (pt *ProcTime) Get(pid int) error { //nolint:staticcheck contents, err := readProcFile(pid, "stat") if err != nil { return err @@ -382,20 +381,20 @@ func (self *ProcTime) Get(pid int) error { //nolint:staticcheck user, _ := strtoull(fields[13]) //nolint:errcheck sys, _ := strtoull(fields[14]) //nolint:errcheck // convert to millis - self.User = user * (1000 / system.ticks) - self.Sys = sys * (1000 / system.ticks) - self.Total = self.User + self.Sys + pt.User = user * (1000 / system.ticks) + pt.Sys = sys * (1000 / system.ticks) + pt.Total = pt.User + pt.Sys // convert to millis - self.StartTime, _ = strtoull(fields[21]) //nolint:errcheck - self.StartTime /= system.ticks - self.StartTime += system.btime - self.StartTime *= 1000 + pt.StartTime, _ = strtoull(fields[21]) //nolint:errcheck + pt.StartTime /= system.ticks + pt.StartTime += system.btime + pt.StartTime *= 1000 return nil } -func (self *ProcArgs) Get(pid int) error { //nolint:staticcheck +func (pa *ProcArgs) Get(pid int) error { //nolint:staticcheck contents, err := readProcFile(pid, "cmdline") if err != nil { return err @@ -413,16 +412,16 @@ func (self *ProcArgs) Get(pid int) error { //nolint:staticcheck args = append(args, string(chop(arg))) } - self.List = args + pa.List = args return nil } -func (self *ProcExe) Get(pid int) error { //nolint:staticcheck +func (pe *ProcExe) Get(pid int) error { //nolint:staticcheck fields := map[string]*string{ - "exe": &self.Name, - "cwd": &self.Cwd, - "root": &self.Root, + "exe": &pe.Name, + "cwd": &pe.Cwd, + "root": &pe.Root, } for name, field := range fields { diff --git a/sigar_linux_test.go b/sigar_linux_test.go index 7403a1e2e..be7804500 100644 --- a/sigar_linux_test.go +++ b/sigar_linux_test.go @@ -611,7 +611,7 @@ DirectMap2M: 34983936 kB`) // // Note that `MemAvailable present yes/no` does not matter in // the results, as the cgroup derived results will write over - // them. Thus we have 2 groups a 4 tests, with identical + // them. Thus, we have 2 groups and 4 tests, with identical // results for the equivalent tests of each group. Describe("With MemAvailable. With v1 cgroup limit. With v1 cgroup swap", func() { diff --git a/sigar_shared.go b/sigar_shared.go index 8cb1df44b..25bea4295 100644 --- a/sigar_shared.go +++ b/sigar_shared.go @@ -4,29 +4,29 @@ import ( "time" ) -func (self *ProcCpu) Get(pid int) error { //nolint:staticcheck - if self.cache == nil { - self.cache = make(map[int]ProcCpu) +func (pc *ProcCpu) Get(pid int) error { //nolint:staticcheck + if pc.cache == nil { + pc.cache = make(map[int]ProcCpu) } - prevProcCpu := self.cache[pid] + prevProcCpu := pc.cache[pid] procTime := &ProcTime{} if err := procTime.Get(pid); err != nil { return err } - self.StartTime = procTime.StartTime - self.User = procTime.User - self.Sys = procTime.Sys - self.Total = procTime.Total + pc.StartTime = procTime.StartTime + pc.User = procTime.User + pc.Sys = procTime.Sys + pc.Total = procTime.Total - self.LastTime = uint64(time.Now().UnixNano() / int64(time.Millisecond)) - self.cache[pid] = *self + pc.LastTime = uint64(time.Now().UnixNano() / int64(time.Millisecond)) + pc.cache[pid] = *pc if prevProcCpu.LastTime == 0 { time.Sleep(100 * time.Millisecond) - return self.Get(pid) + return pc.Get(pid) } - self.Percent = float64(self.Total-prevProcCpu.Total) / float64(self.LastTime-prevProcCpu.LastTime) + pc.Percent = float64(pc.Total-prevProcCpu.Total) / float64(pc.LastTime-prevProcCpu.LastTime) return nil } diff --git a/sigar_unix.go b/sigar_unix.go index bd11fc45c..eb101eabb 100644 --- a/sigar_unix.go +++ b/sigar_unix.go @@ -6,7 +6,7 @@ import ( "syscall" ) -func (self *FileSystemUsage) Get(path string) error { //nolint:staticcheck +func (fs *FileSystemUsage) Get(path string) error { //nolint:staticcheck stat := syscall.Statfs_t{} err := syscall.Statfs(path, &stat) if err != nil { @@ -15,12 +15,12 @@ func (self *FileSystemUsage) Get(path string) error { //nolint:staticcheck bsize := stat.Bsize / 512 - self.Total = (uint64(stat.Blocks) * uint64(bsize)) >> 1 - self.Free = (uint64(stat.Bfree) * uint64(bsize)) >> 1 - self.Avail = (uint64(stat.Bavail) * uint64(bsize)) >> 1 - self.Used = self.Total - self.Free - self.Files = stat.Files - self.FreeFiles = stat.Ffree + fs.Total = (stat.Blocks * uint64(bsize)) >> 1 + fs.Free = (stat.Bfree * uint64(bsize)) >> 1 + fs.Avail = (stat.Bavail * uint64(bsize)) >> 1 + fs.Used = fs.Total - fs.Free + fs.Files = stat.Files + fs.FreeFiles = stat.Ffree return nil } diff --git a/sigar_windows.go b/sigar_windows.go index c22c5eb7e..2d501e51a 100644 --- a/sigar_windows.go +++ b/sigar_windows.go @@ -2,6 +2,7 @@ package sigar import ( "bytes" + "errors" "fmt" "os/exec" "strconv" @@ -9,8 +10,6 @@ import ( "time" "unsafe" - "github.com/pkg/errors" - "github.com/cloudfoundry/gosigar/sys/windows" ) @@ -28,7 +27,7 @@ var ( processQueryLimitedInfoAccess = windows.PROCESS_QUERY_LIMITED_INFORMATION ) -func (self *LoadAverage) Get() error { //nolint:staticcheck +func (la *LoadAverage) Get() error { //nolint:staticcheck return ErrNotImplemented } @@ -127,69 +126,89 @@ func (c *Cpu) Get() error { //nolint:staticcheck return nil } -func (self *CpuList) Get() error { //nolint:staticcheck +func (cl *CpuList) Get() error { //nolint:staticcheck return ErrNotImplemented } -func (self *FileSystemList) Get() error { //nolint:staticcheck +func (fsl *FileSystemList) Get() error { //nolint:staticcheck return ErrNotImplemented } -func (self *ProcList) Get() error { //nolint:staticcheck +func (pl *ProcList) Get() error { //nolint:staticcheck return ErrNotImplemented } -func (self *ProcState) Get(pid int) error { //nolint:staticcheck +func (ps *ProcState) Get(pid int) error { //nolint:staticcheck return ErrNotImplemented } -func (self *ProcMem) Get(pid int) error { //nolint:staticcheck +func (pm *ProcMem) Get(pid int) error { //nolint:staticcheck handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess|windows.PROCESS_VM_READ, false, uint32(pid)) if err != nil { - return errors.Wrapf(err, "OpenProcess failed for pid=%v", pid) + return fmt.Errorf("OpenProcess failed for pid=%v %w", pid, err) } defer syscall.CloseHandle(handle) //nolint:errcheck counters, err := windows.GetProcessMemoryInfo(handle) if err != nil { - return errors.Wrapf(err, "GetProcessMemoryInfo failed for pid=%v", pid) + return fmt.Errorf("GetProcessMemoryInfo failed for pid=%v %w", pid, err) } - self.Resident = uint64(counters.WorkingSetSize) - self.Size = uint64(counters.PrivateUsage) + pm.Resident = uint64(counters.WorkingSetSize) + pm.Size = uint64(counters.PrivateUsage) return nil } -func (self *ProcTime) Get(pid int) error { //nolint:staticcheck +func (pt *ProcTime) Get(pid int) error { //nolint:staticcheck handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess, false, uint32(pid)) if err != nil { - return errors.Wrapf(err, "OpenProcess failed for pid=%v", pid) + return fmt.Errorf("OpenProcess failed for pid=%v %w", pid, err) } defer syscall.CloseHandle(handle) //nolint:errcheck var CPU syscall.Rusage if err := syscall.GetProcessTimes(handle, &CPU.CreationTime, &CPU.ExitTime, &CPU.KernelTime, &CPU.UserTime); err != nil { - return errors.Wrapf(err, "GetProcessTimes failed for pid=%v", pid) + return fmt.Errorf("GetProcessTimes failed for pid=%v %w", pid, err) } // Windows epoch times are expressed as time elapsed since midnight on - // January 1, 1601 at Greenwich, England. This converts the Filetime to + // January 1, 1601, at Greenwich, England. This converts the Filetime to // unix epoch in milliseconds. - self.StartTime = uint64(CPU.CreationTime.Nanoseconds() / 1e6) + pt.StartTime = uint64(CPU.CreationTime.Nanoseconds() / 1e6) // Convert to millis. - self.User = uint64(windows.FiletimeToDuration(&CPU.UserTime).Nanoseconds() / 1e6) - self.Sys = uint64(windows.FiletimeToDuration(&CPU.KernelTime).Nanoseconds() / 1e6) - self.Total = self.User + self.Sys + pt.User = uint64(windows.FiletimeToDuration(&CPU.UserTime).Nanoseconds() / 1e6) + pt.Sys = uint64(windows.FiletimeToDuration(&CPU.KernelTime).Nanoseconds() / 1e6) + pt.Total = pt.User + pt.Sys return nil } -func (self *ProcArgs) Get(pid int) error { //nolint:staticcheck - return ErrNotImplemented +func (pa *ProcArgs) Get(pid int) error { //nolint:staticcheck + handle, err := syscall.OpenProcess(processQueryLimitedInfoAccess|windows.PROCESS_VM_READ, false, uint32(pid)) + if err != nil { + return fmt.Errorf("OpenProcess failed for pid=%v %w", pid, err) + } + defer syscall.CloseHandle(handle) //nolint:errcheck + pbi, err := windows.NtQueryProcessBasicInformation(handle) + if err != nil { + return fmt.Errorf("NtQueryProcessBasicInformation failed for pid=%v %w", pid, err) + } + userProcParams, err := windows.GetUserProcessParams(handle, pbi) + if err != nil { + return nil + } + argsW, err := windows.ReadProcessUnicodeString(handle, &userProcParams.CommandLine) + if err == nil { + pa.List, err = windows.ByteSliceToStringSlice(argsW) + if err != nil { + return err + } + } + return nil } -func (self *ProcExe) Get(pid int) error { //nolint:staticcheck +func (pe *ProcExe) Get(pid int) error { //nolint:staticcheck return ErrNotImplemented } @@ -202,13 +221,9 @@ func (fs *FileSystemUsage) Get(path string) error { //nolint:staticcheck var ( SectorsPerCluster uint32 BytesPerSector uint32 - - // Free clusters available to the user - // associated with the calling thread. + // NumberOfFreeClusters available to the user associated with the calling thread. NumberOfFreeClusters uint32 - - // Total clusters available to the user - // associated with the calling thread. + // TotalNumberOfClusters available to the user associated with the calling thread. TotalNumberOfClusters uint32 ) r1, _, e1 := syscall.SyscallN(procGetDiskFreeSpace.Addr(), @@ -233,7 +248,8 @@ func (fs *FileSystemUsage) Get(path string) error { //nolint:staticcheck func checkErrno(r1 uintptr, e1 error) error { if r1 == 0 { - if e, ok := e1.(syscall.Errno); ok && e != 0 { + var e syscall.Errno + if errors.As(e1, &e) && e != 0 { return e1 } return syscall.EINVAL diff --git a/sys/windows/ntquery.go b/sys/windows/ntquery.go index d2a578ac3..521530235 100644 --- a/sys/windows/ntquery.go +++ b/sys/windows/ntquery.go @@ -5,13 +5,12 @@ package windows import ( "bytes" "encoding/binary" + "fmt" "io" "runtime" "syscall" "time" "unsafe" - - "github.com/pkg/errors" ) // On both 32-bit and 64-bit systems NtQuerySystemInformation expects the @@ -40,7 +39,7 @@ func NtQueryProcessBasicInformation(handle syscall.Handle) (ProcessBasicInformat size := uint32(unsafe.Sizeof(processBasicInfo)) ntStatus, _ := _NtQueryInformationProcess(handle, 0, processBasicInfoPtr, size, nil) //nolint:errcheck if ntStatus != 0 { - return ProcessBasicInformation{}, errors.Errorf("NtQueryInformationProcess failed, NTSTATUS=0x%X", ntStatus) + return ProcessBasicInformation{}, fmt.Errorf("NtQueryInformationProcess failed, NTSTATUS=0x%X", ntStatus) } return processBasicInfo, nil @@ -88,7 +87,7 @@ func NtQuerySystemProcessorPerformanceInformation() ([]SystemProcessorPerformanc var returnLength uint32 ntStatus, _ := _NtQuerySystemInformation(systemProcessorPerformanceInformation, &b[0], uint32(len(b)), &returnLength) //nolint:errcheck if ntStatus != STATUS_SUCCESS { - return nil, errors.Errorf("NtQuerySystemInformation failed, NTSTATUS=0x%X, bufLength=%v, returnLength=%v", ntStatus, len(b), returnLength) + return nil, fmt.Errorf("NtQuerySystemInformation failed, NTSTATUS=0x%X, bufLength=%v, returnLength=%v", ntStatus, len(b), returnLength) } return readSystemProcessorPerformanceInformationBuffer(b) @@ -106,14 +105,14 @@ func readSystemProcessorPerformanceInformationBuffer(b []byte) ([]SystemProcesso for i := 0; i < n; i++ { _, err := r.Seek(int64(i*sizeofSystemProcessorPerformanceInformation), io.SeekStart) if err != nil { - return nil, errors.Wrapf(err, "failed to seek to cpuN=%v in buffer", i) + return nil, fmt.Errorf("failed to seek to cpuN=%v in buffer %w", i, err) } times := make([]uint64, 3) for j := range times { err := binary.Read(r, binary.LittleEndian, ×[j]) if err != nil { - return nil, errors.Wrapf(err, "failed reading cpu times for cpuN=%v", i) + return nil, fmt.Errorf("failed reading cpu times for cpuN=%v %w", i, err) } } diff --git a/sys/windows/privileges.go b/sys/windows/privileges.go index a36fca203..3d1f6c276 100644 --- a/sys/windows/privileges.go +++ b/sys/windows/privileges.go @@ -6,13 +6,13 @@ import ( "bytes" "encoding/binary" "encoding/json" + "errors" "fmt" "runtime" "strings" "sync" "syscall" - "github.com/pkg/errors" "golang.org/x/sys/windows" ) @@ -27,7 +27,7 @@ const ( SeDebugPrivilege = "SeDebugPrivilege" ) -// Errors returned by AdjustTokenPrivileges. +// ERROR_NOT_ALL_ASSIGNED Errors returned by AdjustTokenPrivileges. const ( ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300 ) @@ -102,8 +102,8 @@ type DebugInfo struct { } func (d DebugInfo) String() string { - bytes, _ := json.Marshal(d) //nolint:errcheck - return string(bytes) + b, _ := json.Marshal(d) //nolint:errcheck + return string(b) } // LookupPrivilegeName looks up a privilege name given a LUID value. @@ -112,7 +112,7 @@ func LookupPrivilegeName(systemName string, luid int64) (string, error) { bufSize := uint32(len(buf)) err := _LookupPrivilegeName(systemName, &luid, &buf[0], &bufSize) if err != nil { - return "", errors.Wrapf(err, "LookupPrivilegeName failed for luid=%v", luid) + return "", fmt.Errorf("LookupPrivilegeName failed for luid=%v %w", luid, err) } return syscall.UTF16ToString(buf), nil @@ -128,7 +128,7 @@ func mapPrivileges(names []string) ([]int64, error) { if !ok { err := _LookupPrivilegeValue("", name, &p) if err != nil { - return nil, errors.Wrapf(err, "LookupPrivilegeValue failed on '%v'", name) + return nil, fmt.Errorf("LookupPrivilegeValue failed on '%v' %w", name, err) } privNames[name] = p } @@ -157,8 +157,8 @@ func EnableTokenPrivileges(token syscall.Token, privileges ...string) error { if !success { return err } - if err == ERROR_NOT_ALL_ASSIGNED { - return errors.Wrap(err, "error not all privileges were assigned") + if errors.Is(err, ERROR_NOT_ALL_ASSIGNED) { + return fmt.Errorf("error not all privileges were assigned %w", err) } return nil @@ -177,13 +177,13 @@ func GetTokenPrivileges(token syscall.Token) (map[string]Privilege, error) { b := bytes.NewBuffer(make([]byte, size)) err := syscall.GetTokenInformation(token, syscall.TokenPrivileges, &b.Bytes()[0], uint32(b.Len()), &size) if err != nil { - return nil, errors.Wrap(err, "GetTokenInformation failed") + return nil, fmt.Errorf("GetTokenInformation failed %w", err) } var privilegeCount uint32 err = binary.Read(b, binary.LittleEndian, &privilegeCount) if err != nil { - return nil, errors.Wrap(err, "failed to read PrivilegeCount") + return nil, fmt.Errorf("failed to read PrivilegeCount %w", err) } rtn := make(map[string]Privilege, privilegeCount) @@ -191,18 +191,18 @@ func GetTokenPrivileges(token syscall.Token) (map[string]Privilege, error) { var luid int64 err = binary.Read(b, binary.LittleEndian, &luid) if err != nil { - return nil, errors.Wrap(err, "failed to read LUID value") + return nil, fmt.Errorf("failed to read LUID value %w", err) } var attributes uint32 err = binary.Read(b, binary.LittleEndian, &attributes) if err != nil { - return nil, errors.Wrap(err, "failed to read attributes") + return nil, fmt.Errorf("failed to read attributes %w", err) } name, err := LookupPrivilegeName("", luid) if err != nil { - return nil, errors.Wrapf(err, "LookupPrivilegeName failed for LUID=%v", luid) + return nil, fmt.Errorf("LookupPrivilegeName failed for LUID=%v %w", luid, err) } rtn[name] = Privilege{ @@ -222,18 +222,18 @@ func GetTokenPrivileges(token syscall.Token) (map[string]Privilege, error) { func GetTokenUser(token syscall.Token) (User, error) { tokenUser, err := token.GetTokenUser() if err != nil { - return User{}, errors.Wrap(err, "GetTokenUser failed") + return User{}, fmt.Errorf("GetTokenUser failed %w", err) } var user User user.SID, err = tokenUser.User.Sid.String() if err != nil { - return user, errors.Wrap(err, "ConvertSidToStringSid failed") + return user, fmt.Errorf("ConvertSidToStringSid failed %w", err) } user.Account, user.Domain, user.Type, err = tokenUser.User.Sid.LookupAccount("") if err != nil { - return user, errors.Wrap(err, "LookupAccountSid failed") + return user, fmt.Errorf("LookupAccountSid failed %w", err) } return user, nil diff --git a/sys/windows/syscall_windows.go b/sys/windows/syscall_windows.go index 7f74945a8..3169f00a5 100644 --- a/sys/windows/syscall_windows.go +++ b/sys/windows/syscall_windows.go @@ -1,12 +1,11 @@ package windows import ( + "errors" "fmt" "syscall" "time" "unsafe" - - "github.com/pkg/errors" ) var ( @@ -139,7 +138,7 @@ func GetLogicalDriveStrings() ([]string, error) { // Determine the size of the buffer required to receive all drives. bufferLength, err := _GetLogicalDriveStringsW(0, nil) if err != nil { - return nil, errors.Wrap(err, "GetLogicalDriveStringsW failed to get buffer length") + return nil, fmt.Errorf("GetLogicalDriveStringsW failed to get buffer length %w", err) } if bufferLength < 0 { //nolint:staticcheck return nil, errors.New("GetLogicalDriveStringsW returned an invalid buffer length") @@ -148,7 +147,7 @@ func GetLogicalDriveStrings() ([]string, error) { buffer := make([]uint16, bufferLength) _, err = _GetLogicalDriveStringsW(uint32(len(buffer)), &buffer[0]) if err != nil { - return nil, errors.Wrap(err, "GetLogicalDriveStringsW failed") + return nil, fmt.Errorf("GetLogicalDriveStringsW failed %w", err) } // Split the uint16 slice at null-terminators. @@ -179,7 +178,7 @@ func GlobalMemoryStatusEx() (MemoryStatusEx, error) { memoryStatusEx := MemoryStatusEx{length: sizeofMemoryStatusEx} err := _GlobalMemoryStatusEx(&memoryStatusEx) if err != nil { - return MemoryStatusEx{}, errors.Wrap(err, "GlobalMemoryStatusEx failed") + return MemoryStatusEx{}, fmt.Errorf("GlobalMemoryStatusEx failed %w", err) } return memoryStatusEx, nil @@ -192,7 +191,7 @@ func GetProcessMemoryInfo(handle syscall.Handle) (ProcessMemoryCountersEx, error processMemoryCountersEx := ProcessMemoryCountersEx{cb: sizeofProcessMemoryCountersEx} err := _GetProcessMemoryInfo(handle, &processMemoryCountersEx, processMemoryCountersEx.cb) if err != nil { - return ProcessMemoryCountersEx{}, errors.Wrap(err, "GetProcessMemoryInfo failed") + return ProcessMemoryCountersEx{}, fmt.Errorf("GetProcessMemoryInfo failed %w", err) } return processMemoryCountersEx, nil @@ -205,7 +204,7 @@ func GetProcessImageFileName(handle syscall.Handle) (string, error) { buffer := make([]uint16, MAX_PATH) _, err := _GetProcessImageFileName(handle, &buffer[0], uint32(len(buffer))) if err != nil { - return "", errors.Wrap(err, "GetProcessImageFileName failed") + return "", fmt.Errorf("GetProcessImageFileName failed %w", err) } return syscall.UTF16ToString(buffer), nil @@ -219,7 +218,7 @@ func GetSystemTimes() (idle, kernel, user time.Duration, err error) { var idleTime, kernelTime, userTime syscall.Filetime err = _GetSystemTimes(&idleTime, &kernelTime, &userTime) if err != nil { - return 0, 0, 0, errors.Wrap(err, "GetSystemTimes failed") + return 0, 0, 0, fmt.Errorf("GetSystemTimes failed %w", err) } idle = FiletimeToDuration(&idleTime) @@ -244,12 +243,12 @@ func FiletimeToDuration(ft *syscall.Filetime) time.Duration { func GetDriveType(rootPathName string) (DriveType, error) { rootPathNamePtr, err := syscall.UTF16PtrFromString(rootPathName) if err != nil { - return DRIVE_UNKNOWN, errors.Wrapf(err, "UTF16PtrFromString failed for rootPathName=%v", rootPathName) + return DRIVE_UNKNOWN, fmt.Errorf("UTF16PtrFromString failed for rootPathName=%v %w", rootPathName, err) } dt, err := _GetDriveType(rootPathNamePtr) if err != nil { - return DRIVE_UNKNOWN, errors.Wrapf(err, "GetDriveType failed for rootPathName=%v", rootPathName) + return DRIVE_UNKNOWN, fmt.Errorf("GetDriveType failed for rootPathName=%v %w", rootPathName, err) } return dt, nil @@ -271,7 +270,7 @@ func EnumProcesses() ([]uint32, error) { pidsWritten := int(bytesWritten) / sizeofUint32 if int(bytesWritten)%sizeofUint32 != 0 || pidsWritten > len(pids) { - return nil, errors.Errorf("EnumProcesses returned an invalid bytesWritten value of %v", bytesWritten) + return nil, fmt.Errorf("EnumProcesses returned an invalid bytesWritten value of %v", bytesWritten) } pids = pids[:pidsWritten] @@ -285,7 +284,7 @@ func EnumProcesses() ([]uint32, error) { var err error pids, err = enumProcesses(size) if err != nil { - return nil, errors.Wrap(err, "EnumProcesses failed") + return nil, fmt.Errorf("EnumProcesses failed %w", err) } if len(pids) < size { @@ -293,7 +292,7 @@ func EnumProcesses() ([]uint32, error) { } // Increase the size the pids array and retry the enumProcesses call - // because the array wasn't large enough to hold all of the processes. + // because the array wasn't large enough to hold all the processes. size *= 2 } @@ -308,7 +307,7 @@ func EnumProcesses() ([]uint32, error) { func GetDiskFreeSpaceEx(directoryName string) (freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes uint64, err error) { directoryNamePtr, err := syscall.UTF16PtrFromString(directoryName) if err != nil { - return 0, 0, 0, errors.Wrapf(err, "UTF16PtrFromString failed for directoryName=%v", directoryName) + return 0, 0, 0, fmt.Errorf("UTF16PtrFromString failed for directoryName=%v %w", directoryName, err) } err = _GetDiskFreeSpaceEx(directoryNamePtr, &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes) @@ -341,7 +340,7 @@ func Process32First(handle syscall.Handle) (ProcessEntry32, error) { processEntry32 := ProcessEntry32{size: sizeofProcessEntry32} err := _Process32First(handle, &processEntry32) if err != nil { - return ProcessEntry32{}, errors.Wrap(err, "Process32First failed") + return ProcessEntry32{}, fmt.Errorf("Process32First failed %w", err) } return processEntry32, nil @@ -355,12 +354,105 @@ func Process32Next(handle syscall.Handle) (ProcessEntry32, error) { processEntry32 := ProcessEntry32{size: sizeofProcessEntry32} err := _Process32Next(handle, &processEntry32) if err != nil { - return ProcessEntry32{}, errors.Wrap(err, "Process32Next failed") + return ProcessEntry32{}, fmt.Errorf("Process32Next failed %w", err) } return processEntry32, nil } +type UnicodeString struct { + Length uint16 + MaximumLength uint16 + Buffer uintptr +} + +type RtlUserProcessParameters struct { + Reserved1 [16]byte + Reserved2 [10]uintptr + ImagePathName UnicodeString + CommandLine UnicodeString +} + +func GetUserProcessParams(handle syscall.Handle, pbi ProcessBasicInformation) (*RtlUserProcessParameters, error) { + const pebUserProcessParametersOffset = 0x20 + userProcParamsAddr := pbi.PebBaseAddress + pebUserProcessParametersOffset + + var userProcParamsPtr uintptr + err := ReadProcessMemory(handle, userProcParamsAddr, (*byte)(unsafe.Pointer(&userProcParamsPtr)), unsafe.Sizeof(userProcParamsPtr)) + if err != nil { + return nil, fmt.Errorf("ReadProcessMemory failed for user process parameters pointer %w", err) + } + + userProcParams := &RtlUserProcessParameters{} + err = ReadProcessMemory(handle, userProcParamsPtr, (*byte)(unsafe.Pointer(userProcParams)), unsafe.Sizeof(*userProcParams)) + if err != nil { + return nil, fmt.Errorf("ReadProcessMemory failed for user process parameters %w", err) + } + + return userProcParams, nil +} + +func ReadProcessUnicodeString(handle syscall.Handle, s *UnicodeString) ([]byte, error) { + if s.Length == 0 || s.Buffer == 0 { + return nil, errors.New("UnicodeString is empty") + } + + buf := make([]byte, s.Length) + err := ReadProcessMemory(handle, s.Buffer, &buf[0], uintptr(s.Length)) + if err != nil { + return nil, fmt.Errorf("ReadProcessMemory failed for UnicodeString %w", err) + } + + return buf, nil +} + +func ByteSliceToStringSlice(buf []byte) ([]string, error) { + if len(buf) == 0 { + return nil, errors.New("empty buffer") + } + + words := make([]uint16, len(buf)/2) + for i := range words { + words[i] = uint16(buf[i*2]) | uint16(buf[i*2+1])<<8 + } + + var args []string + var start int + for i, w := range words { + if w == 0 { + if i > start { + args = append(args, syscall.UTF16ToString(words[start:i])) + } + start = i + 1 + } + } + if start < len(words) { + args = append(args, syscall.UTF16ToString(words[start:])) + } + + return args, nil +} + +func ReadProcessMemory(handle syscall.Handle, baseAddress uintptr, dest *byte, size uintptr) error { + var numRead uintptr + err := _ReadProcessMemory(handle, baseAddress, dest, size, &numRead) + if err != nil { + return fmt.Errorf("ReadProcessMemory failed %w", err) + } + if numRead != size { + return fmt.Errorf("ReadProcessMemory read %d bytes, expected %d", numRead, size) + } + return nil +} + +func GetTickCount64() (uint64, error) { + ticks, err := _GetTickCount64() + if err != nil { + return 0, fmt.Errorf("GetTickCount64 failed %w", err) + } + return ticks, nil +} + // Use "GOOS=windows go generate -v -x ." to generate the source. // Add -trace to enable debug prints around syscalls. @@ -383,3 +475,5 @@ func Process32Next(handle syscall.Handle) (ProcessEntry32, error) { //sys _LookupPrivilegeName(systemName string, luid *int64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW //sys _LookupPrivilegeValue(systemName string, name string, luid *int64) (err error) = advapi32.LookupPrivilegeValueW //sys _AdjustTokenPrivileges(token syscall.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges +//sys _ReadProcessMemory(handle syscall.Handle, baseAddress uintptr, buffer *byte, size uintptr, numRead *uintptr) (err error) = kernel32.ReadProcessMemory +//sys _GetTickCount64() (milliseconds uint64, err error) = kernel32.GetTickCount64 diff --git a/sys/windows/syscall_windows_test.go b/sys/windows/syscall_windows_test.go index 4ac7afe51..aeae85d76 100644 --- a/sys/windows/syscall_windows_test.go +++ b/sys/windows/syscall_windows_test.go @@ -1,12 +1,12 @@ package windows import ( + "errors" "os" "runtime" "syscall" "testing" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) @@ -102,7 +102,7 @@ func TestGetDiskFreeSpaceEx(t *testing.T) { t.Fatal(err) } - // Ignore CDROM drives. They return an error if the drive is emtpy. + // Ignore CD-ROM drives. They return an error if the drive is empty. if dt != DRIVE_CDROM { free, total, totalFree, err := GetDiskFreeSpaceEx(drive) if err != nil { @@ -124,13 +124,13 @@ func TestCreateToolhelp32Snapshot(t *testing.T) { if err != nil { t.Fatal(err) } - defer syscall.CloseHandle(syscall.Handle(handle)) //nolint:errcheck + defer syscall.CloseHandle(handle) //nolint:errcheck // Iterate over the snapshots until our PID is found. pid := uint32(syscall.Getpid()) for { process, err := Process32Next(handle) - if errors.Cause(err) == syscall.ERROR_NO_MORE_FILES { + if errors.Is(err, syscall.ERROR_NO_MORE_FILES) { break } if err != nil { diff --git a/sys/windows/zsyscall_windows.go b/sys/windows/zsyscall_windows.go index fb07cbf1d..b6101c8d0 100644 --- a/sys/windows/zsyscall_windows.go +++ b/sys/windows/zsyscall_windows.go @@ -31,6 +31,8 @@ var ( procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW") procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") + procReadProcessMemory = modkernel32.NewProc("ReadProcessMemory") + procGetTickCount64 = modkernel32.NewProc("GetTickCount64") ) func _GlobalMemoryStatusEx(buffer *MemoryStatusEx) (err error) { @@ -260,3 +262,28 @@ func _AdjustTokenPrivileges(token syscall.Token, releaseAll bool, input *byte, o } return } + +func _ReadProcessMemory(handle syscall.Handle, baseAddress uintptr, buffer *byte, size uintptr, numRead *uintptr) (err error) { + r1, _, e1 := syscall.SyscallN(procReadProcessMemory.Addr(), uintptr(handle), uintptr(baseAddress), uintptr(unsafe.Pointer(buffer)), uintptr(size), uintptr(unsafe.Pointer(numRead))) + if r1 == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func _GetTickCount64() (milliseconds uint64, err error) { + r0, _, e1 := syscall.SyscallN(procGetTickCount64.Addr()) + milliseconds = uint64(r0) + if milliseconds == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1b..000000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 9159de03e..000000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.11.x - - 1.12.x - - 1.13.x - - tip - -script: - - make check diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e75..000000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/Makefile b/vendor/github.com/pkg/errors/Makefile deleted file mode 100644 index ce9d7cded..000000000 --- a/vendor/github.com/pkg/errors/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -PKGS := github.com/pkg/errors -SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) -GO := go - -check: test vet gofmt misspell unconvert staticcheck ineffassign unparam - -test: - $(GO) test $(PKGS) - -vet: | test - $(GO) vet $(PKGS) - -staticcheck: - $(GO) get honnef.co/go/tools/cmd/staticcheck - staticcheck -checks all $(PKGS) - -misspell: - $(GO) get github.com/client9/misspell/cmd/misspell - misspell \ - -locale GB \ - -error \ - *.md *.go - -unconvert: - $(GO) get github.com/mdempsky/unconvert - unconvert -v $(PKGS) - -ineffassign: - $(GO) get github.com/gordonklaus/ineffassign - find $(SRCDIRS) -name '*.go' | xargs ineffassign - -pedantic: check errcheck - -unparam: - $(GO) get mvdan.cc/unparam - unparam ./... - -errcheck: - $(GO) get github.com/kisielk/errcheck - errcheck $(PKGS) - -gofmt: - @echo Checking code is gofmted - @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 54dfdcb12..000000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Roadmap - -With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: - -- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) -- 1.0. Final release. - -## Contributing - -Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. - -Before sending a PR, please discuss your change by raising an issue. - -## License - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade0..000000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 161aea258..000000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,288 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which when applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// together with the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required, the errors.WithStack and -// errors.WithMessage functions destructure errors.Wrap into its component -// operations: annotating an error with a stack trace and with a message, -// respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error that does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// Although the causer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported: -// -// %s print the error. If the error has a Cause it will be -// printed recursively. -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface: -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// The returned errors.StackTrace type is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d\n", f, f) -// } -// } -// -// Although the stackTracer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withStack) Unwrap() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is called, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -// WithMessagef annotates err with the format specifier. -// If err is nil, WithMessagef returns nil. -func WithMessagef(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withMessage) Unwrap() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go deleted file mode 100644 index be0d10d0c..000000000 --- a/vendor/github.com/pkg/errors/go113.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build go1.13 - -package errors - -import ( - stderrors "errors" -) - -// Is reports whether any error in err's chain matches target. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error is considered to match a target if it is equal to that target or if -// it implements a method Is(error) bool such that Is(target) returns true. -func Is(err, target error) bool { return stderrors.Is(err, target) } - -// As finds the first error in err's chain that matches target, and if so, sets -// target to that error value and returns true. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that -// As(target) returns true. In the latter case, the As method is responsible for -// setting target. -// -// As will panic if target is not a non-nil pointer to either a type that implements -// error, or to any interface type. As returns false if err is nil. -func As(err error, target interface{}) bool { return stderrors.As(err, target) } - -// Unwrap returns the result of calling the Unwrap method on err, if err's -// type contains an Unwrap method returning error. -// Otherwise, Unwrap returns nil. -func Unwrap(err error) error { - return stderrors.Unwrap(err) -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 779a8348f..000000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,177 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strconv" - "strings" -) - -// Frame represents a program counter inside a stack frame. -// For historical reasons if Frame is interpreted as a uintptr -// its value represents the program counter + 1. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// name returns the name of this function, if known. -func (f Frame) name() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - return fn.Name() -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (\n\t) -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - io.WriteString(s, f.name()) - io.WriteString(s, "\n\t") - io.WriteString(s, f.file()) - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - io.WriteString(s, strconv.Itoa(f.line())) - case 'n': - io.WriteString(s, funcname(f.name())) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// MarshalText formats a stacktrace Frame as a text string. The output is the -// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. -func (f Frame) MarshalText() ([]byte, error) { - name := f.name() - if name == "unknown" { - return []byte(name), nil - } - return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -// Format formats the stack of Frames according to the fmt.Formatter interface. -// -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+v Prints filename, function, and line number for each Frame in the stack. -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - io.WriteString(s, "\n") - f.Format(s, verb) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - st.formatSlice(s, verb) - } - case 's': - st.formatSlice(s, verb) - } -} - -// formatSlice will format this StackTrace into the given buffer as a slice of -// Frame, only valid when called with '%s' or '%v'. -func (st StackTrace) formatSlice(s fmt.State, verb rune) { - io.WriteString(s, "[") - for i, f := range st { - if i > 0 { - io.WriteString(s, " ") - } - f.Format(s, verb) - } - io.WriteString(s, "]") -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} diff --git a/vendor/modules.txt b/vendor/modules.txt index be57751e7..6dbf8a347 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -60,9 +60,6 @@ github.com/onsi/gomega/matchers/support/goraph/edge github.com/onsi/gomega/matchers/support/goraph/node github.com/onsi/gomega/matchers/support/goraph/util github.com/onsi/gomega/types -# github.com/pkg/errors v0.9.1 -## explicit -github.com/pkg/errors # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib