2 * lxc: linux Container library
4 * Copyright © 2016 Canonical Ltd.
7 * Serge Hallyn <serge.hallyn@ubuntu.com>
8 * Christian Brauner <christian.brauner@ubuntu.com>
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
27 * cgroup backend. The original cgfs.c was designed to be as flexible
28 * as possible. It would try to find cgroup filesystems no matter where
29 * or how you had them mounted, and deduce the most usable mount for
32 * This new implementation assumes that cgroup filesystems are mounted
33 * under /sys/fs/cgroup/clist where clist is either the controller, or
34 * a comman-separated list of controllers.
48 #include <linux/kdev_t.h>
49 #include <linux/types.h>
50 #include <sys/types.h>
54 #include "cgroup_utils.h"
59 #include "storage/storage.h"
63 #include "include/strlcpy.h"
67 #include "include/strlcat.h"
70 #define __cgfsng_ops__
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=", sizeof("name=") - 1);
140 memcpy(prefixed
+ sizeof("name=") - 1, entry
, len
);
141 prefixed
[len
+ 5] = '\0';
145 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
148 * We also handle named subsystems here. Any controller which is not a kernel
149 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
150 * we refuse to use because we're not sure which we have here.
151 * (TODO: We could work around this in some cases by just remounting to be
152 * unambiguous, or by comparing mountpoint contents with current cgroup.)
154 * The last entry will always be NULL.
156 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
162 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
163 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
164 ERROR("It is both a named and kernel subsystem");
168 newentry
= append_null_to_list((void ***)clist
);
170 if (strncmp(entry
, "name=", 5) == 0)
171 copy
= must_copy_string(entry
);
172 else if (string_in_list(klist
, entry
))
173 copy
= must_copy_string(entry
);
175 copy
= cg_legacy_must_prefix_named(entry
);
177 (*clist
)[newentry
] = copy
;
180 /* Given a handler's cgroup data, return the struct hierarchy for the controller
181 * @c, or NULL if there is none.
183 struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *c
)
187 if (!ops
->hierarchies
)
190 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
192 /* This is the empty unified hierarchy. */
193 if (ops
->hierarchies
[i
]->controllers
&&
194 !ops
->hierarchies
[i
]->controllers
[0])
195 return ops
->hierarchies
[i
];
200 if (string_in_list(ops
->hierarchies
[i
]->controllers
, c
))
201 return ops
->hierarchies
[i
];
207 #define BATCH_SIZE 50
208 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
210 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
211 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
213 if (!*mem
|| newbatches
> oldbatches
) {
214 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
218 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
220 size_t full
= oldlen
+ newlen
;
222 batch_realloc(dest
, oldlen
, full
+ 1);
224 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
227 /* Slurp in a whole file */
228 static char *read_file(const char *fnam
)
231 char *line
= NULL
, *buf
= NULL
;
232 size_t len
= 0, fulllen
= 0;
235 f
= fopen(fnam
, "r");
238 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
239 append_line(&buf
, fulllen
, line
, linelen
);
247 /* Taken over modified from the kernel sources. */
248 #define NBITS 32 /* bits in uint32_t */
249 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
250 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
252 static void set_bit(unsigned bit
, uint32_t *bitarr
)
254 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
257 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
259 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
262 static bool is_set(unsigned bit
, uint32_t *bitarr
)
264 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
267 /* Create cpumask from cpulist aka turn:
275 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
281 arrlen
= BITS_TO_LONGS(nbits
);
282 bitarr
= calloc(arrlen
, sizeof(uint32_t));
286 lxc_iterate_parts(token
, buf
, ",") {
291 start
= strtoul(token
, NULL
, 0);
293 range
= strchr(token
, '-');
295 end
= strtoul(range
+ 1, NULL
, 0);
297 if (!(start
<= end
)) {
308 set_bit(start
++, bitarr
);
314 /* Turn cpumask into simple, comma-separated cpulist. */
315 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
319 char **cpulist
= NULL
;
320 char numstr
[INTTYPE_TO_STRLEN(size_t)] = {0};
322 for (i
= 0; i
<= nbits
; i
++) {
323 if (!is_set(i
, bitarr
))
326 ret
= snprintf(numstr
, sizeof(numstr
), "%zu", i
);
327 if (ret
< 0 || (size_t)ret
>= sizeof(numstr
)) {
328 lxc_free_array((void **)cpulist
, free
);
332 ret
= lxc_append_string(&cpulist
, numstr
);
334 lxc_free_array((void **)cpulist
, free
);
342 return lxc_string_join(",", (const char **)cpulist
, false);
345 static ssize_t
get_max_cpus(char *cpulist
)
348 char *maxcpus
= cpulist
;
351 c1
= strrchr(maxcpus
, ',');
355 c2
= strrchr(maxcpus
, '-');
369 cpus
= strtoul(c1
, NULL
, 0);
376 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
377 static bool cg_legacy_filter_and_set_cpus(char *path
, bool am_initialized
)
381 char *lastslash
, *fpath
, oldv
;
382 ssize_t maxisol
= 0, maxposs
= 0;
383 char *cpulist
= NULL
, *isolcpus
= NULL
, *posscpus
= NULL
;
384 uint32_t *isolmask
= NULL
, *possmask
= NULL
;
385 bool bret
= false, flipped_bit
= false;
387 lastslash
= strrchr(path
, '/');
389 ERROR("Failed to detect \"/\" in \"%s\"", path
);
394 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
395 posscpus
= read_file(fpath
);
397 SYSERROR("Failed to read file \"%s\"", fpath
);
401 /* Get maximum number of cpus found in possible cpuset. */
402 maxposs
= get_max_cpus(posscpus
);
403 if (maxposs
< 0 || maxposs
>= INT_MAX
- 1)
406 if (!file_exists(__ISOL_CPUS
)) {
407 /* This system doesn't expose isolated cpus. */
408 DEBUG("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
410 /* No isolated cpus but we weren't already initialized by
411 * someone. We should simply copy the parents cpuset.cpus
414 if (!am_initialized
) {
415 DEBUG("Copying cpu settings of parent cgroup");
418 /* No isolated cpus but we were already initialized by someone.
419 * Nothing more to do for us.
424 isolcpus
= read_file(__ISOL_CPUS
);
426 SYSERROR("Failed to read file \""__ISOL_CPUS
"\"");
429 if (!isdigit(isolcpus
[0])) {
430 TRACE("No isolated cpus detected");
432 /* No isolated cpus but we weren't already initialized by
433 * someone. We should simply copy the parents cpuset.cpus
436 if (!am_initialized
) {
437 DEBUG("Copying cpu settings of parent cgroup");
440 /* No isolated cpus but we were already initialized by someone.
441 * Nothing more to do for us.
446 /* Get maximum number of cpus found in isolated cpuset. */
447 maxisol
= get_max_cpus(isolcpus
);
448 if (maxisol
< 0 || maxisol
>= INT_MAX
- 1)
451 if (maxposs
< maxisol
)
455 possmask
= lxc_cpumask(posscpus
, maxposs
);
457 ERROR("Failed to create cpumask for possible cpus");
461 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
463 ERROR("Failed to create cpumask for isolated cpus");
467 for (i
= 0; i
<= maxposs
; i
++) {
468 if (!is_set(i
, isolmask
) || !is_set(i
, possmask
))
472 clear_bit(i
, possmask
);
476 DEBUG("No isolated cpus present in cpuset");
479 DEBUG("Removed isolated cpus from cpuset");
481 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
483 ERROR("Failed to create cpu list");
490 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
491 ret
= lxc_write_to_file(fpath
, cpulist
, strlen(cpulist
), false, 0666);
493 SYSERROR("Failed to write cpu list to \"%s\"", fpath
);
506 if (posscpus
!= cpulist
)
514 /* Copy contents of parent(@path)/@file to @path/@file */
515 static bool copy_parent_file(char *path
, char *file
)
518 char *fpath
, *lastslash
, oldv
;
522 lastslash
= strrchr(path
, '/');
524 ERROR("Failed to detect \"/\" in \"%s\"", path
);
529 fpath
= must_make_path(path
, file
, NULL
);
530 len
= lxc_read_from_file(fpath
, NULL
, 0);
534 value
= must_alloc(len
+ 1);
535 ret
= lxc_read_from_file(fpath
, value
, len
);
541 fpath
= must_make_path(path
, file
, NULL
);
542 ret
= lxc_write_to_file(fpath
, value
, len
, false, 0666);
544 SYSERROR("Failed to write \"%s\" to file \"%s\"", value
, fpath
);
550 SYSERROR("Failed to read file \"%s\"", fpath
);
556 /* Initialize the cpuset hierarchy in first directory of @gname and set
557 * cgroup.clone_children so that children inherit settings. Since the
558 * h->base_path is populated by init or ourselves, we know it is already
561 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
, char *cgname
)
565 char *cgpath
, *clonechildrenpath
, *slash
;
567 if (!string_in_list(h
->controllers
, "cpuset"))
572 slash
= strchr(cgname
, '/');
576 cgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgname
, NULL
);
580 ret
= mkdir(cgpath
, 0755);
582 if (errno
!= EEXIST
) {
583 SYSERROR("Failed to create directory \"%s\"", cgpath
);
590 must_make_path(cgpath
, "cgroup.clone_children", NULL
);
591 /* unified hierarchy doesn't have clone_children */
592 if (!file_exists(clonechildrenpath
)) {
593 free(clonechildrenpath
);
598 ret
= lxc_read_from_file(clonechildrenpath
, &v
, 1);
600 SYSERROR("Failed to read file \"%s\"", clonechildrenpath
);
601 free(clonechildrenpath
);
606 /* Make sure any isolated cpus are removed from cpuset.cpus. */
607 if (!cg_legacy_filter_and_set_cpus(cgpath
, v
== '1')) {
608 SYSERROR("Failed to remove isolated cpus");
609 free(clonechildrenpath
);
614 /* Already set for us by someone else. */
616 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
617 free(clonechildrenpath
);
622 /* copy parent's settings */
623 if (!copy_parent_file(cgpath
, "cpuset.mems")) {
624 SYSERROR("Failed to copy \"cpuset.mems\" settings");
626 free(clonechildrenpath
);
631 ret
= lxc_write_to_file(clonechildrenpath
, "1", 1, false, 0666);
633 /* Set clone_children so children inherit our settings */
634 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath
);
635 free(clonechildrenpath
);
638 free(clonechildrenpath
);
642 /* Given two null-terminated lists of strings, return true if any string is in
645 static bool controller_lists_intersect(char **l1
, char **l2
)
652 for (i
= 0; l1
[i
]; i
++) {
653 if (string_in_list(l2
, l1
[i
]))
660 /* For a null-terminated list of controllers @clist, return true if any of those
661 * controllers is already listed the null-terminated list of hierarchies @hlist.
662 * Realistically, if one is present, all must be present.
664 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
671 for (i
= 0; hlist
[i
]; i
++)
672 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
678 /* Return true if the controller @entry is found in the null-terminated list of
679 * hierarchies @hlist.
681 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
688 for (i
= 0; hlist
[i
]; i
++)
689 if (string_in_list(hlist
[i
]->controllers
, entry
))
695 /* Return true if all of the controllers which we require have been found. The
696 * required list is freezer and anything in lxc.cgroup.use.
698 static bool all_controllers_found(struct cgroup_ops
*ops
)
701 struct hierarchy
**hlist
= ops
->hierarchies
;
703 if (!controller_found(hlist
, "freezer")) {
704 ERROR("No freezer controller mountpoint found");
708 if (!ops
->cgroup_use
)
711 for (cur
= ops
->cgroup_use
; cur
&& *cur
; cur
++)
712 if (!controller_found(hlist
, *cur
)) {
713 ERROR("No %s controller mountpoint found", *cur
);
720 /* Get the controllers from a mountinfo line There are other ways we could get
721 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
722 * could parse the mount options. But we simply assume that the mountpoint must
723 * be /sys/fs/cgroup/controller-list
725 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
728 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
729 * for legacy hierarchies.
732 char *dup
, *p2
, *tok
;
733 char *p
= line
, *sep
= ",";
736 for (i
= 0; i
< 4; i
++) {
743 /* Note, if we change how mountinfo works, then our caller will need to
744 * verify /sys/fs/cgroup/ in this field.
746 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0) {
747 ERROR("Found hierarchy not under /sys/fs/cgroup: \"%s\"", p
);
754 ERROR("Corrupt mountinfo");
759 if (type
== CGROUP_SUPER_MAGIC
) {
760 /* strdup() here for v1 hierarchies. Otherwise
761 * lxc_iterate_parts() will destroy mountpoints such as
762 * "/sys/fs/cgroup/cpu,cpuacct".
768 lxc_iterate_parts(tok
, dup
, sep
) {
769 must_append_controller(klist
, nlist
, &aret
, tok
);
779 static char **cg_unified_make_empty_controller(void)
784 newentry
= append_null_to_list((void ***)&aret
);
785 aret
[newentry
] = NULL
;
789 static char **cg_unified_get_controllers(const char *file
)
795 buf
= read_file(file
);
799 lxc_iterate_parts(tok
, buf
, sep
) {
803 newentry
= append_null_to_list((void ***)&aret
);
804 copy
= must_copy_string(tok
);
805 aret
[newentry
] = copy
;
812 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
813 char *base_cgroup
, int type
)
815 struct hierarchy
*new;
818 new = must_alloc(sizeof(*new));
819 new->controllers
= clist
;
820 new->mountpoint
= mountpoint
;
821 new->base_cgroup
= base_cgroup
;
822 new->fullcgpath
= NULL
;
825 newentry
= append_null_to_list((void ***)h
);
826 (*h
)[newentry
] = new;
830 /* Get a copy of the mountpoint from @line, which is a line from
831 * /proc/self/mountinfo.
833 static char *cg_hybrid_get_mountpoint(char *line
)
838 char *p
= line
, *sret
= NULL
;
840 for (i
= 0; i
< 4; i
++) {
847 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
850 p2
= strchr(p
+ 15, ' ');
856 sret
= must_alloc(len
+ 1);
857 memcpy(sret
, p
, len
);
862 /* Given a multi-line string, return a null-terminated copy of the current line. */
863 static char *copy_to_eol(char *p
)
865 char *p2
= strchr(p
, '\n'), *sret
;
872 sret
= must_alloc(len
+ 1);
873 memcpy(sret
, p
, len
);
878 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
879 * /proc/self/cgroup file. Check whether controller c is present.
881 static bool controller_in_clist(char *cgline
, char *c
)
883 char *tok
, *eol
, *tmp
;
886 eol
= strchr(cgline
, ':');
891 tmp
= alloca(len
+ 1);
892 memcpy(tmp
, cgline
, len
);
895 lxc_iterate_parts(tok
, tmp
, ",") {
896 if (strcmp(tok
, c
) == 0)
903 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
906 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
909 char *p
= basecginfo
;
912 bool is_cgv2_base_cgroup
= false;
914 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
915 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
916 is_cgv2_base_cgroup
= true;
923 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
928 return copy_to_eol(p
);
938 static void must_append_string(char ***list
, char *entry
)
943 newentry
= append_null_to_list((void ***)list
);
944 copy
= must_copy_string(entry
);
945 (*list
)[newentry
] = copy
;
948 static int get_existing_subsystems(char ***klist
, char ***nlist
)
954 f
= fopen("/proc/self/cgroup", "r");
958 while (getline(&line
, &len
, f
) != -1) {
960 p
= strchr(line
, ':');
969 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
970 * contains an entry of the form:
974 * In this case we use "cgroup2" as controller name.
977 must_append_string(klist
, "cgroup2");
981 lxc_iterate_parts(tok
, p
, ",") {
982 if (strncmp(tok
, "name=", 5) == 0)
983 must_append_string(nlist
, tok
);
985 must_append_string(klist
, tok
);
994 static void trim(char *s
)
999 while ((len
> 1) && (s
[len
- 1] == '\n'))
1003 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
1006 struct hierarchy
**it
;
1008 if (!ops
->hierarchies
) {
1009 TRACE(" No hierarchies found");
1013 TRACE(" Hierarchies:");
1014 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
1018 TRACE(" %d: base_cgroup: %s", i
, (*it
)->base_cgroup
? (*it
)->base_cgroup
: "(null)");
1019 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
1020 TRACE(" controllers:");
1021 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
1022 TRACE(" %d: %s", j
, *cit
);
1026 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
1032 TRACE("basecginfo is:");
1033 TRACE("%s", basecginfo
);
1035 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
1036 TRACE("kernel subsystem %d: %s", k
, *it
);
1038 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
1039 TRACE("named subsystem %d: %s", k
, *it
);
1042 static int cgroup_rmdir(struct hierarchy
**hierarchies
,
1043 const char *container_cgroup
)
1047 if (!container_cgroup
|| !hierarchies
)
1050 for (i
= 0; hierarchies
[i
]; i
++) {
1052 struct hierarchy
*h
= hierarchies
[i
];
1057 ret
= recursive_destroy(h
->fullcgpath
);
1059 WARN("Failed to destroy \"%s\"", h
->fullcgpath
);
1061 free(h
->fullcgpath
);
1062 h
->fullcgpath
= NULL
;
1068 struct generic_userns_exec_data
{
1069 struct hierarchy
**hierarchies
;
1070 const char *container_cgroup
;
1071 struct lxc_conf
*conf
;
1072 uid_t origuid
; /* target uid in parent namespace */
1076 static int cgroup_rmdir_wrapper(void *data
)
1079 struct generic_userns_exec_data
*arg
= data
;
1080 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1081 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1083 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1085 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid
,
1086 (int)nsgid
, (int)nsgid
);
1090 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1092 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid
,
1093 (int)nsuid
, (int)nsuid
);
1097 ret
= setgroups(0, NULL
);
1098 if (ret
< 0 && errno
!= EPERM
) {
1099 SYSERROR("Failed to setgroups(0, NULL)");
1103 return cgroup_rmdir(arg
->hierarchies
, arg
->container_cgroup
);
1106 __cgfsng_ops__
static void cgfsng_destroy(struct cgroup_ops
*ops
, struct lxc_handler
*handler
)
1109 struct generic_userns_exec_data wrap
;
1112 wrap
.container_cgroup
= ops
->container_cgroup
;
1113 wrap
.hierarchies
= ops
->hierarchies
;
1114 wrap
.conf
= handler
->conf
;
1116 if (handler
->conf
&& !lxc_list_empty(&handler
->conf
->id_map
))
1117 ret
= userns_exec_1(handler
->conf
, cgroup_rmdir_wrapper
, &wrap
,
1118 "cgroup_rmdir_wrapper");
1120 ret
= cgroup_rmdir(ops
->hierarchies
, ops
->container_cgroup
);
1122 WARN("Failed to destroy cgroups");
1127 static bool cg_unified_create_cgroup(struct hierarchy
*h
, char *cgname
)
1129 size_t i
, parts_len
;
1131 size_t full_len
= 0;
1132 char *add_controllers
= NULL
, *cgroup
= NULL
;
1133 char **parts
= NULL
;
1136 if (h
->version
!= CGROUP2_SUPER_MAGIC
)
1139 if (!h
->controllers
)
1142 /* For now we simply enable all controllers that we have detected by
1143 * creating a string like "+memory +pids +cpu +io".
1144 * TODO: In the near future we might want to support "-<controller>"
1145 * etc. but whether supporting semantics like this make sense will need
1148 for (it
= h
->controllers
; it
&& *it
; it
++) {
1149 full_len
+= strlen(*it
) + 2;
1150 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
1152 if (h
->controllers
[0] == *it
)
1153 add_controllers
[0] = '\0';
1155 (void)strlcat(add_controllers
, "+", full_len
+ 1);
1156 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
1158 if ((it
+ 1) && *(it
+ 1))
1159 (void)strlcat(add_controllers
, " ", full_len
+ 1);
1162 parts
= lxc_string_split(cgname
, '/');
1166 parts_len
= lxc_array_len((void **)parts
);
1170 cgroup
= must_make_path(h
->mountpoint
, h
->base_cgroup
, NULL
);
1171 for (i
= 0; i
< parts_len
; i
++) {
1175 cgroup
= must_append_path(cgroup
, parts
[i
], NULL
);
1176 target
= must_make_path(cgroup
, "cgroup.subtree_control", NULL
);
1177 ret
= lxc_write_to_file(target
, add_controllers
, full_len
, false, 0666);
1180 SYSERROR("Could not enable \"%s\" controllers in the "
1181 "unified cgroup \"%s\"", add_controllers
, cgroup
);
1189 lxc_free_array((void **)parts
, free
);
1190 free(add_controllers
);
1195 static bool create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1199 h
->fullcgpath
= must_make_path(h
->mountpoint
, h
->base_cgroup
, cgname
, NULL
);
1200 if (dir_exists(h
->fullcgpath
)) {
1201 ERROR("The cgroup \"%s\" already existed", h
->fullcgpath
);
1205 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1206 ERROR("Failed to handle legacy cpuset controller");
1210 ret
= mkdir_p(h
->fullcgpath
, 0755);
1212 ERROR("Failed to create cgroup \"%s\"", h
->fullcgpath
);
1216 return cg_unified_create_cgroup(h
, cgname
);
1219 static void remove_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1223 ret
= rmdir(h
->fullcgpath
);
1225 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", h
->fullcgpath
);
1227 free(h
->fullcgpath
);
1228 h
->fullcgpath
= NULL
;
1231 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1232 * next cgroup_pattern-1, -2, ..., -999.
1234 __cgfsng_ops__
static inline bool cgfsng_create(struct cgroup_ops
*ops
,
1235 struct lxc_handler
*handler
)
1239 char *container_cgroup
, *offset
, *tmp
;
1241 struct lxc_conf
*conf
= handler
->conf
;
1243 if (ops
->container_cgroup
) {
1244 WARN("cgfsng_create called a second time: %s", ops
->container_cgroup
);
1251 if (conf
->cgroup_meta
.dir
)
1252 tmp
= lxc_string_join("/", (const char *[]){conf
->cgroup_meta
.dir
, handler
->name
, NULL
}, false);
1254 tmp
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1256 ERROR("Failed expanding cgroup name pattern");
1260 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1261 container_cgroup
= must_alloc(len
);
1262 (void)strlcpy(container_cgroup
, tmp
, len
);
1264 offset
= container_cgroup
+ len
- 5;
1268 ERROR("Too many conflicting cgroup names");
1275 ret
= snprintf(offset
, 5, "-%d", idx
);
1276 if (ret
< 0 || (size_t)ret
>= 5) {
1277 FILE *f
= fopen("/dev/null", "w");
1279 fprintf(f
, "Workaround for GCC7 bug: "
1280 "https://gcc.gnu.org/bugzilla/"
1281 "show_bug.cgi?id=78969");
1287 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1288 if (!create_path_for_hierarchy(ops
->hierarchies
[i
], container_cgroup
)) {
1290 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->fullcgpath
);
1291 free(ops
->hierarchies
[i
]->fullcgpath
);
1292 ops
->hierarchies
[i
]->fullcgpath
= NULL
;
1293 for (j
= 0; j
< i
; j
++)
1294 remove_path_for_hierarchy(ops
->hierarchies
[j
], container_cgroup
);
1300 ops
->container_cgroup
= container_cgroup
;
1305 free(container_cgroup
);
1310 __cgfsng_ops__
static bool cgfsng_enter(struct cgroup_ops
*ops
, pid_t pid
)
1315 len
= snprintf(pidstr
, 25, "%d", pid
);
1316 if (len
< 0 || len
>= 25)
1319 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1323 fullpath
= must_make_path(ops
->hierarchies
[i
]->fullcgpath
,
1324 "cgroup.procs", NULL
);
1325 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
1327 SYSERROR("Failed to enter cgroup \"%s\"", fullpath
);
1337 static int chowmod(char *path
, uid_t chown_uid
, gid_t chown_gid
,
1342 ret
= chown(path
, chown_uid
, chown_gid
);
1344 SYSWARN("Failed to chown(%s, %d, %d)", path
, (int)chown_uid
, (int)chown_gid
);
1348 ret
= chmod(path
, chmod_mode
);
1350 SYSWARN("Failed to chmod(%s, %d)", path
, (int)chmod_mode
);
1357 /* chgrp the container cgroups to container group. We leave
1358 * the container owner as cgroup owner. So we must make the
1359 * directories 775 so that the container can create sub-cgroups.
1361 * Also chown the tasks and cgroup.procs files. Those may not
1362 * exist depending on kernel version.
1364 static int chown_cgroup_wrapper(void *data
)
1368 struct generic_userns_exec_data
*arg
= data
;
1369 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1370 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1372 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1374 SYSERROR("Failed to setresgid(%d, %d, %d)",
1375 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1379 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1381 SYSERROR("Failed to setresuid(%d, %d, %d)",
1382 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1386 ret
= setgroups(0, NULL
);
1387 if (ret
< 0 && errno
!= EPERM
) {
1388 SYSERROR("Failed to setgroups(0, NULL)");
1392 destuid
= get_ns_uid(arg
->origuid
);
1393 if (destuid
== LXC_INVALID_UID
)
1396 for (i
= 0; arg
->hierarchies
[i
]; i
++) {
1398 char *path
= arg
->hierarchies
[i
]->fullcgpath
;
1400 ret
= chowmod(path
, destuid
, nsgid
, 0775);
1404 /* Failures to chown() these are inconvenient but not
1405 * detrimental We leave these owned by the container launcher,
1406 * so that container root can write to the files to attach. We
1407 * chmod() them 664 so that container systemd can write to the
1408 * files (which systemd in wily insists on doing).
1411 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
) {
1412 fullpath
= must_make_path(path
, "tasks", NULL
);
1413 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1417 fullpath
= must_make_path(path
, "cgroup.procs", NULL
);
1418 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1421 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1424 fullpath
= must_make_path(path
, "cgroup.subtree_control", NULL
);
1425 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1428 fullpath
= must_make_path(path
, "cgroup.threads", NULL
);
1429 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1436 __cgfsng_ops__
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1437 struct lxc_conf
*conf
)
1439 struct generic_userns_exec_data wrap
;
1441 if (lxc_list_empty(&conf
->id_map
))
1444 wrap
.origuid
= geteuid();
1446 wrap
.hierarchies
= ops
->hierarchies
;
1449 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
,
1450 "chown_cgroup_wrapper") < 0) {
1451 ERROR("Error requesting cgroup chown in new user namespace");
1458 /* cgroup-full:* is done, no need to create subdirs */
1459 static bool cg_mount_needs_subdirs(int type
)
1461 if (type
>= LXC_AUTO_CGROUP_FULL_RO
)
1467 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1468 * remount controller ro if needed and bindmount the cgroupfs onto
1469 * controll/the/cg/path.
1471 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1472 char *controllerpath
, char *cgpath
,
1473 const char *container_cgroup
)
1475 int ret
, remount_flags
;
1477 int flags
= MS_BIND
;
1479 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1480 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1482 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
1483 controllerpath
, controllerpath
);
1487 remount_flags
= add_required_remount_flags(controllerpath
,
1489 flags
| MS_REMOUNT
);
1490 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1491 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1494 SYSERROR("Failed to remount \"%s\" ro", controllerpath
);
1498 INFO("Remounted %s read-only", controllerpath
);
1501 sourcepath
= must_make_path(h
->mountpoint
, h
->base_cgroup
,
1502 container_cgroup
, NULL
);
1503 if (type
== LXC_AUTO_CGROUP_RO
)
1506 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1508 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1512 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1514 if (flags
& MS_RDONLY
) {
1515 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1516 flags
| MS_REMOUNT
);
1517 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1519 SYSERROR("Failed to remount \"%s\" ro", cgpath
);
1523 INFO("Remounted %s read-only", cgpath
);
1527 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1531 /* __cg_mount_direct
1533 * Mount cgroup hierarchies directly without using bind-mounts. The main
1534 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1535 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1537 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1538 const char *controllerpath
)
1541 char *controllers
= NULL
;
1542 char *fstype
= "cgroup2";
1543 unsigned long flags
= 0;
1548 flags
|= MS_RELATIME
;
1550 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1553 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1554 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1560 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1563 SYSERROR("Failed to mount \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1567 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1571 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1572 const char *controllerpath
)
1574 return __cg_mount_direct(type
, h
, controllerpath
);
1577 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1578 const char *controllerpath
)
1580 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1583 return __cg_mount_direct(type
, h
, controllerpath
);
1586 __cgfsng_ops__
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1587 struct lxc_handler
*handler
,
1588 const char *root
, int type
)
1591 char *tmpfspath
= NULL
;
1592 bool has_cgns
= false, retval
= false, wants_force_mount
= false;
1594 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1597 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1598 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1599 wants_force_mount
= true;
1602 if (!wants_force_mount
){
1603 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1604 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1606 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1609 has_cgns
= cgns_supported();
1610 if (has_cgns
&& !wants_force_mount
)
1613 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1614 type
= LXC_AUTO_CGROUP_MIXED
;
1615 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1616 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1619 tmpfspath
= must_make_path(root
, "/sys/fs/cgroup", NULL
);
1620 ret
= safe_mount(NULL
, tmpfspath
, "tmpfs",
1621 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1622 "size=10240k,mode=755", root
);
1626 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1627 char *controllerpath
, *path2
;
1628 struct hierarchy
*h
= ops
->hierarchies
[i
];
1629 char *controller
= strrchr(h
->mountpoint
, '/');
1635 controllerpath
= must_make_path(tmpfspath
, controller
, NULL
);
1636 if (dir_exists(controllerpath
)) {
1637 free(controllerpath
);
1641 ret
= mkdir(controllerpath
, 0755);
1643 SYSERROR("Error creating cgroup path: %s", controllerpath
);
1644 free(controllerpath
);
1648 if (has_cgns
&& wants_force_mount
) {
1649 /* If cgroup namespaces are supported but the container
1650 * will not have CAP_SYS_ADMIN after it has started we
1651 * need to mount the cgroups manually.
1653 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1654 free(controllerpath
);
1661 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1663 free(controllerpath
);
1667 if (!cg_mount_needs_subdirs(type
)) {
1668 free(controllerpath
);
1672 path2
= must_make_path(controllerpath
, h
->base_cgroup
,
1673 ops
->container_cgroup
, NULL
);
1674 ret
= mkdir_p(path2
, 0755);
1676 free(controllerpath
);
1681 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1682 path2
, ops
->container_cgroup
);
1683 free(controllerpath
);
1695 static int recursive_count_nrtasks(char *dirname
)
1697 struct dirent
*direntp
;
1702 dir
= opendir(dirname
);
1706 while ((direntp
= readdir(dir
))) {
1709 if (!strcmp(direntp
->d_name
, ".") ||
1710 !strcmp(direntp
->d_name
, ".."))
1713 path
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1715 if (lstat(path
, &mystat
))
1718 if (!S_ISDIR(mystat
.st_mode
))
1721 count
+= recursive_count_nrtasks(path
);
1726 path
= must_make_path(dirname
, "cgroup.procs", NULL
);
1727 ret
= lxc_count_file_lines(path
);
1732 (void)closedir(dir
);
1737 __cgfsng_ops__
static int cgfsng_nrtasks(struct cgroup_ops
*ops
)
1742 if (!ops
->container_cgroup
|| !ops
->hierarchies
)
1745 path
= must_make_path(ops
->hierarchies
[0]->fullcgpath
, NULL
);
1746 count
= recursive_count_nrtasks(path
);
1751 /* Only root needs to escape to the cgroup of its init. */
1752 __cgfsng_ops__
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1753 struct lxc_conf
*conf
)
1757 if (conf
->cgroup_meta
.keep
|| geteuid())
1760 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1764 fullpath
= must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1765 ops
->hierarchies
[i
]->base_cgroup
,
1766 "cgroup.procs", NULL
);
1767 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1769 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath
);
1779 __cgfsng_ops__
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1783 for (i
= 0; ops
->hierarchies
[i
]; i
++)
1789 __cgfsng_ops__
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
, char ***out
)
1793 /* sanity check n */
1794 for (i
= 0; i
< n
; i
++)
1795 if (!ops
->hierarchies
[i
])
1798 *out
= ops
->hierarchies
[i
]->controllers
;
1803 #define THAWED "THAWED"
1804 #define THAWED_LEN (strlen(THAWED))
1806 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
1809 __cgfsng_ops__
static bool cgfsng_unfreeze(struct cgroup_ops
*ops
)
1813 struct hierarchy
*h
;
1815 h
= get_hierarchy(ops
, "freezer");
1819 fullpath
= must_make_path(h
->fullcgpath
, "freezer.state", NULL
);
1820 ret
= lxc_write_to_file(fullpath
, THAWED
, THAWED_LEN
, false, 0666);
1828 __cgfsng_ops__
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
1829 const char *controller
)
1831 struct hierarchy
*h
;
1833 h
= get_hierarchy(ops
, controller
);
1835 WARN("Failed to find hierarchy for controller \"%s\"",
1836 controller
? controller
: "(null)");
1840 return h
->fullcgpath
? h
->fullcgpath
+ strlen(h
->mountpoint
) : NULL
;
1843 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
1844 * which must be freed by the caller.
1846 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
1848 const char *filename
)
1850 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
1853 /* Technically, we're always at a delegation boundary here (This is especially
1854 * true when cgroup namespaces are available.). The reasoning is that in order
1855 * for us to have been able to start a container in the first place the root
1856 * cgroup must have been a leaf node. Now, either the container's init system
1857 * has populated the cgroup and kept it as a leaf node or it has created
1858 * subtrees. In the former case we will simply attach to the leaf node we
1859 * created when we started the container in the latter case we create our own
1860 * cgroup for the attaching process.
1862 static int __cg_unified_attach(const struct hierarchy
*h
, const char *name
,
1863 const char *lxcpath
, const char *pidstr
,
1864 size_t pidstr_len
, const char *controller
)
1868 int fret
= -1, idx
= 0;
1869 char *base_path
= NULL
, *container_cgroup
= NULL
, *full_path
= NULL
;
1871 container_cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
1873 if (!container_cgroup
)
1876 base_path
= must_make_path(h
->mountpoint
, container_cgroup
, NULL
);
1877 full_path
= must_make_path(base_path
, "cgroup.procs", NULL
);
1878 /* cgroup is populated */
1879 ret
= lxc_write_to_file(full_path
, pidstr
, pidstr_len
, false, 0666);
1880 if (ret
< 0 && errno
!= EBUSY
)
1888 len
= strlen(base_path
) + sizeof("/lxc-1000") - 1 +
1889 sizeof("/cgroup-procs") - 1;
1890 full_path
= must_alloc(len
+ 1);
1893 ret
= snprintf(full_path
, len
+ 1, "%s/lxc-%d",
1896 ret
= snprintf(full_path
, len
+ 1, "%s/lxc", base_path
);
1897 if (ret
< 0 || (size_t)ret
>= len
+ 1)
1900 ret
= mkdir_p(full_path
, 0755);
1901 if (ret
< 0 && errno
!= EEXIST
)
1904 (void)strlcat(full_path
, "/cgroup.procs", len
+ 1);
1905 ret
= lxc_write_to_file(full_path
, pidstr
, len
, false, 0666);
1909 /* this is a non-leaf node */
1913 } while (++idx
> 0 && idx
< 1000);
1921 free(container_cgroup
);
1927 __cgfsng_ops__
static bool cgfsng_attach(struct cgroup_ops
*ops
, const char *name
,
1928 const char *lxcpath
, pid_t pid
)
1933 len
= snprintf(pidstr
, 25, "%d", pid
);
1934 if (len
< 0 || len
>= 25)
1937 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1939 char *fullpath
= NULL
;
1940 struct hierarchy
*h
= ops
->hierarchies
[i
];
1942 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
1943 ret
= __cg_unified_attach(h
, name
, lxcpath
, pidstr
, len
,
1951 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
1956 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
1958 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
1960 SYSERROR("Failed to attach %d to %s", (int)pid
, fullpath
);
1970 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
1971 * don't have a cgroup_data set up, so we ask the running container through the
1972 * commands API for the cgroup path.
1974 __cgfsng_ops__
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
1975 char *value
, size_t len
, const char *name
,
1976 const char *lxcpath
)
1979 size_t controller_len
;
1980 char *controller
, *p
, *path
;
1981 struct hierarchy
*h
;
1983 controller_len
= strlen(filename
);
1984 controller
= alloca(controller_len
+ 1);
1985 (void)strlcpy(controller
, filename
, controller_len
+ 1);
1987 p
= strchr(controller
, '.');
1991 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
1996 h
= get_hierarchy(ops
, controller
);
2000 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2001 ret
= lxc_read_from_file(fullpath
, value
, len
);
2009 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2010 * don't have a cgroup_data set up, so we ask the running container through the
2011 * commands API for the cgroup path.
2013 __cgfsng_ops__
static int cgfsng_set(struct cgroup_ops
*ops
,
2014 const char *filename
, const char *value
,
2015 const char *name
, const char *lxcpath
)
2018 size_t controller_len
;
2019 char *controller
, *p
, *path
;
2020 struct hierarchy
*h
;
2022 controller_len
= strlen(filename
);
2023 controller
= alloca(controller_len
+ 1);
2024 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2026 p
= strchr(controller
, '.');
2030 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2035 h
= get_hierarchy(ops
, controller
);
2039 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2040 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2048 /* take devices cgroup line
2050 * and convert it to a valid
2051 * type major:minor mode
2052 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2055 static int convert_devpath(const char *invalue
, char *dest
)
2058 char *p
, *path
, type
;
2059 unsigned long minor
, major
;
2064 path
= must_copy_string(invalue
);
2066 /* Read path followed by mode. Ignore any trailing text.
2067 * A ' # comment' would be legal. Technically other text is not
2068 * legal, we could check for that if we cared to.
2070 for (n_parts
= 1, p
= path
; *p
&& n_parts
< 3; p
++) {
2092 ret
= stat(path
, &sb
);
2096 mode_t m
= sb
.st_mode
& S_IFMT
;
2105 ERROR("Unsupported device type %i for \"%s\"", m
, path
);
2110 major
= MAJOR(sb
.st_rdev
);
2111 minor
= MINOR(sb
.st_rdev
);
2112 ret
= snprintf(dest
, 50, "%c %lu:%lu %s", type
, major
, minor
, mode
);
2113 if (ret
< 0 || ret
>= 50) {
2114 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2115 "chars)", type
, major
, minor
, mode
);
2116 ret
= -ENAMETOOLONG
;
2126 /* Called from setup_limits - here we have the container's cgroup_data because
2127 * we created the cgroups.
2129 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2134 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2135 char converted_value
[50];
2136 struct hierarchy
*h
;
2138 char *controller
= NULL
;
2140 len
= strlen(filename
);
2141 controller
= alloca(len
+ 1);
2142 (void)strlcpy(controller
, filename
, len
+ 1);
2144 p
= strchr(controller
, '.');
2148 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2149 ret
= convert_devpath(value
, converted_value
);
2152 value
= converted_value
;
2155 h
= get_hierarchy(ops
, controller
);
2157 ERROR("Failed to setup limits for the \"%s\" controller. "
2158 "The controller seems to be unused by \"cgfsng\" cgroup "
2159 "driver or not enabled on the cgroup hierarchy",
2165 fullpath
= must_make_path(h
->fullcgpath
, filename
, NULL
);
2166 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2171 static bool __cg_legacy_setup_limits(struct cgroup_ops
*ops
,
2172 struct lxc_list
*cgroup_settings
,
2175 struct lxc_list
*iterator
, *next
, *sorted_cgroup_settings
;
2176 struct lxc_cgroup
*cg
;
2179 if (lxc_list_empty(cgroup_settings
))
2182 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2183 if (!sorted_cgroup_settings
)
2186 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2187 cg
= iterator
->elem
;
2189 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2190 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
)) {
2191 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2192 WARN("Failed to set \"%s\" to \"%s\"",
2193 cg
->subsystem
, cg
->value
);
2196 WARN("Failed to set \"%s\" to \"%s\"",
2197 cg
->subsystem
, cg
->value
);
2200 DEBUG("Set controller \"%s\" set to \"%s\"",
2201 cg
->subsystem
, cg
->value
);
2206 INFO("Limits for the legacy cgroup hierarchies have been setup");
2208 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2209 lxc_list_del(iterator
);
2212 free(sorted_cgroup_settings
);
2216 static bool __cg_unified_setup_limits(struct cgroup_ops
*ops
,
2217 struct lxc_list
*cgroup_settings
)
2219 struct lxc_list
*iterator
;
2220 struct hierarchy
*h
= ops
->unified
;
2222 if (lxc_list_empty(cgroup_settings
))
2228 lxc_list_for_each(iterator
, cgroup_settings
) {
2231 struct lxc_cgroup
*cg
= iterator
->elem
;
2233 fullpath
= must_make_path(h
->fullcgpath
, cg
->subsystem
, NULL
);
2234 ret
= lxc_write_to_file(fullpath
, cg
->value
, strlen(cg
->value
), false, 0666);
2237 SYSERROR("Failed to set \"%s\" to \"%s\"",
2238 cg
->subsystem
, cg
->value
);
2241 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2244 INFO("Limits for the unified cgroup hierarchy have been setup");
2248 __cgfsng_ops__
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2249 struct lxc_conf
*conf
,
2254 bret
= __cg_legacy_setup_limits(ops
, &conf
->cgroup
, do_devices
);
2258 return __cg_unified_setup_limits(ops
, &conf
->cgroup2
);
2261 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
2264 char **cur_ctrl
, **cur_use
;
2266 if (!ops
->cgroup_use
)
2269 for (cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
2272 for (cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
2273 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
2289 /* At startup, parse_hierarchies finds all the info we need about cgroup
2290 * mountpoints and current cgroups, and stores it in @d.
2292 static bool cg_hybrid_init(struct cgroup_ops
*ops
, bool keep
)
2299 char **klist
= NULL
, **nlist
= NULL
;
2301 /* Root spawned containers escape the current cgroup, so use init's
2302 * cgroups as our base in that case.
2304 if (!keep
&& (geteuid() == 0))
2305 basecginfo
= read_file("/proc/1/cgroup");
2307 basecginfo
= read_file("/proc/self/cgroup");
2311 ret
= get_existing_subsystems(&klist
, &nlist
);
2313 ERROR("Failed to retrieve available legacy cgroup controllers");
2318 f
= fopen("/proc/self/mountinfo", "r");
2320 ERROR("Failed to open \"/proc/self/mountinfo\"");
2325 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
2327 while (getline(&line
, &len
, f
) != -1) {
2330 struct hierarchy
*new;
2331 char *base_cgroup
= NULL
, *mountpoint
= NULL
;
2332 char **controller_list
= NULL
;
2334 type
= get_cgroup_version(line
);
2338 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
2341 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
2342 if (type
== CGROUP2_SUPER_MAGIC
)
2343 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2344 else if (type
== CGROUP_SUPER_MAGIC
)
2345 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
2346 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
2347 if (type
== CGROUP_SUPER_MAGIC
)
2348 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2349 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
2350 if (type
== CGROUP2_SUPER_MAGIC
)
2351 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2354 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
2355 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
2358 if (type
== CGROUP_SUPER_MAGIC
)
2359 if (controller_list_is_dup(ops
->hierarchies
, controller_list
))
2362 mountpoint
= cg_hybrid_get_mountpoint(line
);
2364 ERROR("Failed parsing mountpoint from \"%s\"", line
);
2368 if (type
== CGROUP_SUPER_MAGIC
)
2369 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
2371 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
2373 ERROR("Failed to find current cgroup");
2378 prune_init_scope(base_cgroup
);
2379 if (type
== CGROUP2_SUPER_MAGIC
)
2380 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
2382 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
2386 if (type
== CGROUP2_SUPER_MAGIC
) {
2387 char *cgv2_ctrl_path
;
2389 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
2390 "cgroup.controllers",
2393 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
2394 free(cgv2_ctrl_path
);
2395 if (!controller_list
) {
2396 controller_list
= cg_unified_make_empty_controller();
2397 TRACE("No controllers are enabled for "
2398 "delegation in the unified hierarchy");
2402 /* Exclude all controllers that cgroup use does not want. */
2403 if (!cgroup_use_wants_controllers(ops
, controller_list
))
2406 new = add_hierarchy(&ops
->hierarchies
, controller_list
, mountpoint
, base_cgroup
, type
);
2407 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
)
2413 free_string_list(controller_list
);
2418 free_string_list(klist
);
2419 free_string_list(nlist
);
2426 TRACE("Writable cgroup hierarchies:");
2427 lxc_cgfsng_print_hierarchies(ops
);
2429 /* verify that all controllers in cgroup.use and all crucial
2430 * controllers are accounted for
2432 if (!all_controllers_found(ops
))
2438 static int cg_is_pure_unified(void)
2444 ret
= statfs("/sys/fs/cgroup", &fs
);
2448 if (is_fs_type(&fs
, CGROUP2_SUPER_MAGIC
))
2449 return CGROUP2_SUPER_MAGIC
;
2454 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
2455 static char *cg_unified_get_current_cgroup(bool keep
)
2457 char *basecginfo
, *base_cgroup
;
2460 if (!keep
&& (geteuid() == 0))
2461 basecginfo
= read_file("/proc/1/cgroup");
2463 basecginfo
= read_file("/proc/self/cgroup");
2467 base_cgroup
= strstr(basecginfo
, "0::/");
2469 goto cleanup_on_err
;
2471 base_cgroup
= base_cgroup
+ 3;
2472 copy
= copy_to_eol(base_cgroup
);
2474 goto cleanup_on_err
;
2484 static int cg_unified_init(struct cgroup_ops
*ops
, bool keep
)
2487 char *mountpoint
, *subtree_path
;
2489 char *base_cgroup
= NULL
;
2491 ret
= cg_is_pure_unified();
2492 if (ret
== -ENOMEDIUM
)
2495 if (ret
!= CGROUP2_SUPER_MAGIC
)
2498 base_cgroup
= cg_unified_get_current_cgroup(keep
);
2501 prune_init_scope(base_cgroup
);
2503 /* We assume that we have already been given controllers to delegate
2504 * further down the hierarchy. If not it is up to the user to delegate
2507 mountpoint
= must_copy_string("/sys/fs/cgroup");
2508 subtree_path
= must_make_path(mountpoint
, base_cgroup
,
2509 "cgroup.subtree_control", NULL
);
2510 delegatable
= cg_unified_get_controllers(subtree_path
);
2513 delegatable
= cg_unified_make_empty_controller();
2514 if (!delegatable
[0])
2515 TRACE("No controllers are enabled for delegation");
2517 /* TODO: If the user requested specific controllers via lxc.cgroup.use
2518 * we should verify here. The reason I'm not doing it right is that I'm
2519 * not convinced that lxc.cgroup.use will be the future since it is a
2520 * global property. I much rather have an option that lets you request
2521 * controllers per container.
2524 add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
2526 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2527 return CGROUP2_SUPER_MAGIC
;
2530 static bool cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
2534 bool keep
= conf
->cgroup_meta
.keep
;
2536 tmp
= lxc_global_config_value("lxc.cgroup.use");
2538 char *chop
, *cur
, *pin
;
2540 pin
= must_copy_string(tmp
);
2543 lxc_iterate_parts(cur
, chop
, ",") {
2544 must_append_string(&ops
->cgroup_use
, cur
);
2550 ret
= cg_unified_init(ops
, keep
);
2554 if (ret
== CGROUP2_SUPER_MAGIC
)
2557 return cg_hybrid_init(ops
, keep
);
2560 __cgfsng_ops__
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(struct lxc_conf
*conf
)
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
, conf
)) {
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
;