Skip to content

Commit fd372f6

Browse files
authored
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
1 parent 87d5cda commit fd372f6

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

cli/clistat/cgroup.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ func readInt64Prefix(fs afero.Fs, path, prefix string) (int64, error) {
338338

339339
scn := bufio.NewScanner(bytes.NewReader(data))
340340
for scn.Scan() {
341-
line := scn.Text()
341+
line := strings.TrimSpace(scn.Text())
342342
if !strings.HasPrefix(line, prefix) {
343343
continue
344344
}

cli/clistat/container.go

+11-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@ import (
1010
)
1111

1212
const (
13-
procMounts = "/proc/mounts"
14-
procOneCgroup = "/proc/1/cgroup"
13+
procMounts = "/proc/mounts"
14+
procOneCgroup = "/proc/1/cgroup"
15+
kubernetesDefaultServiceAccountToken = "/var/run/secrets/kubernetes.io/serviceaccount/token" //nolint:gosec
1516
)
1617

1718
// IsContainerized returns whether the host is containerized.
@@ -38,6 +39,14 @@ func IsContainerized(fs afero.Fs) (ok bool, err error) {
3839
}
3940
}
4041

42+
// Sometimes the above method of sniffing /proc/1/cgroup isn't reliable.
43+
// If a Kubernetes service account token is present, that's
44+
// also a good indication that we are in a container.
45+
_, err = afero.ReadFile(fs, kubernetesDefaultServiceAccountToken)
46+
if err == nil {
47+
return true, nil
48+
}
49+
4150
// Last-ditch effort to detect Sysbox containers.
4251
// Check if we have anything mounted as type sysboxfs in /proc/mounts
4352
mountsData, err := afero.ReadFile(fs, procMounts)

0 commit comments

Comments
 (0)