From efcb7f04ee34b9ac176e6dc6b71553aae6ab2bbd Mon Sep 17 00:00:00 2001 From: Giuseppe Scrivano Date: Tue, 21 Sep 2021 16:42:14 +0200 Subject: [PATCH] pids: fix reading pids when running in a cgroup v1 container OCI runtimes might mount the container cgroup at the cgroup root itself, breaking the correspondence between what is displayed in /proc/$PID/cgroup and the path under the cgroup root. When the cgroup path doesn't exist, check if the process is still alive and attempt to read the pids from the root cgroup. Signed-off-by: Giuseppe Scrivano --- internal/proc/pids.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/internal/proc/pids.go b/internal/proc/pids.go index c235afb..2687396 100644 --- a/internal/proc/pids.go +++ b/internal/proc/pids.go @@ -69,7 +69,8 @@ func GetPIDsFromCgroup(pid string) ([]string, error) { // cgroup. func getPIDsFromCgroupV1(pid string) ([]string, error) { // First, find the corresponding path to the PID cgroup. - f, err := os.Open(fmt.Sprintf("/proc/%s/cgroup", pid)) + pidPath := fmt.Sprintf("/proc/%s/cgroup", pid) + f, err := os.Open(pidPath) if err != nil { return nil, err } @@ -95,7 +96,18 @@ func getPIDsFromCgroupV1(pid string) ([]string, error) { // Second, extract the PIDs inside the cgroup. f, err = os.Open(cgroupPath) if err != nil { - return nil, err + if os.IsNotExist(err) { + // OCI runtimes might mount the container cgroup at the root, breaking what it showed + // in /proc/$PID/cgroup and the path. + // Check if the PID still exists to make sure the process is still alive. + if _, errStat := os.Stat(pidPath); errStat == nil { + cgroupPath = filepath.Join(cgroups.CgroupRoot, "pids", "cgroup.procs") + f, err = os.Open(cgroupPath) + } + } + if err != nil { + return nil, err + } } defer f.Close()