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
This commit is contained in:
Cian Johnston 2023-07-21 11:18:56 +01:00 committed by GitHub
parent 87d5cdaf58
commit fd372f6735
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 3 deletions

View File

@ -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
}

View File

@ -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)