1<chapter xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xml:id="sec-cgroups">
2 <title>Control Groups</title>
3 <para>
4 To keep track of the processes in a running system, systemd uses
5 <emphasis>control groups</emphasis> (cgroups). A control group is a
6 set of processes used to allocate resources such as CPU, memory or
7 I/O bandwidth. There can be multiple control group hierarchies,
8 allowing each kind of resource to be managed independently.
9 </para>
10 <para>
11 The command <literal>systemd-cgls</literal> lists all control groups
12 in the <literal>systemd</literal> hierarchy, which is what systemd
13 uses to keep track of the processes belonging to each service or
14 user session:
15 </para>
16 <programlisting>
17$ systemd-cgls
18├─user
19│ └─eelco
20│ └─c1
21│ ├─ 2567 -:0
22│ ├─ 2682 kdeinit4: kdeinit4 Running...
23│ ├─ ...
24│ └─10851 sh -c less -R
25└─system
26 ├─httpd.service
27 │ ├─2444 httpd -f /nix/store/3pyacby5cpr55a03qwbnndizpciwq161-httpd.conf -DNO_DETACH
28 │ └─...
29 ├─dhcpcd.service
30 │ └─2376 dhcpcd --config /nix/store/f8dif8dsi2yaa70n03xir8r653776ka6-dhcpcd.conf
31 └─ ...
32</programlisting>
33 <para>
34 Similarly, <literal>systemd-cgls cpu</literal> shows the cgroups in
35 the CPU hierarchy, which allows per-cgroup CPU scheduling
36 priorities. By default, every systemd service gets its own CPU
37 cgroup, while all user sessions are in the top-level CPU cgroup.
38 This ensures, for instance, that a thousand run-away processes in
39 the <literal>httpd.service</literal> cgroup cannot starve the CPU
40 for one process in the <literal>postgresql.service</literal> cgroup.
41 (By contrast, it they were in the same cgroup, then the PostgreSQL
42 process would get 1/1001 of the cgroup’s CPU time.) You can limit a
43 service’s CPU share in <literal>configuration.nix</literal>:
44 </para>
45 <programlisting language="bash">
46systemd.services.httpd.serviceConfig.CPUShares = 512;
47</programlisting>
48 <para>
49 By default, every cgroup has 1024 CPU shares, so this will halve the
50 CPU allocation of the <literal>httpd.service</literal> cgroup.
51 </para>
52 <para>
53 There also is a <literal>memory</literal> hierarchy that controls
54 memory allocation limits; by default, all processes are in the
55 top-level cgroup, so any service or session can exhaust all
56 available memory. Per-cgroup memory limits can be specified in
57 <literal>configuration.nix</literal>; for instance, to limit
58 <literal>httpd.service</literal> to 512 MiB of RAM (excluding swap):
59 </para>
60 <programlisting language="bash">
61systemd.services.httpd.serviceConfig.MemoryLimit = "512M";
62</programlisting>
63 <para>
64 The command <literal>systemd-cgtop</literal> shows a continuously
65 updated list of all cgroups with their CPU and memory usage.
66 </para>
67</chapter>