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"
59 #include "storage/storage.h"
63 #include "include/strlcpy.h"
67 #include "include/strlcat.h"
70 lxc_log_define(cgfsng
, cgroup
);
72 static void free_string_list(char **clist
)
79 for (i
= 0; clist
[i
]; i
++)
85 /* Allocate a pointer, do not fail. */
86 static void *must_alloc(size_t sz
)
88 return must_realloc(NULL
, sz
);
91 /* Given a pointer to a null-terminated array of pointers, realloc to add one
92 * entry, and point the new entry to NULL. Do not fail. Return the index to the
93 * second-to-last entry - that is, the one which is now available for use
94 * (keeping the list null-terminated).
96 static int append_null_to_list(void ***list
)
101 for (; (*list
)[newentry
]; newentry
++)
104 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
105 (*list
)[newentry
+ 1] = NULL
;
109 /* Given a null-terminated array of strings, check whether @entry is one of the
112 static bool string_in_list(char **list
, const char *entry
)
119 for (i
= 0; list
[i
]; i
++)
120 if (strcmp(list
[i
], entry
) == 0)
126 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
127 * "name=systemd". Do not fail.
129 static char *cg_legacy_must_prefix_named(char *entry
)
135 prefixed
= must_alloc(len
+ 6);
137 memcpy(prefixed
, "name=", sizeof("name=") - 1);
138 memcpy(prefixed
+ sizeof("name=") - 1, entry
, len
);
139 prefixed
[len
+ 5] = '\0';
143 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
146 * We also handle named subsystems here. Any controller which is not a kernel
147 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
148 * we refuse to use because we're not sure which we have here.
149 * (TODO: We could work around this in some cases by just remounting to be
150 * unambiguous, or by comparing mountpoint contents with current cgroup.)
152 * The last entry will always be NULL.
154 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
160 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
161 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
162 ERROR("It is both a named and kernel subsystem");
166 newentry
= append_null_to_list((void ***)clist
);
168 if (strncmp(entry
, "name=", 5) == 0)
169 copy
= must_copy_string(entry
);
170 else if (string_in_list(klist
, entry
))
171 copy
= must_copy_string(entry
);
173 copy
= cg_legacy_must_prefix_named(entry
);
175 (*clist
)[newentry
] = copy
;
178 /* Given a handler's cgroup data, return the struct hierarchy for the controller
179 * @c, or NULL if there is none.
181 struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *c
)
185 if (!ops
->hierarchies
)
188 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
190 /* This is the empty unified hierarchy. */
191 if (ops
->hierarchies
[i
]->controllers
&&
192 !ops
->hierarchies
[i
]->controllers
[0])
193 return ops
->hierarchies
[i
];
198 if (string_in_list(ops
->hierarchies
[i
]->controllers
, c
))
199 return ops
->hierarchies
[i
];
205 #define BATCH_SIZE 50
206 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
208 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
209 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
211 if (!*mem
|| newbatches
> oldbatches
) {
212 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
216 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
218 size_t full
= oldlen
+ newlen
;
220 batch_realloc(dest
, oldlen
, full
+ 1);
222 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
225 /* Slurp in a whole file */
226 static char *read_file(const char *fnam
)
229 char *line
= NULL
, *buf
= NULL
;
230 size_t len
= 0, fulllen
= 0;
233 f
= fopen(fnam
, "r");
236 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
237 append_line(&buf
, fulllen
, line
, linelen
);
245 /* Taken over modified from the kernel sources. */
246 #define NBITS 32 /* bits in uint32_t */
247 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
248 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
250 static void set_bit(unsigned bit
, uint32_t *bitarr
)
252 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
255 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
257 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
260 static bool is_set(unsigned bit
, uint32_t *bitarr
)
262 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
265 /* Create cpumask from cpulist aka turn:
273 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
279 arrlen
= BITS_TO_LONGS(nbits
);
280 bitarr
= calloc(arrlen
, sizeof(uint32_t));
284 lxc_iterate_parts(token
, buf
, ",") {
289 start
= strtoul(token
, NULL
, 0);
291 range
= strchr(token
, '-');
293 end
= strtoul(range
+ 1, NULL
, 0);
295 if (!(start
<= end
)) {
306 set_bit(start
++, bitarr
);
312 /* Turn cpumask into simple, comma-separated cpulist. */
313 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
317 char **cpulist
= NULL
;
318 char numstr
[INTTYPE_TO_STRLEN(size_t)] = {0};
320 for (i
= 0; i
<= nbits
; i
++) {
321 if (!is_set(i
, bitarr
))
324 ret
= snprintf(numstr
, sizeof(numstr
), "%zu", i
);
325 if (ret
< 0 || (size_t)ret
>= sizeof(numstr
)) {
326 lxc_free_array((void **)cpulist
, free
);
330 ret
= lxc_append_string(&cpulist
, numstr
);
332 lxc_free_array((void **)cpulist
, free
);
340 return lxc_string_join(",", (const char **)cpulist
, false);
343 static ssize_t
get_max_cpus(char *cpulist
)
346 char *maxcpus
= cpulist
;
349 c1
= strrchr(maxcpus
, ',');
353 c2
= strrchr(maxcpus
, '-');
367 cpus
= strtoul(c1
, NULL
, 0);
374 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
375 static bool cg_legacy_filter_and_set_cpus(char *path
, bool am_initialized
)
379 char *lastslash
, *fpath
, oldv
;
380 ssize_t maxisol
= 0, maxposs
= 0;
381 char *cpulist
= NULL
, *isolcpus
= NULL
, *posscpus
= NULL
;
382 uint32_t *isolmask
= NULL
, *possmask
= NULL
;
383 bool bret
= false, flipped_bit
= false;
385 lastslash
= strrchr(path
, '/');
387 ERROR("Failed to detect \"/\" in \"%s\"", path
);
392 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
393 posscpus
= read_file(fpath
);
395 SYSERROR("Failed to read file \"%s\"", fpath
);
399 /* Get maximum number of cpus found in possible cpuset. */
400 maxposs
= get_max_cpus(posscpus
);
401 if (maxposs
< 0 || maxposs
>= INT_MAX
- 1)
404 if (!file_exists(__ISOL_CPUS
)) {
405 /* This system doesn't expose isolated cpus. */
406 DEBUG("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
408 /* No isolated cpus but we weren't already initialized by
409 * someone. We should simply copy the parents cpuset.cpus
412 if (!am_initialized
) {
413 DEBUG("Copying cpu settings of parent cgroup");
416 /* No isolated cpus but we were already initialized by someone.
417 * Nothing more to do for us.
422 isolcpus
= read_file(__ISOL_CPUS
);
424 SYSERROR("Failed to read file \""__ISOL_CPUS
"\"");
427 if (!isdigit(isolcpus
[0])) {
428 TRACE("No isolated cpus detected");
430 /* No isolated cpus but we weren't already initialized by
431 * someone. We should simply copy the parents cpuset.cpus
434 if (!am_initialized
) {
435 DEBUG("Copying cpu settings of parent cgroup");
438 /* No isolated cpus but we were already initialized by someone.
439 * Nothing more to do for us.
444 /* Get maximum number of cpus found in isolated cpuset. */
445 maxisol
= get_max_cpus(isolcpus
);
446 if (maxisol
< 0 || maxisol
>= INT_MAX
- 1)
449 if (maxposs
< maxisol
)
453 possmask
= lxc_cpumask(posscpus
, maxposs
);
455 ERROR("Failed to create cpumask for possible cpus");
459 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
461 ERROR("Failed to create cpumask for isolated cpus");
465 for (i
= 0; i
<= maxposs
; i
++) {
466 if (!is_set(i
, isolmask
) || !is_set(i
, possmask
))
470 clear_bit(i
, possmask
);
474 DEBUG("No isolated cpus present in cpuset");
477 DEBUG("Removed isolated cpus from cpuset");
479 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
481 ERROR("Failed to create cpu list");
488 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
489 ret
= lxc_write_to_file(fpath
, cpulist
, strlen(cpulist
), false, 0666);
491 SYSERROR("Failed to write cpu list to \"%s\"", fpath
);
504 if (posscpus
!= cpulist
)
512 /* Copy contents of parent(@path)/@file to @path/@file */
513 static bool copy_parent_file(char *path
, char *file
)
516 char *fpath
, *lastslash
, oldv
;
520 lastslash
= strrchr(path
, '/');
522 ERROR("Failed to detect \"/\" in \"%s\"", path
);
527 fpath
= must_make_path(path
, file
, NULL
);
528 len
= lxc_read_from_file(fpath
, NULL
, 0);
532 value
= must_alloc(len
+ 1);
533 ret
= lxc_read_from_file(fpath
, value
, len
);
539 fpath
= must_make_path(path
, file
, NULL
);
540 ret
= lxc_write_to_file(fpath
, value
, len
, false, 0666);
542 SYSERROR("Failed to write \"%s\" to file \"%s\"", value
, fpath
);
548 SYSERROR("Failed to read file \"%s\"", fpath
);
554 /* Initialize the cpuset hierarchy in first directory of @gname and set
555 * cgroup.clone_children so that children inherit settings. Since the
556 * h->base_path is populated by init or ourselves, we know it is already
559 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
, char *cgname
)
563 char *cgpath
, *clonechildrenpath
, *slash
;
565 if (!string_in_list(h
->controllers
, "cpuset"))
570 slash
= strchr(cgname
, '/');
574 cgpath
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
578 ret
= mkdir(cgpath
, 0755);
580 if (errno
!= EEXIST
) {
581 SYSERROR("Failed to create directory \"%s\"", cgpath
);
588 must_make_path(cgpath
, "cgroup.clone_children", NULL
);
589 /* unified hierarchy doesn't have clone_children */
590 if (!file_exists(clonechildrenpath
)) {
591 free(clonechildrenpath
);
596 ret
= lxc_read_from_file(clonechildrenpath
, &v
, 1);
598 SYSERROR("Failed to read file \"%s\"", clonechildrenpath
);
599 free(clonechildrenpath
);
604 /* Make sure any isolated cpus are removed from cpuset.cpus. */
605 if (!cg_legacy_filter_and_set_cpus(cgpath
, v
== '1')) {
606 SYSERROR("Failed to remove isolated cpus");
607 free(clonechildrenpath
);
612 /* Already set for us by someone else. */
614 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
615 free(clonechildrenpath
);
620 /* copy parent's settings */
621 if (!copy_parent_file(cgpath
, "cpuset.mems")) {
622 SYSERROR("Failed to copy \"cpuset.mems\" settings");
624 free(clonechildrenpath
);
629 ret
= lxc_write_to_file(clonechildrenpath
, "1", 1, false, 0666);
631 /* Set clone_children so children inherit our settings */
632 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath
);
633 free(clonechildrenpath
);
636 free(clonechildrenpath
);
640 /* Given two null-terminated lists of strings, return true if any string is in
643 static bool controller_lists_intersect(char **l1
, char **l2
)
650 for (i
= 0; l1
[i
]; i
++) {
651 if (string_in_list(l2
, l1
[i
]))
658 /* For a null-terminated list of controllers @clist, return true if any of those
659 * controllers is already listed the null-terminated list of hierarchies @hlist.
660 * Realistically, if one is present, all must be present.
662 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
669 for (i
= 0; hlist
[i
]; i
++)
670 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
676 /* Return true if the controller @entry is found in the null-terminated list of
677 * hierarchies @hlist.
679 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
686 for (i
= 0; hlist
[i
]; i
++)
687 if (string_in_list(hlist
[i
]->controllers
, entry
))
693 /* Return true if all of the controllers which we require have been found. The
694 * required list is freezer and anything in lxc.cgroup.use.
696 static bool all_controllers_found(struct cgroup_ops
*ops
)
699 struct hierarchy
**hlist
= ops
->hierarchies
;
701 if (!controller_found(hlist
, "freezer")) {
702 ERROR("No freezer controller mountpoint found");
706 if (!ops
->cgroup_use
)
709 for (cur
= ops
->cgroup_use
; cur
&& *cur
; cur
++)
710 if (!controller_found(hlist
, *cur
)) {
711 ERROR("No %s controller mountpoint found", *cur
);
718 /* Get the controllers from a mountinfo line There are other ways we could get
719 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
720 * could parse the mount options. But we simply assume that the mountpoint must
721 * be /sys/fs/cgroup/controller-list
723 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
726 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
727 * for legacy hierarchies.
730 char *dup
, *p2
, *tok
;
731 char *p
= line
, *sep
= ",";
734 for (i
= 0; i
< 4; i
++) {
741 /* Note, if we change how mountinfo works, then our caller will need to
742 * verify /sys/fs/cgroup/ in this field.
744 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0) {
745 ERROR("Found hierarchy not under /sys/fs/cgroup: \"%s\"", p
);
752 ERROR("Corrupt mountinfo");
757 if (type
== CGROUP_SUPER_MAGIC
) {
758 /* strdup() here for v1 hierarchies. Otherwise
759 * lxc_iterate_parts() will destroy mountpoints such as
760 * "/sys/fs/cgroup/cpu,cpuacct".
766 lxc_iterate_parts(tok
, dup
, sep
) {
767 must_append_controller(klist
, nlist
, &aret
, tok
);
777 static char **cg_unified_make_empty_controller(void)
782 newentry
= append_null_to_list((void ***)&aret
);
783 aret
[newentry
] = NULL
;
787 static char **cg_unified_get_controllers(const char *file
)
793 buf
= read_file(file
);
797 lxc_iterate_parts(tok
, buf
, sep
) {
801 newentry
= append_null_to_list((void ***)&aret
);
802 copy
= must_copy_string(tok
);
803 aret
[newentry
] = copy
;
810 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
811 char *container_base_path
, int type
)
813 struct hierarchy
*new;
816 new = must_alloc(sizeof(*new));
817 new->controllers
= clist
;
818 new->mountpoint
= mountpoint
;
819 new->container_base_path
= container_base_path
;
820 new->container_full_path
= NULL
;
821 new->monitor_full_path
= NULL
;
824 newentry
= append_null_to_list((void ***)h
);
825 (*h
)[newentry
] = new;
829 /* Get a copy of the mountpoint from @line, which is a line from
830 * /proc/self/mountinfo.
832 static char *cg_hybrid_get_mountpoint(char *line
)
837 char *p
= line
, *sret
= NULL
;
839 for (i
= 0; i
< 4; i
++) {
846 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
849 p2
= strchr(p
+ 15, ' ');
855 sret
= must_alloc(len
+ 1);
856 memcpy(sret
, p
, len
);
861 /* Given a multi-line string, return a null-terminated copy of the current line. */
862 static char *copy_to_eol(char *p
)
864 char *p2
= strchr(p
, '\n'), *sret
;
871 sret
= must_alloc(len
+ 1);
872 memcpy(sret
, p
, len
);
877 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
878 * /proc/self/cgroup file. Check whether controller c is present.
880 static bool controller_in_clist(char *cgline
, char *c
)
882 char *tok
, *eol
, *tmp
;
885 eol
= strchr(cgline
, ':');
890 tmp
= alloca(len
+ 1);
891 memcpy(tmp
, cgline
, len
);
894 lxc_iterate_parts(tok
, tmp
, ",") {
895 if (strcmp(tok
, c
) == 0)
902 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
905 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
908 char *p
= basecginfo
;
911 bool is_cgv2_base_cgroup
= false;
913 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
914 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
915 is_cgv2_base_cgroup
= true;
922 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
927 return copy_to_eol(p
);
937 static void must_append_string(char ***list
, char *entry
)
942 newentry
= append_null_to_list((void ***)list
);
943 copy
= must_copy_string(entry
);
944 (*list
)[newentry
] = copy
;
947 static int get_existing_subsystems(char ***klist
, char ***nlist
)
953 f
= fopen("/proc/self/cgroup", "r");
957 while (getline(&line
, &len
, f
) != -1) {
959 p
= strchr(line
, ':');
968 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
969 * contains an entry of the form:
973 * In this case we use "cgroup2" as controller name.
976 must_append_string(klist
, "cgroup2");
980 lxc_iterate_parts(tok
, p
, ",") {
981 if (strncmp(tok
, "name=", 5) == 0)
982 must_append_string(nlist
, tok
);
984 must_append_string(klist
, tok
);
993 static void trim(char *s
)
998 while ((len
> 1) && (s
[len
- 1] == '\n'))
1002 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
1005 struct hierarchy
**it
;
1007 if (!ops
->hierarchies
) {
1008 TRACE(" No hierarchies found");
1012 TRACE(" Hierarchies:");
1013 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
1017 TRACE(" %d: base_cgroup: %s", i
, (*it
)->container_base_path
? (*it
)->container_base_path
: "(null)");
1018 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
1019 TRACE(" controllers:");
1020 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
1021 TRACE(" %d: %s", j
, *cit
);
1025 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
1031 TRACE("basecginfo is:");
1032 TRACE("%s", basecginfo
);
1034 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
1035 TRACE("kernel subsystem %d: %s", k
, *it
);
1037 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
1038 TRACE("named subsystem %d: %s", k
, *it
);
1041 static int cgroup_rmdir(struct hierarchy
**hierarchies
,
1042 const char *container_cgroup
)
1046 if (!container_cgroup
|| !hierarchies
)
1049 for (i
= 0; hierarchies
[i
]; i
++) {
1051 struct hierarchy
*h
= hierarchies
[i
];
1053 if (!h
->container_full_path
)
1056 ret
= recursive_destroy(h
->container_full_path
);
1058 WARN("Failed to destroy \"%s\"", h
->container_full_path
);
1060 free(h
->container_full_path
);
1061 h
->container_full_path
= NULL
;
1067 struct generic_userns_exec_data
{
1068 struct hierarchy
**hierarchies
;
1069 const char *container_cgroup
;
1070 struct lxc_conf
*conf
;
1071 uid_t origuid
; /* target uid in parent namespace */
1075 static int cgroup_rmdir_wrapper(void *data
)
1078 struct generic_userns_exec_data
*arg
= data
;
1079 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1080 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1082 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1084 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid
,
1085 (int)nsgid
, (int)nsgid
);
1089 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1091 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid
,
1092 (int)nsuid
, (int)nsuid
);
1096 ret
= setgroups(0, NULL
);
1097 if (ret
< 0 && errno
!= EPERM
) {
1098 SYSERROR("Failed to setgroups(0, NULL)");
1102 return cgroup_rmdir(arg
->hierarchies
, arg
->container_cgroup
);
1105 __cgfsng_ops
static void cgfsng_destroy(struct cgroup_ops
*ops
, struct lxc_handler
*handler
)
1108 struct generic_userns_exec_data wrap
;
1111 wrap
.container_cgroup
= ops
->container_cgroup
;
1112 wrap
.hierarchies
= ops
->hierarchies
;
1113 wrap
.conf
= handler
->conf
;
1115 if (handler
->conf
&& !lxc_list_empty(&handler
->conf
->id_map
))
1116 ret
= userns_exec_1(handler
->conf
, cgroup_rmdir_wrapper
, &wrap
,
1117 "cgroup_rmdir_wrapper");
1119 ret
= cgroup_rmdir(ops
->hierarchies
, ops
->container_cgroup
);
1121 WARN("Failed to destroy cgroups");
1126 static bool cg_unified_create_cgroup(struct hierarchy
*h
, char *cgname
)
1128 size_t i
, parts_len
;
1130 size_t full_len
= 0;
1131 char *add_controllers
= NULL
, *cgroup
= NULL
;
1132 char **parts
= NULL
;
1135 if (h
->version
!= CGROUP2_SUPER_MAGIC
)
1138 if (!h
->controllers
)
1141 /* For now we simply enable all controllers that we have detected by
1142 * creating a string like "+memory +pids +cpu +io".
1143 * TODO: In the near future we might want to support "-<controller>"
1144 * etc. but whether supporting semantics like this make sense will need
1147 for (it
= h
->controllers
; it
&& *it
; it
++) {
1148 full_len
+= strlen(*it
) + 2;
1149 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
1151 if (h
->controllers
[0] == *it
)
1152 add_controllers
[0] = '\0';
1154 (void)strlcat(add_controllers
, "+", full_len
+ 1);
1155 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
1157 if ((it
+ 1) && *(it
+ 1))
1158 (void)strlcat(add_controllers
, " ", full_len
+ 1);
1161 parts
= lxc_string_split(cgname
, '/');
1165 parts_len
= lxc_array_len((void **)parts
);
1169 cgroup
= must_make_path(h
->mountpoint
, h
->container_base_path
, NULL
);
1170 for (i
= 0; i
< parts_len
; i
++) {
1174 cgroup
= must_append_path(cgroup
, parts
[i
], NULL
);
1175 target
= must_make_path(cgroup
, "cgroup.subtree_control", NULL
);
1176 ret
= lxc_write_to_file(target
, add_controllers
, full_len
, false, 0666);
1179 SYSERROR("Could not enable \"%s\" controllers in the "
1180 "unified cgroup \"%s\"", add_controllers
, cgroup
);
1188 lxc_free_array((void **)parts
, free
);
1189 free(add_controllers
);
1194 static bool monitor_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1198 h
->monitor_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1199 if (dir_exists(h
->monitor_full_path
))
1202 ret
= mkdir_p(h
->monitor_full_path
, 0755);
1204 ERROR("Failed to create cgroup \"%s\"", h
->monitor_full_path
);
1208 return cg_unified_create_cgroup(h
, cgname
);
1211 static bool container_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1215 h
->container_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1216 if (dir_exists(h
->container_full_path
)) {
1217 ERROR("The cgroup \"%s\" already existed", h
->container_full_path
);
1221 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1222 ERROR("Failed to handle legacy cpuset controller");
1226 ret
= mkdir_p(h
->container_full_path
, 0755);
1228 ERROR("Failed to create cgroup \"%s\"", h
->container_full_path
);
1232 return cg_unified_create_cgroup(h
, cgname
);
1235 static void remove_path_for_hierarchy(struct hierarchy
*h
, char *cgname
, bool monitor
)
1241 full_path
= h
->monitor_full_path
;
1243 full_path
= h
->container_full_path
;
1245 ret
= rmdir(full_path
);
1247 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", full_path
);
1252 h
->monitor_full_path
= NULL
;
1254 h
->container_full_path
= NULL
;
1257 __cgfsng_ops
static inline bool cgfsng_monitor_create(struct cgroup_ops
*ops
,
1258 struct lxc_handler
*handler
)
1260 char *monitor_cgroup
;
1262 struct lxc_conf
*conf
= handler
->conf
;
1267 if (conf
->cgroup_meta
.dir
)
1268 monitor_cgroup
= lxc_string_join("/", (const char *[]){conf
->cgroup_meta
.dir
, ops
->monitor_pattern
, handler
->name
, NULL
}, false);
1270 monitor_cgroup
= must_make_path(ops
->monitor_pattern
, handler
->name
, NULL
);
1271 if (!monitor_cgroup
)
1274 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1275 if (!monitor_create_path_for_hierarchy(ops
->hierarchies
[i
], monitor_cgroup
)) {
1276 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->monitor_full_path
);
1277 free(ops
->hierarchies
[i
]->container_full_path
);
1278 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1279 for (int j
= 0; j
< i
; j
++)
1280 remove_path_for_hierarchy(ops
->hierarchies
[j
], monitor_cgroup
, true);
1288 free(monitor_cgroup
);
1293 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1294 * next cgroup_pattern-1, -2, ..., -999.
1296 __cgfsng_ops
static inline bool cgfsng_payload_create(struct cgroup_ops
*ops
,
1297 struct lxc_handler
*handler
)
1301 char *container_cgroup
, *offset
, *tmp
;
1303 struct lxc_conf
*conf
= handler
->conf
;
1305 if (ops
->container_cgroup
) {
1306 WARN("cgfsng_create called a second time: %s", ops
->container_cgroup
);
1313 if (conf
->cgroup_meta
.dir
)
1314 tmp
= lxc_string_join("/", (const char *[]){conf
->cgroup_meta
.dir
, handler
->name
, NULL
}, false);
1316 tmp
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1318 ERROR("Failed expanding cgroup name pattern");
1322 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1323 container_cgroup
= must_alloc(len
);
1324 (void)strlcpy(container_cgroup
, tmp
, len
);
1326 offset
= container_cgroup
+ len
- 5;
1330 ERROR("Too many conflicting cgroup names");
1337 ret
= snprintf(offset
, 5, "-%d", idx
);
1338 if (ret
< 0 || (size_t)ret
>= 5) {
1339 FILE *f
= fopen("/dev/null", "w");
1341 fprintf(f
, "Workaround for GCC7 bug: "
1342 "https://gcc.gnu.org/bugzilla/"
1343 "show_bug.cgi?id=78969");
1349 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1350 if (!container_create_path_for_hierarchy(ops
->hierarchies
[i
], container_cgroup
)) {
1351 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->container_full_path
);
1352 free(ops
->hierarchies
[i
]->container_full_path
);
1353 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1354 for (int j
= 0; j
< i
; j
++)
1355 remove_path_for_hierarchy(ops
->hierarchies
[j
], container_cgroup
, false);
1361 ops
->container_cgroup
= container_cgroup
;
1366 free(container_cgroup
);
1371 __cgfsng_ops
static bool __do_cgroup_enter(struct cgroup_ops
*ops
, pid_t pid
,
1377 len
= snprintf(pidstr
, 25, "%d", pid
);
1378 if (len
< 0 || len
>= 25)
1381 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1386 path
= must_make_path(ops
->hierarchies
[i
]->monitor_full_path
,
1387 "cgroup.procs", NULL
);
1389 path
= must_make_path(ops
->hierarchies
[i
]->container_full_path
,
1390 "cgroup.procs", NULL
);
1391 ret
= lxc_write_to_file(path
, pidstr
, len
, false, 0666);
1393 SYSERROR("Failed to enter cgroup \"%s\"", path
);
1403 __cgfsng_ops
static bool cgfsng_monitor_enter(struct cgroup_ops
*ops
, pid_t pid
)
1405 return __do_cgroup_enter(ops
, pid
, true);
1408 static bool cgfsng_payload_enter(struct cgroup_ops
*ops
, pid_t pid
)
1410 return __do_cgroup_enter(ops
, pid
, false);
1413 static int chowmod(char *path
, uid_t chown_uid
, gid_t chown_gid
,
1418 ret
= chown(path
, chown_uid
, chown_gid
);
1420 SYSWARN("Failed to chown(%s, %d, %d)", path
, (int)chown_uid
, (int)chown_gid
);
1424 ret
= chmod(path
, chmod_mode
);
1426 SYSWARN("Failed to chmod(%s, %d)", path
, (int)chmod_mode
);
1433 /* chgrp the container cgroups to container group. We leave
1434 * the container owner as cgroup owner. So we must make the
1435 * directories 775 so that the container can create sub-cgroups.
1437 * Also chown the tasks and cgroup.procs files. Those may not
1438 * exist depending on kernel version.
1440 static int chown_cgroup_wrapper(void *data
)
1444 struct generic_userns_exec_data
*arg
= data
;
1445 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1446 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1448 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1450 SYSERROR("Failed to setresgid(%d, %d, %d)",
1451 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1455 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1457 SYSERROR("Failed to setresuid(%d, %d, %d)",
1458 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1462 ret
= setgroups(0, NULL
);
1463 if (ret
< 0 && errno
!= EPERM
) {
1464 SYSERROR("Failed to setgroups(0, NULL)");
1468 destuid
= get_ns_uid(arg
->origuid
);
1469 if (destuid
== LXC_INVALID_UID
)
1472 for (i
= 0; arg
->hierarchies
[i
]; i
++) {
1474 char *path
= arg
->hierarchies
[i
]->container_full_path
;
1476 ret
= chowmod(path
, destuid
, nsgid
, 0775);
1480 /* Failures to chown() these are inconvenient but not
1481 * detrimental We leave these owned by the container launcher,
1482 * so that container root can write to the files to attach. We
1483 * chmod() them 664 so that container systemd can write to the
1484 * files (which systemd in wily insists on doing).
1487 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
) {
1488 fullpath
= must_make_path(path
, "tasks", NULL
);
1489 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1493 fullpath
= must_make_path(path
, "cgroup.procs", NULL
);
1494 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1497 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1500 fullpath
= must_make_path(path
, "cgroup.subtree_control", NULL
);
1501 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1504 fullpath
= must_make_path(path
, "cgroup.threads", NULL
);
1505 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1512 __cgfsng_ops
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1513 struct lxc_conf
*conf
)
1515 struct generic_userns_exec_data wrap
;
1517 if (lxc_list_empty(&conf
->id_map
))
1520 wrap
.origuid
= geteuid();
1522 wrap
.hierarchies
= ops
->hierarchies
;
1525 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
,
1526 "chown_cgroup_wrapper") < 0) {
1527 ERROR("Error requesting cgroup chown in new user namespace");
1534 /* cgroup-full:* is done, no need to create subdirs */
1535 static bool cg_mount_needs_subdirs(int type
)
1537 if (type
>= LXC_AUTO_CGROUP_FULL_RO
)
1543 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1544 * remount controller ro if needed and bindmount the cgroupfs onto
1545 * controll/the/cg/path.
1547 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1548 char *controllerpath
, char *cgpath
,
1549 const char *container_cgroup
)
1551 int ret
, remount_flags
;
1553 int flags
= MS_BIND
;
1555 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1556 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1558 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
1559 controllerpath
, controllerpath
);
1563 remount_flags
= add_required_remount_flags(controllerpath
,
1565 flags
| MS_REMOUNT
);
1566 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1567 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1570 SYSERROR("Failed to remount \"%s\" ro", controllerpath
);
1574 INFO("Remounted %s read-only", controllerpath
);
1577 sourcepath
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1578 container_cgroup
, NULL
);
1579 if (type
== LXC_AUTO_CGROUP_RO
)
1582 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1584 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1588 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1590 if (flags
& MS_RDONLY
) {
1591 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1592 flags
| MS_REMOUNT
);
1593 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1595 SYSERROR("Failed to remount \"%s\" ro", cgpath
);
1599 INFO("Remounted %s read-only", cgpath
);
1603 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1607 /* __cg_mount_direct
1609 * Mount cgroup hierarchies directly without using bind-mounts. The main
1610 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1611 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1613 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1614 const char *controllerpath
)
1617 char *controllers
= NULL
;
1618 char *fstype
= "cgroup2";
1619 unsigned long flags
= 0;
1624 flags
|= MS_RELATIME
;
1626 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1629 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1630 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1636 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1639 SYSERROR("Failed to mount \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1643 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1647 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1648 const char *controllerpath
)
1650 return __cg_mount_direct(type
, h
, controllerpath
);
1653 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1654 const char *controllerpath
)
1656 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1659 return __cg_mount_direct(type
, h
, controllerpath
);
1662 __cgfsng_ops
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1663 struct lxc_handler
*handler
,
1664 const char *root
, int type
)
1667 char *tmpfspath
= NULL
;
1668 bool has_cgns
= false, retval
= false, wants_force_mount
= false;
1670 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1673 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1674 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1675 wants_force_mount
= true;
1678 if (!wants_force_mount
){
1679 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1680 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1682 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1685 has_cgns
= cgns_supported();
1686 if (has_cgns
&& !wants_force_mount
)
1689 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1690 type
= LXC_AUTO_CGROUP_MIXED
;
1691 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1692 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1695 tmpfspath
= must_make_path(root
, "/sys/fs/cgroup", NULL
);
1696 ret
= safe_mount(NULL
, tmpfspath
, "tmpfs",
1697 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1698 "size=10240k,mode=755", root
);
1702 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1703 char *controllerpath
, *path2
;
1704 struct hierarchy
*h
= ops
->hierarchies
[i
];
1705 char *controller
= strrchr(h
->mountpoint
, '/');
1711 controllerpath
= must_make_path(tmpfspath
, controller
, NULL
);
1712 if (dir_exists(controllerpath
)) {
1713 free(controllerpath
);
1717 ret
= mkdir(controllerpath
, 0755);
1719 SYSERROR("Error creating cgroup path: %s", controllerpath
);
1720 free(controllerpath
);
1724 if (has_cgns
&& wants_force_mount
) {
1725 /* If cgroup namespaces are supported but the container
1726 * will not have CAP_SYS_ADMIN after it has started we
1727 * need to mount the cgroups manually.
1729 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1730 free(controllerpath
);
1737 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1739 free(controllerpath
);
1743 if (!cg_mount_needs_subdirs(type
)) {
1744 free(controllerpath
);
1748 path2
= must_make_path(controllerpath
, h
->container_base_path
,
1749 ops
->container_cgroup
, NULL
);
1750 ret
= mkdir_p(path2
, 0755);
1752 free(controllerpath
);
1757 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1758 path2
, ops
->container_cgroup
);
1759 free(controllerpath
);
1771 static int recursive_count_nrtasks(char *dirname
)
1773 struct dirent
*direntp
;
1778 dir
= opendir(dirname
);
1782 while ((direntp
= readdir(dir
))) {
1785 if (!strcmp(direntp
->d_name
, ".") ||
1786 !strcmp(direntp
->d_name
, ".."))
1789 path
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1791 if (lstat(path
, &mystat
))
1794 if (!S_ISDIR(mystat
.st_mode
))
1797 count
+= recursive_count_nrtasks(path
);
1802 path
= must_make_path(dirname
, "cgroup.procs", NULL
);
1803 ret
= lxc_count_file_lines(path
);
1808 (void)closedir(dir
);
1813 __cgfsng_ops
static int cgfsng_nrtasks(struct cgroup_ops
*ops
)
1818 if (!ops
->container_cgroup
|| !ops
->hierarchies
)
1821 path
= must_make_path(ops
->hierarchies
[0]->container_full_path
, NULL
);
1822 count
= recursive_count_nrtasks(path
);
1827 /* Only root needs to escape to the cgroup of its init. */
1828 __cgfsng_ops
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1829 struct lxc_conf
*conf
)
1833 if (conf
->cgroup_meta
.relative
|| geteuid())
1836 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1840 fullpath
= must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1841 ops
->hierarchies
[i
]->container_base_path
,
1842 "cgroup.procs", NULL
);
1843 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1845 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath
);
1855 __cgfsng_ops
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1859 for (i
= 0; ops
->hierarchies
[i
]; i
++)
1865 __cgfsng_ops
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
, char ***out
)
1869 /* sanity check n */
1870 for (i
= 0; i
< n
; i
++)
1871 if (!ops
->hierarchies
[i
])
1874 *out
= ops
->hierarchies
[i
]->controllers
;
1879 #define THAWED "THAWED"
1880 #define THAWED_LEN (strlen(THAWED))
1882 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
1885 __cgfsng_ops
static bool cgfsng_unfreeze(struct cgroup_ops
*ops
)
1889 struct hierarchy
*h
;
1891 h
= get_hierarchy(ops
, "freezer");
1895 fullpath
= must_make_path(h
->container_full_path
, "freezer.state", NULL
);
1896 ret
= lxc_write_to_file(fullpath
, THAWED
, THAWED_LEN
, false, 0666);
1904 __cgfsng_ops
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
1905 const char *controller
)
1907 struct hierarchy
*h
;
1909 h
= get_hierarchy(ops
, controller
);
1911 WARN("Failed to find hierarchy for controller \"%s\"",
1912 controller
? controller
: "(null)");
1916 return h
->container_full_path
? h
->container_full_path
+ strlen(h
->mountpoint
) : NULL
;
1919 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
1920 * which must be freed by the caller.
1922 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
1924 const char *filename
)
1926 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
1929 /* Technically, we're always at a delegation boundary here (This is especially
1930 * true when cgroup namespaces are available.). The reasoning is that in order
1931 * for us to have been able to start a container in the first place the root
1932 * cgroup must have been a leaf node. Now, either the container's init system
1933 * has populated the cgroup and kept it as a leaf node or it has created
1934 * subtrees. In the former case we will simply attach to the leaf node we
1935 * created when we started the container in the latter case we create our own
1936 * cgroup for the attaching process.
1938 static int __cg_unified_attach(const struct hierarchy
*h
, const char *name
,
1939 const char *lxcpath
, const char *pidstr
,
1940 size_t pidstr_len
, const char *controller
)
1944 int fret
= -1, idx
= 0;
1945 char *base_path
= NULL
, *container_cgroup
= NULL
, *full_path
= NULL
;
1947 container_cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
1949 if (!container_cgroup
)
1952 base_path
= must_make_path(h
->mountpoint
, container_cgroup
, NULL
);
1953 full_path
= must_make_path(base_path
, "cgroup.procs", NULL
);
1954 /* cgroup is populated */
1955 ret
= lxc_write_to_file(full_path
, pidstr
, pidstr_len
, false, 0666);
1956 if (ret
< 0 && errno
!= EBUSY
)
1964 len
= strlen(base_path
) + sizeof("/lxc-1000") - 1 +
1965 sizeof("/cgroup-procs") - 1;
1966 full_path
= must_alloc(len
+ 1);
1969 ret
= snprintf(full_path
, len
+ 1, "%s/lxc-%d",
1972 ret
= snprintf(full_path
, len
+ 1, "%s/lxc", base_path
);
1973 if (ret
< 0 || (size_t)ret
>= len
+ 1)
1976 ret
= mkdir_p(full_path
, 0755);
1977 if (ret
< 0 && errno
!= EEXIST
)
1980 (void)strlcat(full_path
, "/cgroup.procs", len
+ 1);
1981 ret
= lxc_write_to_file(full_path
, pidstr
, len
, false, 0666);
1985 /* this is a non-leaf node */
1989 } while (++idx
> 0 && idx
< 1000);
1997 free(container_cgroup
);
2003 __cgfsng_ops
static bool cgfsng_attach(struct cgroup_ops
*ops
, const char *name
,
2004 const char *lxcpath
, pid_t pid
)
2009 len
= snprintf(pidstr
, 25, "%d", pid
);
2010 if (len
< 0 || len
>= 25)
2013 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
2015 char *fullpath
= NULL
;
2016 struct hierarchy
*h
= ops
->hierarchies
[i
];
2018 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2019 ret
= __cg_unified_attach(h
, name
, lxcpath
, pidstr
, len
,
2027 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2032 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2034 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2036 SYSERROR("Failed to attach %d to %s", (int)pid
, fullpath
);
2046 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2047 * don't have a cgroup_data set up, so we ask the running container through the
2048 * commands API for the cgroup path.
2050 __cgfsng_ops
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
2051 char *value
, size_t len
, const char *name
,
2052 const char *lxcpath
)
2055 size_t controller_len
;
2056 char *controller
, *p
, *path
;
2057 struct hierarchy
*h
;
2059 controller_len
= strlen(filename
);
2060 controller
= alloca(controller_len
+ 1);
2061 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2063 p
= strchr(controller
, '.');
2067 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2072 h
= get_hierarchy(ops
, controller
);
2076 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2077 ret
= lxc_read_from_file(fullpath
, value
, len
);
2085 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2086 * don't have a cgroup_data set up, so we ask the running container through the
2087 * commands API for the cgroup path.
2089 __cgfsng_ops
static int cgfsng_set(struct cgroup_ops
*ops
,
2090 const char *filename
, const char *value
,
2091 const char *name
, const char *lxcpath
)
2094 size_t controller_len
;
2095 char *controller
, *p
, *path
;
2096 struct hierarchy
*h
;
2098 controller_len
= strlen(filename
);
2099 controller
= alloca(controller_len
+ 1);
2100 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2102 p
= strchr(controller
, '.');
2106 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2111 h
= get_hierarchy(ops
, controller
);
2115 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2116 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2124 /* take devices cgroup line
2126 * and convert it to a valid
2127 * type major:minor mode
2128 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2131 static int convert_devpath(const char *invalue
, char *dest
)
2134 char *p
, *path
, type
;
2135 unsigned long minor
, major
;
2140 path
= must_copy_string(invalue
);
2142 /* Read path followed by mode. Ignore any trailing text.
2143 * A ' # comment' would be legal. Technically other text is not
2144 * legal, we could check for that if we cared to.
2146 for (n_parts
= 1, p
= path
; *p
&& n_parts
< 3; p
++) {
2168 ret
= stat(path
, &sb
);
2172 mode_t m
= sb
.st_mode
& S_IFMT
;
2181 ERROR("Unsupported device type %i for \"%s\"", m
, path
);
2186 major
= MAJOR(sb
.st_rdev
);
2187 minor
= MINOR(sb
.st_rdev
);
2188 ret
= snprintf(dest
, 50, "%c %lu:%lu %s", type
, major
, minor
, mode
);
2189 if (ret
< 0 || ret
>= 50) {
2190 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2191 "chars)", type
, major
, minor
, mode
);
2192 ret
= -ENAMETOOLONG
;
2202 /* Called from setup_limits - here we have the container's cgroup_data because
2203 * we created the cgroups.
2205 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2210 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2211 char converted_value
[50];
2212 struct hierarchy
*h
;
2214 char *controller
= NULL
;
2216 len
= strlen(filename
);
2217 controller
= alloca(len
+ 1);
2218 (void)strlcpy(controller
, filename
, len
+ 1);
2220 p
= strchr(controller
, '.');
2224 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2225 ret
= convert_devpath(value
, converted_value
);
2228 value
= converted_value
;
2231 h
= get_hierarchy(ops
, controller
);
2233 ERROR("Failed to setup limits for the \"%s\" controller. "
2234 "The controller seems to be unused by \"cgfsng\" cgroup "
2235 "driver or not enabled on the cgroup hierarchy",
2241 fullpath
= must_make_path(h
->container_full_path
, filename
, NULL
);
2242 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2247 static bool __cg_legacy_setup_limits(struct cgroup_ops
*ops
,
2248 struct lxc_list
*cgroup_settings
,
2251 struct lxc_list
*iterator
, *next
, *sorted_cgroup_settings
;
2252 struct lxc_cgroup
*cg
;
2255 if (lxc_list_empty(cgroup_settings
))
2258 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2259 if (!sorted_cgroup_settings
)
2262 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2263 cg
= iterator
->elem
;
2265 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2266 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
)) {
2267 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2268 WARN("Failed to set \"%s\" to \"%s\"",
2269 cg
->subsystem
, cg
->value
);
2272 WARN("Failed to set \"%s\" to \"%s\"",
2273 cg
->subsystem
, cg
->value
);
2276 DEBUG("Set controller \"%s\" set to \"%s\"",
2277 cg
->subsystem
, cg
->value
);
2282 INFO("Limits for the legacy cgroup hierarchies have been setup");
2284 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2285 lxc_list_del(iterator
);
2288 free(sorted_cgroup_settings
);
2292 static bool __cg_unified_setup_limits(struct cgroup_ops
*ops
,
2293 struct lxc_list
*cgroup_settings
)
2295 struct lxc_list
*iterator
;
2296 struct hierarchy
*h
= ops
->unified
;
2298 if (lxc_list_empty(cgroup_settings
))
2304 lxc_list_for_each(iterator
, cgroup_settings
) {
2307 struct lxc_cgroup
*cg
= iterator
->elem
;
2309 fullpath
= must_make_path(h
->container_full_path
, cg
->subsystem
, NULL
);
2310 ret
= lxc_write_to_file(fullpath
, cg
->value
, strlen(cg
->value
), false, 0666);
2313 SYSERROR("Failed to set \"%s\" to \"%s\"",
2314 cg
->subsystem
, cg
->value
);
2317 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2320 INFO("Limits for the unified cgroup hierarchy have been setup");
2324 __cgfsng_ops
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2325 struct lxc_conf
*conf
,
2330 bret
= __cg_legacy_setup_limits(ops
, &conf
->cgroup
, do_devices
);
2334 return __cg_unified_setup_limits(ops
, &conf
->cgroup2
);
2337 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
2340 char **cur_ctrl
, **cur_use
;
2342 if (!ops
->cgroup_use
)
2345 for (cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
2348 for (cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
2349 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
2365 /* At startup, parse_hierarchies finds all the info we need about cgroup
2366 * mountpoints and current cgroups, and stores it in @d.
2368 static bool cg_hybrid_init(struct cgroup_ops
*ops
, bool relative
)
2375 char **klist
= NULL
, **nlist
= NULL
;
2377 /* Root spawned containers escape the current cgroup, so use init's
2378 * cgroups as our base in that case.
2380 if (!relative
&& (geteuid() == 0))
2381 basecginfo
= read_file("/proc/1/cgroup");
2383 basecginfo
= read_file("/proc/self/cgroup");
2387 ret
= get_existing_subsystems(&klist
, &nlist
);
2389 ERROR("Failed to retrieve available legacy cgroup controllers");
2394 f
= fopen("/proc/self/mountinfo", "r");
2396 ERROR("Failed to open \"/proc/self/mountinfo\"");
2401 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
2403 while (getline(&line
, &len
, f
) != -1) {
2406 struct hierarchy
*new;
2407 char *base_cgroup
= NULL
, *mountpoint
= NULL
;
2408 char **controller_list
= NULL
;
2410 type
= get_cgroup_version(line
);
2414 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
2417 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
2418 if (type
== CGROUP2_SUPER_MAGIC
)
2419 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2420 else if (type
== CGROUP_SUPER_MAGIC
)
2421 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
2422 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
2423 if (type
== CGROUP_SUPER_MAGIC
)
2424 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2425 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
2426 if (type
== CGROUP2_SUPER_MAGIC
)
2427 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2430 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
2431 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
2434 if (type
== CGROUP_SUPER_MAGIC
)
2435 if (controller_list_is_dup(ops
->hierarchies
, controller_list
))
2438 mountpoint
= cg_hybrid_get_mountpoint(line
);
2440 ERROR("Failed parsing mountpoint from \"%s\"", line
);
2444 if (type
== CGROUP_SUPER_MAGIC
)
2445 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
2447 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
2449 ERROR("Failed to find current cgroup");
2454 prune_init_scope(base_cgroup
);
2455 if (type
== CGROUP2_SUPER_MAGIC
)
2456 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
2458 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
2462 if (type
== CGROUP2_SUPER_MAGIC
) {
2463 char *cgv2_ctrl_path
;
2465 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
2466 "cgroup.controllers",
2469 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
2470 free(cgv2_ctrl_path
);
2471 if (!controller_list
) {
2472 controller_list
= cg_unified_make_empty_controller();
2473 TRACE("No controllers are enabled for "
2474 "delegation in the unified hierarchy");
2478 /* Exclude all controllers that cgroup use does not want. */
2479 if (!cgroup_use_wants_controllers(ops
, controller_list
))
2482 new = add_hierarchy(&ops
->hierarchies
, controller_list
, mountpoint
, base_cgroup
, type
);
2483 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
)
2489 free_string_list(controller_list
);
2494 free_string_list(klist
);
2495 free_string_list(nlist
);
2502 TRACE("Writable cgroup hierarchies:");
2503 lxc_cgfsng_print_hierarchies(ops
);
2505 /* verify that all controllers in cgroup.use and all crucial
2506 * controllers are accounted for
2508 if (!all_controllers_found(ops
))
2514 static int cg_is_pure_unified(void)
2520 ret
= statfs("/sys/fs/cgroup", &fs
);
2524 if (is_fs_type(&fs
, CGROUP2_SUPER_MAGIC
))
2525 return CGROUP2_SUPER_MAGIC
;
2530 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
2531 static char *cg_unified_get_current_cgroup(bool relative
)
2533 char *basecginfo
, *base_cgroup
;
2536 if (!relative
&& (geteuid() == 0))
2537 basecginfo
= read_file("/proc/1/cgroup");
2539 basecginfo
= read_file("/proc/self/cgroup");
2543 base_cgroup
= strstr(basecginfo
, "0::/");
2545 goto cleanup_on_err
;
2547 base_cgroup
= base_cgroup
+ 3;
2548 copy
= copy_to_eol(base_cgroup
);
2550 goto cleanup_on_err
;
2560 static int cg_unified_init(struct cgroup_ops
*ops
, bool relative
)
2563 char *mountpoint
, *subtree_path
;
2565 char *base_cgroup
= NULL
;
2567 ret
= cg_is_pure_unified();
2568 if (ret
== -ENOMEDIUM
)
2571 if (ret
!= CGROUP2_SUPER_MAGIC
)
2574 base_cgroup
= cg_unified_get_current_cgroup(relative
);
2577 prune_init_scope(base_cgroup
);
2579 /* We assume that we have already been given controllers to delegate
2580 * further down the hierarchy. If not it is up to the user to delegate
2583 mountpoint
= must_copy_string("/sys/fs/cgroup");
2584 subtree_path
= must_make_path(mountpoint
, base_cgroup
,
2585 "cgroup.subtree_control", NULL
);
2586 delegatable
= cg_unified_get_controllers(subtree_path
);
2589 delegatable
= cg_unified_make_empty_controller();
2590 if (!delegatable
[0])
2591 TRACE("No controllers are enabled for delegation");
2593 /* TODO: If the user requested specific controllers via lxc.cgroup.use
2594 * we should verify here. The reason I'm not doing it right is that I'm
2595 * not convinced that lxc.cgroup.use will be the future since it is a
2596 * global property. I much rather have an option that lets you request
2597 * controllers per container.
2600 add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
2602 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2603 return CGROUP2_SUPER_MAGIC
;
2606 static bool cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
2610 bool relative
= conf
->cgroup_meta
.relative
;
2612 tmp
= lxc_global_config_value("lxc.cgroup.use");
2614 char *chop
, *cur
, *pin
;
2616 pin
= must_copy_string(tmp
);
2619 lxc_iterate_parts(cur
, chop
, ",") {
2620 must_append_string(&ops
->cgroup_use
, cur
);
2626 ret
= cg_unified_init(ops
, relative
);
2630 if (ret
== CGROUP2_SUPER_MAGIC
)
2633 return cg_hybrid_init(ops
, relative
);
2636 __cgfsng_ops
static bool cgfsng_data_init(struct cgroup_ops
*ops
)
2638 const char *cgroup_pattern
;
2640 /* copy system-wide cgroup information */
2641 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
2642 if (!cgroup_pattern
) {
2643 /* lxc.cgroup.pattern is only NULL on error. */
2644 ERROR("Failed to retrieve cgroup pattern");
2647 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
2648 ops
->monitor_pattern
= must_copy_string("lxc.monitor");
2653 struct cgroup_ops
*cgfsng_ops_init(struct lxc_conf
*conf
)
2655 struct cgroup_ops
*cgfsng_ops
;
2657 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
2661 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
2662 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
2664 if (!cg_init(cgfsng_ops
, conf
)) {
2669 cgfsng_ops
->data_init
= cgfsng_data_init
;
2670 cgfsng_ops
->destroy
= cgfsng_destroy
;
2671 cgfsng_ops
->monitor_create
= cgfsng_monitor_create
;
2672 cgfsng_ops
->monitor_enter
= cgfsng_monitor_enter
;
2673 cgfsng_ops
->payload_create
= cgfsng_payload_create
;
2674 cgfsng_ops
->payload_enter
= cgfsng_payload_enter
;
2675 cgfsng_ops
->escape
= cgfsng_escape
;
2676 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
2677 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
2678 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
2679 cgfsng_ops
->get
= cgfsng_get
;
2680 cgfsng_ops
->set
= cgfsng_set
;
2681 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
2682 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
2683 cgfsng_ops
->driver
= "cgfsng";
2684 cgfsng_ops
->version
= "1.0.0";
2685 cgfsng_ops
->attach
= cgfsng_attach
;
2686 cgfsng_ops
->chown
= cgfsng_chown
;
2687 cgfsng_ops
->mount
= cgfsng_mount
;
2688 cgfsng_ops
->nrtasks
= cgfsng_nrtasks
;