2 * lxc: linux Container library
4 * Copyright © 2016 Canonical Ltd.
7 * Serge Hallyn <serge.hallyn@ubuntu.com>
8 * Christian Brauner <christian.brauner@ubuntu.com>
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
27 * cgroup backend. The original cgfs.c was designed to be as flexible
28 * as possible. It would try to find cgroup filesystems no matter where
29 * or how you had them mounted, and deduce the most usable mount for
32 * This new implementation assumes that cgroup filesystems are mounted
33 * under /sys/fs/cgroup/clist where clist is either the controller, or
34 * a comman-separated list of controllers.
48 #include <linux/kdev_t.h>
49 #include <linux/types.h>
50 #include <sys/types.h>
54 #include "cgroup_utils.h"
58 #include "storage/storage.h"
61 lxc_log_define(lxc_cgfsng
, lxc
);
63 static void free_string_list(char **clist
)
70 for (i
= 0; clist
[i
]; i
++)
76 /* Allocate a pointer, do not fail. */
77 static void *must_alloc(size_t sz
)
79 return must_realloc(NULL
, sz
);
82 /* Given a pointer to a null-terminated array of pointers, realloc to add one
83 * entry, and point the new entry to NULL. Do not fail. Return the index to the
84 * second-to-last entry - that is, the one which is now available for use
85 * (keeping the list null-terminated).
87 static int append_null_to_list(void ***list
)
92 for (; (*list
)[newentry
]; newentry
++)
95 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
96 (*list
)[newentry
+ 1] = NULL
;
100 /* Given a null-terminated array of strings, check whether @entry is one of the
103 static bool string_in_list(char **list
, const char *entry
)
110 for (i
= 0; list
[i
]; i
++)
111 if (strcmp(list
[i
], entry
) == 0)
117 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
118 * "name=systemd". Do not fail.
120 static char *cg_legacy_must_prefix_named(char *entry
)
126 prefixed
= must_alloc(len
+ 6);
128 memcpy(prefixed
, "name=", sizeof("name=") - 1);
129 memcpy(prefixed
+ sizeof("name=") - 1, entry
, len
);
130 prefixed
[len
+ 5] = '\0';
134 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
137 * We also handle named subsystems here. Any controller which is not a kernel
138 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
139 * we refuse to use because we're not sure which we have here.
140 * (TODO: We could work around this in some cases by just remounting to be
141 * unambiguous, or by comparing mountpoint contents with current cgroup.)
143 * The last entry will always be NULL.
145 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
151 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
152 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
153 ERROR("It is both a named and kernel subsystem");
157 newentry
= append_null_to_list((void ***)clist
);
159 if (strncmp(entry
, "name=", 5) == 0)
160 copy
= must_copy_string(entry
);
161 else if (string_in_list(klist
, entry
))
162 copy
= must_copy_string(entry
);
164 copy
= cg_legacy_must_prefix_named(entry
);
166 (*clist
)[newentry
] = copy
;
169 /* Given a handler's cgroup data, return the struct hierarchy for the controller
170 * @c, or NULL if there is none.
172 struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *c
)
176 if (!ops
->hierarchies
)
179 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
181 /* This is the empty unified hierarchy. */
182 if (ops
->hierarchies
[i
]->controllers
&&
183 !ops
->hierarchies
[i
]->controllers
[0])
184 return ops
->hierarchies
[i
];
189 if (string_in_list(ops
->hierarchies
[i
]->controllers
, c
))
190 return ops
->hierarchies
[i
];
196 #define BATCH_SIZE 50
197 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
199 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
200 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
202 if (!*mem
|| newbatches
> oldbatches
) {
203 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
207 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
209 size_t full
= oldlen
+ newlen
;
211 batch_realloc(dest
, oldlen
, full
+ 1);
213 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
216 /* Slurp in a whole file */
217 static char *read_file(const char *fnam
)
220 char *line
= NULL
, *buf
= NULL
;
221 size_t len
= 0, fulllen
= 0;
224 f
= fopen(fnam
, "r");
227 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
228 append_line(&buf
, fulllen
, line
, linelen
);
236 /* Taken over modified from the kernel sources. */
237 #define NBITS 32 /* bits in uint32_t */
238 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
239 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
241 static void set_bit(unsigned bit
, uint32_t *bitarr
)
243 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
246 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
248 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
251 static bool is_set(unsigned bit
, uint32_t *bitarr
)
253 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
256 /* Create cpumask from cpulist aka turn:
264 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
269 char *saveptr
= NULL
;
271 arrlen
= BITS_TO_LONGS(nbits
);
272 bitarr
= calloc(arrlen
, sizeof(uint32_t));
276 for (; (token
= strtok_r(buf
, ",", &saveptr
)); buf
= NULL
) {
281 start
= strtoul(token
, NULL
, 0);
283 range
= strchr(token
, '-');
285 end
= strtoul(range
+ 1, NULL
, 0);
287 if (!(start
<= end
)) {
298 set_bit(start
++, bitarr
);
304 /* Turn cpumask into simple, comma-separated cpulist. */
305 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
309 char **cpulist
= NULL
;
310 char numstr
[LXC_NUMSTRLEN64
] = {0};
312 for (i
= 0; i
<= nbits
; i
++) {
313 if (!is_set(i
, bitarr
))
316 ret
= snprintf(numstr
, LXC_NUMSTRLEN64
, "%zu", i
);
317 if (ret
< 0 || (size_t)ret
>= LXC_NUMSTRLEN64
) {
318 lxc_free_array((void **)cpulist
, free
);
322 ret
= lxc_append_string(&cpulist
, numstr
);
324 lxc_free_array((void **)cpulist
, free
);
332 return lxc_string_join(",", (const char **)cpulist
, false);
335 static ssize_t
get_max_cpus(char *cpulist
)
338 char *maxcpus
= cpulist
;
341 c1
= strrchr(maxcpus
, ',');
345 c2
= strrchr(maxcpus
, '-');
359 cpus
= strtoul(c1
, NULL
, 0);
366 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
367 static bool cg_legacy_filter_and_set_cpus(char *path
, bool am_initialized
)
371 char *lastslash
, *fpath
, oldv
;
372 ssize_t maxisol
= 0, maxposs
= 0;
373 char *cpulist
= NULL
, *isolcpus
= NULL
, *posscpus
= NULL
;
374 uint32_t *isolmask
= NULL
, *possmask
= NULL
;
375 bool bret
= false, flipped_bit
= false;
377 lastslash
= strrchr(path
, '/');
379 ERROR("Failed to detect \"/\" in \"%s\"", path
);
384 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
385 posscpus
= read_file(fpath
);
387 SYSERROR("Failed to read file \"%s\"", fpath
);
391 /* Get maximum number of cpus found in possible cpuset. */
392 maxposs
= get_max_cpus(posscpus
);
396 if (!file_exists(__ISOL_CPUS
)) {
397 /* This system doesn't expose isolated cpus. */
398 DEBUG("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
400 /* No isolated cpus but we weren't already initialized by
401 * someone. We should simply copy the parents cpuset.cpus
404 if (!am_initialized
) {
405 DEBUG("Copying cpu settings of parent cgroup");
408 /* No isolated cpus but we were already initialized by someone.
409 * Nothing more to do for us.
414 isolcpus
= read_file(__ISOL_CPUS
);
416 SYSERROR("Failed to read file \""__ISOL_CPUS
"\"");
419 if (!isdigit(isolcpus
[0])) {
420 TRACE("No isolated cpus detected");
422 /* No isolated cpus but we weren't already initialized by
423 * someone. We should simply copy the parents cpuset.cpus
426 if (!am_initialized
) {
427 DEBUG("Copying cpu settings of parent cgroup");
430 /* No isolated cpus but we were already initialized by someone.
431 * Nothing more to do for us.
436 /* Get maximum number of cpus found in isolated cpuset. */
437 maxisol
= get_max_cpus(isolcpus
);
441 if (maxposs
< maxisol
)
445 possmask
= lxc_cpumask(posscpus
, maxposs
);
447 ERROR("Failed to create cpumask for possible cpus");
451 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
453 ERROR("Failed to create cpumask for isolated cpus");
457 for (i
= 0; i
<= maxposs
; i
++) {
458 if (!is_set(i
, isolmask
) || !is_set(i
, possmask
))
462 clear_bit(i
, possmask
);
466 DEBUG("No isolated cpus present in cpuset");
469 DEBUG("Removed isolated cpus from cpuset");
471 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
473 ERROR("Failed to create cpu list");
480 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
481 ret
= lxc_write_to_file(fpath
, cpulist
, strlen(cpulist
), false, 0666);
483 SYSERROR("Failed to write cpu list to \"%s\"", fpath
);
496 if (posscpus
!= cpulist
)
504 /* Copy contents of parent(@path)/@file to @path/@file */
505 static bool copy_parent_file(char *path
, char *file
)
508 char *fpath
, *lastslash
, oldv
;
512 lastslash
= strrchr(path
, '/');
514 ERROR("Failed to detect \"/\" in \"%s\"", path
);
519 fpath
= must_make_path(path
, file
, NULL
);
520 len
= lxc_read_from_file(fpath
, NULL
, 0);
524 value
= must_alloc(len
+ 1);
525 ret
= lxc_read_from_file(fpath
, value
, len
);
531 fpath
= must_make_path(path
, file
, NULL
);
532 ret
= lxc_write_to_file(fpath
, value
, len
, false, 0666);
534 SYSERROR("Failed to write \"%s\" to file \"%s\"", value
, fpath
);
540 SYSERROR("Failed to read file \"%s\"", fpath
);
546 /* Initialize the cpuset hierarchy in first directory of @gname and set
547 * cgroup.clone_children so that children inherit settings. Since the
548 * h->base_path is populated by init or ourselves, we know it is already
551 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
, char *cgname
)
555 char *cgpath
, *clonechildrenpath
, *slash
;
557 if (!string_in_list(h
->controllers
, "cpuset"))
562 slash
= strchr(cgname
, '/');
566 cgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgname
, NULL
);
570 ret
= mkdir(cgpath
, 0755);
572 if (errno
!= EEXIST
) {
573 SYSERROR("Failed to create directory \"%s\"", cgpath
);
580 must_make_path(cgpath
, "cgroup.clone_children", NULL
);
581 /* unified hierarchy doesn't have clone_children */
582 if (!file_exists(clonechildrenpath
)) {
583 free(clonechildrenpath
);
588 ret
= lxc_read_from_file(clonechildrenpath
, &v
, 1);
590 SYSERROR("Failed to read file \"%s\"", clonechildrenpath
);
591 free(clonechildrenpath
);
596 /* Make sure any isolated cpus are removed from cpuset.cpus. */
597 if (!cg_legacy_filter_and_set_cpus(cgpath
, v
== '1')) {
598 SYSERROR("Failed to remove isolated cpus");
599 free(clonechildrenpath
);
604 /* Already set for us by someone else. */
606 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
607 free(clonechildrenpath
);
612 /* copy parent's settings */
613 if (!copy_parent_file(cgpath
, "cpuset.mems")) {
614 SYSERROR("Failed to copy \"cpuset.mems\" settings");
616 free(clonechildrenpath
);
621 ret
= lxc_write_to_file(clonechildrenpath
, "1", 1, false, 0666);
623 /* Set clone_children so children inherit our settings */
624 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath
);
625 free(clonechildrenpath
);
628 free(clonechildrenpath
);
632 /* Given two null-terminated lists of strings, return true if any string is in
635 static bool controller_lists_intersect(char **l1
, char **l2
)
642 for (i
= 0; l1
[i
]; i
++) {
643 if (string_in_list(l2
, l1
[i
]))
650 /* For a null-terminated list of controllers @clist, return true if any of those
651 * controllers is already listed the null-terminated list of hierarchies @hlist.
652 * Realistically, if one is present, all must be present.
654 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
661 for (i
= 0; hlist
[i
]; i
++)
662 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
668 /* Return true if the controller @entry is found in the null-terminated list of
669 * hierarchies @hlist.
671 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
678 for (i
= 0; hlist
[i
]; i
++)
679 if (string_in_list(hlist
[i
]->controllers
, entry
))
685 /* Return true if all of the controllers which we require have been found. The
686 * required list is freezer and anything in lxc.cgroup.use.
688 static bool all_controllers_found(struct cgroup_ops
*ops
)
691 char *saveptr
= NULL
;
692 struct hierarchy
**hlist
= ops
->hierarchies
;
694 if (!controller_found(hlist
, "freezer")) {
695 ERROR("No freezer controller mountpoint found");
699 if (!ops
->cgroup_use
)
702 for (; (p
= strtok_r(ops
->cgroup_use
, ",", &saveptr
)); ops
->cgroup_use
= NULL
)
703 if (!controller_found(hlist
, p
)) {
704 ERROR("No %s controller mountpoint found", p
);
711 /* Get the controllers from a mountinfo line There are other ways we could get
712 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
713 * could parse the mount options. But we simply assume that the mountpoint must
714 * be /sys/fs/cgroup/controller-list
716 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
719 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
720 * for legacy hierarchies.
723 char *dup
, *p2
, *tok
;
724 char *p
= line
, *saveptr
= NULL
, *sep
= ",";
727 for (i
= 0; i
< 4; i
++) {
734 /* Note, if we change how mountinfo works, then our caller will need to
735 * verify /sys/fs/cgroup/ in this field.
737 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0) {
738 ERROR("Found hierarchy not under /sys/fs/cgroup: \"%s\"", p
);
745 ERROR("Corrupt mountinfo");
750 if (type
== CGROUP_SUPER_MAGIC
) {
751 /* strdup() here for v1 hierarchies. Otherwise strtok_r() will
752 * destroy mountpoints such as "/sys/fs/cgroup/cpu,cpuacct".
758 for (tok
= strtok_r(dup
, sep
, &saveptr
); tok
;
759 tok
= strtok_r(NULL
, sep
, &saveptr
))
760 must_append_controller(klist
, nlist
, &aret
, tok
);
769 static char **cg_unified_make_empty_controller(void)
774 newentry
= append_null_to_list((void ***)&aret
);
775 aret
[newentry
] = NULL
;
779 static char **cg_unified_get_controllers(const char *file
)
782 char *saveptr
= NULL
, *sep
= " \t\n";
785 buf
= read_file(file
);
789 for (tok
= strtok_r(buf
, sep
, &saveptr
); tok
;
790 tok
= strtok_r(NULL
, sep
, &saveptr
)) {
794 newentry
= append_null_to_list((void ***)&aret
);
795 copy
= must_copy_string(tok
);
796 aret
[newentry
] = copy
;
803 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
804 char *base_cgroup
, int type
)
806 struct hierarchy
*new;
809 new = must_alloc(sizeof(*new));
810 new->controllers
= clist
;
811 new->mountpoint
= mountpoint
;
812 new->base_cgroup
= base_cgroup
;
813 new->fullcgpath
= NULL
;
816 newentry
= append_null_to_list((void ***)h
);
817 (*h
)[newentry
] = new;
821 /* Get a copy of the mountpoint from @line, which is a line from
822 * /proc/self/mountinfo.
824 static char *cg_hybrid_get_mountpoint(char *line
)
829 char *p
= line
, *sret
= NULL
;
831 for (i
= 0; i
< 4; i
++) {
838 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
841 p2
= strchr(p
+ 15, ' ');
847 sret
= must_alloc(len
+ 1);
848 memcpy(sret
, p
, len
);
853 /* Given a multi-line string, return a null-terminated copy of the current line. */
854 static char *copy_to_eol(char *p
)
856 char *p2
= strchr(p
, '\n'), *sret
;
863 sret
= must_alloc(len
+ 1);
864 memcpy(sret
, p
, len
);
869 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
870 * /proc/self/cgroup file. Check whether controller c is present.
872 static bool controller_in_clist(char *cgline
, char *c
)
874 char *tok
, *saveptr
= NULL
, *eol
, *tmp
;
877 eol
= strchr(cgline
, ':');
882 tmp
= alloca(len
+ 1);
883 memcpy(tmp
, cgline
, len
);
886 for (tok
= strtok_r(tmp
, ",", &saveptr
); tok
;
887 tok
= strtok_r(NULL
, ",", &saveptr
)) {
888 if (strcmp(tok
, c
) == 0)
895 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
898 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
901 char *p
= basecginfo
;
904 bool is_cgv2_base_cgroup
= false;
906 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
907 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
908 is_cgv2_base_cgroup
= true;
915 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
920 return copy_to_eol(p
);
930 static void must_append_string(char ***list
, char *entry
)
935 newentry
= append_null_to_list((void ***)list
);
936 copy
= must_copy_string(entry
);
937 (*list
)[newentry
] = copy
;
940 static int get_existing_subsystems(char ***klist
, char ***nlist
)
946 f
= fopen("/proc/self/cgroup", "r");
950 while (getline(&line
, &len
, f
) != -1) {
951 char *p
, *p2
, *tok
, *saveptr
= NULL
;
952 p
= strchr(line
, ':');
961 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
962 * contains an entry of the form:
966 * In this case we use "cgroup2" as controller name.
969 must_append_string(klist
, "cgroup2");
973 for (tok
= strtok_r(p
, ",", &saveptr
); tok
;
974 tok
= strtok_r(NULL
, ",", &saveptr
)) {
975 if (strncmp(tok
, "name=", 5) == 0)
976 must_append_string(nlist
, tok
);
978 must_append_string(klist
, tok
);
987 static void trim(char *s
)
992 while ((len
> 1) && (s
[len
- 1] == '\n'))
996 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
999 struct hierarchy
**it
;
1001 if (!ops
->hierarchies
) {
1002 TRACE(" No hierarchies found");
1006 TRACE(" Hierarchies:");
1007 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
1011 TRACE(" %d: base_cgroup: %s", i
, (*it
)->base_cgroup
? (*it
)->base_cgroup
: "(null)");
1012 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
1013 TRACE(" controllers:");
1014 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
1015 TRACE(" %d: %s", j
, *cit
);
1019 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
1025 TRACE("basecginfo is:");
1026 TRACE("%s", basecginfo
);
1028 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
1029 TRACE("kernel subsystem %d: %s", k
, *it
);
1031 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
1032 TRACE("named subsystem %d: %s", k
, *it
);
1035 static int recursive_destroy(char *dirname
)
1038 struct dirent
*direntp
;
1042 dir
= opendir(dirname
);
1046 while ((direntp
= readdir(dir
))) {
1050 if (!strcmp(direntp
->d_name
, ".") ||
1051 !strcmp(direntp
->d_name
, ".."))
1054 pathname
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1056 ret
= lstat(pathname
, &mystat
);
1059 WARN("Failed to stat \"%s\"", pathname
);
1064 if (!S_ISDIR(mystat
.st_mode
))
1067 ret
= recursive_destroy(pathname
);
1074 ret
= rmdir(dirname
);
1077 WARN("%s - Failed to delete \"%s\"", strerror(errno
), dirname
);
1081 ret
= closedir(dir
);
1084 WARN("%s - Failed to delete \"%s\"", strerror(errno
), dirname
);
1091 static int cgroup_rmdir(struct hierarchy
**hierarchies
,
1092 const char *container_cgroup
)
1096 if (!container_cgroup
|| !hierarchies
)
1099 for (i
= 0; hierarchies
[i
]; i
++) {
1101 struct hierarchy
*h
= hierarchies
[i
];
1106 ret
= recursive_destroy(h
->fullcgpath
);
1108 WARN("Failed to destroy \"%s\"", h
->fullcgpath
);
1110 free(h
->fullcgpath
);
1111 h
->fullcgpath
= NULL
;
1117 struct generic_userns_exec_data
{
1118 struct hierarchy
**hierarchies
;
1119 const char *container_cgroup
;
1120 struct lxc_conf
*conf
;
1121 uid_t origuid
; /* target uid in parent namespace */
1125 static int cgroup_rmdir_wrapper(void *data
)
1128 struct generic_userns_exec_data
*arg
= data
;
1129 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1130 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1132 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1134 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid
,
1135 (int)nsgid
, (int)nsgid
);
1139 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1141 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid
,
1142 (int)nsuid
, (int)nsuid
);
1146 ret
= setgroups(0, NULL
);
1147 if (ret
< 0 && errno
!= EPERM
) {
1148 SYSERROR("Failed to setgroups(0, NULL)");
1152 return cgroup_rmdir(arg
->hierarchies
, arg
->container_cgroup
);
1155 static void cgfsng_destroy(struct cgroup_ops
*ops
, struct lxc_handler
*handler
)
1158 struct generic_userns_exec_data wrap
;
1161 wrap
.container_cgroup
= ops
->container_cgroup
;
1162 wrap
.hierarchies
= ops
->hierarchies
;
1163 wrap
.conf
= handler
->conf
;
1165 if (handler
->conf
&& !lxc_list_empty(&handler
->conf
->id_map
))
1166 ret
= userns_exec_1(handler
->conf
, cgroup_rmdir_wrapper
, &wrap
,
1167 "cgroup_rmdir_wrapper");
1169 ret
= cgroup_rmdir(ops
->hierarchies
, ops
->container_cgroup
);
1171 WARN("Failed to destroy cgroups");
1176 static bool cg_unified_create_cgroup(struct hierarchy
*h
, char *cgname
)
1178 size_t i
, parts_len
;
1180 size_t full_len
= 0;
1181 char *add_controllers
= NULL
, *cgroup
= NULL
;
1182 char **parts
= NULL
;
1185 if (h
->version
!= CGROUP2_SUPER_MAGIC
)
1188 if (!h
->controllers
)
1191 /* For now we simply enable all controllers that we have detected by
1192 * creating a string like "+memory +pids +cpu +io".
1193 * TODO: In the near future we might want to support "-<controller>"
1194 * etc. but whether supporting semantics like this make sense will need
1197 for (it
= h
->controllers
; it
&& *it
; it
++) {
1198 full_len
+= strlen(*it
) + 2;
1199 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
1200 if (h
->controllers
[0] == *it
)
1201 add_controllers
[0] = '\0';
1202 strcat(add_controllers
, "+");
1203 strcat(add_controllers
, *it
);
1204 if ((it
+ 1) && *(it
+ 1))
1205 strcat(add_controllers
, " ");
1208 parts
= lxc_string_split(cgname
, '/');
1211 parts_len
= lxc_array_len((void **)parts
);
1215 cgroup
= must_make_path(h
->mountpoint
, h
->base_cgroup
, NULL
);
1216 for (i
= 0; i
< parts_len
; i
++) {
1220 cgroup
= must_append_path(cgroup
, parts
[i
], NULL
);
1221 target
= must_make_path(cgroup
, "cgroup.subtree_control", NULL
);
1222 ret
= lxc_write_to_file(target
, add_controllers
, full_len
, false, 0666);
1225 SYSERROR("Could not enable \"%s\" controllers in the "
1226 "unified cgroup \"%s\"", add_controllers
, cgroup
);
1234 lxc_free_array((void **)parts
, free
);
1235 free(add_controllers
);
1240 static bool create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1244 h
->fullcgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgname
, NULL
);
1245 if (dir_exists(h
->fullcgpath
)) {
1246 ERROR("The cgroup \"%s\" already existed", h
->fullcgpath
);
1250 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1251 ERROR("Failed to handle legacy cpuset controller");
1255 ret
= mkdir_p(h
->fullcgpath
, 0755);
1257 ERROR("Failed to create cgroup \"%s\"", h
->fullcgpath
);
1261 return cg_unified_create_cgroup(h
, cgname
);
1264 static void remove_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1268 ret
= rmdir(h
->fullcgpath
);
1270 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", h
->fullcgpath
);
1272 free(h
->fullcgpath
);
1273 h
->fullcgpath
= NULL
;
1276 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1277 * next cgroup_pattern-1, -2, ..., -999.
1279 static inline bool cgfsng_create(struct cgroup_ops
*ops
,
1280 struct lxc_handler
*handler
)
1284 char *container_cgroup
, *offset
, *tmp
;
1286 struct lxc_conf
*conf
= handler
->conf
;
1287 const char *join_args
[] = {conf
->cgroup_meta
.dir
, handler
->name
, NULL
};
1289 if (ops
->container_cgroup
) {
1290 WARN("cgfsng_create called a second time: %s", ops
->container_cgroup
);
1297 if (conf
->cgroup_meta
.dir
)
1298 tmp
= lxc_string_join("/", join_args
, false);
1300 tmp
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1302 ERROR("Failed expanding cgroup name pattern");
1305 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1306 container_cgroup
= must_alloc(len
);
1307 strcpy(container_cgroup
, tmp
);
1309 offset
= container_cgroup
+ len
- 5;
1313 ERROR("Too many conflicting cgroup names");
1320 ret
= snprintf(offset
, 5, "-%d", idx
);
1321 if (ret
< 0 || (size_t)ret
>= 5) {
1322 FILE *f
= fopen("/dev/null", "w");
1324 fprintf(f
, "Workaround for GCC7 bug: "
1325 "https://gcc.gnu.org/bugzilla/"
1326 "show_bug.cgi?id=78969");
1332 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1333 if (!create_path_for_hierarchy(ops
->hierarchies
[i
], container_cgroup
)) {
1335 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->fullcgpath
);
1336 free(ops
->hierarchies
[i
]->fullcgpath
);
1337 ops
->hierarchies
[i
]->fullcgpath
= NULL
;
1338 for (j
= 0; j
< i
; j
++)
1339 remove_path_for_hierarchy(ops
->hierarchies
[j
], container_cgroup
);
1345 ops
->container_cgroup
= container_cgroup
;
1350 free(container_cgroup
);
1355 static bool cgfsng_enter(struct cgroup_ops
*ops
, pid_t pid
)
1360 len
= snprintf(pidstr
, 25, "%d", pid
);
1361 if (len
< 0 || len
>= 25)
1364 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1368 fullpath
= must_make_path(ops
->hierarchies
[i
]->fullcgpath
,
1369 "cgroup.procs", NULL
);
1370 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
1372 SYSERROR("Failed to enter cgroup \"%s\"", fullpath
);
1382 static int chowmod(char *path
, uid_t chown_uid
, gid_t chown_gid
,
1387 ret
= chown(path
, chown_uid
, chown_gid
);
1389 WARN("%s - Failed to chown(%s, %d, %d)", strerror(errno
), path
,
1390 (int)chown_uid
, (int)chown_gid
);
1394 ret
= chmod(path
, chmod_mode
);
1396 WARN("%s - Failed to chmod(%s, %d)", strerror(errno
), path
,
1404 /* chgrp the container cgroups to container group. We leave
1405 * the container owner as cgroup owner. So we must make the
1406 * directories 775 so that the container can create sub-cgroups.
1408 * Also chown the tasks and cgroup.procs files. Those may not
1409 * exist depending on kernel version.
1411 static int chown_cgroup_wrapper(void *data
)
1415 struct generic_userns_exec_data
*arg
= data
;
1416 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1417 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1419 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1421 SYSERROR("Failed to setresgid(%d, %d, %d)",
1422 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1426 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1428 SYSERROR("Failed to setresuid(%d, %d, %d)",
1429 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1433 ret
= setgroups(0, NULL
);
1434 if (ret
< 0 && errno
!= EPERM
) {
1435 SYSERROR("Failed to setgroups(0, NULL)");
1439 destuid
= get_ns_uid(arg
->origuid
);
1441 for (i
= 0; arg
->hierarchies
[i
]; i
++) {
1443 char *path
= arg
->hierarchies
[i
]->fullcgpath
;
1445 ret
= chowmod(path
, destuid
, nsgid
, 0775);
1449 /* Failures to chown() these are inconvenient but not
1450 * detrimental We leave these owned by the container launcher,
1451 * so that container root can write to the files to attach. We
1452 * chmod() them 664 so that container systemd can write to the
1453 * files (which systemd in wily insists on doing).
1456 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
) {
1457 fullpath
= must_make_path(path
, "tasks", NULL
);
1458 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1462 fullpath
= must_make_path(path
, "cgroup.procs", NULL
);
1463 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1466 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1469 fullpath
= must_make_path(path
, "cgroup.subtree_control", NULL
);
1470 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1473 fullpath
= must_make_path(path
, "cgroup.threads", NULL
);
1474 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1481 static bool cgfsng_chown(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
1483 struct generic_userns_exec_data wrap
;
1485 if (lxc_list_empty(&conf
->id_map
))
1488 wrap
.origuid
= geteuid();
1490 wrap
.hierarchies
= ops
->hierarchies
;
1493 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
,
1494 "chown_cgroup_wrapper") < 0) {
1495 ERROR("Error requesting cgroup chown in new user namespace");
1502 /* cgroup-full:* is done, no need to create subdirs */
1503 static bool cg_mount_needs_subdirs(int type
)
1505 if (type
>= LXC_AUTO_CGROUP_FULL_RO
)
1511 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1512 * remount controller ro if needed and bindmount the cgroupfs onto
1513 * controll/the/cg/path.
1515 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1516 char *controllerpath
, char *cgpath
,
1517 const char *container_cgroup
)
1519 int ret
, remount_flags
;
1521 int flags
= MS_BIND
;
1523 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1524 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1526 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
1527 controllerpath
, controllerpath
);
1531 remount_flags
= add_required_remount_flags(controllerpath
,
1533 flags
| MS_REMOUNT
);
1534 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1535 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1538 SYSERROR("Failed to remount \"%s\" ro", controllerpath
);
1542 INFO("Remounted %s read-only", controllerpath
);
1545 sourcepath
= must_make_path(h
->mountpoint
, h
->base_cgroup
,
1546 container_cgroup
, NULL
);
1547 if (type
== LXC_AUTO_CGROUP_RO
)
1550 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1552 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1556 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1558 if (flags
& MS_RDONLY
) {
1559 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1560 flags
| MS_REMOUNT
);
1561 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1563 SYSERROR("Failed to remount \"%s\" ro", cgpath
);
1567 INFO("Remounted %s read-only", cgpath
);
1571 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1575 /* __cg_mount_direct
1577 * Mount cgroup hierarchies directly without using bind-mounts. The main
1578 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1579 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1581 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1582 const char *controllerpath
)
1585 char *controllers
= NULL
;
1586 char *fstype
= "cgroup2";
1587 unsigned long flags
= 0;
1592 flags
|= MS_RELATIME
;
1594 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1597 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1598 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1604 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1607 SYSERROR("Failed to mount \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1611 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1615 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1616 const char *controllerpath
)
1618 return __cg_mount_direct(type
, h
, controllerpath
);
1621 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1622 const char *controllerpath
)
1624 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1627 return __cg_mount_direct(type
, h
, controllerpath
);
1630 static bool cgfsng_mount(struct cgroup_ops
*ops
, struct lxc_handler
*handler
,
1631 const char *root
, int type
)
1634 char *tmpfspath
= NULL
;
1635 bool has_cgns
= false, retval
= false, wants_force_mount
= false;
1637 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1640 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1641 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1642 wants_force_mount
= true;
1645 if (!wants_force_mount
){
1646 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1647 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1649 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1652 has_cgns
= cgns_supported();
1653 if (has_cgns
&& !wants_force_mount
)
1656 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1657 type
= LXC_AUTO_CGROUP_MIXED
;
1658 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1659 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1662 tmpfspath
= must_make_path(root
, "/sys/fs/cgroup", NULL
);
1663 ret
= safe_mount(NULL
, tmpfspath
, "tmpfs",
1664 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1665 "size=10240k,mode=755", root
);
1669 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1670 char *controllerpath
, *path2
;
1671 struct hierarchy
*h
= ops
->hierarchies
[i
];
1672 char *controller
= strrchr(h
->mountpoint
, '/');
1678 controllerpath
= must_make_path(tmpfspath
, controller
, NULL
);
1679 if (dir_exists(controllerpath
)) {
1680 free(controllerpath
);
1684 ret
= mkdir(controllerpath
, 0755);
1686 SYSERROR("Error creating cgroup path: %s", controllerpath
);
1687 free(controllerpath
);
1691 if (has_cgns
&& wants_force_mount
) {
1692 /* If cgroup namespaces are supported but the container
1693 * will not have CAP_SYS_ADMIN after it has started we
1694 * need to mount the cgroups manually.
1696 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1697 free(controllerpath
);
1704 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1706 free(controllerpath
);
1710 if (!cg_mount_needs_subdirs(type
)) {
1711 free(controllerpath
);
1715 path2
= must_make_path(controllerpath
, h
->base_cgroup
,
1716 ops
->container_cgroup
, NULL
);
1717 ret
= mkdir_p(path2
, 0755);
1719 free(controllerpath
);
1724 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1725 path2
, ops
->container_cgroup
);
1726 free(controllerpath
);
1738 static int recursive_count_nrtasks(char *dirname
)
1740 struct dirent
*direntp
;
1745 dir
= opendir(dirname
);
1749 while ((direntp
= readdir(dir
))) {
1755 if (!strcmp(direntp
->d_name
, ".") ||
1756 !strcmp(direntp
->d_name
, ".."))
1759 path
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1761 if (lstat(path
, &mystat
))
1764 if (!S_ISDIR(mystat
.st_mode
))
1767 count
+= recursive_count_nrtasks(path
);
1772 path
= must_make_path(dirname
, "cgroup.procs", NULL
);
1773 ret
= lxc_count_file_lines(path
);
1778 (void)closedir(dir
);
1783 static int cgfsng_nrtasks(struct cgroup_ops
*ops
)
1788 if (!ops
->container_cgroup
|| !ops
->hierarchies
)
1791 path
= must_make_path(ops
->hierarchies
[0]->fullcgpath
, NULL
);
1792 count
= recursive_count_nrtasks(path
);
1797 /* Only root needs to escape to the cgroup of its init. */
1798 static bool cgfsng_escape(const struct cgroup_ops
*ops
)
1805 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1809 fullpath
= must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1810 ops
->hierarchies
[i
]->base_cgroup
,
1811 "cgroup.procs", NULL
);
1812 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1814 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath
);
1824 static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1828 for (i
= 0; ops
->hierarchies
[i
]; i
++)
1834 static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
, char ***out
)
1838 /* sanity check n */
1839 for (i
= 0; i
< n
; i
++)
1840 if (!ops
->hierarchies
[i
])
1843 *out
= ops
->hierarchies
[i
]->controllers
;
1848 #define THAWED "THAWED"
1849 #define THAWED_LEN (strlen(THAWED))
1851 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
1854 static bool cgfsng_unfreeze(struct cgroup_ops
*ops
)
1858 struct hierarchy
*h
;
1860 h
= get_hierarchy(ops
, "freezer");
1864 fullpath
= must_make_path(h
->fullcgpath
, "freezer.state", NULL
);
1865 ret
= lxc_write_to_file(fullpath
, THAWED
, THAWED_LEN
, false, 0666);
1873 static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
1874 const char *controller
)
1876 struct hierarchy
*h
;
1878 h
= get_hierarchy(ops
, controller
);
1880 WARN("Failed to find hierarchy for controller \"%s\"",
1881 controller
? controller
: "(null)");
1885 return h
->fullcgpath
? h
->fullcgpath
+ strlen(h
->mountpoint
) : NULL
;
1888 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
1889 * which must be freed by the caller.
1891 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
1893 const char *filename
)
1895 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
1898 /* Technically, we're always at a delegation boundary here (This is especially
1899 * true when cgroup namespaces are available.). The reasoning is that in order
1900 * for us to have been able to start a container in the first place the root
1901 * cgroup must have been a leaf node. Now, either the container's init system
1902 * has populated the cgroup and kept it as a leaf node or it has created
1903 * subtrees. In the former case we will simply attach to the leaf node we
1904 * created when we started the container in the latter case we create our own
1905 * cgroup for the attaching process.
1907 static int __cg_unified_attach(const struct hierarchy
*h
, const char *name
,
1908 const char *lxcpath
, const char *pidstr
,
1909 size_t pidstr_len
, const char *controller
)
1913 int fret
= -1, idx
= 0;
1914 char *base_path
= NULL
, *container_cgroup
= NULL
, *full_path
= NULL
;
1916 container_cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
1918 if (!container_cgroup
)
1921 base_path
= must_make_path(h
->mountpoint
, container_cgroup
, NULL
);
1922 full_path
= must_make_path(base_path
, "cgroup.procs", NULL
);
1923 /* cgroup is populated */
1924 ret
= lxc_write_to_file(full_path
, pidstr
, pidstr_len
, false, 0666);
1925 if (ret
< 0 && errno
!= EBUSY
)
1933 len
= strlen(base_path
) + sizeof("/lxc-1000") - 1 +
1934 sizeof("/cgroup-procs") - 1;
1935 full_path
= must_alloc(len
+ 1);
1938 ret
= snprintf(full_path
, len
+ 1, "%s/lxc-%d",
1941 ret
= snprintf(full_path
, len
+ 1, "%s/lxc", base_path
);
1942 if (ret
< 0 || (size_t)ret
>= len
+ 1)
1945 ret
= mkdir_p(full_path
, 0755);
1946 if (ret
< 0 && errno
!= EEXIST
)
1949 strcat(full_path
, "/cgroup.procs");
1950 ret
= lxc_write_to_file(full_path
, pidstr
, len
, false, 0666);
1954 /* this is a non-leaf node */
1958 } while (++idx
> 0 && idx
< 1000);
1966 free(container_cgroup
);
1972 static bool cgfsng_attach(struct cgroup_ops
*ops
, const char *name
,
1973 const char *lxcpath
, pid_t pid
)
1978 len
= snprintf(pidstr
, 25, "%d", pid
);
1979 if (len
< 0 || len
>= 25)
1982 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1984 char *fullpath
= NULL
;
1985 struct hierarchy
*h
= ops
->hierarchies
[i
];
1987 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
1988 ret
= __cg_unified_attach(h
, name
, lxcpath
, pidstr
, len
,
1996 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2001 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2003 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2005 SYSERROR("Failed to attach %d to %s", (int)pid
, fullpath
);
2015 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2016 * don't have a cgroup_data set up, so we ask the running container through the
2017 * commands API for the cgroup path.
2019 static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
, char *value
,
2020 size_t len
, const char *name
, const char *lxcpath
)
2023 size_t controller_len
;
2024 char *controller
, *p
, *path
;
2025 struct hierarchy
*h
;
2027 controller_len
= strlen(filename
);
2028 controller
= alloca(controller_len
+ 1);
2029 strcpy(controller
, filename
);
2030 p
= strchr(controller
, '.');
2034 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2039 h
= get_hierarchy(ops
, controller
);
2043 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2044 ret
= lxc_read_from_file(fullpath
, value
, len
);
2052 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2053 * don't have a cgroup_data set up, so we ask the running container through the
2054 * commands API for the cgroup path.
2056 static int cgfsng_set(struct cgroup_ops
*ops
, const char *filename
,
2057 const char *value
, const char *name
, const char *lxcpath
)
2060 size_t controller_len
;
2061 char *controller
, *p
, *path
;
2062 struct hierarchy
*h
;
2064 controller_len
= strlen(filename
);
2065 controller
= alloca(controller_len
+ 1);
2066 strcpy(controller
, filename
);
2067 p
= strchr(controller
, '.');
2071 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2076 h
= get_hierarchy(ops
, controller
);
2080 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2081 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2089 /* take devices cgroup line
2091 * and convert it to a valid
2092 * type major:minor mode
2093 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2096 static int convert_devpath(const char *invalue
, char *dest
)
2099 char *p
, *path
, type
;
2100 unsigned long minor
, major
;
2105 path
= must_copy_string(invalue
);
2107 /* Read path followed by mode. Ignore any trailing text.
2108 * A ' # comment' would be legal. Technically other text is not
2109 * legal, we could check for that if we cared to.
2111 for (n_parts
= 1, p
= path
; *p
&& n_parts
< 3; p
++) {
2133 ret
= stat(path
, &sb
);
2137 mode_t m
= sb
.st_mode
& S_IFMT
;
2146 ERROR("Unsupported device type %i for \"%s\"", m
, path
);
2151 major
= MAJOR(sb
.st_rdev
);
2152 minor
= MINOR(sb
.st_rdev
);
2153 ret
= snprintf(dest
, 50, "%c %lu:%lu %s", type
, major
, minor
, mode
);
2154 if (ret
< 0 || ret
>= 50) {
2155 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2156 "chars)", type
, major
, minor
, mode
);
2157 ret
= -ENAMETOOLONG
;
2167 /* Called from setup_limits - here we have the container's cgroup_data because
2168 * we created the cgroups.
2170 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2175 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2176 char converted_value
[50];
2177 struct hierarchy
*h
;
2179 char *controller
= NULL
;
2181 len
= strlen(filename
);
2182 controller
= alloca(len
+ 1);
2183 strcpy(controller
, filename
);
2184 p
= strchr(controller
, '.');
2188 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2189 ret
= convert_devpath(value
, converted_value
);
2192 value
= converted_value
;
2195 h
= get_hierarchy(ops
, controller
);
2197 ERROR("Failed to setup limits for the \"%s\" controller. "
2198 "The controller seems to be unused by \"cgfsng\" cgroup "
2199 "driver or not enabled on the cgroup hierarchy",
2205 fullpath
= must_make_path(h
->fullcgpath
, filename
, NULL
);
2206 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2211 static bool __cg_legacy_setup_limits(struct cgroup_ops
*ops
,
2212 struct lxc_list
*cgroup_settings
,
2215 struct lxc_list
*iterator
, *next
, *sorted_cgroup_settings
;
2216 struct lxc_cgroup
*cg
;
2219 if (lxc_list_empty(cgroup_settings
))
2222 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2223 if (!sorted_cgroup_settings
)
2226 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2227 cg
= iterator
->elem
;
2229 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2230 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
)) {
2231 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2232 WARN("Failed to set \"%s\" to \"%s\"",
2233 cg
->subsystem
, cg
->value
);
2236 WARN("Failed to set \"%s\" to \"%s\"",
2237 cg
->subsystem
, cg
->value
);
2240 DEBUG("Set controller \"%s\" set to \"%s\"",
2241 cg
->subsystem
, cg
->value
);
2246 INFO("Limits for the legacy cgroup hierarchies have been setup");
2248 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2249 lxc_list_del(iterator
);
2252 free(sorted_cgroup_settings
);
2256 static bool __cg_unified_setup_limits(struct cgroup_ops
*ops
,
2257 struct lxc_list
*cgroup_settings
)
2259 struct lxc_list
*iterator
;
2260 struct hierarchy
*h
= ops
->unified
;
2262 if (lxc_list_empty(cgroup_settings
))
2268 lxc_list_for_each(iterator
, cgroup_settings
) {
2271 struct lxc_cgroup
*cg
= iterator
->elem
;
2273 fullpath
= must_make_path(h
->fullcgpath
, cg
->subsystem
, NULL
);
2274 ret
= lxc_write_to_file(fullpath
, cg
->value
, strlen(cg
->value
), false, 0666);
2277 SYSERROR("Failed to set \"%s\" to \"%s\"",
2278 cg
->subsystem
, cg
->value
);
2281 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2284 INFO("Limits for the unified cgroup hierarchy have been setup");
2288 static bool cgfsng_setup_limits(struct cgroup_ops
*ops
, struct lxc_conf
*conf
,
2293 bret
= __cg_legacy_setup_limits(ops
, &conf
->cgroup
, do_devices
);
2297 return __cg_unified_setup_limits(ops
, &conf
->cgroup2
);
2300 /* At startup, parse_hierarchies finds all the info we need about cgroup
2301 * mountpoints and current cgroups, and stores it in @d.
2303 static bool cg_hybrid_init(struct cgroup_ops
*ops
)
2311 char **klist
= NULL
, **nlist
= NULL
;
2313 /* Root spawned containers escape the current cgroup, so use init's
2314 * cgroups as our base in that case.
2316 will_escape
= (geteuid() == 0);
2318 basecginfo
= read_file("/proc/1/cgroup");
2320 basecginfo
= read_file("/proc/self/cgroup");
2324 ret
= get_existing_subsystems(&klist
, &nlist
);
2326 ERROR("Failed to retrieve available legacy cgroup controllers");
2331 f
= fopen("/proc/self/mountinfo", "r");
2333 ERROR("Failed to open \"/proc/self/mountinfo\"");
2338 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
2340 while (getline(&line
, &len
, f
) != -1) {
2343 struct hierarchy
*new;
2344 char *base_cgroup
= NULL
, *mountpoint
= NULL
;
2345 char **controller_list
= NULL
;
2347 type
= get_cgroup_version(line
);
2351 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
2354 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
2355 if (type
== CGROUP2_SUPER_MAGIC
)
2356 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2357 else if (type
== CGROUP_SUPER_MAGIC
)
2358 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
2359 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
2360 if (type
== CGROUP_SUPER_MAGIC
)
2361 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2362 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
2363 if (type
== CGROUP2_SUPER_MAGIC
)
2364 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2367 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
2368 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
2371 if (type
== CGROUP_SUPER_MAGIC
)
2372 if (controller_list_is_dup(ops
->hierarchies
, controller_list
))
2375 mountpoint
= cg_hybrid_get_mountpoint(line
);
2377 ERROR("Failed parsing mountpoint from \"%s\"", line
);
2381 if (type
== CGROUP_SUPER_MAGIC
)
2382 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
2384 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
2386 ERROR("Failed to find current cgroup");
2391 prune_init_scope(base_cgroup
);
2392 if (type
== CGROUP2_SUPER_MAGIC
)
2393 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
2395 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
2399 if (type
== CGROUP2_SUPER_MAGIC
) {
2400 char *cgv2_ctrl_path
;
2402 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
2403 "cgroup.controllers",
2406 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
2407 free(cgv2_ctrl_path
);
2408 if (!controller_list
) {
2409 controller_list
= cg_unified_make_empty_controller();
2410 TRACE("No controllers are enabled for "
2411 "delegation in the unified hierarchy");
2415 new = add_hierarchy(&ops
->hierarchies
, controller_list
, mountpoint
, base_cgroup
, type
);
2416 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
)
2422 free_string_list(controller_list
);
2427 free_string_list(klist
);
2428 free_string_list(nlist
);
2435 TRACE("Writable cgroup hierarchies:");
2436 lxc_cgfsng_print_hierarchies(ops
);
2438 /* verify that all controllers in cgroup.use and all crucial
2439 * controllers are accounted for
2441 if (!all_controllers_found(ops
))
2447 static int cg_is_pure_unified(void)
2453 ret
= statfs("/sys/fs/cgroup", &fs
);
2457 if (is_fs_type(&fs
, CGROUP2_SUPER_MAGIC
))
2458 return CGROUP2_SUPER_MAGIC
;
2463 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
2464 static char *cg_unified_get_current_cgroup(void)
2466 char *basecginfo
, *base_cgroup
;
2470 will_escape
= (geteuid() == 0);
2472 basecginfo
= read_file("/proc/1/cgroup");
2474 basecginfo
= read_file("/proc/self/cgroup");
2478 base_cgroup
= strstr(basecginfo
, "0::/");
2480 goto cleanup_on_err
;
2482 base_cgroup
= base_cgroup
+ 3;
2483 copy
= copy_to_eol(base_cgroup
);
2485 goto cleanup_on_err
;
2495 static int cg_unified_init(struct cgroup_ops
*ops
)
2498 char *mountpoint
, *subtree_path
;
2500 char *base_cgroup
= NULL
;
2502 ret
= cg_is_pure_unified();
2503 if (ret
== -ENOMEDIUM
)
2506 if (ret
!= CGROUP2_SUPER_MAGIC
)
2509 base_cgroup
= cg_unified_get_current_cgroup();
2512 prune_init_scope(base_cgroup
);
2514 /* We assume that we have already been given controllers to delegate
2515 * further down the hierarchy. If not it is up to the user to delegate
2518 mountpoint
= must_copy_string("/sys/fs/cgroup");
2519 subtree_path
= must_make_path(mountpoint
, base_cgroup
,
2520 "cgroup.subtree_control", NULL
);
2521 delegatable
= cg_unified_get_controllers(subtree_path
);
2524 delegatable
= cg_unified_make_empty_controller();
2525 if (!delegatable
[0])
2526 TRACE("No controllers are enabled for delegation");
2528 /* TODO: If the user requested specific controllers via lxc.cgroup.use
2529 * we should verify here. The reason I'm not doing it right is that I'm
2530 * not convinced that lxc.cgroup.use will be the future since it is a
2531 * global property. I much rather have an option that lets you request
2532 * controllers per container.
2535 add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
2537 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2538 return CGROUP2_SUPER_MAGIC
;
2541 static bool cg_init(struct cgroup_ops
*ops
)
2546 tmp
= lxc_global_config_value("lxc.cgroup.use");
2548 ops
->cgroup_use
= must_copy_string(tmp
);
2550 ret
= cg_unified_init(ops
);
2554 if (ret
== CGROUP2_SUPER_MAGIC
)
2557 return cg_hybrid_init(ops
);
2560 static bool cgfsng_data_init(struct cgroup_ops
*ops
)
2562 const char *cgroup_pattern
;
2564 /* copy system-wide cgroup information */
2565 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
2566 if (!cgroup_pattern
) {
2567 /* lxc.cgroup.pattern is only NULL on error. */
2568 ERROR("Failed to retrieve cgroup pattern");
2571 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
2576 struct cgroup_ops
*cgfsng_ops_init(void)
2578 struct cgroup_ops
*cgfsng_ops
;
2580 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
2584 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
2585 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
2587 if (!cg_init(cgfsng_ops
)) {
2592 cgfsng_ops
->data_init
= cgfsng_data_init
;
2593 cgfsng_ops
->destroy
= cgfsng_destroy
;
2594 cgfsng_ops
->create
= cgfsng_create
;
2595 cgfsng_ops
->enter
= cgfsng_enter
;
2596 cgfsng_ops
->escape
= cgfsng_escape
;
2597 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
2598 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
2599 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
2600 cgfsng_ops
->get
= cgfsng_get
;
2601 cgfsng_ops
->set
= cgfsng_set
;
2602 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
2603 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
2604 cgfsng_ops
->driver
= "cgfsng";
2605 cgfsng_ops
->version
= "1.0.0";
2606 cgfsng_ops
->attach
= cgfsng_attach
;
2607 cgfsng_ops
->chown
= cgfsng_chown
;
2608 cgfsng_ops
->mount
= cgfsng_mount
;
2609 cgfsng_ops
->nrtasks
= cgfsng_nrtasks
;