Systemd – Limiting Resource Use per User with Cgroups

cgroupdebian-bustersystemd

Debian 10: I want to limit memory, CPU etc for all users except root; I have found several articles about this, but so far they all revolve around cgconfig, which doesn't seem to be the way it is done now. I have seen some suggestions to use slices instead, so for UID 1000, create something like:

# cat /lib/systemd/system/user-1000.slice
[Unit]
Description=User and Session Slice
Documentation=man:systemd.special(7)
Before=slices.target
MemoryHigh=20M

[Slice]
Slice=user-slice

[Install]
WantedBy=multi-user.target

and enable it with systemctl enable user-1000.slice. This appears to half work:

 $ systemctl status user-1000.slice
Warning: The unit file, source configuration file or drop-ins of user-1000.slice changed on disk. Run 'systemctl daemon-reload' to reload units.
● user-1000.slice - User Slice of UID 1000
   Loaded: loaded (/lib/systemd/system/user-1000.slice; enabled; vendor preset: enabled)
  Drop-In: /usr/lib/systemd/system/user-.slice.d
           └─10-defaults.conf
   Active: active since Thu 2020-07-09 07:37:28 UTC; 1h 8min ago
     Docs: man:systemd.special(7)
           man:user@.service(5)
    Tasks: 7 (limit: 5237)
   Memory: 5.4M
   CGroup: /user.slice/user-1000.slice
           ├─session-15.scope
           │ ├─1089 sshd: jan [priv]
           │ ├─1107 sshd: jan@pts/1
           │ ├─1108 -bash
           │ ├─1113 systemctl status user-1000.slice
           │ └─1114 pager
           └─user@1000.service
             └─init.scope
               ├─1092 /lib/systemd/systemd --user
               └─1093 (sd-pam)

However, MemoryHigh isn't set:

 $ systemctl show user-1000.slice
Slice=user.slice
ControlGroup=/user.slice/user-1000.slice
...
MemoryHigh=infinity
...

I seem to be very close, but there must be something missing – what is it?

Best Answer

You missed the warning that was printed on screen:

Warning: The unit file, source configuration file or drop-ins of user-1000.slice changed on disk. Run 'systemctl daemon-reload' to reload units.

When you change systemd units, you must systemctl daemon-reload to have systemd re-read them. In addition, affected units need to be restarted.

That said, if you want the change to apply to all users, you should probably be overriding user.slice instead. And of course you should never edit the system-shipped files, but instead use overrides via drop-in files.

Related Topic