Cgroups/systemd: How to create a cgroup for a process tree [non-root]

cgroupssystemd

As a non-root user, I'd like to be able to start a process that will start a bunch of other processes (think of a 'make' session, or the way Google Chrome starts a process for each tab) and have the entire process tree be visible as a unit – for instance, I want to see that this subtree is consuming 200% CPU. I do have sudo access, but would prefer not to use it.

The nearest equivalent I have is systemd-run --scope, but I can't then find the process tree or the scope in systemd-cgls or equivalent. Also, that has to run as root, so I would have to sudo, then drop privileges with a wrapper. Is there a better way to do this? Debian Jessie ideally, or Stretch if I have to. The simpler the solution, the better, as that would let me deploy it to multiple computers without a maintenance hassle.

Best Answer

You don't need to be root to start a user-scoped group with systemd-run:

$ systemd-run --user --scope /bin/bash 
  Running scope as unit run-23318.scope.
  $ sleep 999 &
  [1] 23369

You can see the unit:

$ systemctl --user status run-23318.scope
* run-23318.scope - /bin/bash
  Loaded: loaded (/run/user/1000/systemd/user/run-23318.scope; static; 
         vendor preset: enabled)
 Drop-In: /run/user/1000/systemd/user/run-23318.scope.d
      `-50-Description.conf
  Active: active (running) since Sun 2016-07-17 08:16:51 CEST; 10min ago
  CGroup: /user.slice/user-1000.slice/user@1000.service/run-23318.scope
      |-23318 /bin/bash
      `-23369 sleep 999
  Jul 17 08:16:51 home systemd[1056]: Started /bin/bash.
  Jul 17 08:16:51 home systemd[1056]: Starting /bin/bash.

and also with

$ systemd-cgls /user.slice/user-1000.slice/user@1000.service/run-23318.scope
   /user.slice/user-1000.slice/user@1000.service/run-23318.scope:
   |-23318 /bin/bash
   `-23369 sleep 999
Related Question