Skip to content

Commit aff90ce

Browse files
Mazen050pashagolub
andauthored
[-] fix file leak in GetPathUnderlyingDeviceID, fixes #1185 (#1192)
* add file close to avoid leak * add tests for psutil_linux * add 'os' import to psutil_test.go * skip tests on non-Linux OS --------- Co-authored-by: Pavlo Golub <pavlo.golub@gmail.com>
1 parent c7a9e93 commit aff90ce

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

internal/reaper/psutil_linux.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ func GetPathUnderlyingDeviceID(path string) (uint64, error) {
1010
if err != nil {
1111
return 0, err
1212
}
13+
defer fp.Close()
14+
1315
fi, err := fp.Stat()
1416
if err != nil {
1517
return 0, err

internal/reaper/psutil_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package reaper
22

33
import (
4+
"runtime"
45
"slices"
56
"testing"
67

78
"github.com/cybertec-postgresql/pgwatch/v5/internal/metrics"
89

910
"maps"
11+
"os"
1012

1113
"github.com/stretchr/testify/assert"
1214
)
@@ -73,3 +75,34 @@ func TestGetLoadAvgLocal(t *testing.T) {
7375
resultKeys := slices.Collect(maps.Keys(result[0]))
7476
a.ElementsMatch(resultKeys, expectedKeys)
7577
}
78+
79+
func TestGetPathUnderlyingDeviceID(t *testing.T) {
80+
if runtime.GOOS != "linux" {
81+
t.Skip("GetPathUnderlyingDeviceID is not implemented")
82+
}
83+
a := assert.New(t)
84+
tmpDir := t.TempDir()
85+
createFile := func(name string) string {
86+
f, err := os.CreateTemp(tmpDir, name)
87+
a.NoError(err)
88+
defer f.Close()
89+
return f.Name()
90+
}
91+
92+
file1Path := createFile("file1")
93+
devID1, err := GetPathUnderlyingDeviceID(file1Path)
94+
a.NoError(err)
95+
96+
file2Path := createFile("file2")
97+
devID2, err := GetPathUnderlyingDeviceID(file2Path)
98+
a.NoError(err)
99+
a.Equal(devID1, devID2)
100+
}
101+
102+
func TestGetPathUnderlyingDeviceID_NotFound(t *testing.T) {
103+
if runtime.GOOS != "linux" {
104+
t.Skip("GetPathUnderlyingDeviceID is not implemented")
105+
}
106+
_, err := GetPathUnderlyingDeviceID("/this/path/should/not/exist/nofile")
107+
assert.Error(t, err)
108+
}

0 commit comments

Comments
 (0)