2 * lxc: linux Container library
4 * Copyright © 2016 Canonical Ltd.
7 * Serge Hallyn <serge.hallyn@ubuntu.com>
8 * Christian Brauner <christian.brauner@ubuntu.com>
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
27 * cgroup backend. The original cgfs.c was designed to be as flexible
28 * as possible. It would try to find cgroup filesystems no matter where
29 * or how you had them mounted, and deduce the most usable mount for
32 * This new implementation assumes that cgroup filesystems are mounted
33 * under /sys/fs/cgroup/clist where clist is either the controller, or
34 * a comman-separated list of controllers.
48 #include <linux/kdev_t.h>
49 #include <linux/types.h>
50 #include <sys/types.h>
54 #include "cgroup_utils.h"
58 #include "storage/storage.h"
61 lxc_log_define(lxc_cgfsng
, lxc
);
63 static struct cgroup_ops cgfsng_ops
;
65 /* A descriptor for a mounted hierarchy
69 * Either NULL, or a null-terminated list of all the co-mounted controllers.
71 * Either NULL, or a null-terminated list of all enabled controllers.
74 * - The mountpoint we will use.
76 * It will be either /sys/fs/cgroup/controller or
77 * /sys/fs/cgroup/controllerlist.
79 * It will either be /sys/fs/cgroup or /sys/fs/cgroup/<mountpoint-name>
80 * depending on whether this is a hybrid cgroup layout (mix of legacy and
81 * unified hierarchies) or a pure unified cgroup layout.
84 * - The cgroup under which the container cgroup path
85 * is created. This will be either the caller's cgroup (if not root), or
86 * init's cgroup (if root).
89 * - The full path to the containers cgroup.
93 * If the hierarchy is a legacy hierarchy this will be set to
96 * If the hierarchy is a legacy hierarchy this will be set to
97 * CGROUP2_SUPER_MAGIC.
107 /* The cgroup data which is attached to the lxc_handler.
110 * - A copy of lxc.cgroup.pattern.
113 * - If not null, the cgroup which was created for the container. For each
114 * hierarchy, it is created under the @hierarchy->base_cgroup directory.
115 * Relative to the base_cgroup it is the same for all hierarchies.
118 * - The name of the container.
121 * - A copy of the container's cgroup information. This overrides
125 * - What cgroup layout the container is running with.
126 * - CGROUP_LAYOUT_UNKNOWN
127 * The cgroup layout could not be determined. This should be treated as an
129 * - CGROUP_LAYOUT_LEGACY
130 * The container is running with all controllers mounted into legacy cgroup
132 * - CGROUP_LAYOUT_HYBRID
133 * The container is running with at least one controller mounted into a
134 * legacy cgroup hierarchy and a mountpoint for the unified hierarchy. The
135 * unified hierarchy can be empty (no controllers enabled) or non-empty
136 * (controllers enabled).
137 * - CGROUP_LAYOUT_UNIFIED
138 * The container is running on a pure unified cgroup hierarchy. The unified
139 * hierarchy can be empty (no controllers enabled) or non-empty (controllers
142 struct cgfsng_handler_data
{
143 char *cgroup_pattern
;
144 char *container_cgroup
; /* cgroup we created for the container */
145 char *name
; /* container name */
146 /* per-container cgroup information */
147 struct lxc_cgroup cgroup_meta
;
148 cgroup_layout_t cgroup_layout
;
152 * - A NULL-terminated array of struct hierarchy, one per legacy hierarchy. No
153 * duplicates. First sufficient, writeable mounted hierarchy wins.
155 struct hierarchy
**hierarchies
;
156 /* Pointer to the unified hierarchy in the null terminated list @hierarchies.
157 * This is merely a convenience for hybrid cgroup layouts to easily retrieve the
158 * unified hierarchy without iterating throught @hierarchies.
160 struct hierarchy
*unified
;
163 * - What cgroup layout the container is running with.
164 * - CGROUP_LAYOUT_UNKNOWN
165 * The cgroup layout could not be determined. This should be treated as an
167 * - CGROUP_LAYOUT_LEGACY
168 * The container is running with all controllers mounted into legacy cgroup
170 * - CGROUP_LAYOUT_HYBRID
171 * The container is running with at least one controller mounted into a
172 * legacy cgroup hierarchy and a mountpoint for the unified hierarchy. The
173 * unified hierarchy can be empty (no controllers enabled) or non-empty
174 * (controllers enabled).
175 * - CGROUP_LAYOUT_UNIFIED
176 * The container is running on a pure unified cgroup hierarchy. The unified
177 * hierarchy can be empty (no controllers enabled) or non-empty (controllers
180 cgroup_layout_t cgroup_layout
;
181 /* What controllers is the container supposed to use. */
185 * - Whether to print debug info to stdout for the cgfsng driver.
187 static bool lxc_cgfsng_debug
;
189 #define CGFSNG_DEBUG(format, ...) \
191 if (lxc_cgfsng_debug) \
192 printf("cgfsng: " format, ##__VA_ARGS__); \
195 static void free_string_list(char **clist
)
202 for (i
= 0; clist
[i
]; i
++)
208 /* Allocate a pointer, do not fail. */
209 static void *must_alloc(size_t sz
)
211 return must_realloc(NULL
, sz
);
214 /* Given a pointer to a null-terminated array of pointers, realloc to add one
215 * entry, and point the new entry to NULL. Do not fail. Return the index to the
216 * second-to-last entry - that is, the one which is now available for use
217 * (keeping the list null-terminated).
219 static int append_null_to_list(void ***list
)
224 for (; (*list
)[newentry
]; newentry
++)
227 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
228 (*list
)[newentry
+ 1] = NULL
;
232 /* Given a null-terminated array of strings, check whether @entry is one of the
235 static bool string_in_list(char **list
, const char *entry
)
242 for (i
= 0; list
[i
]; i
++)
243 if (strcmp(list
[i
], entry
) == 0)
249 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
250 * "name=systemd". Do not fail.
252 static char *cg_legacy_must_prefix_named(char *entry
)
258 prefixed
= must_alloc(len
+ 6);
260 memcpy(prefixed
, "name=", sizeof("name="));
261 memcpy(prefixed
+ sizeof("name="), entry
, len
);
262 prefixed
[len
+ 5] = '\0';
266 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
269 * We also handle named subsystems here. Any controller which is not a kernel
270 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
271 * we refuse to use because we're not sure which we have here.
272 * (TODO: We could work around this in some cases by just remounting to be
273 * unambiguous, or by comparing mountpoint contents with current cgroup.)
275 * The last entry will always be NULL.
277 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
283 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
284 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
285 ERROR("It is both a named and kernel subsystem");
289 newentry
= append_null_to_list((void ***)clist
);
291 if (strncmp(entry
, "name=", 5) == 0)
292 copy
= must_copy_string(entry
);
293 else if (string_in_list(klist
, entry
))
294 copy
= must_copy_string(entry
);
296 copy
= cg_legacy_must_prefix_named(entry
);
298 (*clist
)[newentry
] = copy
;
301 static void free_handler_data(struct cgfsng_handler_data
*d
)
303 free(d
->cgroup_pattern
);
304 free(d
->container_cgroup
);
306 if (d
->cgroup_meta
.dir
)
307 free(d
->cgroup_meta
.dir
);
308 if (d
->cgroup_meta
.controllers
)
309 free(d
->cgroup_meta
.controllers
);
313 /* Given a handler's cgroup data, return the struct hierarchy for the controller
314 * @c, or NULL if there is none.
316 struct hierarchy
*get_hierarchy(const char *c
)
323 for (i
= 0; hierarchies
[i
]; i
++) {
325 /* This is the empty unified hierarchy. */
326 if (hierarchies
[i
]->controllers
&&
327 !hierarchies
[i
]->controllers
[0])
328 return hierarchies
[i
];
333 if (string_in_list(hierarchies
[i
]->controllers
, c
))
334 return hierarchies
[i
];
340 #define BATCH_SIZE 50
341 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
343 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
344 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
346 if (!*mem
|| newbatches
> oldbatches
) {
347 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
351 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
353 size_t full
= oldlen
+ newlen
;
355 batch_realloc(dest
, oldlen
, full
+ 1);
357 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
360 /* Slurp in a whole file */
361 static char *read_file(const char *fnam
)
364 char *line
= NULL
, *buf
= NULL
;
365 size_t len
= 0, fulllen
= 0;
368 f
= fopen(fnam
, "r");
371 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
372 append_line(&buf
, fulllen
, line
, linelen
);
380 /* Taken over modified from the kernel sources. */
381 #define NBITS 32 /* bits in uint32_t */
382 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
383 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
385 static void set_bit(unsigned bit
, uint32_t *bitarr
)
387 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
390 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
392 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
395 static bool is_set(unsigned bit
, uint32_t *bitarr
)
397 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
400 /* Create cpumask from cpulist aka turn:
408 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
413 char *saveptr
= NULL
;
415 arrlen
= BITS_TO_LONGS(nbits
);
416 bitarr
= calloc(arrlen
, sizeof(uint32_t));
420 for (; (token
= strtok_r(buf
, ",", &saveptr
)); buf
= NULL
) {
425 start
= strtoul(token
, NULL
, 0);
427 range
= strchr(token
, '-');
429 end
= strtoul(range
+ 1, NULL
, 0);
431 if (!(start
<= end
)) {
442 set_bit(start
++, bitarr
);
448 /* Turn cpumask into simple, comma-separated cpulist. */
449 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
453 char **cpulist
= NULL
;
454 char numstr
[LXC_NUMSTRLEN64
] = {0};
456 for (i
= 0; i
<= nbits
; i
++) {
457 if (!is_set(i
, bitarr
))
460 ret
= snprintf(numstr
, LXC_NUMSTRLEN64
, "%zu", i
);
461 if (ret
< 0 || (size_t)ret
>= LXC_NUMSTRLEN64
) {
462 lxc_free_array((void **)cpulist
, free
);
466 ret
= lxc_append_string(&cpulist
, numstr
);
468 lxc_free_array((void **)cpulist
, free
);
476 return lxc_string_join(",", (const char **)cpulist
, false);
479 static ssize_t
get_max_cpus(char *cpulist
)
482 char *maxcpus
= cpulist
;
485 c1
= strrchr(maxcpus
, ',');
489 c2
= strrchr(maxcpus
, '-');
503 cpus
= strtoul(c1
, NULL
, 0);
510 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
511 static bool cg_legacy_filter_and_set_cpus(char *path
, bool am_initialized
)
515 char *lastslash
, *fpath
, oldv
;
516 ssize_t maxisol
= 0, maxposs
= 0;
517 char *cpulist
= NULL
, *isolcpus
= NULL
, *posscpus
= NULL
;
518 uint32_t *isolmask
= NULL
, *possmask
= NULL
;
519 bool bret
= false, flipped_bit
= false;
521 lastslash
= strrchr(path
, '/');
523 ERROR("Failed to detect \"/\" in \"%s\"", path
);
528 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
529 posscpus
= read_file(fpath
);
531 SYSERROR("Failed to read file \"%s\"", fpath
);
535 /* Get maximum number of cpus found in possible cpuset. */
536 maxposs
= get_max_cpus(posscpus
);
540 if (!file_exists(__ISOL_CPUS
)) {
541 /* This system doesn't expose isolated cpus. */
542 DEBUG("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
544 /* No isolated cpus but we weren't already initialized by
545 * someone. We should simply copy the parents cpuset.cpus
548 if (!am_initialized
) {
549 DEBUG("Copying cpu settings of parent cgroup");
552 /* No isolated cpus but we were already initialized by someone.
553 * Nothing more to do for us.
558 isolcpus
= read_file(__ISOL_CPUS
);
560 SYSERROR("Failed to read file \""__ISOL_CPUS
"\"");
563 if (!isdigit(isolcpus
[0])) {
564 TRACE("No isolated cpus detected");
566 /* No isolated cpus but we weren't already initialized by
567 * someone. We should simply copy the parents cpuset.cpus
570 if (!am_initialized
) {
571 DEBUG("Copying cpu settings of parent cgroup");
574 /* No isolated cpus but we were already initialized by someone.
575 * Nothing more to do for us.
580 /* Get maximum number of cpus found in isolated cpuset. */
581 maxisol
= get_max_cpus(isolcpus
);
585 if (maxposs
< maxisol
)
589 possmask
= lxc_cpumask(posscpus
, maxposs
);
591 ERROR("Failed to create cpumask for possible cpus");
595 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
597 ERROR("Failed to create cpumask for isolated cpus");
601 for (i
= 0; i
<= maxposs
; i
++) {
602 if (!is_set(i
, isolmask
) || !is_set(i
, possmask
))
606 clear_bit(i
, possmask
);
610 DEBUG("No isolated cpus present in cpuset");
613 DEBUG("Removed isolated cpus from cpuset");
615 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
617 ERROR("Failed to create cpu list");
624 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
625 ret
= lxc_write_to_file(fpath
, cpulist
, strlen(cpulist
), false);
627 SYSERROR("Failed to write cpu list to \"%s\"", fpath
);
640 if (posscpus
!= cpulist
)
648 /* Copy contents of parent(@path)/@file to @path/@file */
649 static bool copy_parent_file(char *path
, char *file
)
652 char *fpath
, *lastslash
, oldv
;
656 lastslash
= strrchr(path
, '/');
658 ERROR("Failed to detect \"/\" in \"%s\"", path
);
663 fpath
= must_make_path(path
, file
, NULL
);
664 len
= lxc_read_from_file(fpath
, NULL
, 0);
668 value
= must_alloc(len
+ 1);
669 ret
= lxc_read_from_file(fpath
, value
, len
);
675 fpath
= must_make_path(path
, file
, NULL
);
676 ret
= lxc_write_to_file(fpath
, value
, len
, false);
678 SYSERROR("Failed to write \"%s\" to file \"%s\"", value
, fpath
);
684 SYSERROR("Failed to read file \"%s\"", fpath
);
690 /* Initialize the cpuset hierarchy in first directory of @gname and set
691 * cgroup.clone_children so that children inherit settings. Since the
692 * h->base_path is populated by init or ourselves, we know it is already
695 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
, char *cgname
)
699 char *cgpath
, *clonechildrenpath
, *slash
;
701 if (!string_in_list(h
->controllers
, "cpuset"))
706 slash
= strchr(cgname
, '/');
710 cgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgname
, NULL
);
714 ret
= mkdir(cgpath
, 0755);
716 if (errno
!= EEXIST
) {
717 SYSERROR("Failed to create directory \"%s\"", cgpath
);
724 must_make_path(cgpath
, "cgroup.clone_children", NULL
);
725 /* unified hierarchy doesn't have clone_children */
726 if (!file_exists(clonechildrenpath
)) {
727 free(clonechildrenpath
);
732 ret
= lxc_read_from_file(clonechildrenpath
, &v
, 1);
734 SYSERROR("Failed to read file \"%s\"", clonechildrenpath
);
735 free(clonechildrenpath
);
740 /* Make sure any isolated cpus are removed from cpuset.cpus. */
741 if (!cg_legacy_filter_and_set_cpus(cgpath
, v
== '1')) {
742 SYSERROR("Failed to remove isolated cpus");
743 free(clonechildrenpath
);
748 /* Already set for us by someone else. */
750 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
751 free(clonechildrenpath
);
756 /* copy parent's settings */
757 if (!copy_parent_file(cgpath
, "cpuset.mems")) {
758 SYSERROR("Failed to copy \"cpuset.mems\" settings");
760 free(clonechildrenpath
);
765 ret
= lxc_write_to_file(clonechildrenpath
, "1", 1, false);
767 /* Set clone_children so children inherit our settings */
768 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath
);
769 free(clonechildrenpath
);
772 free(clonechildrenpath
);
776 /* Given two null-terminated lists of strings, return true if any string is in
779 static bool controller_lists_intersect(char **l1
, char **l2
)
786 for (i
= 0; l1
[i
]; i
++) {
787 if (string_in_list(l2
, l1
[i
]))
794 /* For a null-terminated list of controllers @clist, return true if any of those
795 * controllers is already listed the null-terminated list of hierarchies @hlist.
796 * Realistically, if one is present, all must be present.
798 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
805 for (i
= 0; hlist
[i
]; i
++)
806 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
812 /* Return true if the controller @entry is found in the null-terminated list of
813 * hierarchies @hlist.
815 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
822 for (i
= 0; hlist
[i
]; i
++)
823 if (string_in_list(hlist
[i
]->controllers
, entry
))
829 /* Return true if all of the controllers which we require have been found. The
830 * required list is freezer and anything in lxc.cgroup.use.
832 static bool all_controllers_found(void)
835 char *saveptr
= NULL
;
836 struct hierarchy
**hlist
= hierarchies
;
838 if (!controller_found(hlist
, "freezer")) {
839 CGFSNG_DEBUG("No freezer controller mountpoint found\n");
846 for (p
= strtok_r(cgroup_use
, ",", &saveptr
); p
;
847 p
= strtok_r(NULL
, ",", &saveptr
)) {
848 if (!controller_found(hlist
, p
)) {
849 CGFSNG_DEBUG("No %s controller mountpoint found\n", p
);
857 /* Get the controllers from a mountinfo line There are other ways we could get
858 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
859 * could parse the mount options. But we simply assume that the mountpoint must
860 * be /sys/fs/cgroup/controller-list
862 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
865 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
866 * for legacy hierarchies.
869 char *dup
, *p2
, *tok
;
870 char *p
= line
, *saveptr
= NULL
, *sep
= ",";
873 for (i
= 0; i
< 4; i
++) {
880 /* Note, if we change how mountinfo works, then our caller will need to
881 * verify /sys/fs/cgroup/ in this field.
883 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0) {
884 CGFSNG_DEBUG("Found hierarchy not under /sys/fs/cgroup: \"%s\"\n", p
);
891 CGFSNG_DEBUG("Corrupt mountinfo\n");
896 if (type
== CGROUP_SUPER_MAGIC
) {
897 /* strdup() here for v1 hierarchies. Otherwise strtok_r() will
898 * destroy mountpoints such as "/sys/fs/cgroup/cpu,cpuacct".
904 for (tok
= strtok_r(dup
, sep
, &saveptr
); tok
;
905 tok
= strtok_r(NULL
, sep
, &saveptr
))
906 must_append_controller(klist
, nlist
, &aret
, tok
);
915 static char **cg_unified_make_empty_controller(void)
920 newentry
= append_null_to_list((void ***)&aret
);
921 aret
[newentry
] = NULL
;
925 static char **cg_unified_get_controllers(const char *file
)
928 char *saveptr
= NULL
, *sep
= " \t\n";
931 buf
= read_file(file
);
935 for (tok
= strtok_r(buf
, sep
, &saveptr
); tok
;
936 tok
= strtok_r(NULL
, sep
, &saveptr
)) {
940 newentry
= append_null_to_list((void ***)&aret
);
941 copy
= must_copy_string(tok
);
942 aret
[newentry
] = copy
;
949 static struct hierarchy
*add_hierarchy(char **clist
, char *mountpoint
,
950 char *base_cgroup
, int type
)
952 struct hierarchy
*new;
955 new = must_alloc(sizeof(*new));
956 new->controllers
= clist
;
957 new->mountpoint
= mountpoint
;
958 new->base_cgroup
= base_cgroup
;
959 new->fullcgpath
= NULL
;
962 newentry
= append_null_to_list((void ***)&hierarchies
);
963 hierarchies
[newentry
] = new;
967 /* Get a copy of the mountpoint from @line, which is a line from
968 * /proc/self/mountinfo.
970 static char *cg_hybrid_get_mountpoint(char *line
)
975 char *p
= line
, *sret
= NULL
;
977 for (i
= 0; i
< 4; i
++) {
984 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
987 p2
= strchr(p
+ 15, ' ');
993 sret
= must_alloc(len
+ 1);
994 memcpy(sret
, p
, len
);
999 /* Given a multi-line string, return a null-terminated copy of the current line. */
1000 static char *copy_to_eol(char *p
)
1002 char *p2
= strchr(p
, '\n'), *sret
;
1009 sret
= must_alloc(len
+ 1);
1010 memcpy(sret
, p
, len
);
1015 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
1016 * /proc/self/cgroup file. Check whether controller c is present.
1018 static bool controller_in_clist(char *cgline
, char *c
)
1020 char *tok
, *saveptr
= NULL
, *eol
, *tmp
;
1023 eol
= strchr(cgline
, ':');
1028 tmp
= alloca(len
+ 1);
1029 memcpy(tmp
, cgline
, len
);
1032 for (tok
= strtok_r(tmp
, ",", &saveptr
); tok
;
1033 tok
= strtok_r(NULL
, ",", &saveptr
)) {
1034 if (strcmp(tok
, c
) == 0)
1041 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
1044 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
1047 char *p
= basecginfo
;
1050 bool is_cgv2_base_cgroup
= false;
1052 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
1053 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
1054 is_cgv2_base_cgroup
= true;
1061 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
1066 return copy_to_eol(p
);
1069 p
= strchr(p
, '\n');
1076 static void must_append_string(char ***list
, char *entry
)
1081 newentry
= append_null_to_list((void ***)list
);
1082 copy
= must_copy_string(entry
);
1083 (*list
)[newentry
] = copy
;
1086 static int get_existing_subsystems(char ***klist
, char ***nlist
)
1092 f
= fopen("/proc/self/cgroup", "r");
1096 while (getline(&line
, &len
, f
) != -1) {
1097 char *p
, *p2
, *tok
, *saveptr
= NULL
;
1098 p
= strchr(line
, ':');
1102 p2
= strchr(p
, ':');
1107 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
1108 * contains an entry of the form:
1112 * In this case we use "cgroup2" as controller name.
1114 if ((p2
- p
) == 0) {
1115 must_append_string(klist
, "cgroup2");
1119 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
1120 tok
= strtok_r(NULL
, ",", &saveptr
)) {
1121 if (strncmp(tok
, "name=", 5) == 0)
1122 must_append_string(nlist
, tok
);
1124 must_append_string(klist
, tok
);
1133 static void trim(char *s
)
1138 while ((len
> 1) && (s
[len
- 1] == '\n'))
1142 static void lxc_cgfsng_print_handler_data(const struct cgfsng_handler_data
*d
)
1144 printf("Cgroup information:\n");
1145 printf(" container name: %s\n", d
->name
? d
->name
: "(null)");
1146 printf(" lxc.cgroup.use: %s\n", cgroup_use
? cgroup_use
: "(null)");
1147 printf(" lxc.cgroup.pattern: %s\n",
1148 d
->cgroup_pattern
? d
->cgroup_pattern
: "(null)");
1149 printf(" lxc.cgroup.dir: %s\n",
1150 d
->cgroup_meta
.dir
? d
->cgroup_meta
.dir
: "(null)");
1151 printf(" cgroup: %s\n",
1152 d
->container_cgroup
? d
->container_cgroup
: "(null)");
1155 static void lxc_cgfsng_print_hierarchies()
1158 struct hierarchy
**it
;
1161 printf(" No hierarchies found\n");
1165 printf(" Hierarchies:\n");
1166 for (i
= 0, it
= hierarchies
; it
&& *it
; it
++, i
++) {
1170 printf(" %d: base_cgroup: %s\n", i
, (*it
)->base_cgroup
? (*it
)->base_cgroup
: "(null)");
1171 printf(" mountpoint: %s\n", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
1172 printf(" controllers:\n");
1173 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
1174 printf(" %d: %s\n", j
, *cit
);
1178 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
1184 printf("basecginfo is:\n");
1185 printf("%s\n", basecginfo
);
1187 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
1188 printf("kernel subsystem %d: %s\n", k
, *it
);
1190 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
1191 printf("named subsystem %d: %s\n", k
, *it
);
1194 static void lxc_cgfsng_print_debuginfo(const struct cgfsng_handler_data
*d
)
1196 lxc_cgfsng_print_handler_data(d
);
1197 lxc_cgfsng_print_hierarchies();
1200 /* At startup, parse_hierarchies finds all the info we need about cgroup
1201 * mountpoints and current cgroups, and stores it in @d.
1203 static bool cg_hybrid_init(void)
1211 char **klist
= NULL
, **nlist
= NULL
;
1213 /* Root spawned containers escape the current cgroup, so use init's
1214 * cgroups as our base in that case.
1216 will_escape
= (geteuid() == 0);
1218 basecginfo
= read_file("/proc/1/cgroup");
1220 basecginfo
= read_file("/proc/self/cgroup");
1224 ret
= get_existing_subsystems(&klist
, &nlist
);
1226 CGFSNG_DEBUG("Failed to retrieve available legacy cgroup controllers\n");
1231 f
= fopen("/proc/self/mountinfo", "r");
1233 CGFSNG_DEBUG("Failed to open \"/proc/self/mountinfo\"\n");
1238 if (lxc_cgfsng_debug
)
1239 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
1241 while (getline(&line
, &len
, f
) != -1) {
1244 struct hierarchy
*new;
1245 char *base_cgroup
= NULL
, *mountpoint
= NULL
;
1246 char **controller_list
= NULL
;
1248 type
= get_cgroup_version(line
);
1252 if (type
== CGROUP2_SUPER_MAGIC
&& unified
)
1255 if (cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
1256 if (type
== CGROUP2_SUPER_MAGIC
)
1257 cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
1258 else if (type
== CGROUP_SUPER_MAGIC
)
1259 cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
1260 } else if (cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
1261 if (type
== CGROUP_SUPER_MAGIC
)
1262 cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
1263 } else if (cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
1264 if (type
== CGROUP2_SUPER_MAGIC
)
1265 cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
1268 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
1269 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
1272 if (type
== CGROUP_SUPER_MAGIC
)
1273 if (controller_list_is_dup(hierarchies
, controller_list
))
1276 mountpoint
= cg_hybrid_get_mountpoint(line
);
1278 CGFSNG_DEBUG("Failed parsing mountpoint from \"%s\"\n", line
);
1282 if (type
== CGROUP_SUPER_MAGIC
)
1283 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
1285 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
1287 CGFSNG_DEBUG("Failed to find current cgroup\n");
1292 prune_init_scope(base_cgroup
);
1293 if (type
== CGROUP2_SUPER_MAGIC
)
1294 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
1296 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
1300 if (type
== CGROUP2_SUPER_MAGIC
) {
1301 char *cgv2_ctrl_path
;
1303 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
1304 "cgroup.controllers",
1307 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
1308 free(cgv2_ctrl_path
);
1309 if (!controller_list
)
1310 controller_list
= cg_unified_make_empty_controller();
1313 new = add_hierarchy(controller_list
, mountpoint
, base_cgroup
, type
);
1314 if (type
== CGROUP2_SUPER_MAGIC
&& !unified
)
1320 free_string_list(controller_list
);
1325 free_string_list(klist
);
1326 free_string_list(nlist
);
1333 if (lxc_cgfsng_debug
) {
1334 printf("Writable cgroup hierarchies:\n");
1335 lxc_cgfsng_print_hierarchies();
1338 /* verify that all controllers in cgroup.use and all crucial
1339 * controllers are accounted for
1341 if (!all_controllers_found())
1347 static int cg_is_pure_unified(void)
1353 ret
= statfs("/sys/fs/cgroup", &fs
);
1357 if (is_fs_type(&fs
, CGROUP2_SUPER_MAGIC
))
1358 return CGROUP2_SUPER_MAGIC
;
1363 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
1364 static char *cg_unified_get_current_cgroup(void)
1366 char *basecginfo
, *base_cgroup
;
1370 will_escape
= (geteuid() == 0);
1372 basecginfo
= read_file("/proc/1/cgroup");
1374 basecginfo
= read_file("/proc/self/cgroup");
1378 base_cgroup
= strstr(basecginfo
, "0::/");
1380 goto cleanup_on_err
;
1382 base_cgroup
= base_cgroup
+ 3;
1383 copy
= copy_to_eol(base_cgroup
);
1385 goto cleanup_on_err
;
1395 static int cg_unified_init(void)
1398 char *mountpoint
, *subtree_path
;
1400 char *base_cgroup
= NULL
;
1402 ret
= cg_is_pure_unified();
1403 if (ret
== -ENOMEDIUM
)
1406 if (ret
!= CGROUP2_SUPER_MAGIC
)
1409 base_cgroup
= cg_unified_get_current_cgroup();
1412 prune_init_scope(base_cgroup
);
1414 /* We assume that we have already been given controllers to delegate
1415 * further down the hierarchy. If not it is up to the user to delegate
1418 mountpoint
= must_copy_string("/sys/fs/cgroup");
1419 subtree_path
= must_make_path(mountpoint
, base_cgroup
,
1420 "cgroup.subtree_control", NULL
);
1421 delegatable
= cg_unified_get_controllers(subtree_path
);
1424 delegatable
= cg_unified_make_empty_controller();
1425 if (!delegatable
[0])
1426 CGFSNG_DEBUG("No controllers are enabled for delegation\n");
1428 /* TODO: If the user requested specific controllers via lxc.cgroup.use
1429 * we should verify here. The reason I'm not doing it right is that I'm
1430 * not convinced that lxc.cgroup.use will be the future since it is a
1431 * global property. I much rather have an option that lets you request
1432 * controllers per container.
1435 add_hierarchy(delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
1436 unified
= hierarchies
[0];
1438 cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
1439 return CGROUP2_SUPER_MAGIC
;
1442 static bool cg_init(void)
1448 tmp
= lxc_global_config_value("lxc.cgroup.use");
1449 if (!cgroup_use
&& errno
!= 0) { /* lxc.cgroup.use can be NULL */
1450 CGFSNG_DEBUG("Failed to retrieve list of cgroups to use\n");
1453 cgroup_use
= must_copy_string(tmp
);
1455 ret
= cg_unified_init();
1459 if (ret
== CGROUP2_SUPER_MAGIC
)
1462 return cg_hybrid_init();
1465 static void *cgfsng_init(struct lxc_handler
*handler
)
1467 const char *cgroup_pattern
;
1468 struct cgfsng_handler_data
*d
;
1470 d
= must_alloc(sizeof(*d
));
1471 memset(d
, 0, sizeof(*d
));
1473 /* copy container name */
1474 d
->name
= must_copy_string(handler
->name
);
1476 /* copy per-container cgroup information */
1477 d
->cgroup_meta
.dir
= NULL
;
1478 d
->cgroup_meta
.controllers
= NULL
;
1479 if (handler
->conf
) {
1480 d
->cgroup_meta
.dir
= must_copy_string(handler
->conf
->cgroup_meta
.dir
);
1481 d
->cgroup_meta
.controllers
= must_copy_string(handler
->conf
->cgroup_meta
.controllers
);
1484 /* copy system-wide cgroup information */
1485 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
1486 if (!cgroup_pattern
) {
1487 /* lxc.cgroup.pattern is only NULL on error. */
1488 ERROR("Failed to retrieve cgroup pattern");
1491 d
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
1493 d
->cgroup_layout
= cgroup_layout
;
1494 if (d
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
)
1495 TRACE("Running with legacy cgroup layout");
1496 else if (d
->cgroup_layout
== CGROUP_LAYOUT_HYBRID
)
1497 TRACE("Running with hybrid cgroup layout");
1498 else if (d
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
)
1499 TRACE("Running with unified cgroup layout");
1501 WARN("Running with unknown cgroup layout");
1503 if (lxc_cgfsng_debug
)
1504 lxc_cgfsng_print_debuginfo(d
);
1509 free_handler_data(d
);
1513 static int recursive_destroy(char *dirname
)
1516 struct dirent
*direntp
;
1520 dir
= opendir(dirname
);
1524 while ((direntp
= readdir(dir
))) {
1528 if (!strcmp(direntp
->d_name
, ".") ||
1529 !strcmp(direntp
->d_name
, ".."))
1532 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1534 ret
= lstat(pathname
, &mystat
);
1537 WARN("Failed to stat \"%s\"", pathname
);
1542 if (!S_ISDIR(mystat
.st_mode
))
1545 ret
= recursive_destroy(pathname
);
1552 ret
= rmdir(dirname
);
1555 WARN("%s - Failed to delete \"%s\"", strerror(errno
), dirname
);
1559 ret
= closedir(dir
);
1562 WARN("%s - Failed to delete \"%s\"", strerror(errno
), dirname
);
1569 static int cgroup_rmdir(char *container_cgroup
)
1573 if (!container_cgroup
|| !hierarchies
)
1576 for (i
= 0; hierarchies
[i
]; i
++) {
1578 struct hierarchy
*h
= hierarchies
[i
];
1583 ret
= recursive_destroy(h
->fullcgpath
);
1585 WARN("Failed to destroy \"%s\"", h
->fullcgpath
);
1587 free(h
->fullcgpath
);
1588 h
->fullcgpath
= NULL
;
1594 struct generic_userns_exec_data
{
1595 struct cgfsng_handler_data
*d
;
1596 struct lxc_conf
*conf
;
1597 uid_t origuid
; /* target uid in parent namespace */
1601 static int cgroup_rmdir_wrapper(void *data
)
1604 struct generic_userns_exec_data
*arg
= data
;
1605 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1606 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1608 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1610 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid
,
1611 (int)nsgid
, (int)nsgid
);
1615 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1617 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid
,
1618 (int)nsuid
, (int)nsuid
);
1622 ret
= setgroups(0, NULL
);
1623 if (ret
< 0 && errno
!= EPERM
) {
1624 SYSERROR("Failed to setgroups(0, NULL)");
1628 return cgroup_rmdir(arg
->d
->container_cgroup
);
1631 static void cgfsng_destroy(void *hdata
, struct lxc_conf
*conf
)
1634 struct cgfsng_handler_data
*d
= hdata
;
1635 struct generic_userns_exec_data wrap
;
1644 if (conf
&& !lxc_list_empty(&conf
->id_map
))
1645 ret
= userns_exec_1(conf
, cgroup_rmdir_wrapper
, &wrap
,
1646 "cgroup_rmdir_wrapper");
1648 ret
= cgroup_rmdir(d
->container_cgroup
);
1650 WARN("Failed to destroy cgroups");
1654 free_handler_data(d
);
1657 struct cgroup_ops
*cgfsng_ops_init(void)
1659 if (getenv("LXC_DEBUG_CGFSNG"))
1660 lxc_cgfsng_debug
= true;
1668 static bool cg_unified_create_cgroup(struct hierarchy
*h
, char *cgname
)
1670 size_t i
, parts_len
;
1672 size_t full_len
= 0;
1673 char *add_controllers
= NULL
, *cgroup
= NULL
;
1674 char **parts
= NULL
;
1677 if (h
->version
!= CGROUP2_SUPER_MAGIC
)
1680 if (!h
->controllers
)
1683 /* For now we simply enable all controllers that we have detected by
1684 * creating a string like "+memory +pids +cpu +io".
1685 * TODO: In the near future we might want to support "-<controller>"
1686 * etc. but whether supporting semantics like this make sense will need
1689 for (it
= h
->controllers
; it
&& *it
; it
++) {
1690 full_len
+= strlen(*it
) + 2;
1691 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
1692 if (h
->controllers
[0] == *it
)
1693 add_controllers
[0] = '\0';
1694 strcat(add_controllers
, "+");
1695 strcat(add_controllers
, *it
);
1696 if ((it
+ 1) && *(it
+ 1))
1697 strcat(add_controllers
, " ");
1700 parts
= lxc_string_split(cgname
, '/');
1703 parts_len
= lxc_array_len((void **)parts
);
1707 cgroup
= must_make_path(h
->mountpoint
, h
->base_cgroup
, NULL
);
1708 for (i
= 0; i
< parts_len
; i
++) {
1712 cgroup
= must_append_path(cgroup
, parts
[i
], NULL
);
1713 target
= must_make_path(cgroup
, "cgroup.subtree_control", NULL
);
1714 ret
= lxc_write_to_file(target
, add_controllers
, full_len
, false);
1717 SYSERROR("Could not enable \"%s\" controllers in the "
1718 "unified cgroup \"%s\"", add_controllers
, cgroup
);
1726 lxc_free_array((void **)parts
, free
);
1727 free(add_controllers
);
1732 static bool create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1736 h
->fullcgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgname
, NULL
);
1737 if (dir_exists(h
->fullcgpath
)) {
1738 ERROR("The cgroup \"%s\" already existed", h
->fullcgpath
);
1742 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1743 ERROR("Failed to handle legacy cpuset controller");
1747 ret
= mkdir_p(h
->fullcgpath
, 0755);
1749 ERROR("Failed to create cgroup \"%s\"", h
->fullcgpath
);
1753 return cg_unified_create_cgroup(h
, cgname
);
1756 static void remove_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1760 ret
= rmdir(h
->fullcgpath
);
1762 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", h
->fullcgpath
);
1764 free(h
->fullcgpath
);
1765 h
->fullcgpath
= NULL
;
1768 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1769 * next cgroup_pattern-1, -2, ..., -999.
1771 static inline bool cgfsng_create(void *hdata
)
1775 char *container_cgroup
, *offset
, *tmp
;
1777 struct cgfsng_handler_data
*d
= hdata
;
1782 if (d
->container_cgroup
) {
1783 WARN("cgfsng_create called a second time");
1787 if (d
->cgroup_meta
.dir
)
1788 tmp
= lxc_string_join("/", (const char *[]){d
->cgroup_meta
.dir
, d
->name
, NULL
}, false);
1790 tmp
= lxc_string_replace("%n", d
->name
, d
->cgroup_pattern
);
1792 ERROR("Failed expanding cgroup name pattern");
1795 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1796 container_cgroup
= must_alloc(len
);
1797 strcpy(container_cgroup
, tmp
);
1799 offset
= container_cgroup
+ len
- 5;
1803 ERROR("Too many conflicting cgroup names");
1810 ret
= snprintf(offset
, 5, "-%d", idx
);
1811 if (ret
< 0 || (size_t)ret
>= 5) {
1812 FILE *f
= fopen("/dev/null", "w");
1814 fprintf(f
, "Workaround for GCC7 bug: "
1815 "https://gcc.gnu.org/bugzilla/"
1816 "show_bug.cgi?id=78969");
1822 for (i
= 0; hierarchies
[i
]; i
++) {
1823 if (!create_path_for_hierarchy(hierarchies
[i
], container_cgroup
)) {
1825 ERROR("Failed to create cgroup \"%s\"", hierarchies
[i
]->fullcgpath
);
1826 free(hierarchies
[i
]->fullcgpath
);
1827 hierarchies
[i
]->fullcgpath
= NULL
;
1828 for (j
= 0; j
< i
; j
++)
1829 remove_path_for_hierarchy(hierarchies
[j
], container_cgroup
);
1835 d
->container_cgroup
= container_cgroup
;
1840 free(container_cgroup
);
1845 static bool cgfsng_enter(void *hdata
, pid_t pid
)
1850 len
= snprintf(pidstr
, 25, "%d", pid
);
1851 if (len
< 0 || len
>= 25)
1854 for (i
= 0; hierarchies
[i
]; i
++) {
1858 fullpath
= must_make_path(hierarchies
[i
]->fullcgpath
,
1859 "cgroup.procs", NULL
);
1860 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false);
1862 SYSERROR("Failed to enter cgroup \"%s\"", fullpath
);
1872 static int chowmod(char *path
, uid_t chown_uid
, gid_t chown_gid
,
1877 ret
= chown(path
, chown_uid
, chown_gid
);
1879 WARN("%s - Failed to chown(%s, %d, %d)", strerror(errno
), path
,
1880 (int)chown_uid
, (int)chown_gid
);
1884 ret
= chmod(path
, chmod_mode
);
1886 WARN("%s - Failed to chmod(%s, %d)", strerror(errno
), path
,
1894 /* chgrp the container cgroups to container group. We leave
1895 * the container owner as cgroup owner. So we must make the
1896 * directories 775 so that the container can create sub-cgroups.
1898 * Also chown the tasks and cgroup.procs files. Those may not
1899 * exist depending on kernel version.
1901 static int chown_cgroup_wrapper(void *data
)
1905 struct generic_userns_exec_data
*arg
= data
;
1906 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1907 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1909 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1911 SYSERROR("Failed to setresgid(%d, %d, %d)",
1912 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1916 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1918 SYSERROR("Failed to setresuid(%d, %d, %d)",
1919 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1923 ret
= setgroups(0, NULL
);
1924 if (ret
< 0 && errno
!= EPERM
) {
1925 SYSERROR("Failed to setgroups(0, NULL)");
1929 destuid
= get_ns_uid(arg
->origuid
);
1931 for (i
= 0; hierarchies
[i
]; i
++) {
1933 char *path
= hierarchies
[i
]->fullcgpath
;
1935 ret
= chowmod(path
, destuid
, nsgid
, 0775);
1939 /* Failures to chown() these are inconvenient but not
1940 * detrimental We leave these owned by the container launcher,
1941 * so that container root can write to the files to attach. We
1942 * chmod() them 664 so that container systemd can write to the
1943 * files (which systemd in wily insists on doing).
1946 if (hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
) {
1947 fullpath
= must_make_path(path
, "tasks", NULL
);
1948 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1952 fullpath
= must_make_path(path
, "cgroup.procs", NULL
);
1953 (void)chowmod(fullpath
, destuid
, 0, 0664);
1956 if (hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1959 fullpath
= must_make_path(path
, "cgroup.subtree_control", NULL
);
1960 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1963 fullpath
= must_make_path(path
, "cgroup.threads", NULL
);
1964 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1971 static bool cgfsng_chown(void *hdata
, struct lxc_conf
*conf
)
1973 struct cgfsng_handler_data
*d
= hdata
;
1974 struct generic_userns_exec_data wrap
;
1979 if (lxc_list_empty(&conf
->id_map
))
1982 wrap
.origuid
= geteuid();
1987 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
,
1988 "chown_cgroup_wrapper") < 0) {
1989 ERROR("Error requesting cgroup chown in new user namespace");
1996 /* We've safe-mounted a tmpfs as parent, so we don't need to protect against
1997 * symlinks any more - just use mount.
1999 * mount cgroup-full if requested
2001 static int mount_cgroup_full(int type
, struct hierarchy
*h
, char *dest
,
2002 char *container_cgroup
)
2005 char *rwpath
, *source
;
2007 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
2010 ret
= mount(h
->mountpoint
, dest
, "cgroup", MS_BIND
, NULL
);
2012 SYSERROR("Failed to bind mount cgroup \"%s\" onto \"%s\"",
2013 h
->mountpoint
, dest
);
2017 if (type
!= LXC_AUTO_CGROUP_FULL_RW
) {
2018 unsigned long flags
= MS_BIND
| MS_NOSUID
| MS_NOEXEC
| MS_NODEV
|
2019 MS_REMOUNT
| MS_RDONLY
;
2021 ret
= mount(NULL
, dest
, "cgroup", flags
, NULL
);
2023 SYSERROR("Failed to remount cgroup \"%s\" read-only", dest
);
2028 INFO("Bind mounted \"%s\" onto \"%s\"", h
->mountpoint
, dest
);
2029 if (type
!= LXC_AUTO_CGROUP_FULL_MIXED
)
2032 /* mount just the container path rw */
2033 source
= must_make_path(h
->mountpoint
, h
->base_cgroup
, container_cgroup
, NULL
);
2034 rwpath
= must_make_path(dest
, h
->base_cgroup
, container_cgroup
, NULL
);
2035 ret
= mount(source
, rwpath
, "cgroup", MS_BIND
, NULL
);
2037 WARN("%s - Failed to mount cgroup \"%s\" read-write",
2038 strerror(errno
), rwpath
);
2040 TRACE("Mounted cgroup \"%s\" read-write", rwpath
);
2046 /* cgroup-full:* is done, no need to create subdirs */
2047 static bool cg_mount_needs_subdirs(int type
)
2049 if (type
>= LXC_AUTO_CGROUP_FULL_RO
)
2055 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
2056 * remount controller ro if needed and bindmount the cgroupfs onto
2057 * controll/the/cg/path.
2059 static int do_secondstage_mounts_if_needed(int type
, struct hierarchy
*h
,
2060 char *controllerpath
, char *cgpath
,
2061 const char *container_cgroup
)
2063 int ret
, remount_flags
;
2065 int flags
= MS_BIND
;
2067 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
2068 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
2070 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
2071 controllerpath
, controllerpath
);
2075 remount_flags
= add_required_remount_flags(controllerpath
,
2077 flags
| MS_REMOUNT
);
2078 ret
= mount(controllerpath
, controllerpath
, "cgroup",
2079 MS_REMOUNT
| MS_BIND
| MS_RDONLY
, NULL
);
2081 SYSERROR("Failed to remount \"%s\" ro", controllerpath
);
2085 INFO("Remounted %s read-only", controllerpath
);
2088 sourcepath
= must_make_path(h
->mountpoint
, h
->base_cgroup
,
2089 container_cgroup
, NULL
);
2090 if (type
== LXC_AUTO_CGROUP_RO
)
2093 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
2095 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
2099 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
2101 if (flags
& MS_RDONLY
) {
2102 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
2103 flags
| MS_REMOUNT
);
2104 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
2106 SYSERROR("Failed to remount \"%s\" ro", cgpath
);
2110 INFO("Remounted %s read-only", cgpath
);
2114 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
2118 static int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
2119 const char *controllerpath
)
2122 char *controllers
= NULL
;
2123 char *fstype
= "cgroup2";
2124 unsigned long flags
= 0;
2129 flags
|= MS_RELATIME
;
2131 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
2134 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
2135 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
2141 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
2144 SYSERROR("Failed to mount %s with cgroup filesystem type %s", controllerpath
, fstype
);
2148 DEBUG("Mounted %s with cgroup filesystem type %s", controllerpath
, fstype
);
2152 static bool cgfsng_mount(void *hdata
, const char *root
, int type
)
2155 char *tmpfspath
= NULL
;
2156 bool has_cgns
= false, retval
= false, wants_force_mount
= false;
2157 struct lxc_handler
*handler
= hdata
;
2158 struct cgfsng_handler_data
*d
= handler
->cgroup_data
;
2160 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
2163 if (type
& LXC_AUTO_CGROUP_FORCE
) {
2164 type
&= ~LXC_AUTO_CGROUP_FORCE
;
2165 wants_force_mount
= true;
2168 if (!wants_force_mount
){
2169 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
2170 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
2172 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
2175 has_cgns
= cgns_supported();
2176 if (has_cgns
&& !wants_force_mount
)
2179 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
2180 type
= LXC_AUTO_CGROUP_MIXED
;
2181 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
2182 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
2185 tmpfspath
= must_make_path(root
, "/sys/fs/cgroup", NULL
);
2186 ret
= safe_mount("cgroup_root", tmpfspath
, "tmpfs",
2187 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
2188 "size=10240k,mode=755", root
);
2192 for (i
= 0; hierarchies
[i
]; i
++) {
2193 char *controllerpath
, *path2
;
2194 struct hierarchy
*h
= hierarchies
[i
];
2195 char *controller
= strrchr(h
->mountpoint
, '/');
2201 controllerpath
= must_make_path(tmpfspath
, controller
, NULL
);
2202 if (dir_exists(controllerpath
)) {
2203 free(controllerpath
);
2207 ret
= mkdir(controllerpath
, 0755);
2209 SYSERROR("Error creating cgroup path: %s", controllerpath
);
2210 free(controllerpath
);
2214 if (has_cgns
&& wants_force_mount
) {
2215 /* If cgroup namespaces are supported but the container
2216 * will not have CAP_SYS_ADMIN after it has started we
2217 * need to mount the cgroups manually.
2219 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
2220 free(controllerpath
);
2227 ret
= mount_cgroup_full(type
, h
, controllerpath
, d
->container_cgroup
);
2229 free(controllerpath
);
2233 if (!cg_mount_needs_subdirs(type
)) {
2234 free(controllerpath
);
2238 path2
= must_make_path(controllerpath
, h
->base_cgroup
,
2239 d
->container_cgroup
, NULL
);
2240 ret
= mkdir_p(path2
, 0755);
2242 free(controllerpath
);
2247 ret
= do_secondstage_mounts_if_needed(type
, h
, controllerpath
,
2248 path2
, d
->container_cgroup
);
2249 free(controllerpath
);
2261 static int recursive_count_nrtasks(char *dirname
)
2263 struct dirent
*direntp
;
2268 dir
= opendir(dirname
);
2272 while ((direntp
= readdir(dir
))) {
2278 if (!strcmp(direntp
->d_name
, ".") ||
2279 !strcmp(direntp
->d_name
, ".."))
2282 path
= must_make_path(dirname
, direntp
->d_name
, NULL
);
2284 if (lstat(path
, &mystat
))
2287 if (!S_ISDIR(mystat
.st_mode
))
2290 count
+= recursive_count_nrtasks(path
);
2295 path
= must_make_path(dirname
, "cgroup.procs", NULL
);
2296 ret
= lxc_count_file_lines(path
);
2301 (void)closedir(dir
);
2306 static int cgfsng_nrtasks(void *hdata
)
2310 struct cgfsng_handler_data
*d
= hdata
;
2312 if (!d
|| !d
->container_cgroup
|| !hierarchies
)
2315 path
= must_make_path(hierarchies
[0]->fullcgpath
, NULL
);
2316 count
= recursive_count_nrtasks(path
);
2321 /* Only root needs to escape to the cgroup of its init. */
2322 static bool cgfsng_escape()
2329 for (i
= 0; hierarchies
[i
]; i
++) {
2333 fullpath
= must_make_path(hierarchies
[i
]->mountpoint
,
2334 hierarchies
[i
]->base_cgroup
,
2335 "cgroup.procs", NULL
);
2336 ret
= lxc_write_to_file(fullpath
, "0", 2, false);
2338 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath
);
2348 static int cgfsng_num_hierarchies(void)
2352 for (i
= 0; hierarchies
[i
]; i
++)
2358 static bool cgfsng_get_hierarchies(int n
, char ***out
)
2362 /* sanity check n */
2363 for (i
= 0; i
< n
; i
++)
2364 if (!hierarchies
[i
])
2367 *out
= hierarchies
[i
]->controllers
;
2372 #define THAWED "THAWED"
2373 #define THAWED_LEN (strlen(THAWED))
2375 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
2378 static bool cgfsng_unfreeze(void *hdata
)
2382 struct hierarchy
*h
;
2384 h
= get_hierarchy("freezer");
2388 fullpath
= must_make_path(h
->fullcgpath
, "freezer.state", NULL
);
2389 ret
= lxc_write_to_file(fullpath
, THAWED
, THAWED_LEN
, false);
2397 static const char *cgfsng_get_cgroup(void *hdata
, const char *subsystem
)
2399 struct hierarchy
*h
;
2401 h
= get_hierarchy(subsystem
);
2405 return h
->fullcgpath
? h
->fullcgpath
+ strlen(h
->mountpoint
) : NULL
;
2408 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2409 * which must be freed by the caller.
2411 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
2413 const char *filename
)
2415 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
2418 /* Technically, we're always at a delegation boundary here (This is especially
2419 * true when cgroup namespaces are available.). The reasoning is that in order
2420 * for us to have been able to start a container in the first place the root
2421 * cgroup must have been a leaf node. Now, either the container's init system
2422 * has populated the cgroup and kept it as a leaf node or it has created
2423 * subtrees. In the former case we will simply attach to the leaf node we
2424 * created when we started the container in the latter case we create our own
2425 * cgroup for the attaching process.
2427 static int __cg_unified_attach(const struct hierarchy
*h
, const char *name
,
2428 const char *lxcpath
, const char *pidstr
,
2429 size_t pidstr_len
, const char *controller
)
2433 int fret
= -1, idx
= 0;
2434 char *base_path
= NULL
, *container_cgroup
= NULL
, *full_path
= NULL
;
2436 container_cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2438 if (!container_cgroup
)
2441 base_path
= must_make_path(h
->mountpoint
, container_cgroup
, NULL
);
2442 full_path
= must_make_path(base_path
, "cgroup.procs", NULL
);
2443 /* cgroup is populated */
2444 ret
= lxc_write_to_file(full_path
, pidstr
, pidstr_len
, false);
2445 if (ret
< 0 && errno
!= EBUSY
)
2453 len
= strlen(base_path
) + sizeof("/lxc-1000") - 1 +
2454 sizeof("/cgroup-procs") - 1;
2455 full_path
= must_alloc(len
+ 1);
2458 ret
= snprintf(full_path
, len
+ 1, "%s/lxc-%d",
2461 ret
= snprintf(full_path
, len
+ 1, "%s/lxc", base_path
);
2462 if (ret
< 0 || (size_t)ret
>= len
+ 1)
2465 ret
= mkdir_p(full_path
, 0755);
2466 if (ret
< 0 && errno
!= EEXIST
)
2469 strcat(full_path
, "/cgroup.procs");
2470 ret
= lxc_write_to_file(full_path
, pidstr
, len
, false);
2474 /* this is a non-leaf node */
2478 } while (++idx
> 0 && idx
< 1000);
2486 free(container_cgroup
);
2492 static bool cgfsng_attach(const char *name
, const char *lxcpath
, pid_t pid
)
2497 len
= snprintf(pidstr
, 25, "%d", pid
);
2498 if (len
< 0 || len
>= 25)
2501 for (i
= 0; hierarchies
[i
]; i
++) {
2503 char *fullpath
= NULL
;
2504 struct hierarchy
*h
= hierarchies
[i
];
2506 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2507 ret
= __cg_unified_attach(h
, name
, lxcpath
, pidstr
, len
,
2515 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2520 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2521 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false);
2523 SYSERROR("Failed to attach %d to %s", (int)pid
, fullpath
);
2533 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2534 * don't have a cgroup_data set up, so we ask the running container through the
2535 * commands API for the cgroup path.
2537 static int cgfsng_get(const char *filename
, char *value
, size_t len
,
2538 const char *name
, const char *lxcpath
)
2541 size_t controller_len
;
2542 char *controller
, *p
, *path
;
2543 struct hierarchy
*h
;
2545 controller_len
= strlen(filename
);
2546 controller
= alloca(controller_len
+ 1);
2547 strcpy(controller
, filename
);
2548 p
= strchr(controller
, '.');
2552 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2557 h
= get_hierarchy(controller
);
2561 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2562 ret
= lxc_read_from_file(fullpath
, value
, len
);
2571 * Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits.
2572 * Here we don't have a cgroup_data set up, so we ask the running
2573 * container through the commands API for the cgroup path
2575 static int cgfsng_set(const char *filename
, const char *value
, const char *name
,
2576 const char *lxcpath
)
2579 size_t controller_len
;
2580 char *controller
, *p
, *path
;
2581 struct hierarchy
*h
;
2583 controller_len
= strlen(filename
);
2584 controller
= alloca(controller_len
+ 1);
2585 strcpy(controller
, filename
);
2586 p
= strchr(controller
, '.');
2590 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2595 h
= get_hierarchy(controller
);
2599 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2600 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false);
2609 * take devices cgroup line
2611 * and convert it to a valid
2612 * type major:minor mode
2613 * line. Return <0 on error. Dest is a preallocated buffer
2614 * long enough to hold the output.
2616 static int convert_devpath(const char *invalue
, char *dest
)
2619 char *p
, *path
, type
;
2621 unsigned long minor
, major
;
2625 path
= must_copy_string(invalue
);
2628 * read path followed by mode; ignore any trailing text.
2629 * A ' # comment' would be legal. Technically other text
2630 * is not legal, we could check for that if we cared to
2632 for (n_parts
= 1, p
= path
; *p
&& n_parts
< 3; p
++) {
2650 ret
= stat(path
, &sb
);
2654 mode_t m
= sb
.st_mode
& S_IFMT
;
2663 ERROR("Unsupported device type %i for %s", m
, path
);
2668 major
= MAJOR(sb
.st_rdev
);
2669 minor
= MINOR(sb
.st_rdev
);
2670 ret
= snprintf(dest
, 50, "%c %lu:%lu %s", type
, major
, minor
, mode
);
2671 if (ret
< 0 || ret
>= 50) {
2672 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2673 "chars)", type
, major
, minor
, mode
);
2674 ret
= -ENAMETOOLONG
;
2685 * Called from setup_limits - here we have the container's cgroup_data because
2686 * we created the cgroups
2688 static int cg_legacy_set_data(const char *filename
, const char *value
,
2689 struct cgfsng_handler_data
*d
)
2693 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2694 char converted_value
[50];
2695 struct hierarchy
*h
;
2697 char *controller
= NULL
;
2699 len
= strlen(filename
);
2700 controller
= alloca(len
+ 1);
2701 strcpy(controller
, filename
);
2702 p
= strchr(controller
, '.');
2706 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2707 ret
= convert_devpath(value
, converted_value
);
2710 value
= converted_value
;
2713 h
= get_hierarchy(controller
);
2715 ERROR("Failed to setup limits for the \"%s\" controller. "
2716 "The controller seems to be unused by \"cgfsng\" cgroup "
2717 "driver or not enabled on the cgroup hierarchy",
2723 fullpath
= must_make_path(h
->fullcgpath
, filename
, NULL
);
2724 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false);
2729 static bool __cg_legacy_setup_limits(void *hdata
,
2730 struct lxc_list
*cgroup_settings
,
2733 struct cgfsng_handler_data
*d
= hdata
;
2734 struct lxc_list
*iterator
, *sorted_cgroup_settings
, *next
;
2735 struct lxc_cgroup
*cg
;
2738 if (lxc_list_empty(cgroup_settings
))
2741 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2742 if (!sorted_cgroup_settings
)
2745 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2746 cg
= iterator
->elem
;
2748 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2749 if (cg_legacy_set_data(cg
->subsystem
, cg
->value
, d
)) {
2750 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2751 WARN("Error setting %s to %s for %s",
2752 cg
->subsystem
, cg
->value
, d
->name
);
2755 SYSERROR("Error setting %s to %s for %s",
2756 cg
->subsystem
, cg
->value
, d
->name
);
2759 DEBUG("cgroup '%s' set to '%s'", cg
->subsystem
, cg
->value
);
2764 INFO("Limits for the legacy cgroup hierarchies have been setup");
2766 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2767 lxc_list_del(iterator
);
2770 free(sorted_cgroup_settings
);
2774 static bool __cg_unified_setup_limits(void *hdata
,
2775 struct lxc_list
*cgroup_settings
)
2777 struct lxc_list
*iterator
;
2778 struct hierarchy
*h
= unified
;
2780 if (lxc_list_empty(cgroup_settings
))
2786 lxc_list_for_each(iterator
, cgroup_settings
) {
2789 struct lxc_cgroup
*cg
= iterator
->elem
;
2791 fullpath
= must_make_path(h
->fullcgpath
, cg
->subsystem
, NULL
);
2792 ret
= lxc_write_to_file(fullpath
, cg
->value
, strlen(cg
->value
), false);
2795 SYSERROR("Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2798 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2801 INFO("Limits for the unified cgroup hierarchy have been setup");
2805 static bool cgfsng_setup_limits(void *hdata
, struct lxc_conf
*conf
,
2810 bret
= __cg_legacy_setup_limits(hdata
, &conf
->cgroup
, do_devices
);
2814 return __cg_unified_setup_limits(hdata
, &conf
->cgroup2
);
2817 static struct cgroup_ops cgfsng_ops
= {
2818 .init
= cgfsng_init
,
2819 .destroy
= cgfsng_destroy
,
2820 .create
= cgfsng_create
,
2821 .enter
= cgfsng_enter
,
2822 .escape
= cgfsng_escape
,
2823 .num_hierarchies
= cgfsng_num_hierarchies
,
2824 .get_hierarchies
= cgfsng_get_hierarchies
,
2825 .get_cgroup
= cgfsng_get_cgroup
,
2828 .unfreeze
= cgfsng_unfreeze
,
2829 .setup_limits
= cgfsng_setup_limits
,
2830 .name
= "cgroupfs-ng",
2831 .attach
= cgfsng_attach
,
2832 .chown
= cgfsng_chown
,
2833 .mount_cgroup
= cgfsng_mount
,
2834 .nrtasks
= cgfsng_nrtasks
,
2838 .create_legacy
= NULL
,