Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions getallpids.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package cgroups

import (
"errors"
"io/fs"
"os"
"path/filepath"

"golang.org/x/sys/unix"
)

// GetAllPids returns all pids from the cgroup identified by path, and all its
Expand All @@ -11,17 +15,30 @@ func GetAllPids(path string) ([]int, error) {
var pids []int
err := filepath.WalkDir(path, func(p string, d fs.DirEntry, iErr error) error {
if iErr != nil {
// A descendant cgroup can be removed while we walk, ignore
// any such error unless it's on the root (path) cgroup here
if p != path && ignoreCgroupRemoved(iErr) {
return nil
}
return iErr
}
if !d.IsDir() {
return nil
}
cPids, err := readProcsFile(p)
if err != nil {
if p != path && ignoreCgroupRemoved(err) {
return nil
}
return err
}
pids = append(pids, cPids...)
return nil
})
return pids, err
}

// ignoreCgroupRemoved reports whether err indicates the cgroup was removed.
func ignoreCgroupRemoved(err error) bool {
return os.IsNotExist(err) || errors.Is(err, unix.ENODEV)
}
34 changes: 34 additions & 0 deletions getallpids_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cgroups

import (
"os"
"path/filepath"
"slices"
"testing"
)

Expand All @@ -15,3 +18,34 @@ func BenchmarkGetAllPids(b *testing.B) {
}
b.Logf("iter: %d, total: %d", b.N, total)
}

func TestGetAllPidsIgnoresVanishedSubcgroup(t *testing.T) {
TestMode = true
defer func() { TestMode = false }()

root := t.TempDir()
if err := WriteFile(root, "cgroup.procs", "1\n"); err != nil {
t.Fatal(err)
}
child := filepath.Join(root, "child")
if err := os.Mkdir(child, 0o755); err != nil {
t.Fatal(err)
}
if err := WriteFile(child, "cgroup.procs", "2\n3\n"); err != nil {
t.Fatal(err)
}

// Pretend "vanishing" cgroup, directory exists but not the file to read
if err := os.Mkdir(filepath.Join(root, "gone"), 0o755); err != nil {
t.Fatal(err)
}

pids, err := GetAllPids(root)
if err != nil {
t.Fatalf("GetAllPids errored on a vanished child cgroup: %v", err)
}
slices.Sort(pids)
if want := []int{1, 2, 3}; !slices.Equal(pids, want) {
t.Errorf("GetAllPids() = %v, want %v", pids, want)
}
}