From 25435a3a1c0f5fa960a6dd3938188c14332308d8 Mon Sep 17 00:00:00 2001 From: kruskal <99559985+kruskall@users.noreply.github.com> Date: Thu, 28 Jul 2022 12:39:08 +0200 Subject: [PATCH] feat: replace pkg/errors with Go 1.13 native errors Add support for error wrapping and switch to modern Go 1.13 errors. --- go.mod | 2 +- internal/registry/registry.go | 6 +++--- providers/aix/boottime_aix_ppc64.go | 7 +++---- providers/aix/host_aix_ppc64.go | 9 ++++---- providers/aix/kernel_aix_ppc64.go | 9 ++++---- providers/aix/machineid_aix_ppc64.go | 6 ++---- providers/aix/os_aix_ppc64.go | 5 ++--- providers/aix/process_aix_ppc64.go | 25 +++++++++++----------- providers/darwin/arch_darwin.go | 5 ++--- providers/darwin/boottime_darwin.go | 5 ++--- providers/darwin/host_darwin.go | 4 ++-- providers/darwin/kernel_darwin.go | 5 ++--- providers/darwin/machineid_darwin.go | 10 ++++----- providers/darwin/memory_darwin.go | 6 ++---- providers/darwin/os.go | 12 +++++------ providers/darwin/process_darwin.go | 14 ++++++------- providers/darwin/syscall_darwin.go | 6 ++---- providers/linux/arch_linux.go | 5 ++--- providers/linux/container.go | 5 ++--- providers/linux/host_linux.go | 7 ++++--- providers/linux/kernel_linux.go | 5 ++--- providers/linux/machineid.go | 5 ++--- providers/linux/memory_linux.go | 4 ++-- providers/linux/os.go | 10 ++++----- providers/linux/procnet.go | 13 ++++++------ providers/linux/util.go | 12 +++++------ providers/linux/vmstat.go | 5 ++--- providers/windows/boottime_windows.go | 5 ++--- providers/windows/device_windows.go | 7 ++++--- providers/windows/host_windows.go | 4 ++-- providers/windows/machineid_windows.go | 7 ++++--- providers/windows/os_windows.go | 11 +++++----- providers/windows/process_windows.go | 29 +++++++++++++------------- system_test.go | 6 +++--- types/errors.go | 2 +- 35 files changed, 130 insertions(+), 148 deletions(-) diff --git a/go.mod b/go.mod index 8ae92f3d..536235c3 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,6 @@ go 1.17 require ( github.com/elastic/go-windows v1.0.0 github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 - github.com/pkg/errors v0.8.1 github.com/prometheus/procfs v0.0.0-20190425082905-87a4384529e0 github.com/stretchr/testify v1.3.0 golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a @@ -14,5 +13,6 @@ require ( require ( github.com/davecgh/go-spew v1.1.0 // indirect + github.com/pkg/errors v0.8.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect ) diff --git a/internal/registry/registry.go b/internal/registry/registry.go index 21ba2ed3..071e2d63 100644 --- a/internal/registry/registry.go +++ b/internal/registry/registry.go @@ -18,7 +18,7 @@ package registry import ( - "github.com/pkg/errors" + "fmt" "github.com/elastic/go-sysinfo/types" ) @@ -41,14 +41,14 @@ type ProcessProvider interface { func Register(provider interface{}) { if h, ok := provider.(HostProvider); ok { if hostProvider != nil { - panic(errors.Errorf("HostProvider already registered: %v", hostProvider)) + panic(fmt.Sprintf("HostProvider already registered: %v", hostProvider)) } hostProvider = h } if p, ok := provider.(ProcessProvider); ok { if processProvider != nil { - panic(errors.Errorf("ProcessProvider already registered: %v", processProvider)) + panic(fmt.Sprintf("ProcessProvider already registered: %v", processProvider)) } processProvider = p } diff --git a/providers/aix/boottime_aix_ppc64.go b/providers/aix/boottime_aix_ppc64.go index beaaa553..f1ecd41c 100644 --- a/providers/aix/boottime_aix_ppc64.go +++ b/providers/aix/boottime_aix_ppc64.go @@ -22,10 +22,9 @@ package aix import ( "encoding/binary" + "fmt" "os" "time" - - "github.com/pkg/errors" ) // utmp can't be used by "encoding/binary" if generated by cgo, @@ -60,7 +59,7 @@ func bootTime(filename string) (time.Time, error) { // Get boot time from /etc/utmp file, err := os.Open(filename) if err != nil { - return time.Time{}, errors.Wrap(err, "failed to get host uptime: cannot open /etc/utmp") + return time.Time{}, fmt.Errorf("failed to get host uptime: cannot open /etc/utmp: %w", err) } defer file.Close() @@ -76,5 +75,5 @@ func bootTime(filename string) (time.Time, error) { } } - return time.Time{}, errors.Wrap(err, "failed to get host uptime: no utmp record") + return time.Time{}, fmt.Errorf("failed to get host uptime: no utmp record: %w", err) } diff --git a/providers/aix/host_aix_ppc64.go b/providers/aix/host_aix_ppc64.go index 36257cb9..3cabe3ff 100644 --- a/providers/aix/host_aix_ppc64.go +++ b/providers/aix/host_aix_ppc64.go @@ -31,11 +31,12 @@ package aix import "C" import ( + "errors" + "fmt" "os" "time" "github.com/joeshaw/multierror" - "github.com/pkg/errors" "github.com/elastic/go-sysinfo/internal/registry" "github.com/elastic/go-sysinfo/providers/shared" @@ -80,7 +81,7 @@ func (*host) CPUTime() (types.CPUTimes, error) { cpudata := C.perfstat_cpu_total_t{} if _, err := C.perfstat_cpu_total(nil, &cpudata, C.sizeof_perfstat_cpu_total_t, 1); err != nil { - return types.CPUTimes{}, errors.Wrap(err, "error while callin perfstat_cpu_total") + return types.CPUTimes{}, fmt.Errorf("error while callin perfstat_cpu_total: %w", err) } return types.CPUTimes{ @@ -100,7 +101,7 @@ func (*host) Memory() (*types.HostMemoryInfo, error) { meminfo := C.perfstat_memory_total_t{} _, err := C.perfstat_memory_total(nil, &meminfo, C.sizeof_perfstat_memory_total_t, 1) if err != nil { - return nil, errors.Wrap(err, "perfstat_memory_total failed") + return nil, fmt.Errorf("perfstat_memory_total failed: %w", err) } mem.Total = uint64(meminfo.real_total) * pagesize @@ -137,7 +138,7 @@ type reader struct { func (r *reader) addErr(err error) bool { if err != nil { - if errors.Cause(err) != types.ErrNotImplemented { + if !errors.Is(err, types.ErrNotImplemented) { r.errs = append(r.errs, err) } return true diff --git a/providers/aix/kernel_aix_ppc64.go b/providers/aix/kernel_aix_ppc64.go index 23bc987e..9b03e2ff 100644 --- a/providers/aix/kernel_aix_ppc64.go +++ b/providers/aix/kernel_aix_ppc64.go @@ -26,9 +26,8 @@ package aix import "C" import ( + "fmt" "strconv" - - "github.com/pkg/errors" ) var oslevel string @@ -36,17 +35,17 @@ var oslevel string func getKernelVersion() (int, int, error) { name := C.struct_utsname{} if _, err := C.uname(&name); err != nil { - return 0, 0, errors.Wrap(err, "kernel version: uname") + return 0, 0, fmt.Errorf("kernel version: uname: %w", err) } version, err := strconv.Atoi(C.GoString(&name.version[0])) if err != nil { - return 0, 0, errors.Wrap(err, "parsing kernel version") + return 0, 0, fmt.Errorf("parsing kernel version: %w", err) } release, err := strconv.Atoi(C.GoString(&name.release[0])) if err != nil { - return 0, 0, errors.Wrap(err, "parsing kernel release") + return 0, 0, fmt.Errorf("parsing kernel release: %w", err) } return version, release, nil } diff --git a/providers/aix/machineid_aix_ppc64.go b/providers/aix/machineid_aix_ppc64.go index 1aab374f..13458e5e 100644 --- a/providers/aix/machineid_aix_ppc64.go +++ b/providers/aix/machineid_aix_ppc64.go @@ -25,15 +25,13 @@ package aix */ import "C" -import ( - "github.com/pkg/errors" -) +import "fmt" // MachineID returns the id of the machine func MachineID() (string, error) { name := C.struct_utsname{} if _, err := C.uname(&name); err != nil { - return "", errors.Wrap(err, "machine id") + return "", fmt.Errorf("machine id: %w", err) } return C.GoString(&name.machine[0]), nil } diff --git a/providers/aix/os_aix_ppc64.go b/providers/aix/os_aix_ppc64.go index d10476da..03c87da3 100644 --- a/providers/aix/os_aix_ppc64.go +++ b/providers/aix/os_aix_ppc64.go @@ -21,12 +21,11 @@ package aix import ( + "fmt" "io/ioutil" "strconv" "strings" - "github.com/pkg/errors" - "github.com/elastic/go-sysinfo/types" ) @@ -44,7 +43,7 @@ func getOSInfo() (*types.OSInfo, error) { // Retrieve build version from "/proc/version". procVersion, err := ioutil.ReadFile("/proc/version") if err != nil { - return nil, errors.Wrap(err, "failed to get OS info: cannot open /proc/version") + return nil, fmt.Errorf("failed to get OS info: cannot open /proc/version: %w", err) } build := strings.SplitN(string(procVersion), "\n", 4)[2] diff --git a/providers/aix/process_aix_ppc64.go b/providers/aix/process_aix_ppc64.go index e586decf..cd9f7ed8 100644 --- a/providers/aix/process_aix_ppc64.go +++ b/providers/aix/process_aix_ppc64.go @@ -33,6 +33,7 @@ import "C" import ( "bytes" "encoding/binary" + "fmt" "io" "io/ioutil" "os" @@ -43,8 +44,6 @@ import ( "time" "unsafe" - "github.com/pkg/errors" - "github.com/elastic/go-sysinfo/types" ) @@ -54,7 +53,7 @@ func (aixSystem) Processes() ([]types.Process, error) { // getprocs which will also retrieve kernel threads. files, err := ioutil.ReadDir("/proc") if err != nil { - return nil, errors.Wrap(err, "error while reading /proc") + return nil, fmt.Errorf("error while reading /proc: %w", err) } processes := make([]types.Process, 0, len(files)) @@ -121,7 +120,7 @@ func (p *process) Info() (types.ProcessInfo, error) { err = syscall.ESRCH } if err != nil { - return types.ProcessInfo{}, errors.Wrap(err, "error while calling getprocs") + return types.ProcessInfo{}, fmt.Errorf("error while calling getprocs: %w", err) } p.info.PPID = int(info.pi_ppid) @@ -133,7 +132,7 @@ func (p *process) Info() (types.ProcessInfo, error) { buf := make([]byte, 8192) var args []string if _, err := C.getargs(unsafe.Pointer(&info), C.sizeof_struct_procsinfo64, (*C.char)(&buf[0]), 8192); err != nil { - return types.ProcessInfo{}, errors.Wrap(err, "error while calling getargs") + return types.ProcessInfo{}, fmt.Errorf("error while calling getargs: %w", err) } bbuf := bytes.NewBuffer(buf) @@ -143,7 +142,7 @@ func (p *process) Info() (types.ProcessInfo, error) { break } if err != nil { - return types.ProcessInfo{}, errors.Wrap(err, "error while reading arguments") + return types.ProcessInfo{}, fmt.Errorf("error while reading arguments: %w", err) } args = append(args, string(chop(arg))) @@ -183,7 +182,7 @@ func (p *process) Info() (types.ProcessInfo, error) { cwd, err := os.Readlink("/proc/" + strconv.Itoa(p.pid) + "/cwd") if err != nil { if !os.IsNotExist(err) { - return types.ProcessInfo{}, errors.Wrapf(err, "error while reading /proc/%s/cwd", strconv.Itoa(p.pid)) + return types.ProcessInfo{}, fmt.Errorf("error while reading /proc/%s/cwd: %w", strconv.Itoa(p.pid), err) } } @@ -205,7 +204,7 @@ func (p *process) Environment() (map[string]string, error) { info.pi_pid = C.pid_t(p.pid) if _, err := C.getevars(unsafe.Pointer(&info), C.sizeof_struct_procsinfo64, (*C.char)(&buf[0]), 8192); err != nil { - return nil, errors.Wrap(err, "error while calling getevars") + return nil, fmt.Errorf("error while calling getevars: %w", err) } bbuf := bytes.NewBuffer(buf) @@ -218,12 +217,12 @@ func (p *process) Environment() (map[string]string, error) { break } if err != nil { - return nil, errors.Wrap(err, "error while calling getevars") + return nil, fmt.Errorf("error while calling getevars: %w", err) } pair := bytes.SplitN(chop(line), delim, 2) if len(pair) != 2 { - return nil, errors.Wrap(err, "error reading process environment") + return nil, fmt.Errorf("error reading process environment: %w", err) } p.env[string(pair[0])] = string(pair[1]) } @@ -260,7 +259,7 @@ func (p *process) Memory() (types.MemoryInfo, error) { err = syscall.ESRCH } if err != nil { - return types.MemoryInfo{}, errors.Wrap(err, "error while calling getprocs") + return types.MemoryInfo{}, fmt.Errorf("error while calling getprocs: %w", err) } mem.Resident = uint64(info.pi_drss+info.pi_trss) * pagesize @@ -286,12 +285,12 @@ func (p *process) decodeProcfsFile(name string, data interface{}) error { file, err := os.Open(fileName) if err != nil { - return errors.Wrapf(err, "error while opening %s", fileName) + return fmt.Errorf("error while opening %s: %w", fileName, err) } defer file.Close() if err := binary.Read(file, binary.BigEndian, data); err != nil { - return errors.Wrapf(err, "error while decoding %s", fileName) + return fmt.Errorf("error while decoding %s: %w", fileName, err) } return nil diff --git a/providers/darwin/arch_darwin.go b/providers/darwin/arch_darwin.go index 7236ce64..cc800d14 100644 --- a/providers/darwin/arch_darwin.go +++ b/providers/darwin/arch_darwin.go @@ -21,9 +21,8 @@ package darwin import ( + "fmt" "syscall" - - "github.com/pkg/errors" ) const hardwareMIB = "hw.machine" @@ -31,7 +30,7 @@ const hardwareMIB = "hw.machine" func Architecture() (string, error) { arch, err := syscall.Sysctl(hardwareMIB) if err != nil { - return "", errors.Wrap(err, "failed to get architecture") + return "", fmt.Errorf("failed to get architecture: %w", err) } return arch, nil diff --git a/providers/darwin/boottime_darwin.go b/providers/darwin/boottime_darwin.go index cf3a5b3c..c1eda1a6 100644 --- a/providers/darwin/boottime_darwin.go +++ b/providers/darwin/boottime_darwin.go @@ -21,10 +21,9 @@ package darwin import ( + "fmt" "syscall" "time" - - "github.com/pkg/errors" ) const kernBoottimeMIB = "kern.boottime" @@ -32,7 +31,7 @@ const kernBoottimeMIB = "kern.boottime" func BootTime() (time.Time, error) { var tv syscall.Timeval if err := sysctlByName(kernBoottimeMIB, &tv); err != nil { - return time.Time{}, errors.Wrap(err, "failed to get host uptime") + return time.Time{}, fmt.Errorf("failed to get host uptime: %w", err) } bootTime := time.Unix(int64(tv.Sec), int64(tv.Usec)*int64(time.Microsecond)) diff --git a/providers/darwin/host_darwin.go b/providers/darwin/host_darwin.go index 73d2391c..b612534f 100644 --- a/providers/darwin/host_darwin.go +++ b/providers/darwin/host_darwin.go @@ -21,11 +21,11 @@ package darwin import ( + "errors" "os" "time" "github.com/joeshaw/multierror" - "github.com/pkg/errors" "github.com/elastic/go-sysinfo/internal/registry" "github.com/elastic/go-sysinfo/providers/shared" @@ -150,7 +150,7 @@ type reader struct { func (r *reader) addErr(err error) bool { if err != nil { - if errors.Cause(err) != types.ErrNotImplemented { + if !errors.Is(err, types.ErrNotImplemented) { r.errs = append(r.errs, err) } return true diff --git a/providers/darwin/kernel_darwin.go b/providers/darwin/kernel_darwin.go index 7d574161..cc2a1c6e 100644 --- a/providers/darwin/kernel_darwin.go +++ b/providers/darwin/kernel_darwin.go @@ -21,9 +21,8 @@ package darwin import ( + "fmt" "syscall" - - "github.com/pkg/errors" ) const kernelReleaseMIB = "kern.osrelease" @@ -31,7 +30,7 @@ const kernelReleaseMIB = "kern.osrelease" func KernelVersion() (string, error) { version, err := syscall.Sysctl(kernelReleaseMIB) if err != nil { - return "", errors.Wrap(err, "failed to get kernel version") + return "", fmt.Errorf("failed to get kernel version: %w", err) } return version, nil diff --git a/providers/darwin/machineid_darwin.go b/providers/darwin/machineid_darwin.go index 90c5becb..b4d01fbf 100644 --- a/providers/darwin/machineid_darwin.go +++ b/providers/darwin/machineid_darwin.go @@ -25,9 +25,9 @@ package darwin import "C" import ( + "errors" + "fmt" "unsafe" - - "github.com/pkg/errors" ) // MachineID returns the Hardware UUID also accessible via @@ -45,17 +45,17 @@ func getHostUUID() (string, error) { ret, err := C.gethostuuid(&id[0], &wait) if ret != 0 { if err != nil { - return "", errors.Wrapf(err, "gethostuuid failed with %v", ret) + return "", fmt.Errorf("gethostuuid failed with %v: %w", ret, err) } - return "", errors.Errorf("gethostuuid failed with %v", ret) + return "", fmt.Errorf("gethostuuid failed with %v", ret) } var uuidStringC C.uuid_string_t var uuid [unsafe.Sizeof(uuidStringC)]C.char _, err = C.uuid_unparse_upper(&id[0], &uuid[0]) if err != nil { - return "", errors.Wrap(err, "uuid_unparse_upper failed") + return "", fmt.Errorf("uuid_unparse_upper failed: %w", err) } return C.GoString(&uuid[0]), nil diff --git a/providers/darwin/memory_darwin.go b/providers/darwin/memory_darwin.go index c147b818..868c8511 100644 --- a/providers/darwin/memory_darwin.go +++ b/providers/darwin/memory_darwin.go @@ -20,16 +20,14 @@ package darwin -import ( - "github.com/pkg/errors" -) +import "fmt" const hwMemsizeMIB = "hw.memsize" func MemTotal() (uint64, error) { var size uint64 if err := sysctlByName(hwMemsizeMIB, &size); err != nil { - return 0, errors.Wrap(err, "failed to get mem total") + return 0, fmt.Errorf("failed to get mem total: %w", err) } return size, nil diff --git a/providers/darwin/os.go b/providers/darwin/os.go index 686a0c7a..0dbe8473 100644 --- a/providers/darwin/os.go +++ b/providers/darwin/os.go @@ -18,11 +18,11 @@ package darwin import ( + "fmt" "io/ioutil" "strconv" "strings" - "github.com/pkg/errors" "howett.net/plist" "github.com/elastic/go-sysinfo/types" @@ -39,7 +39,7 @@ const ( func OperatingSystem() (*types.OSInfo, error) { data, err := ioutil.ReadFile(systemVersionPlist) if err != nil { - return nil, errors.Wrap(err, "failed to read plist file") + return nil, fmt.Errorf("failed to read plist file: %w", err) } return getOSInfo(data) @@ -48,22 +48,22 @@ func OperatingSystem() (*types.OSInfo, error) { func getOSInfo(data []byte) (*types.OSInfo, error) { attrs := map[string]string{} if _, err := plist.Unmarshal(data, &attrs); err != nil { - return nil, errors.Wrap(err, "failed to unmarshal plist data") + return nil, fmt.Errorf("failed to unmarshal plist data: %w", err) } productName, found := attrs[plistProductName] if !found { - return nil, errors.Errorf("plist key %v not found", plistProductName) + return nil, fmt.Errorf("plist key %v not found", plistProductName) } version, found := attrs[plistProductVersion] if !found { - return nil, errors.Errorf("plist key %v not found", plistProductVersion) + return nil, fmt.Errorf("plist key %v not found", plistProductVersion) } build, found := attrs[plistProductBuildVersion] if !found { - return nil, errors.Errorf("plist key %v not found", plistProductBuildVersion) + return nil, fmt.Errorf("plist key %v not found", plistProductBuildVersion) } var major, minor, patch int diff --git a/providers/darwin/process_darwin.go b/providers/darwin/process_darwin.go index 025e36aa..a411a037 100644 --- a/providers/darwin/process_darwin.go +++ b/providers/darwin/process_darwin.go @@ -28,13 +28,13 @@ import "C" import ( "bytes" "encoding/binary" + "errors" + "fmt" "os" "strconv" "time" "unsafe" - "github.com/pkg/errors" - "github.com/elastic/go-sysinfo/types" ) @@ -43,9 +43,9 @@ import ( func (s darwinSystem) Processes() ([]types.Process, error) { n, err := C.proc_listallpids(nil, 0) if err != nil { - return nil, errors.Wrapf(err, "error getting process count from proc_listallpids (n = %v)", n) + return nil, fmt.Errorf("error getting process count from proc_listallpids (n = %v): %w", n, err) } else if n <= 0 { - return nil, errors.Errorf("proc_listallpids returned %v", n) + return nil, fmt.Errorf("proc_listallpids returned %v", n) } var pid C.int @@ -53,9 +53,9 @@ func (s darwinSystem) Processes() ([]types.Process, error) { buf := make([]byte, bufsize) n, err = C.proc_listallpids(unsafe.Pointer(&buf[0]), bufsize) if err != nil { - return nil, errors.Wrapf(err, "error getting processes from proc_listallpids (n = %v)", n) + return nil, fmt.Errorf("error getting processes from proc_listallpids (n = %v): %w", n, err) } else if n <= 0 { - return nil, errors.Errorf("proc_listallpids returned %v", n) + return nil, fmt.Errorf("proc_listallpids returned %v", n) } bbuf := bytes.NewBuffer(buf) @@ -63,7 +63,7 @@ func (s darwinSystem) Processes() ([]types.Process, error) { for i := 0; i < int(n); i++ { err = binary.Read(bbuf, binary.LittleEndian, &pid) if err != nil { - return nil, errors.Wrap(err, "error reading binary list of PIDs") + return nil, fmt.Errorf("error reading binary list of PIDs: %w", err) } if pid == 0 { diff --git a/providers/darwin/syscall_darwin.go b/providers/darwin/syscall_darwin.go index 52b1dab6..3cab637d 100644 --- a/providers/darwin/syscall_darwin.go +++ b/providers/darwin/syscall_darwin.go @@ -36,8 +36,6 @@ import ( "sync" "syscall" "unsafe" - - "github.com/pkg/errors" ) // Single-word zero for use when we need a valid pointer to 0 bytes. @@ -182,7 +180,7 @@ func getHostCPULoadInfo() (*cpuUsage, error) { &count) if status != C.KERN_SUCCESS { - return nil, errors.Errorf("host_statistics returned status %d", status) + return nil, fmt.Errorf("host_statistics returned status %d", status) } return &cpu, nil @@ -216,7 +214,7 @@ func getPageSize() (uint64, error) { C.host_t(C.mach_host_self()), (*C.vm_size_t)(unsafe.Pointer(&pageSize))) if status != C.KERN_SUCCESS { - return 0, errors.Errorf("host_page_size returned status %d", status) + return 0, fmt.Errorf("host_page_size returned status %d", status) } return uint64(pageSize), nil diff --git a/providers/linux/arch_linux.go b/providers/linux/arch_linux.go index 13a9574c..e1d28936 100644 --- a/providers/linux/arch_linux.go +++ b/providers/linux/arch_linux.go @@ -18,15 +18,14 @@ package linux import ( + "fmt" "syscall" - - "github.com/pkg/errors" ) func Architecture() (string, error) { var uname syscall.Utsname if err := syscall.Uname(&uname); err != nil { - return "", errors.Wrap(err, "architecture") + return "", fmt.Errorf("architecture: %w", err) } data := make([]byte, 0, len(uname.Machine)) diff --git a/providers/linux/container.go b/providers/linux/container.go index fc668659..7eee188e 100644 --- a/providers/linux/container.go +++ b/providers/linux/container.go @@ -20,10 +20,9 @@ package linux import ( "bufio" "bytes" + "fmt" "io/ioutil" "os" - - "github.com/pkg/errors" ) const procOneCgroup = "/proc/1/cgroup" @@ -36,7 +35,7 @@ func IsContainerized() (bool, error) { return false, nil } - return false, errors.Wrap(err, "failed to read process cgroups") + return false, fmt.Errorf("failed to read process cgroups: %w", err) } return isContainerizedCgroup(data) diff --git a/providers/linux/host_linux.go b/providers/linux/host_linux.go index 7727e722..4898078c 100644 --- a/providers/linux/host_linux.go +++ b/providers/linux/host_linux.go @@ -18,13 +18,14 @@ package linux import ( + "errors" + "fmt" "io/ioutil" "os" "path/filepath" "time" "github.com/joeshaw/multierror" - "github.com/pkg/errors" "github.com/prometheus/procfs" "github.com/elastic/go-sysinfo/internal/registry" @@ -125,7 +126,7 @@ func (h *host) CPUTime() (types.CPUTimes, error) { func newHost(fs procFS) (*host, error) { stat, err := fs.NewStat() if err != nil { - return nil, errors.Wrap(err, "failed to read proc stat") + return nil, fmt.Errorf("failed to read proc stat: %w", err) } h := &host{stat: stat, procFS: fs} @@ -148,7 +149,7 @@ type reader struct { func (r *reader) addErr(err error) bool { if err != nil { - if errors.Cause(err) != types.ErrNotImplemented { + if !errors.Is(err, types.ErrNotImplemented) { r.errs = append(r.errs, err) } return true diff --git a/providers/linux/kernel_linux.go b/providers/linux/kernel_linux.go index 1b88e479..1695fb81 100644 --- a/providers/linux/kernel_linux.go +++ b/providers/linux/kernel_linux.go @@ -18,15 +18,14 @@ package linux import ( + "fmt" "syscall" - - "github.com/pkg/errors" ) func KernelVersion() (string, error) { var uname syscall.Utsname if err := syscall.Uname(&uname); err != nil { - return "", errors.Wrap(err, "kernel version") + return "", fmt.Errorf("kernel version: %w", err) } data := make([]byte, 0, len(uname.Release)) diff --git a/providers/linux/machineid.go b/providers/linux/machineid.go index 7a6b8a70..adfcd109 100644 --- a/providers/linux/machineid.go +++ b/providers/linux/machineid.go @@ -19,11 +19,10 @@ package linux import ( "bytes" + "fmt" "io/ioutil" "os" - "github.com/pkg/errors" - "github.com/elastic/go-sysinfo/types" ) @@ -44,7 +43,7 @@ func MachineID() (string, error) { } // Return with error on any other error - return "", errors.Wrapf(err, "failed to read %v", file) + return "", fmt.Errorf("failed to read %v: %w", file, err) } // Found it diff --git a/providers/linux/memory_linux.go b/providers/linux/memory_linux.go index 758caaba..c04bad0d 100644 --- a/providers/linux/memory_linux.go +++ b/providers/linux/memory_linux.go @@ -18,7 +18,7 @@ package linux import ( - "github.com/pkg/errors" + "fmt" "github.com/elastic/go-sysinfo/types" ) @@ -32,7 +32,7 @@ func parseMemInfo(content []byte) (*types.HostMemoryInfo, error) { err := parseKeyValue(content, ":", func(key, value []byte) error { num, err := parseBytesOrNumber(value) if err != nil { - return errors.Wrapf(err, "failed to parse %v value of %v", string(key), string(value)) + return fmt.Errorf("failed to parse %v value of %v: %w", string(key), string(value), err) } k := string(key) diff --git a/providers/linux/os.go b/providers/linux/os.go index b0402009..230ad852 100644 --- a/providers/linux/os.go +++ b/providers/linux/os.go @@ -20,6 +20,7 @@ package linux import ( "bufio" "bytes" + "fmt" "io/ioutil" "os" "path/filepath" @@ -28,7 +29,6 @@ import ( "strings" "github.com/joeshaw/multierror" - "github.com/pkg/errors" "github.com/elastic/go-sysinfo/types" ) @@ -103,7 +103,7 @@ func getOSRelease(baseDir string) (*types.OSInfo, error) { return nil, err } if len(osRel) == 0 { - return nil, errors.Errorf("%v is empty", osRelease) + return nil, fmt.Errorf("%v is empty: %w", osRelease, err) } return parseOSRelease(append(lsbRel, osRel...)) @@ -214,12 +214,12 @@ func findDistribRelease(baseDir string) (*types.OSInfo, error) { osInfo, err := getDistribRelease(path) if err != nil { - errs = append(errs, errors.Wrapf(err, "in %s", path)) + errs = append(errs, fmt.Errorf("in %s: %w", path, err)) continue } return osInfo, err } - return nil, errors.Wrap(&multierror.MultiError{Errors: errs}, "no valid /etc/-release file found") + return nil, fmt.Errorf("no valid /etc/-release file found: %w", &multierror.MultiError{Errors: errs}) } func getDistribRelease(file string) (*types.OSInfo, error) { @@ -229,7 +229,7 @@ func getDistribRelease(file string) (*types.OSInfo, error) { } parts := bytes.SplitN(data, []byte("\n"), 2) if len(parts) != 2 { - return nil, errors.Errorf("failed to parse %v", file) + return nil, fmt.Errorf("failed to parse %v", file) } // Use distrib as platform name. diff --git a/providers/linux/procnet.go b/providers/linux/procnet.go index a2cc2867..1356c2a8 100644 --- a/providers/linux/procnet.go +++ b/providers/linux/procnet.go @@ -18,13 +18,12 @@ package linux import ( + "errors" "fmt" "reflect" "strconv" "strings" - "github.com/pkg/errors" - "github.com/elastic/go-sysinfo/types" ) @@ -64,13 +63,13 @@ func parseEntry(line1, line2 string) (map[string]uint64, error) { if strings.Contains(value, "-") { signedParsed, err := strconv.ParseInt(value, 10, 64) if err != nil { - return nil, errors.Wrapf(err, "error parsing string to int in line: %#v", valueArr) + return nil, fmt.Errorf("error parsing string to int in line: %#v: %w", valueArr, err) } parsed = uint64(signedParsed) } else { parsed, err = strconv.ParseUint(value, 10, 64) if err != nil { - return nil, errors.Wrapf(err, "error parsing string to int in line: %#v", valueArr) + return nil, fmt.Errorf("error parsing string to int in line: %#v: %w", valueArr, err) } } @@ -97,7 +96,7 @@ func parseNetFile(body string) (map[string]map[string]uint64, error) { } valMap, err := parseEntry(keysSplit[1], valuesSplit[1]) if err != nil { - return nil, errors.Wrap(err, "error parsing lines") + return nil, fmt.Errorf("error parsing lines: %w", err) } fileMetrics[valuesSplit[0]] = valMap } @@ -108,7 +107,7 @@ func parseNetFile(body string) (map[string]map[string]uint64, error) { func getNetSnmpStats(raw []byte) (types.SNMP, error) { snmpData, err := parseNetFile(string(raw)) if err != nil { - return types.SNMP{}, errors.Wrap(err, "error parsing SNMP") + return types.SNMP{}, fmt.Errorf("error parsing SNMP: %w", err) } output := types.SNMP{} fillStruct(&output, snmpData) @@ -120,7 +119,7 @@ func getNetSnmpStats(raw []byte) (types.SNMP, error) { func getNetstatStats(raw []byte) (types.Netstat, error) { netstatData, err := parseNetFile(string(raw)) if err != nil { - return types.Netstat{}, errors.Wrap(err, "error parsing netstat") + return types.Netstat{}, fmt.Errorf("error parsing netstat: %w", err) } output := types.Netstat{} fillStruct(&output, netstatData) diff --git a/providers/linux/util.go b/providers/linux/util.go index 0be3f6b0..b8705a13 100644 --- a/providers/linux/util.go +++ b/providers/linux/util.go @@ -20,10 +20,10 @@ package linux import ( "bufio" "bytes" + "errors" + "fmt" "io/ioutil" "strconv" - - "github.com/pkg/errors" ) func parseKeyValue(content []byte, separator string, callback func(key, value []byte) error) error { @@ -57,12 +57,12 @@ func findValue(filename, separator, key string) (string, error) { } } if len(line) == 0 { - return "", errors.Errorf("%v not found", key) + return "", fmt.Errorf("%v not found", key) } parts := bytes.SplitN(line, []byte(separator), 2) if len(parts) != 2 { - return "", errors.Errorf("unexpected line format for '%v'", string(line)) + return "", fmt.Errorf("unexpected line format for '%v'", string(line)) } return string(bytes.TrimSpace(parts[1])), nil @@ -94,7 +94,7 @@ func parseBytesOrNumber(data []byte) (uint64, error) { num, err := strconv.ParseUint(string(parts[0]), 10, 64) if err != nil { - return 0, errors.Wrap(err, "failed to parse value") + return 0, fmt.Errorf("failed to parse value: %w", err) } var multiplier uint64 = 1 @@ -103,7 +103,7 @@ func parseBytesOrNumber(data []byte) (uint64, error) { case "kB": multiplier = 1024 default: - return 0, errors.Errorf("unhandled unit %v", string(parts[1])) + return 0, fmt.Errorf("unhandled unit %v", string(parts[1])) } } diff --git a/providers/linux/vmstat.go b/providers/linux/vmstat.go index 0a228678..2b9e8780 100644 --- a/providers/linux/vmstat.go +++ b/providers/linux/vmstat.go @@ -18,10 +18,9 @@ package linux import ( + "fmt" "reflect" - "github.com/pkg/errors" - "github.com/elastic/go-sysinfo/types" ) @@ -50,7 +49,7 @@ func parseVMStat(content []byte) (*types.VMStatInfo, error) { // turn our []byte value into an int val, err := parseBytesOrNumber(value) if err != nil { - return errors.Wrapf(err, "failed to parse %v value of %v", string(key), string(value)) + return fmt.Errorf("failed to parse %v value of %v: %w", string(key), string(value), err) } idx, ok := vmstatTagToFieldIndex[string(key)] diff --git a/providers/windows/boottime_windows.go b/providers/windows/boottime_windows.go index 4887cb1a..bf80c608 100644 --- a/providers/windows/boottime_windows.go +++ b/providers/windows/boottime_windows.go @@ -18,17 +18,16 @@ package windows import ( + "fmt" "time" - "github.com/pkg/errors" - windows "github.com/elastic/go-windows" ) func BootTime() (time.Time, error) { msSinceBoot, err := windows.GetTickCount64() if err != nil { - return time.Time{}, errors.Wrap(err, "failed to get boot time") + return time.Time{}, fmt.Errorf("failed to get boot time: %w", err) } bootTime := time.Now().Add(-1 * time.Duration(msSinceBoot) * time.Millisecond) diff --git a/providers/windows/device_windows.go b/providers/windows/device_windows.go index 998295de..372f125f 100644 --- a/providers/windows/device_windows.go +++ b/providers/windows/device_windows.go @@ -18,10 +18,11 @@ package windows import ( + "errors" + "fmt" "strings" "unsafe" - "github.com/pkg/errors" "golang.org/x/sys/windows" ) @@ -111,7 +112,7 @@ func (mapper *deviceMapper) DevicePathToDrivePath(path string) (string, error) { isMUP := strings.Index(pathLower, DeviceMup) == 0 mask, err := mapper.GetLogicalDrives() if err != nil { - return "", errors.Wrap(err, "GetLogicalDrives") + return "", fmt.Errorf("GetLogicalDrives: %w", err) } for bit := uint32(0); mask != 0 && bit < uint32('Z'-'A'+1); bit++ { @@ -177,7 +178,7 @@ func (m testingDeviceProvider) QueryDosDevice(nameW *uint16, buf *uint16, length } path, ok := m[drive] if !ok { - return 0, errors.Errorf("drive %c not found", drive) + return 0, fmt.Errorf("drive %c not found", drive) } n := uint32(len(path)) if n+2 > length { diff --git a/providers/windows/host_windows.go b/providers/windows/host_windows.go index 0bc99e46..96a90d9a 100644 --- a/providers/windows/host_windows.go +++ b/providers/windows/host_windows.go @@ -18,12 +18,12 @@ package windows import ( + "errors" "os" "time" windows "github.com/elastic/go-windows" "github.com/joeshaw/multierror" - "github.com/pkg/errors" "github.com/elastic/go-sysinfo/internal/registry" "github.com/elastic/go-sysinfo/providers/shared" @@ -98,7 +98,7 @@ type reader struct { func (r *reader) addErr(err error) bool { if err != nil { - if errors.Cause(err) != types.ErrNotImplemented { + if !errors.Is(err, types.ErrNotImplemented) { r.errs = append(r.errs, err) } return true diff --git a/providers/windows/machineid_windows.go b/providers/windows/machineid_windows.go index ea814f4c..0c69c89d 100644 --- a/providers/windows/machineid_windows.go +++ b/providers/windows/machineid_windows.go @@ -18,7 +18,8 @@ package windows import ( - "github.com/pkg/errors" + "fmt" + "golang.org/x/sys/windows/registry" ) @@ -33,13 +34,13 @@ func getMachineGUID() (string, error) { k, err := registry.OpenKey(key, path, registry.READ|registry.WOW64_64KEY) if err != nil { - return "", errors.Wrapf(err, `failed to open HKLM\%v`, path) + return "", fmt.Errorf(`failed to open HKLM\%v: %w`, path, err) } defer k.Close() guid, _, err := k.GetStringValue(name) if err != nil { - return "", errors.Wrapf(err, `failed to get value of HKLM\%v\%v`, path, name) + return "", fmt.Errorf(`failed to get value of HKLM\%v\%v: %w`, path, name, err) } return guid, nil diff --git a/providers/windows/os_windows.go b/providers/windows/os_windows.go index 10ed595c..bc74a1ee 100644 --- a/providers/windows/os_windows.go +++ b/providers/windows/os_windows.go @@ -22,7 +22,6 @@ import ( "strconv" "strings" - "github.com/pkg/errors" "golang.org/x/sys/windows/registry" "github.com/elastic/go-sysinfo/types" @@ -35,7 +34,7 @@ func OperatingSystem() (*types.OSInfo, error) { k, err := registry.OpenKey(key, path, flags) if err != nil { - return nil, errors.Wrapf(err, `failed to open HKLM\%v`, path) + return nil, fmt.Errorf(`failed to open HKLM\%v: %w`, path, err) } defer k.Close() @@ -47,7 +46,7 @@ func OperatingSystem() (*types.OSInfo, error) { name := "ProductName" osInfo.Name, _, err = k.GetStringValue(name) if err != nil { - return nil, errors.Wrapf(err, `failed to get value of HKLM\%v\%v`, path, name) + return nil, fmt.Errorf(`failed to get value of HKLM\%v\%v: %w`, path, name, err) } // Newer versions (Win 10 and 2016) have CurrentMajor/CurrentMinor. @@ -61,7 +60,7 @@ func OperatingSystem() (*types.OSInfo, error) { name = "CurrentVersion" osInfo.Version, _, err = k.GetStringValue(name) if err != nil { - return nil, errors.Wrapf(err, `failed to get value of HKLM\%v\%v`, path, name) + return nil, fmt.Errorf(`failed to get value of HKLM\%v\%v: %w`, path, name, err) } parts := strings.SplitN(osInfo.Version, ".", 3) for i, p := range parts { @@ -77,7 +76,7 @@ func OperatingSystem() (*types.OSInfo, error) { name = "CurrentBuild" currentBuild, _, err := k.GetStringValue(name) if err != nil { - return nil, errors.Wrapf(err, `failed to get value of HKLM\%v\%v`, path, name) + return nil, fmt.Errorf(`failed to get value of HKLM\%v\%v: %w`, path, name, err) } osInfo.Build = currentBuild @@ -85,7 +84,7 @@ func OperatingSystem() (*types.OSInfo, error) { name = "UBR" updateBuildRevision, _, err := k.GetIntegerValue(name) if err != nil && err != registry.ErrNotExist { - return nil, errors.Wrapf(err, `failed to get value of HKLM\%v\%v`, path, name) + return nil, fmt.Errorf(`failed to get value of HKLM\%v\%v: %w`, path, name, err) } else { osInfo.Build = fmt.Sprintf("%v.%d", osInfo.Build, updateBuildRevision) } diff --git a/providers/windows/process_windows.go b/providers/windows/process_windows.go index 3bb2a896..e8bf9b8a 100644 --- a/providers/windows/process_windows.go +++ b/providers/windows/process_windows.go @@ -18,6 +18,8 @@ package windows import ( + "errors" + "fmt" "os" "path/filepath" "strings" @@ -25,7 +27,6 @@ import ( "time" "unsafe" - "github.com/pkg/errors" syswin "golang.org/x/sys/windows" windows "github.com/elastic/go-windows" @@ -41,7 +42,7 @@ var ( func (s windowsSystem) Processes() (procs []types.Process, err error) { pids, err := windows.EnumProcesses() if err != nil { - return nil, errors.Wrap(err, "EnumProcesses") + return nil, fmt.Errorf("EnumProcesses: %w", err) } procs = make([]types.Process, 0, len(pids)) var proc types.Process @@ -184,7 +185,7 @@ func getUserProcessParams(handle syscall.Handle, pbi windows.ProcessBasicInforma return params, err } if nRead != uintptr(pebSize) { - return params, errors.Errorf("PEB: short read (%d/%d)", nRead, pebSize) + return params, fmt.Errorf("PEB: short read (%d/%d)", nRead, pebSize) } // Get the RTL_USER_PROCESS_PARAMETERS struct pointer from the PEB @@ -197,7 +198,7 @@ func getUserProcessParams(handle syscall.Handle, pbi windows.ProcessBasicInforma return params, err } if nRead != uintptr(windows.SizeOfRtlUserProcessParameters) { - return params, errors.Errorf("RTL_USER_PROCESS_PARAMETERS: short read (%d/%d)", nRead, windows.SizeOfRtlUserProcessParameters) + return params, fmt.Errorf("RTL_USER_PROCESS_PARAMETERS: short read (%d/%d)", nRead, windows.SizeOfRtlUserProcessParameters) } params = *(*windows.RtlUserProcessParameters)(unsafe.Pointer(¶msBuf[0])) @@ -219,7 +220,7 @@ func readProcessUnicodeString(handle syscall.Handle, s *windows.UnicodeString) ( return nil, err } if nRead != uintptr(s.Size) { - return nil, errors.Errorf("unicode string: short read: (%d/%d)", nRead, s.Size) + return nil, fmt.Errorf("unicode string: short read: (%d/%d)", nRead, s.Size) } return buf, nil } @@ -288,43 +289,41 @@ func (p *process) Info() (types.ProcessInfo, error) { func (p *process) User() (types.UserInfo, error) { handle, err := p.open() if err != nil { - return types.UserInfo{}, errors.Wrap(err, "OpenProcess failed") + return types.UserInfo{}, fmt.Errorf("OpenProcess failed: %w", err) } defer syscall.CloseHandle(handle) var accessToken syswin.Token err = syswin.OpenProcessToken(syswin.Handle(handle), syscall.TOKEN_QUERY, &accessToken) if err != nil { - return types.UserInfo{}, errors.Wrap(err, "OpenProcessToken failed") + return types.UserInfo{}, fmt.Errorf("OpenProcessToken failed: %w", err) } defer accessToken.Close() tokenUser, err := accessToken.GetTokenUser() if err != nil { - return types.UserInfo{}, errors.Wrap(err, "GetTokenUser failed") + return types.UserInfo{}, fmt.Errorf("GetTokenUser failed: %w", err) } sid, err := sidToString(tokenUser.User.Sid) if sid == "" || err != nil { - const errStr = "failed to look up user SID" if err != nil { - return types.UserInfo{}, errors.Wrap(err, errStr) + return types.UserInfo{}, fmt.Errorf("failed to look up user SID: %w", err) } - return types.UserInfo{}, errors.New(errStr) + return types.UserInfo{}, errors.New("failed to look up user SID") } tokenGroup, err := accessToken.GetTokenPrimaryGroup() if err != nil { - return types.UserInfo{}, errors.Wrap(err, "GetTokenPrimaryGroup failed") + return types.UserInfo{}, fmt.Errorf("GetTokenPrimaryGroup failed: %w", err) } gsid, err := sidToString(tokenGroup.PrimaryGroup) if gsid == "" || err != nil { - const errStr = "failed to look up primary group SID" if err != nil { - return types.UserInfo{}, errors.Wrap(err, errStr) + return types.UserInfo{}, fmt.Errorf("failed to look up primary group SID: %w", err) } - return types.UserInfo{}, errors.New(errStr) + return types.UserInfo{}, errors.New("failed to look up primary group SID") } return types.UserInfo{ diff --git a/system_test.go b/system_test.go index e193a695..634f4ab9 100644 --- a/system_test.go +++ b/system_test.go @@ -19,6 +19,8 @@ package sysinfo import ( "encoding/json" + "errors" + "io/fs" "os" osUser "os/user" "runtime" @@ -28,7 +30,6 @@ import ( "testing" "time" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -287,8 +288,7 @@ func TestProcesses(t *testing.T) { for _, proc := range procs { info, err := proc.Info() if err != nil { - cause := errors.Cause(err) - if os.IsPermission(cause) || syscall.ESRCH == cause { + if errors.Is(err, fs.ErrPermission) || errors.Is(err, syscall.ESRCH) { // The process may no longer exist by the time we try fetching // additional information so ignore ESRCH (no such process). continue diff --git a/types/errors.go b/types/errors.go index c7ec1693..7e509bc4 100644 --- a/types/errors.go +++ b/types/errors.go @@ -17,7 +17,7 @@ package types -import "github.com/pkg/errors" +import "errors" // ErrNotImplemented represents an error for a function that is not implemented on a particular platform. var ErrNotImplemented = errors.New("unimplemented")