1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2013 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 #include "path-util.h"
26 #include "cgroup-util.h"
29 void cgroup_context_init(CGroupContext *c) {
32 /* Initialize everything to the kernel defaults, assuming the
33 * structure is preinitialized to 0 */
36 c->memory_limit = c->memory_soft_limit = (uint64_t) -1;
37 c->blockio_weight = 1000;
40 void cgroup_context_free_device_allow(CGroupContext *c, CGroupDeviceAllow *a) {
44 LIST_REMOVE(CGroupDeviceAllow, device_allow, c->device_allow, a);
49 void cgroup_context_free_blockio_device_weight(CGroupContext *c, CGroupBlockIODeviceWeight *w) {
53 LIST_REMOVE(CGroupBlockIODeviceWeight, device_weights, c->blockio_device_weights, w);
58 void cgroup_context_free_blockio_device_bandwidth(CGroupContext *c, CGroupBlockIODeviceBandwidth *b) {
62 LIST_REMOVE(CGroupBlockIODeviceBandwidth, device_bandwidths, c->blockio_device_bandwidths, b);
67 void cgroup_context_done(CGroupContext *c) {
70 while (c->blockio_device_weights)
71 cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
73 while (c->blockio_device_bandwidths)
74 cgroup_context_free_blockio_device_bandwidth(c, c->blockio_device_bandwidths);
76 while (c->device_allow)
77 cgroup_context_free_device_allow(c, c->device_allow);
80 void cgroup_context_dump(CGroupContext *c, FILE* f, const char *prefix) {
81 CGroupBlockIODeviceBandwidth *b;
82 CGroupBlockIODeviceWeight *w;
88 prefix = strempty(prefix);
91 "%sCPUAccounting=%s\n"
92 "%sBlockIOAccounting=%s\n"
93 "%sMemoryAccounting=%s\n"
95 "%sBlockIOWeight%lu\n"
96 "%sMemoryLimit=%" PRIu64 "\n"
97 "%sMemorySoftLimit=%" PRIu64 "\n"
98 "%sDevicePolicy=%s\n",
99 prefix, yes_no(c->cpu_accounting),
100 prefix, yes_no(c->blockio_accounting),
101 prefix, yes_no(c->memory_accounting),
102 prefix, c->cpu_shares,
103 prefix, c->blockio_weight,
104 prefix, c->memory_limit,
105 prefix, c->memory_soft_limit,
106 prefix, cgroup_device_policy_to_string(c->device_policy));
108 LIST_FOREACH(device_allow, a, c->device_allow)
110 "%sDeviceAllow=%s %s%s%s\n",
113 a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
115 LIST_FOREACH(device_weights, w, c->blockio_device_weights)
117 "%sBlockIOWeight=%s %lu",
122 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
123 char buf[FORMAT_BYTES_MAX];
128 b->read ? "BlockIOReadBandwidth" : "BlockIOWriteBandwidth",
130 format_bytes(buf, sizeof(buf), b->bandwidth));
134 static int lookup_blkio_device(const char *p, dev_t *dev) {
143 log_warning("Couldn't stat device %s: %m", p);
147 if (S_ISBLK(st.st_mode))
149 else if (major(st.st_dev) != 0) {
150 /* If this is not a device node then find the block
151 * device this file is stored on */
154 /* If this is a partition, try to get the originating
156 block_get_whole_disk(*dev, dev);
158 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p);
165 static int whitelist_device(const char *path, const char *node, const char *acc) {
166 char buf[2+DECIMAL_STR_MAX(dev_t)*2+2+4];
173 if (stat(node, &st) < 0) {
174 log_warning("Couldn't stat device %s", node);
178 if (!S_ISCHR(st.st_mode) && !S_ISBLK(st.st_mode)) {
179 log_warning("%s is not a device.", node);
185 S_ISCHR(st.st_mode) ? 'c' : 'b',
186 major(st.st_rdev), minor(st.st_rdev),
189 r = cg_set_attribute("devices", path, "devices.allow", buf);
191 log_warning("Failed to set devices.allow on %s: %s", path, strerror(-r));
196 void cgroup_context_apply(CGroupContext *c, CGroupControllerMask mask, const char *path) {
205 if (mask & CGROUP_CPU) {
206 char buf[DECIMAL_STR_MAX(unsigned long) + 1];
208 sprintf(buf, "%lu\n", c->cpu_shares);
209 r = cg_set_attribute("cpu", path, "cpu.shares", buf);
211 log_warning("Failed to set cpu.shares on %s: %s", path, strerror(-r));
214 if (mask & CGROUP_BLKIO) {
215 char buf[MAX3(DECIMAL_STR_MAX(unsigned long)+1,
216 DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(unsigned long)*1,
217 DECIMAL_STR_MAX(dev_t)*2+2+DECIMAL_STR_MAX(uint64_t)+1)];
218 CGroupBlockIODeviceWeight *w;
219 CGroupBlockIODeviceBandwidth *b;
221 sprintf(buf, "%lu\n", c->blockio_weight);
222 r = cg_set_attribute("blkio", path, "blkio.weight", buf);
224 log_warning("Failed to set blkio.weight on %s: %s", path, strerror(-r));
226 /* FIXME: no way to reset this list */
227 LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
230 r = lookup_blkio_device(w->path, &dev);
234 sprintf(buf, "%u:%u %lu", major(dev), minor(dev), w->weight);
235 r = cg_set_attribute("blkio", path, "blkio.weight_device", buf);
237 log_error("Failed to set blkio.weight_device on %s: %s", path, strerror(-r));
240 /* FIXME: no way to reset this list */
241 LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
245 r = lookup_blkio_device(b->path, &dev);
249 a = b->read ? "blkio.throttle.read_bps_device" : "blkio.throttle.write_bps_device";
251 sprintf(buf, "%u:%u %" PRIu64 "\n", major(dev), minor(dev), b->bandwidth);
252 r = cg_set_attribute("blkio", path, a, buf);
254 log_error("Failed to set %s on %s: %s", a, path, strerror(-r));
258 if (mask & CGROUP_MEMORY) {
259 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
261 sprintf(buf, "%" PRIu64 "\n", c->memory_limit);
262 r = cg_set_attribute("memory", path, "memory.limit_in_bytes", buf);
264 log_error("Failed to set memory.limit_in_bytes on %s: %s", path, strerror(-r));
266 sprintf(buf, "%" PRIu64 "\n", c->memory_soft_limit);
267 cg_set_attribute("memory", path, "memory.soft_limit_in_bytes", buf);
269 log_error("Failed to set memory.limit_in_bytes on %s: %s", path, strerror(-r));
272 if (mask & CGROUP_DEVICE) {
273 CGroupDeviceAllow *a;
275 if (c->device_allow || c->device_policy != CGROUP_AUTO)
276 r = cg_set_attribute("devices", path, "devices.deny", "a");
278 r = cg_set_attribute("devices", path, "devices.allow", "a");
280 log_error("Failed to reset devices.list on %s: %s", path, strerror(-r));
282 if (c->device_policy == CGROUP_CLOSED ||
283 (c->device_policy == CGROUP_AUTO && c->device_allow)) {
284 static const char auto_devices[] =
288 "/dev/random\0" "rw\0"
289 "/dev/urandom\0" "rw\0";
293 NULSTR_FOREACH_PAIR(x, y, auto_devices)
294 whitelist_device(path, x, y);
297 LIST_FOREACH(device_allow, a, c->device_allow) {
312 whitelist_device(path, a->path, acc);
317 CGroupControllerMask cgroup_context_get_mask(CGroupContext *c) {
318 CGroupControllerMask mask = 0;
320 /* Figure out which controllers we need */
322 if (c->cpu_accounting || c->cpu_shares != 1024)
323 mask |= CGROUP_CPUACCT | CGROUP_CPU;
325 if (c->blockio_accounting ||
326 c->blockio_weight != 1000 ||
327 c->blockio_device_weights ||
328 c->blockio_device_bandwidths)
329 mask |= CGROUP_BLKIO;
331 if (c->memory_accounting ||
332 c->memory_limit != (uint64_t) -1 ||
333 c->memory_soft_limit != (uint64_t) -1)
334 mask |= CGROUP_MEMORY;
336 if (c->device_allow || c->device_policy != CGROUP_AUTO)
337 mask |= CGROUP_DEVICE;
342 static CGroupControllerMask unit_get_cgroup_mask(Unit *u) {
345 c = unit_get_cgroup_context(u);
349 return cgroup_context_get_mask(c);
352 static CGroupControllerMask unit_get_members_mask(Unit *u) {
353 CGroupControllerMask mask = 0;
359 SET_FOREACH(m, u->dependencies[UNIT_BEFORE], i) {
361 if (UNIT_DEREF(m->slice) != u)
364 mask |= unit_get_cgroup_mask(m) | unit_get_members_mask(m);
370 static CGroupControllerMask unit_get_siblings_mask(Unit *u) {
373 if (!UNIT_ISSET(u->slice))
376 /* Sibling propagation is only relevant for weight-based
377 * controllers, so let's mask out everything else */
378 return unit_get_members_mask(UNIT_DEREF(u->slice)) &
379 (CGROUP_CPU|CGROUP_BLKIO|CGROUP_CPUACCT);
382 static int unit_create_cgroups(Unit *u, CGroupControllerMask mask) {
388 path = unit_default_cgroup_path(u);
392 /* First, create our own group */
393 r = cg_create_with_mask(mask, path);
395 log_error("Failed to create cgroup %s: %s", path, strerror(-r));
397 /* Then, possibly move things over */
398 if (u->cgroup_path && !streq(path, u->cgroup_path)) {
399 r = cg_migrate_with_mask(mask, u->cgroup_path, path);
401 log_error("Failed to migrate cgroup %s: %s", path, strerror(-r));
404 /* And remember the new data */
405 free(u->cgroup_path);
406 u->cgroup_path = path;
407 u->cgroup_realized = true;
408 u->cgroup_mask = mask;
413 static void unit_realize_cgroup_now(Unit *u) {
414 CGroupControllerMask mask;
418 if (u->in_cgroup_queue) {
419 LIST_REMOVE(Unit, cgroup_queue, u->manager->cgroup_queue, u);
420 u->in_cgroup_queue = false;
423 mask = unit_get_cgroup_mask(u) | unit_get_members_mask(u) | unit_get_siblings_mask(u);
424 mask &= u->manager->cgroup_supported;
426 if (u->cgroup_realized &&
427 u->cgroup_mask == mask)
430 /* First, realize parents */
431 if (UNIT_ISSET(u->slice))
432 unit_realize_cgroup_now(UNIT_DEREF(u->slice));
434 /* And then do the real work */
435 unit_create_cgroups(u, mask);
438 static void unit_add_to_cgroup_queue(Unit *u) {
440 if (u->in_cgroup_queue)
443 LIST_PREPEND(Unit, cgroup_queue, u->manager->cgroup_queue, u);
444 u->in_cgroup_queue = true;
447 unsigned manager_dispatch_cgroup_queue(Manager *m) {
451 while ((i = m->cgroup_queue)) {
452 assert(i->in_cgroup_queue);
454 unit_realize_cgroup_now(i);
455 cgroup_context_apply(unit_get_cgroup_context(i), i->cgroup_mask, i->cgroup_path);
462 static void unit_queue_siblings(Unit *u) {
465 /* This adds the siblings of the specified unit and the
466 * siblings of all parent units to the cgroup queue. (But
467 * neither the specified unit itself nor the parents.) */
469 while ((slice = UNIT_DEREF(u->slice))) {
473 SET_FOREACH(m, slice->dependencies[UNIT_BEFORE], i) {
477 if (UNIT_DEREF(m->slice) != slice)
480 unit_add_to_cgroup_queue(m);
487 void unit_realize_cgroup(Unit *u) {
492 c = unit_get_cgroup_context(u);
496 /* So, here's the deal: when realizing the cgroups for this
497 * unit, we need to first create all parents, but there's more
498 * actually: for the weight-based controllers we also need to
499 * make sure that all our siblings (i.e. units that are in the
500 * same slice as we are) have cgroup too. Otherwise things
501 * would become very uneven as each of their processes would
502 * get as much resources as all our group together. This call
503 * will synchronously create the parent cgroups, but will
504 * defer work on the siblings to the next event loop
507 /* Add all sibling slices to the cgroup queue. */
508 unit_queue_siblings(u);
510 /* And realize this one now */
511 unit_realize_cgroup_now(u);
513 /* And apply the values */
514 cgroup_context_apply(c, u->cgroup_mask, u->cgroup_path);
517 void unit_destroy_cgroup(Unit *u) {
525 r = cg_trim_with_mask(u->cgroup_mask, u->cgroup_path, true);
527 log_error("Failed to destroy cgroup %s: %s", u->cgroup_path, strerror(-r));
529 free(u->cgroup_path);
530 u->cgroup_path = NULL;
531 u->cgroup_realized = false;
535 pid_t unit_search_main_pid(Unit *u) {
536 _cleanup_fclose_ FILE *f = NULL;
537 pid_t pid = 0, npid, mypid;
544 if (cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, &f) < 0)
548 while (cg_read_pid(f, &npid) > 0) {
554 /* Ignore processes that aren't our kids */
555 if (get_parent_of_pid(npid, &ppid) >= 0 && ppid != mypid)
559 /* Dang, there's more than one daemonized PID
560 in this group, so we don't know what process
561 is the main process. */
572 int manager_setup_cgroup(Manager *m) {
573 _cleanup_free_ char *path = NULL;
579 /* 0. Be nice to Ingo Molnar #628004 */
580 if (path_is_mount_point("/sys/fs/cgroup/systemd", false) <= 0) {
581 log_warning("No control group support available, not creating root group.");
585 /* 1. Determine hierarchy */
586 free(m->cgroup_root);
587 m->cgroup_root = NULL;
589 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &m->cgroup_root);
591 log_error("Cannot determine cgroup we are running in: %s", strerror(-r));
595 /* Already in /system.slice? If so, let's cut this off again */
596 if (m->running_as == SYSTEMD_SYSTEM) {
597 e = endswith(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
602 /* And make sure to store away the root value without trailing
603 * slash, even for the root dir, so that we can easily prepend
605 if (streq(m->cgroup_root, "/"))
606 m->cgroup_root[0] = 0;
609 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, NULL, &path);
611 log_error("Cannot find cgroup mount point: %s", strerror(-r));
615 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER ". File system hierarchy is at %s.", path);
617 /* 3. Install agent */
618 if (m->running_as == SYSTEMD_SYSTEM) {
619 r = cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER, SYSTEMD_CGROUP_AGENT_PATH);
621 log_warning("Failed to install release agent, ignoring: %s", strerror(-r));
623 log_debug("Installed release agent.");
625 log_debug("Release agent already installed.");
628 /* 4. Realize the system slice and put us in there */
629 a = strappenda(m->cgroup_root, "/" SPECIAL_SYSTEM_SLICE);
630 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, a, 0);
632 log_error("Failed to create root cgroup hierarchy: %s", strerror(-r));
636 /* 5. And pin it, so that it cannot be unmounted */
637 if (m->pin_cgroupfs_fd >= 0)
638 close_nointr_nofail(m->pin_cgroupfs_fd);
640 m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
642 log_error("Failed to open pin file: %m");
646 /* 6. Figure out which controllers are supported */
647 m->cgroup_supported = cg_mask_supported();
652 void manager_shutdown_cgroup(Manager *m, bool delete) {
655 /* We can't really delete the group, since we are in it. But
657 if (delete && m->cgroup_root)
658 cg_trim(SYSTEMD_CGROUP_CONTROLLER, m->cgroup_root, false);
660 if (m->pin_cgroupfs_fd >= 0) {
661 close_nointr_nofail(m->pin_cgroupfs_fd);
662 m->pin_cgroupfs_fd = -1;
665 free(m->cgroup_root);
666 m->cgroup_root = NULL;
669 Unit* manager_get_unit_by_cgroup(Manager *m, const char *cgroup) {
676 u = hashmap_get(m->cgroup_unit, cgroup);
690 u = hashmap_get(m->cgroup_unit, p);
696 Unit *manager_get_unit_by_pid(Manager *m, pid_t pid) {
697 _cleanup_free_ char *cgroup = NULL;
705 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
709 return manager_get_unit_by_cgroup(m, cgroup);
712 int manager_notify_cgroup_empty(Manager *m, const char *cgroup) {
719 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, cgroup, true);
723 u = manager_get_unit_by_cgroup(m, cgroup);
724 if (u && UNIT_VTABLE(u)->notify_cgroup_empty)
725 UNIT_VTABLE(u)->notify_cgroup_empty(u);
730 static const char* const cgroup_device_policy_table[_CGROUP_DEVICE_POLICY_MAX] = {
731 [CGROUP_AUTO] = "auto",
732 [CGROUP_CLOSED] = "closed",
733 [CGROUP_STRICT] = "strict",
736 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy, CGroupDevicePolicy);