From f2c1c515d40ef82db9e62ef7fbeb91893f861c2e Mon Sep 17 00:00:00 2001 From: Cian Johnston Date: Fri, 21 Jul 2023 10:54:29 +0100 Subject: [PATCH 1/2] fix(cli/clistat): improve detection of container environment --- 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 ffa2cf12b8afd..da93035d99911 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 079bffe5e3c43..024a8797e9a67 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" ) // 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) From a13f624d0c9b1b0b99bac6ee357139a39a978893 Mon Sep 17 00:00:00 2001 From: Cian Johnston Date: Fri, 21 Jul 2023 11:05:51 +0100 Subject: [PATCH 2/2] appease the over-cautious secrets detector --- cli/clistat/container.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/clistat/container.go b/cli/clistat/container.go index 024a8797e9a67..bfe9718ad70be 100644 --- a/cli/clistat/container.go +++ b/cli/clistat/container.go @@ -12,7 +12,7 @@ import ( const ( procMounts = "/proc/mounts" procOneCgroup = "/proc/1/cgroup" - kubernetesDefaultServiceAccountToken = "/var/run/secrets/kubernetes.io/serviceaccount/token" + kubernetesDefaultServiceAccountToken = "/var/run/secrets/kubernetes.io/serviceaccount/token" //nolint:gosec ) // IsContainerized returns whether the host is containerized.