Search code examples
processlinux-kernelcgroupslinux-containers

How to monitor the process in a container?


I currently look into the LXC container API. I am trying to figure out how can I make the operating system know to which container the currently running process belongs. In this way, OS can allocate resource for processes according to the container.


Solution

  • I am assuming your query is - Given a PID, how to find the container in which this process is running?

    I will try to answer it based on my recent reading on Linux containers. Each container can be configured to start with its own user and group id mappings.

    From https://linuxcontainers.org/lxc/manpages/man5/lxc.container.conf.5.html:

    lxc.id_map
    Four values must be provided. First a character, either 'u', or 'g', to specify whether user or group ids are being mapped. Next is the first userid as seen in the user namespace of the container. Next is the userid as seen on the host. Finally, a range indicating the number of consecutive ids to map.

    So, you would add something like this in config file (Ex: ~/.config/lxc/default.conf):

    lxc.id_map = u 0 100000 65536
    lxc.id_map = g 0 100000 65536
    

    The above basically means that uids/gids between 0 and 65536 are mapped to numbers between 100000 and 1655356. So, a uid of 0 (root) on container will be seen as 100000 on host

    For Example, inside container it will look something like this:

    root@unpriv_cont:/# ps -ef
    UID        PID  PPID  C STIME TTY          TIME CMD
    root         1     0  0 02:18 ?        00:00:00 /sbin/init
    root       157     1  0 02:18 ?        00:00:00 upstart-udev-bridge --daemon
    

    But on host the same processes will look like this:

    ps -ef | grep 100000
    100000    2204  2077  0 Dec12 ?        00:00:00 /sbin/init
    100000    3170  2204  0 Dec12 ?        00:00:00 upstart-udev-bridge --daemon
    100000    1762  2204  0 Dec12 ?        00:00:00 /lib/systemd/systemd-udevd --daemon
    

    Thus, you can find the container of a process by looking for its UID and relating it to the mapping defined in that container's config.