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.
44 #include <linux/kdev_t.h>
45 #include <linux/types.h>
50 #include <sys/types.h>
55 #include "cgroup_utils.h"
61 #include "storage/storage.h"
65 #include "include/strlcpy.h"
69 #include "include/strlcat.h"
72 lxc_log_define(cgfsng
, cgroup
);
74 static void free_string_list(char **clist
)
81 for (i
= 0; clist
[i
]; i
++)
87 /* Allocate a pointer, do not fail. */
88 static void *must_alloc(size_t sz
)
90 return must_realloc(NULL
, sz
);
93 /* Given a pointer to a null-terminated array of pointers, realloc to add one
94 * entry, and point the new entry to NULL. Do not fail. Return the index to the
95 * second-to-last entry - that is, the one which is now available for use
96 * (keeping the list null-terminated).
98 static int append_null_to_list(void ***list
)
103 for (; (*list
)[newentry
]; newentry
++)
106 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
107 (*list
)[newentry
+ 1] = NULL
;
111 /* Given a null-terminated array of strings, check whether @entry is one of the
114 static bool string_in_list(char **list
, const char *entry
)
121 for (i
= 0; list
[i
]; i
++)
122 if (strcmp(list
[i
], entry
) == 0)
128 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
129 * "name=systemd". Do not fail.
131 static char *cg_legacy_must_prefix_named(char *entry
)
137 prefixed
= must_alloc(len
+ 6);
139 memcpy(prefixed
, "name=", STRLITERALLEN("name="));
140 memcpy(prefixed
+ STRLITERALLEN("name="), entry
, len
);
141 prefixed
[len
+ 5] = '\0';
146 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
149 * We also handle named subsystems here. Any controller which is not a kernel
150 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
151 * we refuse to use because we're not sure which we have here.
152 * (TODO: We could work around this in some cases by just remounting to be
153 * unambiguous, or by comparing mountpoint contents with current cgroup.)
155 * The last entry will always be NULL.
157 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
163 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
164 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
165 ERROR("It is both a named and kernel subsystem");
169 newentry
= append_null_to_list((void ***)clist
);
171 if (strncmp(entry
, "name=", 5) == 0)
172 copy
= must_copy_string(entry
);
173 else if (string_in_list(klist
, entry
))
174 copy
= must_copy_string(entry
);
176 copy
= cg_legacy_must_prefix_named(entry
);
178 (*clist
)[newentry
] = copy
;
181 /* Given a handler's cgroup data, return the struct hierarchy for the controller
182 * @c, or NULL if there is none.
184 struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *controller
)
190 if (!ops
->hierarchies
) {
191 TRACE("There are no useable cgroup controllers");
195 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
197 /* This is the empty unified hierarchy. */
198 if (ops
->hierarchies
[i
]->controllers
&&
199 !ops
->hierarchies
[i
]->controllers
[0])
200 return ops
->hierarchies
[i
];
205 if (string_in_list(ops
->hierarchies
[i
]->controllers
, controller
))
206 return ops
->hierarchies
[i
];
210 WARN("There is no useable %s controller", controller
);
212 WARN("There is no empty unified cgroup hierarchy");
217 #define BATCH_SIZE 50
218 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
220 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
221 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
223 if (!*mem
|| newbatches
> oldbatches
) {
224 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
228 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
230 size_t full
= oldlen
+ newlen
;
232 batch_realloc(dest
, oldlen
, full
+ 1);
234 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
237 /* Slurp in a whole file */
238 static char *read_file(const char *fnam
)
241 char *line
= NULL
, *buf
= NULL
;
242 size_t len
= 0, fulllen
= 0;
245 f
= fopen(fnam
, "r");
248 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
249 append_line(&buf
, fulllen
, line
, linelen
);
257 /* Taken over modified from the kernel sources. */
258 #define NBITS 32 /* bits in uint32_t */
259 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
260 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
262 static void set_bit(unsigned bit
, uint32_t *bitarr
)
264 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
267 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
269 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
272 static bool is_set(unsigned bit
, uint32_t *bitarr
)
274 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
277 /* Create cpumask from cpulist aka turn:
285 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
291 arrlen
= BITS_TO_LONGS(nbits
);
292 bitarr
= calloc(arrlen
, sizeof(uint32_t));
296 lxc_iterate_parts(token
, buf
, ",") {
301 start
= strtoul(token
, NULL
, 0);
303 range
= strchr(token
, '-');
305 end
= strtoul(range
+ 1, NULL
, 0);
307 if (!(start
<= end
)) {
318 set_bit(start
++, bitarr
);
324 /* Turn cpumask into simple, comma-separated cpulist. */
325 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
329 char **cpulist
= NULL
;
330 char numstr
[INTTYPE_TO_STRLEN(size_t)] = {0};
332 for (i
= 0; i
<= nbits
; i
++) {
333 if (!is_set(i
, bitarr
))
336 ret
= snprintf(numstr
, sizeof(numstr
), "%zu", i
);
337 if (ret
< 0 || (size_t)ret
>= sizeof(numstr
)) {
338 lxc_free_array((void **)cpulist
, free
);
342 ret
= lxc_append_string(&cpulist
, numstr
);
344 lxc_free_array((void **)cpulist
, free
);
352 return lxc_string_join(",", (const char **)cpulist
, false);
355 static ssize_t
get_max_cpus(char *cpulist
)
358 char *maxcpus
= cpulist
;
361 c1
= strrchr(maxcpus
, ',');
365 c2
= strrchr(maxcpus
, '-');
379 cpus
= strtoul(c1
, NULL
, 0);
386 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
387 static bool cg_legacy_filter_and_set_cpus(char *path
, bool am_initialized
)
391 char *lastslash
, *fpath
, oldv
;
392 ssize_t maxisol
= 0, maxposs
= 0;
393 char *cpulist
= NULL
, *isolcpus
= NULL
, *posscpus
= NULL
;
394 uint32_t *isolmask
= NULL
, *possmask
= NULL
;
395 bool bret
= false, flipped_bit
= false;
397 lastslash
= strrchr(path
, '/');
399 ERROR("Failed to detect \"/\" in \"%s\"", path
);
404 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
405 posscpus
= read_file(fpath
);
407 SYSERROR("Failed to read file \"%s\"", fpath
);
411 /* Get maximum number of cpus found in possible cpuset. */
412 maxposs
= get_max_cpus(posscpus
);
413 if (maxposs
< 0 || maxposs
>= INT_MAX
- 1)
416 if (!file_exists(__ISOL_CPUS
)) {
417 /* This system doesn't expose isolated cpus. */
418 DEBUG("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
420 /* No isolated cpus but we weren't already initialized by
421 * someone. We should simply copy the parents cpuset.cpus
424 if (!am_initialized
) {
425 DEBUG("Copying cpu settings of parent cgroup");
428 /* No isolated cpus but we were already initialized by someone.
429 * Nothing more to do for us.
434 isolcpus
= read_file(__ISOL_CPUS
);
436 SYSERROR("Failed to read file \""__ISOL_CPUS
"\"");
439 if (!isdigit(isolcpus
[0])) {
440 TRACE("No isolated cpus detected");
442 /* No isolated cpus but we weren't already initialized by
443 * someone. We should simply copy the parents cpuset.cpus
446 if (!am_initialized
) {
447 DEBUG("Copying cpu settings of parent cgroup");
450 /* No isolated cpus but we were already initialized by someone.
451 * Nothing more to do for us.
456 /* Get maximum number of cpus found in isolated cpuset. */
457 maxisol
= get_max_cpus(isolcpus
);
458 if (maxisol
< 0 || maxisol
>= INT_MAX
- 1)
461 if (maxposs
< maxisol
)
465 possmask
= lxc_cpumask(posscpus
, maxposs
);
467 ERROR("Failed to create cpumask for possible cpus");
471 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
473 ERROR("Failed to create cpumask for isolated cpus");
477 for (i
= 0; i
<= maxposs
; i
++) {
478 if (!is_set(i
, isolmask
) || !is_set(i
, possmask
))
482 clear_bit(i
, possmask
);
486 DEBUG("No isolated cpus present in cpuset");
489 DEBUG("Removed isolated cpus from cpuset");
491 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
493 ERROR("Failed to create cpu list");
500 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
501 ret
= lxc_write_to_file(fpath
, cpulist
, strlen(cpulist
), false, 0666);
503 SYSERROR("Failed to write cpu list to \"%s\"", fpath
);
516 if (posscpus
!= cpulist
)
524 /* Copy contents of parent(@path)/@file to @path/@file */
525 static bool copy_parent_file(char *path
, char *file
)
528 char *fpath
, *lastslash
, oldv
;
532 lastslash
= strrchr(path
, '/');
534 ERROR("Failed to detect \"/\" in \"%s\"", path
);
539 fpath
= must_make_path(path
, file
, NULL
);
540 len
= lxc_read_from_file(fpath
, NULL
, 0);
544 value
= must_alloc(len
+ 1);
545 ret
= lxc_read_from_file(fpath
, value
, len
);
551 fpath
= must_make_path(path
, file
, NULL
);
552 ret
= lxc_write_to_file(fpath
, value
, len
, false, 0666);
554 SYSERROR("Failed to write \"%s\" to file \"%s\"", value
, fpath
);
560 SYSERROR("Failed to read file \"%s\"", fpath
);
566 /* Initialize the cpuset hierarchy in first directory of @gname and set
567 * cgroup.clone_children so that children inherit settings. Since the
568 * h->base_path is populated by init or ourselves, we know it is already
571 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
, char *cgname
)
575 char *cgpath
, *clonechildrenpath
, *slash
;
577 if (!string_in_list(h
->controllers
, "cpuset"))
582 slash
= strchr(cgname
, '/');
586 cgpath
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
590 ret
= mkdir(cgpath
, 0755);
592 if (errno
!= EEXIST
) {
593 SYSERROR("Failed to create directory \"%s\"", cgpath
);
599 clonechildrenpath
= must_make_path(cgpath
, "cgroup.clone_children", NULL
);
600 /* unified hierarchy doesn't have clone_children */
601 if (!file_exists(clonechildrenpath
)) {
602 free(clonechildrenpath
);
607 ret
= lxc_read_from_file(clonechildrenpath
, &v
, 1);
609 SYSERROR("Failed to read file \"%s\"", clonechildrenpath
);
610 free(clonechildrenpath
);
615 /* Make sure any isolated cpus are removed from cpuset.cpus. */
616 if (!cg_legacy_filter_and_set_cpus(cgpath
, v
== '1')) {
617 SYSERROR("Failed to remove isolated cpus");
618 free(clonechildrenpath
);
623 /* Already set for us by someone else. */
625 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
626 free(clonechildrenpath
);
631 /* copy parent's settings */
632 if (!copy_parent_file(cgpath
, "cpuset.mems")) {
633 SYSERROR("Failed to copy \"cpuset.mems\" settings");
635 free(clonechildrenpath
);
640 ret
= lxc_write_to_file(clonechildrenpath
, "1", 1, false, 0666);
642 /* Set clone_children so children inherit our settings */
643 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath
);
644 free(clonechildrenpath
);
647 free(clonechildrenpath
);
651 /* Given two null-terminated lists of strings, return true if any string is in
654 static bool controller_lists_intersect(char **l1
, char **l2
)
661 for (i
= 0; l1
[i
]; i
++) {
662 if (string_in_list(l2
, l1
[i
]))
669 /* For a null-terminated list of controllers @clist, return true if any of those
670 * controllers is already listed the null-terminated list of hierarchies @hlist.
671 * Realistically, if one is present, all must be present.
673 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
680 for (i
= 0; hlist
[i
]; i
++)
681 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
687 /* Return true if the controller @entry is found in the null-terminated list of
688 * hierarchies @hlist.
690 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
697 for (i
= 0; hlist
[i
]; i
++)
698 if (string_in_list(hlist
[i
]->controllers
, entry
))
704 /* Return true if all of the controllers which we require have been found. The
705 * required list is freezer and anything in lxc.cgroup.use.
707 static bool all_controllers_found(struct cgroup_ops
*ops
)
710 struct hierarchy
**hlist
= ops
->hierarchies
;
712 if (!controller_found(hlist
, "freezer")) {
713 ERROR("No freezer controller mountpoint found");
717 if (!ops
->cgroup_use
)
720 for (cur
= ops
->cgroup_use
; cur
&& *cur
; cur
++)
721 if (!controller_found(hlist
, *cur
)) {
722 ERROR("No %s controller mountpoint found", *cur
);
729 /* Get the controllers from a mountinfo line There are other ways we could get
730 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
731 * could parse the mount options. But we simply assume that the mountpoint must
732 * be /sys/fs/cgroup/controller-list
734 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
737 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
738 * for legacy hierarchies.
741 char *dup
, *p2
, *tok
;
742 char *p
= line
, *sep
= ",";
745 for (i
= 0; i
< 4; i
++) {
752 /* Note, if we change how mountinfo works, then our caller will need to
753 * verify /sys/fs/cgroup/ in this field.
755 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0) {
756 ERROR("Found hierarchy not under /sys/fs/cgroup: \"%s\"", p
);
763 ERROR("Corrupt mountinfo");
768 if (type
== CGROUP_SUPER_MAGIC
) {
769 /* strdup() here for v1 hierarchies. Otherwise
770 * lxc_iterate_parts() will destroy mountpoints such as
771 * "/sys/fs/cgroup/cpu,cpuacct".
777 lxc_iterate_parts(tok
, dup
, sep
) {
778 must_append_controller(klist
, nlist
, &aret
, tok
);
788 static char **cg_unified_make_empty_controller(void)
793 newentry
= append_null_to_list((void ***)&aret
);
794 aret
[newentry
] = NULL
;
798 static char **cg_unified_get_controllers(const char *file
)
804 buf
= read_file(file
);
808 lxc_iterate_parts(tok
, buf
, sep
) {
812 newentry
= append_null_to_list((void ***)&aret
);
813 copy
= must_copy_string(tok
);
814 aret
[newentry
] = copy
;
821 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
822 char *container_base_path
, int type
)
824 struct hierarchy
*new;
827 new = must_alloc(sizeof(*new));
828 new->controllers
= clist
;
829 new->mountpoint
= mountpoint
;
830 new->container_base_path
= container_base_path
;
831 new->container_full_path
= NULL
;
832 new->monitor_full_path
= NULL
;
835 newentry
= append_null_to_list((void ***)h
);
836 (*h
)[newentry
] = new;
840 /* Get a copy of the mountpoint from @line, which is a line from
841 * /proc/self/mountinfo.
843 static char *cg_hybrid_get_mountpoint(char *line
)
848 char *p
= line
, *sret
= NULL
;
850 for (i
= 0; i
< 4; i
++) {
857 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
860 p2
= strchr(p
+ 15, ' ');
866 sret
= must_alloc(len
+ 1);
867 memcpy(sret
, p
, len
);
872 /* Given a multi-line string, return a null-terminated copy of the current line. */
873 static char *copy_to_eol(char *p
)
875 char *p2
= strchr(p
, '\n'), *sret
;
882 sret
= must_alloc(len
+ 1);
883 memcpy(sret
, p
, len
);
888 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
889 * /proc/self/cgroup file. Check whether controller c is present.
891 static bool controller_in_clist(char *cgline
, char *c
)
893 char *tok
, *eol
, *tmp
;
896 eol
= strchr(cgline
, ':');
901 tmp
= alloca(len
+ 1);
902 memcpy(tmp
, cgline
, len
);
905 lxc_iterate_parts(tok
, tmp
, ",") {
906 if (strcmp(tok
, c
) == 0)
913 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
916 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
919 char *p
= basecginfo
;
922 bool is_cgv2_base_cgroup
= false;
924 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
925 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
926 is_cgv2_base_cgroup
= true;
933 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
938 return copy_to_eol(p
);
948 static void must_append_string(char ***list
, char *entry
)
953 newentry
= append_null_to_list((void ***)list
);
954 copy
= must_copy_string(entry
);
955 (*list
)[newentry
] = copy
;
958 static int get_existing_subsystems(char ***klist
, char ***nlist
)
964 f
= fopen("/proc/self/cgroup", "r");
968 while (getline(&line
, &len
, f
) != -1) {
970 p
= strchr(line
, ':');
979 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
980 * contains an entry of the form:
984 * In this case we use "cgroup2" as controller name.
987 must_append_string(klist
, "cgroup2");
991 lxc_iterate_parts(tok
, p
, ",") {
992 if (strncmp(tok
, "name=", 5) == 0)
993 must_append_string(nlist
, tok
);
995 must_append_string(klist
, tok
);
1004 static void trim(char *s
)
1009 while ((len
> 1) && (s
[len
- 1] == '\n'))
1013 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
1016 struct hierarchy
**it
;
1018 if (!ops
->hierarchies
) {
1019 TRACE(" No hierarchies found");
1023 TRACE(" Hierarchies:");
1024 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
1028 TRACE(" %d: base_cgroup: %s", i
, (*it
)->container_base_path
? (*it
)->container_base_path
: "(null)");
1029 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
1030 TRACE(" controllers:");
1031 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
1032 TRACE(" %d: %s", j
, *cit
);
1036 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
1042 TRACE("basecginfo is:");
1043 TRACE("%s", basecginfo
);
1045 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
1046 TRACE("kernel subsystem %d: %s", k
, *it
);
1048 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
1049 TRACE("named subsystem %d: %s", k
, *it
);
1052 static int cgroup_rmdir(struct hierarchy
**hierarchies
,
1053 const char *container_cgroup
)
1057 if (!container_cgroup
|| !hierarchies
)
1060 for (i
= 0; hierarchies
[i
]; i
++) {
1062 struct hierarchy
*h
= hierarchies
[i
];
1064 if (!h
->container_full_path
)
1067 ret
= recursive_destroy(h
->container_full_path
);
1069 WARN("Failed to destroy \"%s\"", h
->container_full_path
);
1071 free(h
->container_full_path
);
1072 h
->container_full_path
= NULL
;
1078 struct generic_userns_exec_data
{
1079 struct hierarchy
**hierarchies
;
1080 const char *container_cgroup
;
1081 struct lxc_conf
*conf
;
1082 uid_t origuid
; /* target uid in parent namespace */
1086 static int cgroup_rmdir_wrapper(void *data
)
1089 struct generic_userns_exec_data
*arg
= data
;
1090 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1091 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1093 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1095 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid
,
1096 (int)nsgid
, (int)nsgid
);
1100 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1102 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid
,
1103 (int)nsuid
, (int)nsuid
);
1107 ret
= setgroups(0, NULL
);
1108 if (ret
< 0 && errno
!= EPERM
) {
1109 SYSERROR("Failed to setgroups(0, NULL)");
1113 return cgroup_rmdir(arg
->hierarchies
, arg
->container_cgroup
);
1116 __cgfsng_ops
static void cgfsng_payload_destroy(struct cgroup_ops
*ops
,
1117 struct lxc_handler
*handler
)
1120 struct generic_userns_exec_data wrap
;
1123 wrap
.container_cgroup
= ops
->container_cgroup
;
1124 wrap
.hierarchies
= ops
->hierarchies
;
1125 wrap
.conf
= handler
->conf
;
1127 if (handler
->conf
&& !lxc_list_empty(&handler
->conf
->id_map
))
1128 ret
= userns_exec_1(handler
->conf
, cgroup_rmdir_wrapper
, &wrap
,
1129 "cgroup_rmdir_wrapper");
1131 ret
= cgroup_rmdir(ops
->hierarchies
, ops
->container_cgroup
);
1133 WARN("Failed to destroy cgroups");
1138 __cgfsng_ops
static void cgfsng_monitor_destroy(struct cgroup_ops
*ops
,
1139 struct lxc_handler
*handler
)
1143 struct lxc_conf
*conf
= handler
->conf
;
1144 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1146 if (!ops
->hierarchies
)
1149 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", handler
->monitor_pid
);
1150 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
1153 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1156 struct hierarchy
*h
= ops
->hierarchies
[i
];
1158 if (!h
->monitor_full_path
)
1161 if (conf
&& conf
->cgroup_meta
.dir
)
1162 pivot_path
= must_make_path(h
->mountpoint
,
1163 h
->container_base_path
,
1164 conf
->cgroup_meta
.dir
,
1166 "cgroup.procs", NULL
);
1168 pivot_path
= must_make_path(h
->mountpoint
,
1169 h
->container_base_path
,
1171 "cgroup.procs", NULL
);
1173 chop
= strrchr(pivot_path
, '/');
1177 ret
= mkdir_p(pivot_path
, 0755);
1178 if (ret
< 0 && errno
!= EEXIST
) {
1179 SYSWARN("Failed to create cgroup \"%s\"\n", pivot_path
);
1186 /* Move ourselves into the pivot cgroup to delete our own
1189 ret
= lxc_write_to_file(pivot_path
, pidstr
, len
, false, 0666);
1191 SYSWARN("Failed to move monitor %s to \"%s\"\n", pidstr
, pivot_path
);
1195 ret
= recursive_destroy(h
->monitor_full_path
);
1197 WARN("Failed to destroy \"%s\"", h
->monitor_full_path
);
1204 static bool cg_unified_create_cgroup(struct hierarchy
*h
, char *cgname
)
1206 size_t i
, parts_len
;
1208 size_t full_len
= 0;
1209 char *add_controllers
= NULL
, *cgroup
= NULL
;
1210 char **parts
= NULL
;
1213 if (h
->version
!= CGROUP2_SUPER_MAGIC
)
1216 if (!h
->controllers
)
1219 /* For now we simply enable all controllers that we have detected by
1220 * creating a string like "+memory +pids +cpu +io".
1221 * TODO: In the near future we might want to support "-<controller>"
1222 * etc. but whether supporting semantics like this make sense will need
1225 for (it
= h
->controllers
; it
&& *it
; it
++) {
1226 full_len
+= strlen(*it
) + 2;
1227 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
1229 if (h
->controllers
[0] == *it
)
1230 add_controllers
[0] = '\0';
1232 (void)strlcat(add_controllers
, "+", full_len
+ 1);
1233 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
1235 if ((it
+ 1) && *(it
+ 1))
1236 (void)strlcat(add_controllers
, " ", full_len
+ 1);
1239 parts
= lxc_string_split(cgname
, '/');
1243 parts_len
= lxc_array_len((void **)parts
);
1247 cgroup
= must_make_path(h
->mountpoint
, h
->container_base_path
, NULL
);
1248 for (i
= 0; i
< parts_len
; i
++) {
1252 cgroup
= must_append_path(cgroup
, parts
[i
], NULL
);
1253 target
= must_make_path(cgroup
, "cgroup.subtree_control", NULL
);
1254 ret
= lxc_write_to_file(target
, add_controllers
, full_len
, false, 0666);
1257 SYSERROR("Could not enable \"%s\" controllers in the "
1258 "unified cgroup \"%s\"", add_controllers
, cgroup
);
1266 lxc_free_array((void **)parts
, free
);
1267 free(add_controllers
);
1272 static int mkdir_eexist_on_last(const char *dir
, mode_t mode
)
1274 const char *tmp
= dir
;
1275 const char *orig
= dir
;
1278 orig_len
= strlen(dir
);
1284 dir
= tmp
+ strspn(tmp
, "/");
1285 tmp
= dir
+ strcspn(dir
, "/");
1288 cur_len
= dir
- orig
;
1289 makeme
= strndup(orig
, cur_len
);
1293 ret
= mkdir(makeme
, mode
);
1295 if ((errno
!= EEXIST
) || (orig_len
== cur_len
)) {
1296 SYSERROR("Failed to create directory \"%s\"", makeme
);
1303 } while (tmp
!= dir
);
1308 static bool monitor_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1312 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1313 ERROR("Failed to handle legacy cpuset controller");
1317 h
->monitor_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1318 ret
= mkdir_eexist_on_last(h
->monitor_full_path
, 0755);
1320 ERROR("Failed to create cgroup \"%s\"", h
->monitor_full_path
);
1324 return cg_unified_create_cgroup(h
, cgname
);
1327 static bool container_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1331 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1332 ERROR("Failed to handle legacy cpuset controller");
1336 h
->container_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1337 ret
= mkdir_eexist_on_last(h
->container_full_path
, 0755);
1339 ERROR("Failed to create cgroup \"%s\"", h
->container_full_path
);
1343 return cg_unified_create_cgroup(h
, cgname
);
1346 static void remove_path_for_hierarchy(struct hierarchy
*h
, char *cgname
, bool monitor
)
1352 full_path
= h
->monitor_full_path
;
1354 full_path
= h
->container_full_path
;
1356 ret
= rmdir(full_path
);
1358 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", full_path
);
1363 h
->monitor_full_path
= NULL
;
1365 h
->container_full_path
= NULL
;
1368 __cgfsng_ops
static inline bool cgfsng_monitor_create(struct cgroup_ops
*ops
,
1369 struct lxc_handler
*handler
)
1371 char *monitor_cgroup
, *offset
, *tmp
;
1375 struct lxc_conf
*conf
= handler
->conf
;
1380 if (conf
->cgroup_meta
.dir
)
1381 tmp
= lxc_string_join("/",
1382 (const char *[]){conf
->cgroup_meta
.dir
,
1383 ops
->monitor_pattern
,
1384 handler
->name
, NULL
},
1387 tmp
= must_make_path(ops
->monitor_pattern
, handler
->name
, NULL
);
1391 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1392 monitor_cgroup
= must_realloc(tmp
, len
);
1393 offset
= monitor_cgroup
+ len
- 5;
1398 int ret
= snprintf(offset
, 5, "-%d", idx
);
1399 if (ret
< 0 || (size_t)ret
>= 5)
1403 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1404 if (!monitor_create_path_for_hierarchy(ops
->hierarchies
[i
], monitor_cgroup
)) {
1405 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->monitor_full_path
);
1406 free(ops
->hierarchies
[i
]->container_full_path
);
1407 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1409 for (int j
= 0; j
< i
; j
++)
1410 remove_path_for_hierarchy(ops
->hierarchies
[j
], monitor_cgroup
, true);
1416 } while (ops
->hierarchies
[i
] && idx
> 0 && idx
< 1000);
1420 INFO("The monitor process uses \"%s\" as cgroup", monitor_cgroup
);
1424 free(monitor_cgroup
);
1429 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1430 * next cgroup_pattern-1, -2, ..., -999.
1432 __cgfsng_ops
static inline bool cgfsng_payload_create(struct cgroup_ops
*ops
,
1433 struct lxc_handler
*handler
)
1437 char *container_cgroup
, *offset
, *tmp
;
1439 struct lxc_conf
*conf
= handler
->conf
;
1441 if (ops
->container_cgroup
) {
1442 WARN("cgfsng_create called a second time: %s", ops
->container_cgroup
);
1449 if (conf
->cgroup_meta
.dir
)
1450 tmp
= lxc_string_join("/", (const char *[]){conf
->cgroup_meta
.dir
, handler
->name
, NULL
}, false);
1452 tmp
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1454 ERROR("Failed expanding cgroup name pattern");
1458 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1459 container_cgroup
= must_alloc(len
);
1460 (void)strlcpy(container_cgroup
, tmp
, len
);
1462 offset
= container_cgroup
+ len
- 5;
1466 ERROR("Too many conflicting cgroup names");
1473 ret
= snprintf(offset
, 5, "-%d", idx
);
1474 if (ret
< 0 || (size_t)ret
>= 5) {
1475 FILE *f
= fopen("/dev/null", "w");
1477 fprintf(f
, "Workaround for GCC7 bug: "
1478 "https://gcc.gnu.org/bugzilla/"
1479 "show_bug.cgi?id=78969");
1485 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1486 if (!container_create_path_for_hierarchy(ops
->hierarchies
[i
], container_cgroup
)) {
1487 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->container_full_path
);
1488 free(ops
->hierarchies
[i
]->container_full_path
);
1489 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1490 for (int j
= 0; j
< i
; j
++)
1491 remove_path_for_hierarchy(ops
->hierarchies
[j
], container_cgroup
, false);
1497 ops
->container_cgroup
= container_cgroup
;
1498 INFO("The container uses \"%s\" as cgroup", container_cgroup
);
1503 free(container_cgroup
);
1508 __cgfsng_ops
static bool __do_cgroup_enter(struct cgroup_ops
*ops
, pid_t pid
,
1512 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1514 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", pid
);
1515 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
1518 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1523 path
= must_make_path(ops
->hierarchies
[i
]->monitor_full_path
,
1524 "cgroup.procs", NULL
);
1526 path
= must_make_path(ops
->hierarchies
[i
]->container_full_path
,
1527 "cgroup.procs", NULL
);
1528 ret
= lxc_write_to_file(path
, pidstr
, len
, false, 0666);
1530 SYSERROR("Failed to enter cgroup \"%s\"", path
);
1540 __cgfsng_ops
static bool cgfsng_monitor_enter(struct cgroup_ops
*ops
, pid_t pid
)
1542 return __do_cgroup_enter(ops
, pid
, true);
1545 static bool cgfsng_payload_enter(struct cgroup_ops
*ops
, pid_t pid
)
1547 return __do_cgroup_enter(ops
, pid
, false);
1550 static int chowmod(char *path
, uid_t chown_uid
, gid_t chown_gid
,
1555 ret
= chown(path
, chown_uid
, chown_gid
);
1557 SYSWARN("Failed to chown(%s, %d, %d)", path
, (int)chown_uid
, (int)chown_gid
);
1561 ret
= chmod(path
, chmod_mode
);
1563 SYSWARN("Failed to chmod(%s, %d)", path
, (int)chmod_mode
);
1570 /* chgrp the container cgroups to container group. We leave
1571 * the container owner as cgroup owner. So we must make the
1572 * directories 775 so that the container can create sub-cgroups.
1574 * Also chown the tasks and cgroup.procs files. Those may not
1575 * exist depending on kernel version.
1577 static int chown_cgroup_wrapper(void *data
)
1581 struct generic_userns_exec_data
*arg
= data
;
1582 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1583 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1585 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1587 SYSERROR("Failed to setresgid(%d, %d, %d)",
1588 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1592 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1594 SYSERROR("Failed to setresuid(%d, %d, %d)",
1595 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1599 ret
= setgroups(0, NULL
);
1600 if (ret
< 0 && errno
!= EPERM
) {
1601 SYSERROR("Failed to setgroups(0, NULL)");
1605 destuid
= get_ns_uid(arg
->origuid
);
1606 if (destuid
== LXC_INVALID_UID
)
1609 for (i
= 0; arg
->hierarchies
[i
]; i
++) {
1611 char *path
= arg
->hierarchies
[i
]->container_full_path
;
1613 ret
= chowmod(path
, destuid
, nsgid
, 0775);
1617 /* Failures to chown() these are inconvenient but not
1618 * detrimental We leave these owned by the container launcher,
1619 * so that container root can write to the files to attach. We
1620 * chmod() them 664 so that container systemd can write to the
1621 * files (which systemd in wily insists on doing).
1624 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
) {
1625 fullpath
= must_make_path(path
, "tasks", NULL
);
1626 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1630 fullpath
= must_make_path(path
, "cgroup.procs", NULL
);
1631 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1634 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1637 fullpath
= must_make_path(path
, "cgroup.subtree_control", NULL
);
1638 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1641 fullpath
= must_make_path(path
, "cgroup.threads", NULL
);
1642 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1649 __cgfsng_ops
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1650 struct lxc_conf
*conf
)
1652 struct generic_userns_exec_data wrap
;
1654 if (lxc_list_empty(&conf
->id_map
))
1657 wrap
.origuid
= geteuid();
1659 wrap
.hierarchies
= ops
->hierarchies
;
1662 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
,
1663 "chown_cgroup_wrapper") < 0) {
1664 ERROR("Error requesting cgroup chown in new user namespace");
1671 /* cgroup-full:* is done, no need to create subdirs */
1672 static bool cg_mount_needs_subdirs(int type
)
1674 if (type
>= LXC_AUTO_CGROUP_FULL_RO
)
1680 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1681 * remount controller ro if needed and bindmount the cgroupfs onto
1682 * controll/the/cg/path.
1684 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1685 char *controllerpath
, char *cgpath
,
1686 const char *container_cgroup
)
1688 int ret
, remount_flags
;
1690 int flags
= MS_BIND
;
1692 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1693 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1695 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
1696 controllerpath
, controllerpath
);
1700 remount_flags
= add_required_remount_flags(controllerpath
,
1702 flags
| MS_REMOUNT
);
1703 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1704 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1707 SYSERROR("Failed to remount \"%s\" ro", controllerpath
);
1711 INFO("Remounted %s read-only", controllerpath
);
1714 sourcepath
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1715 container_cgroup
, NULL
);
1716 if (type
== LXC_AUTO_CGROUP_RO
)
1719 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1721 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1725 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1727 if (flags
& MS_RDONLY
) {
1728 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1729 flags
| MS_REMOUNT
);
1730 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1732 SYSERROR("Failed to remount \"%s\" ro", cgpath
);
1736 INFO("Remounted %s read-only", cgpath
);
1740 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1744 /* __cg_mount_direct
1746 * Mount cgroup hierarchies directly without using bind-mounts. The main
1747 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1748 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1750 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1751 const char *controllerpath
)
1754 char *controllers
= NULL
;
1755 char *fstype
= "cgroup2";
1756 unsigned long flags
= 0;
1761 flags
|= MS_RELATIME
;
1763 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1766 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1767 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1773 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1776 SYSERROR("Failed to mount \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1780 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1784 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1785 const char *controllerpath
)
1787 return __cg_mount_direct(type
, h
, controllerpath
);
1790 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1791 const char *controllerpath
)
1793 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1796 return __cg_mount_direct(type
, h
, controllerpath
);
1799 __cgfsng_ops
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1800 struct lxc_handler
*handler
,
1801 const char *root
, int type
)
1804 char *tmpfspath
= NULL
;
1805 bool has_cgns
= false, retval
= false, wants_force_mount
= false;
1807 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1810 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1811 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1812 wants_force_mount
= true;
1815 if (!wants_force_mount
){
1816 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1817 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1819 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1822 has_cgns
= cgns_supported();
1823 if (has_cgns
&& !wants_force_mount
)
1826 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1827 type
= LXC_AUTO_CGROUP_MIXED
;
1828 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1829 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1832 tmpfspath
= must_make_path(root
, "/sys/fs/cgroup", NULL
);
1833 ret
= safe_mount(NULL
, tmpfspath
, "tmpfs",
1834 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1835 "size=10240k,mode=755", root
);
1839 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1840 char *controllerpath
, *path2
;
1841 struct hierarchy
*h
= ops
->hierarchies
[i
];
1842 char *controller
= strrchr(h
->mountpoint
, '/');
1848 controllerpath
= must_make_path(tmpfspath
, controller
, NULL
);
1849 if (dir_exists(controllerpath
)) {
1850 free(controllerpath
);
1854 ret
= mkdir(controllerpath
, 0755);
1856 SYSERROR("Error creating cgroup path: %s", controllerpath
);
1857 free(controllerpath
);
1861 if (has_cgns
&& wants_force_mount
) {
1862 /* If cgroup namespaces are supported but the container
1863 * will not have CAP_SYS_ADMIN after it has started we
1864 * need to mount the cgroups manually.
1866 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1867 free(controllerpath
);
1874 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1876 free(controllerpath
);
1880 if (!cg_mount_needs_subdirs(type
)) {
1881 free(controllerpath
);
1885 path2
= must_make_path(controllerpath
, h
->container_base_path
,
1886 ops
->container_cgroup
, NULL
);
1887 ret
= mkdir_p(path2
, 0755);
1889 free(controllerpath
);
1894 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1895 path2
, ops
->container_cgroup
);
1896 free(controllerpath
);
1908 static int recursive_count_nrtasks(char *dirname
)
1910 struct dirent
*direntp
;
1915 dir
= opendir(dirname
);
1919 while ((direntp
= readdir(dir
))) {
1922 if (!strcmp(direntp
->d_name
, ".") ||
1923 !strcmp(direntp
->d_name
, ".."))
1926 path
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1928 if (lstat(path
, &mystat
))
1931 if (!S_ISDIR(mystat
.st_mode
))
1934 count
+= recursive_count_nrtasks(path
);
1939 path
= must_make_path(dirname
, "cgroup.procs", NULL
);
1940 ret
= lxc_count_file_lines(path
);
1945 (void)closedir(dir
);
1950 __cgfsng_ops
static int cgfsng_nrtasks(struct cgroup_ops
*ops
)
1955 if (!ops
->container_cgroup
|| !ops
->hierarchies
)
1958 path
= must_make_path(ops
->hierarchies
[0]->container_full_path
, NULL
);
1959 count
= recursive_count_nrtasks(path
);
1964 /* Only root needs to escape to the cgroup of its init. */
1965 __cgfsng_ops
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1966 struct lxc_conf
*conf
)
1970 if (conf
->cgroup_meta
.relative
|| geteuid())
1973 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1977 fullpath
= must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1978 ops
->hierarchies
[i
]->container_base_path
,
1979 "cgroup.procs", NULL
);
1980 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1982 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath
);
1992 __cgfsng_ops
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1996 for (i
= 0; ops
->hierarchies
[i
]; i
++)
2002 __cgfsng_ops
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
, char ***out
)
2006 /* sanity check n */
2007 for (i
= 0; i
< n
; i
++)
2008 if (!ops
->hierarchies
[i
])
2011 *out
= ops
->hierarchies
[i
]->controllers
;
2016 #define THAWED "THAWED"
2017 #define THAWED_LEN (strlen(THAWED))
2019 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
2022 __cgfsng_ops
static bool cgfsng_unfreeze(struct cgroup_ops
*ops
)
2026 struct hierarchy
*h
;
2028 h
= get_hierarchy(ops
, "freezer");
2032 fullpath
= must_make_path(h
->container_full_path
, "freezer.state", NULL
);
2033 ret
= lxc_write_to_file(fullpath
, THAWED
, THAWED_LEN
, false, 0666);
2041 __cgfsng_ops
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
2042 const char *controller
)
2044 struct hierarchy
*h
;
2046 h
= get_hierarchy(ops
, controller
);
2048 WARN("Failed to find hierarchy for controller \"%s\"",
2049 controller
? controller
: "(null)");
2053 return h
->container_full_path
? h
->container_full_path
+ strlen(h
->mountpoint
) : NULL
;
2056 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2057 * which must be freed by the caller.
2059 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
2061 const char *filename
)
2063 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
2066 /* Technically, we're always at a delegation boundary here (This is especially
2067 * true when cgroup namespaces are available.). The reasoning is that in order
2068 * for us to have been able to start a container in the first place the root
2069 * cgroup must have been a leaf node. Now, either the container's init system
2070 * has populated the cgroup and kept it as a leaf node or it has created
2071 * subtrees. In the former case we will simply attach to the leaf node we
2072 * created when we started the container in the latter case we create our own
2073 * cgroup for the attaching process.
2075 static int __cg_unified_attach(const struct hierarchy
*h
, const char *name
,
2076 const char *lxcpath
, const char *pidstr
,
2077 size_t pidstr_len
, const char *controller
)
2081 int fret
= -1, idx
= 0;
2082 char *base_path
= NULL
, *container_cgroup
= NULL
, *full_path
= NULL
;
2084 container_cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2086 if (!container_cgroup
)
2089 base_path
= must_make_path(h
->mountpoint
, container_cgroup
, NULL
);
2090 full_path
= must_make_path(base_path
, "cgroup.procs", NULL
);
2091 /* cgroup is populated */
2092 ret
= lxc_write_to_file(full_path
, pidstr
, pidstr_len
, false, 0666);
2093 if (ret
< 0 && errno
!= EBUSY
)
2101 len
= strlen(base_path
) + STRLITERALLEN("/lxc-1000") +
2102 STRLITERALLEN("/cgroup-procs");
2103 full_path
= must_alloc(len
+ 1);
2106 ret
= snprintf(full_path
, len
+ 1, "%s/lxc-%d",
2109 ret
= snprintf(full_path
, len
+ 1, "%s/lxc", base_path
);
2110 if (ret
< 0 || (size_t)ret
>= len
+ 1)
2113 ret
= mkdir_p(full_path
, 0755);
2114 if (ret
< 0 && errno
!= EEXIST
)
2117 (void)strlcat(full_path
, "/cgroup.procs", len
+ 1);
2118 ret
= lxc_write_to_file(full_path
, pidstr
, len
, false, 0666);
2122 /* this is a non-leaf node */
2126 } while (++idx
> 0 && idx
< 1000);
2134 free(container_cgroup
);
2140 __cgfsng_ops
static bool cgfsng_attach(struct cgroup_ops
*ops
, const char *name
,
2141 const char *lxcpath
, pid_t pid
)
2144 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
2146 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", pid
);
2147 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
2150 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
2152 char *fullpath
= NULL
;
2153 struct hierarchy
*h
= ops
->hierarchies
[i
];
2155 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2156 ret
= __cg_unified_attach(h
, name
, lxcpath
, pidstr
, len
,
2164 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2169 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2171 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2173 SYSERROR("Failed to attach %d to %s", (int)pid
, fullpath
);
2183 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2184 * don't have a cgroup_data set up, so we ask the running container through the
2185 * commands API for the cgroup path.
2187 __cgfsng_ops
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
2188 char *value
, size_t len
, const char *name
,
2189 const char *lxcpath
)
2192 size_t controller_len
;
2193 char *controller
, *p
, *path
;
2194 struct hierarchy
*h
;
2196 controller_len
= strlen(filename
);
2197 controller
= alloca(controller_len
+ 1);
2198 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2200 p
= strchr(controller
, '.');
2204 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2209 h
= get_hierarchy(ops
, controller
);
2213 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2214 ret
= lxc_read_from_file(fullpath
, value
, len
);
2222 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2223 * don't have a cgroup_data set up, so we ask the running container through the
2224 * commands API for the cgroup path.
2226 __cgfsng_ops
static int cgfsng_set(struct cgroup_ops
*ops
,
2227 const char *filename
, const char *value
,
2228 const char *name
, const char *lxcpath
)
2231 size_t controller_len
;
2232 char *controller
, *p
, *path
;
2233 struct hierarchy
*h
;
2235 controller_len
= strlen(filename
);
2236 controller
= alloca(controller_len
+ 1);
2237 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2239 p
= strchr(controller
, '.');
2243 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2248 h
= get_hierarchy(ops
, controller
);
2252 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2253 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2261 /* take devices cgroup line
2263 * and convert it to a valid
2264 * type major:minor mode
2265 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2268 static int convert_devpath(const char *invalue
, char *dest
)
2271 char *p
, *path
, type
;
2272 unsigned long minor
, major
;
2277 path
= must_copy_string(invalue
);
2279 /* Read path followed by mode. Ignore any trailing text.
2280 * A ' # comment' would be legal. Technically other text is not
2281 * legal, we could check for that if we cared to.
2283 for (n_parts
= 1, p
= path
; *p
&& n_parts
< 3; p
++) {
2305 ret
= stat(path
, &sb
);
2309 mode_t m
= sb
.st_mode
& S_IFMT
;
2318 ERROR("Unsupported device type %i for \"%s\"", m
, path
);
2323 major
= MAJOR(sb
.st_rdev
);
2324 minor
= MINOR(sb
.st_rdev
);
2325 ret
= snprintf(dest
, 50, "%c %lu:%lu %s", type
, major
, minor
, mode
);
2326 if (ret
< 0 || ret
>= 50) {
2327 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2328 "chars)", type
, major
, minor
, mode
);
2329 ret
= -ENAMETOOLONG
;
2339 /* Called from setup_limits - here we have the container's cgroup_data because
2340 * we created the cgroups.
2342 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2347 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2348 char converted_value
[50];
2349 struct hierarchy
*h
;
2351 char *controller
= NULL
;
2353 len
= strlen(filename
);
2354 controller
= alloca(len
+ 1);
2355 (void)strlcpy(controller
, filename
, len
+ 1);
2357 p
= strchr(controller
, '.');
2361 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2362 ret
= convert_devpath(value
, converted_value
);
2365 value
= converted_value
;
2368 h
= get_hierarchy(ops
, controller
);
2370 ERROR("Failed to setup limits for the \"%s\" controller. "
2371 "The controller seems to be unused by \"cgfsng\" cgroup "
2372 "driver or not enabled on the cgroup hierarchy",
2378 fullpath
= must_make_path(h
->container_full_path
, filename
, NULL
);
2379 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2384 static bool __cg_legacy_setup_limits(struct cgroup_ops
*ops
,
2385 struct lxc_list
*cgroup_settings
,
2388 struct lxc_list
*iterator
, *next
, *sorted_cgroup_settings
;
2389 struct lxc_cgroup
*cg
;
2392 if (lxc_list_empty(cgroup_settings
))
2395 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2396 if (!sorted_cgroup_settings
)
2399 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2400 cg
= iterator
->elem
;
2402 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2403 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
)) {
2404 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2405 WARN("Failed to set \"%s\" to \"%s\"",
2406 cg
->subsystem
, cg
->value
);
2409 WARN("Failed to set \"%s\" to \"%s\"",
2410 cg
->subsystem
, cg
->value
);
2413 DEBUG("Set controller \"%s\" set to \"%s\"",
2414 cg
->subsystem
, cg
->value
);
2419 INFO("Limits for the legacy cgroup hierarchies have been setup");
2421 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2422 lxc_list_del(iterator
);
2425 free(sorted_cgroup_settings
);
2429 static bool __cg_unified_setup_limits(struct cgroup_ops
*ops
,
2430 struct lxc_list
*cgroup_settings
)
2432 struct lxc_list
*iterator
;
2433 struct hierarchy
*h
= ops
->unified
;
2435 if (lxc_list_empty(cgroup_settings
))
2441 lxc_list_for_each(iterator
, cgroup_settings
) {
2444 struct lxc_cgroup
*cg
= iterator
->elem
;
2446 fullpath
= must_make_path(h
->container_full_path
, cg
->subsystem
, NULL
);
2447 ret
= lxc_write_to_file(fullpath
, cg
->value
, strlen(cg
->value
), false, 0666);
2450 SYSERROR("Failed to set \"%s\" to \"%s\"",
2451 cg
->subsystem
, cg
->value
);
2454 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2457 INFO("Limits for the unified cgroup hierarchy have been setup");
2461 __cgfsng_ops
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2462 struct lxc_conf
*conf
,
2467 bret
= __cg_legacy_setup_limits(ops
, &conf
->cgroup
, do_devices
);
2471 return __cg_unified_setup_limits(ops
, &conf
->cgroup2
);
2474 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
2477 char **cur_ctrl
, **cur_use
;
2479 if (!ops
->cgroup_use
)
2482 for (cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
2485 for (cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
2486 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
2502 /* At startup, parse_hierarchies finds all the info we need about cgroup
2503 * mountpoints and current cgroups, and stores it in @d.
2505 static bool cg_hybrid_init(struct cgroup_ops
*ops
, bool relative
)
2512 char **klist
= NULL
, **nlist
= NULL
;
2514 /* Root spawned containers escape the current cgroup, so use init's
2515 * cgroups as our base in that case.
2517 if (!relative
&& (geteuid() == 0))
2518 basecginfo
= read_file("/proc/1/cgroup");
2520 basecginfo
= read_file("/proc/self/cgroup");
2524 ret
= get_existing_subsystems(&klist
, &nlist
);
2526 ERROR("Failed to retrieve available legacy cgroup controllers");
2531 f
= fopen("/proc/self/mountinfo", "r");
2533 ERROR("Failed to open \"/proc/self/mountinfo\"");
2538 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
2540 while (getline(&line
, &len
, f
) != -1) {
2543 struct hierarchy
*new;
2544 char *base_cgroup
= NULL
, *mountpoint
= NULL
;
2545 char **controller_list
= NULL
;
2547 type
= get_cgroup_version(line
);
2551 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
2554 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
2555 if (type
== CGROUP2_SUPER_MAGIC
)
2556 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2557 else if (type
== CGROUP_SUPER_MAGIC
)
2558 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
2559 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
2560 if (type
== CGROUP_SUPER_MAGIC
)
2561 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2562 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
2563 if (type
== CGROUP2_SUPER_MAGIC
)
2564 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2567 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
2568 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
2571 if (type
== CGROUP_SUPER_MAGIC
)
2572 if (controller_list_is_dup(ops
->hierarchies
, controller_list
))
2575 mountpoint
= cg_hybrid_get_mountpoint(line
);
2577 ERROR("Failed parsing mountpoint from \"%s\"", line
);
2581 if (type
== CGROUP_SUPER_MAGIC
)
2582 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
2584 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
2586 ERROR("Failed to find current cgroup");
2591 prune_init_scope(base_cgroup
);
2592 if (type
== CGROUP2_SUPER_MAGIC
)
2593 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
2595 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
2599 if (type
== CGROUP2_SUPER_MAGIC
) {
2600 char *cgv2_ctrl_path
;
2602 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
2603 "cgroup.controllers",
2606 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
2607 free(cgv2_ctrl_path
);
2608 if (!controller_list
) {
2609 controller_list
= cg_unified_make_empty_controller();
2610 TRACE("No controllers are enabled for "
2611 "delegation in the unified hierarchy");
2615 /* Exclude all controllers that cgroup use does not want. */
2616 if (!cgroup_use_wants_controllers(ops
, controller_list
))
2619 new = add_hierarchy(&ops
->hierarchies
, controller_list
, mountpoint
, base_cgroup
, type
);
2620 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
)
2626 free_string_list(controller_list
);
2631 free_string_list(klist
);
2632 free_string_list(nlist
);
2639 TRACE("Writable cgroup hierarchies:");
2640 lxc_cgfsng_print_hierarchies(ops
);
2642 /* verify that all controllers in cgroup.use and all crucial
2643 * controllers are accounted for
2645 if (!all_controllers_found(ops
))
2651 static int cg_is_pure_unified(void)
2657 ret
= statfs("/sys/fs/cgroup", &fs
);
2661 if (is_fs_type(&fs
, CGROUP2_SUPER_MAGIC
))
2662 return CGROUP2_SUPER_MAGIC
;
2667 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
2668 static char *cg_unified_get_current_cgroup(bool relative
)
2670 char *basecginfo
, *base_cgroup
;
2673 if (!relative
&& (geteuid() == 0))
2674 basecginfo
= read_file("/proc/1/cgroup");
2676 basecginfo
= read_file("/proc/self/cgroup");
2680 base_cgroup
= strstr(basecginfo
, "0::/");
2682 goto cleanup_on_err
;
2684 base_cgroup
= base_cgroup
+ 3;
2685 copy
= copy_to_eol(base_cgroup
);
2687 goto cleanup_on_err
;
2697 static int cg_unified_init(struct cgroup_ops
*ops
, bool relative
)
2700 char *mountpoint
, *subtree_path
;
2702 char *base_cgroup
= NULL
;
2704 ret
= cg_is_pure_unified();
2705 if (ret
== -ENOMEDIUM
)
2708 if (ret
!= CGROUP2_SUPER_MAGIC
)
2711 base_cgroup
= cg_unified_get_current_cgroup(relative
);
2714 prune_init_scope(base_cgroup
);
2716 /* We assume that we have already been given controllers to delegate
2717 * further down the hierarchy. If not it is up to the user to delegate
2720 mountpoint
= must_copy_string("/sys/fs/cgroup");
2721 subtree_path
= must_make_path(mountpoint
, base_cgroup
,
2722 "cgroup.subtree_control", NULL
);
2723 delegatable
= cg_unified_get_controllers(subtree_path
);
2726 delegatable
= cg_unified_make_empty_controller();
2727 if (!delegatable
[0])
2728 TRACE("No controllers are enabled for delegation");
2730 /* TODO: If the user requested specific controllers via lxc.cgroup.use
2731 * we should verify here. The reason I'm not doing it right is that I'm
2732 * not convinced that lxc.cgroup.use will be the future since it is a
2733 * global property. I much rather have an option that lets you request
2734 * controllers per container.
2737 add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
2739 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2740 return CGROUP2_SUPER_MAGIC
;
2743 static bool cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
2747 bool relative
= conf
->cgroup_meta
.relative
;
2749 tmp
= lxc_global_config_value("lxc.cgroup.use");
2751 char *chop
, *cur
, *pin
;
2753 pin
= must_copy_string(tmp
);
2756 lxc_iterate_parts(cur
, chop
, ",") {
2757 must_append_string(&ops
->cgroup_use
, cur
);
2763 ret
= cg_unified_init(ops
, relative
);
2767 if (ret
== CGROUP2_SUPER_MAGIC
)
2770 return cg_hybrid_init(ops
, relative
);
2773 __cgfsng_ops
static bool cgfsng_data_init(struct cgroup_ops
*ops
)
2775 const char *cgroup_pattern
;
2777 /* copy system-wide cgroup information */
2778 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
2779 if (!cgroup_pattern
) {
2780 /* lxc.cgroup.pattern is only NULL on error. */
2781 ERROR("Failed to retrieve cgroup pattern");
2784 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
2785 ops
->monitor_pattern
= MONITOR_CGROUP
;
2790 struct cgroup_ops
*cgfsng_ops_init(struct lxc_conf
*conf
)
2792 struct cgroup_ops
*cgfsng_ops
;
2794 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
2798 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
2799 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
2801 if (!cg_init(cgfsng_ops
, conf
)) {
2806 cgfsng_ops
->data_init
= cgfsng_data_init
;
2807 cgfsng_ops
->payload_destroy
= cgfsng_payload_destroy
;
2808 cgfsng_ops
->monitor_destroy
= cgfsng_monitor_destroy
;
2809 cgfsng_ops
->monitor_create
= cgfsng_monitor_create
;
2810 cgfsng_ops
->monitor_enter
= cgfsng_monitor_enter
;
2811 cgfsng_ops
->payload_create
= cgfsng_payload_create
;
2812 cgfsng_ops
->payload_enter
= cgfsng_payload_enter
;
2813 cgfsng_ops
->escape
= cgfsng_escape
;
2814 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
2815 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
2816 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
2817 cgfsng_ops
->get
= cgfsng_get
;
2818 cgfsng_ops
->set
= cgfsng_set
;
2819 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
2820 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
2821 cgfsng_ops
->driver
= "cgfsng";
2822 cgfsng_ops
->version
= "1.0.0";
2823 cgfsng_ops
->attach
= cgfsng_attach
;
2824 cgfsng_ops
->chown
= cgfsng_chown
;
2825 cgfsng_ops
->mount
= cgfsng_mount
;
2826 cgfsng_ops
->nrtasks
= cgfsng_nrtasks
;