From fd372f673582ae59bed22b75dcde398f5bec081b Mon Sep 17 00:00:00 2001 From: Cian Johnston Date: Fri, 21 Jul 2023 11:18:56 +0100 Subject: [PATCH] fix(cli/clistat): improve detection of container environment (#8643) Use the presence of /var/run/secrets/kubernetes.io/serviceaccount/token to determine if we are in a container in addition to sniffing /proc/1/cgroup --- cli/clistat/cgroup.go | 2 +- cli/clistat/container.go | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/cli/clistat/cgroup.go b/cli/clistat/cgroup.go index ffa2cf12b8..da93035d99 100644 --- a/cli/clistat/cgroup.go +++ b/cli/clistat/cgroup.go @@ -338,7 +338,7 @@ func readInt64Prefix(fs afero.Fs, path, prefix string) (int64, error) { scn := bufio.NewScanner(bytes.NewReader(data)) for scn.Scan() { - line := scn.Text() + line := strings.TrimSpace(scn.Text()) if !strings.HasPrefix(line, prefix) { continue } diff --git a/cli/clistat/container.go b/cli/clistat/container.go index 079bffe5e3..bfe9718ad7 100644 --- a/cli/clistat/container.go +++ b/cli/clistat/container.go @@ -10,8 +10,9 @@ import ( ) const ( - procMounts = "/proc/mounts" - procOneCgroup = "/proc/1/cgroup" + procMounts = "/proc/mounts" + procOneCgroup = "/proc/1/cgroup" + kubernetesDefaultServiceAccountToken = "/var/run/secrets/kubernetes.io/serviceaccount/token" //nolint:gosec ) // IsContainerized returns whether the host is containerized. @@ -38,6 +39,14 @@ func IsContainerized(fs afero.Fs) (ok bool, err error) { } } + // Sometimes the above method of sniffing /proc/1/cgroup isn't reliable. + // If a Kubernetes service account token is present, that's + // also a good indication that we are in a container. + _, err = afero.ReadFile(fs, kubernetesDefaultServiceAccountToken) + if err == nil { + return true, nil + } + // Last-ditch effort to detect Sysbox containers. // Check if we have anything mounted as type sysboxfs in /proc/mounts mountsData, err := afero.ReadFile(fs, procMounts)