Skip to content

Commit 27a568d

Browse files
committed
improve container detection using container specific files
1 parent c12d8cd commit 27a568d

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

proc/proc.go

+23
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,12 @@ func GetContainerRuntime(tgid, pid int) ContainerRuntime {
150150
return runtime
151151
}
152152

153+
// Check for container specific files
154+
runtime = detectContainerFiles()
155+
if runtime != RuntimeNotFound {
156+
return runtime
157+
}
158+
153159
return RuntimeNotFound
154160
}
155161

@@ -167,6 +173,23 @@ func getContainerRuntime(input string) ContainerRuntime {
167173
return RuntimeNotFound
168174
}
169175

176+
// Related implementation: https://github.com/systemd/systemd/blob/6604fb0207ee10e8dc05d67f6fe45de0b193b5c4/src/basic/virt.c#L523-L549
177+
func detectContainerFiles() ContainerRuntime {
178+
files := map[ContainerRuntime]string{}
179+
// https://github.com/containers/podman/issues/3586#issuecomment-661918679
180+
files[RuntimePodman] = "/run/.containerenv"
181+
// https://github.com/moby/moby/issues/18355
182+
files[RuntimeDocker] = "/.dockerenv"
183+
184+
for runtime, file := range files {
185+
if fileExists(file) {
186+
return runtime
187+
}
188+
}
189+
190+
return RuntimeNotFound
191+
}
192+
170193
// GetContainerID returns the container ID for a process if it's running in a container.
171194
// If pid is less than one, it returns the container ID for "self".
172195
func GetContainerID(tgid, pid int) string {

0 commit comments

Comments
 (0)