From 7c1aa06a5eb4682ab50883dd1cf0eb5ff0ab4cf7 Mon Sep 17 00:00:00 2001 From: Punya Biswal Date: Wed, 8 Sep 2021 16:15:26 -0400 Subject: [PATCH] Respond to review comments * use LookPath for better error messages * support procfs in containers --- mem/mem_bsd.go | 6 +++++- mem/mem_linux.go | 5 ++++- mem/mem_solaris.go | 6 +++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/mem/mem_bsd.go b/mem/mem_bsd.go index 058f8fa..98826b0 100644 --- a/mem/mem_bsd.go +++ b/mem/mem_bsd.go @@ -24,7 +24,11 @@ func SwapDevices() ([]*SwapDevice, error) { } func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - output, err := exec.Command(swapCommand, "-lk").Output() + swapCommandPath, err := exec.LookPath(swapCommand) + if err != nil { + return nil, fmt.Errorf("could not find command %q: %w", swapCommand, err) + } + output, err := exec.Command(swapCommandPath, "-lk").Output() if err != nil { return nil, fmt.Errorf("could not execute %q: %w", swapCommand, err) } diff --git a/mem/mem_linux.go b/mem/mem_linux.go index fe653b2..8c3445a 100644 --- a/mem/mem_linux.go +++ b/mem/mem_linux.go @@ -14,6 +14,7 @@ import ( "strings" "github.com/shirou/gopsutil/internal/common" + "github.com/shirou/gopsutil/v3/internal/common" "golang.org/x/sys/unix" ) @@ -430,7 +431,7 @@ func calcuateAvailVmem(ret *VirtualMemoryStat, retEx *VirtualMemoryExStat) uint6 return availMemory } -const swapsFilePath = "/proc/swaps" +const swapsFilename = "swaps" // swaps file column indexes const ( @@ -446,6 +447,7 @@ func SwapDevices() ([]*SwapDevice, error) { } func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { + swapsFilePath := common.HostProc(swapsFilename) f, err := os.Open(swapsFilePath) if err != nil { return nil, err @@ -456,6 +458,7 @@ func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { } func parseSwapsFile(r io.Reader) ([]*SwapDevice, error) { + swapsFilePath := common.HostProc(swapsFilename) scanner := bufio.NewScanner(r) if !scanner.Scan() { if err := scanner.Err(); err != nil { diff --git a/mem/mem_solaris.go b/mem/mem_solaris.go index 2b161d1..353d4cf 100644 --- a/mem/mem_solaris.go +++ b/mem/mem_solaris.go @@ -141,7 +141,11 @@ func SwapDevices() ([]*SwapDevice, error) { } func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) { - output, err := exec.Command(swapsCommand, "-l").Output() + swapsCommandPath, err := exec.LookPath(swapsCommand) + if err != nil { + return nil, fmt.Errorf("could not find command %q: %w", swapCommand, err) + } + output, err := exec.Command(swapsCommandPath, "-l").Output() if err != nil { return nil, fmt.Errorf("could not execute %q: %w", swapsCommand, err) }