benfred / py-spy

Sampling profiler for Python programs
MIT License
12.14k stars 400 forks source link

Docker detection code fails with cgroups v2 #614

Open benfred opened 9 months ago

benfred commented 9 months ago

In the event of a permissions denied error, py-spy attempts to see if you are running in a docker container and if so displays an error message to make sure you've enabled SYS_PTRACE:

https://github.com/benfred/py-spy/blob/492b41c07c26c6edbe061da942c8dae41d86091e/src/main.rs#L474C1-L486

This works by checking the contents of /proc/self/cgroups - but only works with cgroups v1, and in cgroups v2 this fails since this file only contains 0::/ , and no message is displayed.

One idea is to directly test for the SYS_PTRACE capability https://github.com/benfred/py-spy/pull/459#discussion_r734874566

According to https://stackoverflow.com/questions/68816329/how-to-get-docker-container-id-from-within-the-container-with-cgroup-v2 , we can also probably inspect /proc/self/mountinfo to figure out if we're running in docker.

Another option is to look for the presence of a /.dockerenv file - though this isn't recommended https://github.com/moby/moby/issues/18355#issuecomment-220484748