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 comma-separated list of controllers.
44 #include <linux/kdev_t.h>
45 #include <linux/types.h>
50 #include <sys/types.h>
55 #include "cgroup_utils.h"
61 #include "storage/storage.h"
65 #include "include/strlcpy.h"
69 #include "include/strlcat.h"
72 lxc_log_define(cgfsng
, cgroup
);
74 static void free_string_list(char **clist
)
81 for (i
= 0; clist
[i
]; i
++)
87 /* Given a pointer to a null-terminated array of pointers, realloc to add one
88 * entry, and point the new entry to NULL. Do not fail. Return the index to the
89 * second-to-last entry - that is, the one which is now available for use
90 * (keeping the list null-terminated).
92 static int append_null_to_list(void ***list
)
97 for (; (*list
)[newentry
]; newentry
++)
100 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
101 (*list
)[newentry
+ 1] = NULL
;
105 /* Given a null-terminated array of strings, check whether @entry is one of the
108 static bool string_in_list(char **list
, const char *entry
)
115 for (i
= 0; list
[i
]; i
++)
116 if (strcmp(list
[i
], entry
) == 0)
122 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
123 * "name=systemd". Do not fail.
125 static char *cg_legacy_must_prefix_named(char *entry
)
131 prefixed
= must_realloc(NULL
, len
+ 6);
133 memcpy(prefixed
, "name=", STRLITERALLEN("name="));
134 memcpy(prefixed
+ STRLITERALLEN("name="), entry
, len
);
135 prefixed
[len
+ 5] = '\0';
140 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
143 * We also handle named subsystems here. Any controller which is not a kernel
144 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
145 * we refuse to use because we're not sure which we have here.
146 * (TODO: We could work around this in some cases by just remounting to be
147 * unambiguous, or by comparing mountpoint contents with current cgroup.)
149 * The last entry will always be NULL.
151 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
157 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
158 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
159 ERROR("It is both a named and kernel subsystem");
163 newentry
= append_null_to_list((void ***)clist
);
165 if (strncmp(entry
, "name=", 5) == 0)
166 copy
= must_copy_string(entry
);
167 else if (string_in_list(klist
, entry
))
168 copy
= must_copy_string(entry
);
170 copy
= cg_legacy_must_prefix_named(entry
);
172 (*clist
)[newentry
] = copy
;
175 /* Given a handler's cgroup data, return the struct hierarchy for the controller
176 * @c, or NULL if there is none.
178 struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *controller
)
184 if (!ops
->hierarchies
) {
185 TRACE("There are no useable cgroup controllers");
189 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
191 /* This is the empty unified hierarchy. */
192 if (ops
->hierarchies
[i
]->controllers
&&
193 !ops
->hierarchies
[i
]->controllers
[0])
194 return ops
->hierarchies
[i
];
199 if (string_in_list(ops
->hierarchies
[i
]->controllers
, controller
))
200 return ops
->hierarchies
[i
];
204 WARN("There is no useable %s controller", controller
);
206 WARN("There is no empty unified cgroup hierarchy");
211 #define BATCH_SIZE 50
212 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
214 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
215 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
217 if (!*mem
|| newbatches
> oldbatches
) {
218 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
222 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
224 size_t full
= oldlen
+ newlen
;
226 batch_realloc(dest
, oldlen
, full
+ 1);
228 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
231 /* Slurp in a whole file */
232 static char *read_file(const char *fnam
)
235 char *line
= NULL
, *buf
= NULL
;
236 size_t len
= 0, fulllen
= 0;
239 f
= fopen(fnam
, "r");
242 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
243 append_line(&buf
, fulllen
, line
, linelen
);
251 /* Taken over modified from the kernel sources. */
252 #define NBITS 32 /* bits in uint32_t */
253 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
254 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
256 static void set_bit(unsigned bit
, uint32_t *bitarr
)
258 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
261 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
263 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
266 static bool is_set(unsigned bit
, uint32_t *bitarr
)
268 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
271 /* Create cpumask from cpulist aka turn:
279 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
285 arrlen
= BITS_TO_LONGS(nbits
);
286 bitarr
= calloc(arrlen
, sizeof(uint32_t));
290 lxc_iterate_parts(token
, buf
, ",") {
295 start
= strtoul(token
, NULL
, 0);
297 range
= strchr(token
, '-');
299 end
= strtoul(range
+ 1, NULL
, 0);
301 if (!(start
<= end
)) {
312 set_bit(start
++, bitarr
);
318 /* Turn cpumask into simple, comma-separated cpulist. */
319 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
323 char **cpulist
= NULL
;
324 char numstr
[INTTYPE_TO_STRLEN(size_t)] = {0};
326 for (i
= 0; i
<= nbits
; i
++) {
327 if (!is_set(i
, bitarr
))
330 ret
= snprintf(numstr
, sizeof(numstr
), "%zu", i
);
331 if (ret
< 0 || (size_t)ret
>= sizeof(numstr
)) {
332 lxc_free_array((void **)cpulist
, free
);
336 ret
= lxc_append_string(&cpulist
, numstr
);
338 lxc_free_array((void **)cpulist
, free
);
346 return lxc_string_join(",", (const char **)cpulist
, false);
349 static ssize_t
get_max_cpus(char *cpulist
)
352 char *maxcpus
= cpulist
;
355 c1
= strrchr(maxcpus
, ',');
359 c2
= strrchr(maxcpus
, '-');
373 cpus
= strtoul(c1
, NULL
, 0);
380 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
381 static bool cg_legacy_filter_and_set_cpus(char *path
, bool am_initialized
)
385 char *lastslash
, *fpath
, oldv
;
386 ssize_t maxisol
= 0, maxposs
= 0;
387 char *cpulist
= NULL
, *isolcpus
= NULL
, *posscpus
= NULL
;
388 uint32_t *isolmask
= NULL
, *possmask
= NULL
;
389 bool bret
= false, flipped_bit
= false;
391 lastslash
= strrchr(path
, '/');
393 ERROR("Failed to detect \"/\" in \"%s\"", path
);
398 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
399 posscpus
= read_file(fpath
);
401 SYSERROR("Failed to read file \"%s\"", fpath
);
405 /* Get maximum number of cpus found in possible cpuset. */
406 maxposs
= get_max_cpus(posscpus
);
407 if (maxposs
< 0 || maxposs
>= INT_MAX
- 1)
410 if (!file_exists(__ISOL_CPUS
)) {
411 /* This system doesn't expose isolated cpus. */
412 DEBUG("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
414 /* No isolated cpus but we weren't already initialized by
415 * someone. We should simply copy the parents cpuset.cpus
418 if (!am_initialized
) {
419 DEBUG("Copying cpu settings of parent cgroup");
422 /* No isolated cpus but we were already initialized by someone.
423 * Nothing more to do for us.
428 isolcpus
= read_file(__ISOL_CPUS
);
430 SYSERROR("Failed to read file \""__ISOL_CPUS
"\"");
433 if (!isdigit(isolcpus
[0])) {
434 TRACE("No isolated cpus detected");
436 /* No isolated cpus but we weren't already initialized by
437 * someone. We should simply copy the parents cpuset.cpus
440 if (!am_initialized
) {
441 DEBUG("Copying cpu settings of parent cgroup");
444 /* No isolated cpus but we were already initialized by someone.
445 * Nothing more to do for us.
450 /* Get maximum number of cpus found in isolated cpuset. */
451 maxisol
= get_max_cpus(isolcpus
);
452 if (maxisol
< 0 || maxisol
>= INT_MAX
- 1)
455 if (maxposs
< maxisol
)
459 possmask
= lxc_cpumask(posscpus
, maxposs
);
461 ERROR("Failed to create cpumask for possible cpus");
465 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
467 ERROR("Failed to create cpumask for isolated cpus");
471 for (i
= 0; i
<= maxposs
; i
++) {
472 if (!is_set(i
, isolmask
) || !is_set(i
, possmask
))
476 clear_bit(i
, possmask
);
480 DEBUG("No isolated cpus present in cpuset");
483 DEBUG("Removed isolated cpus from cpuset");
485 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
487 ERROR("Failed to create cpu list");
494 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
495 ret
= lxc_write_to_file(fpath
, cpulist
, strlen(cpulist
), false, 0666);
497 SYSERROR("Failed to write cpu list to \"%s\"", fpath
);
510 if (posscpus
!= cpulist
)
518 /* Copy contents of parent(@path)/@file to @path/@file */
519 static bool copy_parent_file(char *path
, char *file
)
522 char *fpath
, *lastslash
, oldv
;
526 lastslash
= strrchr(path
, '/');
528 ERROR("Failed to detect \"/\" in \"%s\"", path
);
533 fpath
= must_make_path(path
, file
, NULL
);
534 len
= lxc_read_from_file(fpath
, NULL
, 0);
538 value
= must_realloc(NULL
, len
+ 1);
539 ret
= lxc_read_from_file(fpath
, value
, len
);
545 fpath
= must_make_path(path
, file
, NULL
);
546 ret
= lxc_write_to_file(fpath
, value
, len
, false, 0666);
548 SYSERROR("Failed to write \"%s\" to file \"%s\"", value
, fpath
);
554 SYSERROR("Failed to read file \"%s\"", fpath
);
560 /* Initialize the cpuset hierarchy in first directory of @gname and set
561 * cgroup.clone_children so that children inherit settings. Since the
562 * h->base_path is populated by init or ourselves, we know it is already
565 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
, char *cgname
)
569 char *cgpath
, *clonechildrenpath
, *slash
;
571 if (!string_in_list(h
->controllers
, "cpuset"))
576 slash
= strchr(cgname
, '/');
580 cgpath
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
584 ret
= mkdir(cgpath
, 0755);
586 if (errno
!= EEXIST
) {
587 SYSERROR("Failed to create directory \"%s\"", cgpath
);
593 clonechildrenpath
= must_make_path(cgpath
, "cgroup.clone_children", NULL
);
594 /* unified hierarchy doesn't have clone_children */
595 if (!file_exists(clonechildrenpath
)) {
596 free(clonechildrenpath
);
601 ret
= lxc_read_from_file(clonechildrenpath
, &v
, 1);
603 SYSERROR("Failed to read file \"%s\"", clonechildrenpath
);
604 free(clonechildrenpath
);
609 /* Make sure any isolated cpus are removed from cpuset.cpus. */
610 if (!cg_legacy_filter_and_set_cpus(cgpath
, v
== '1')) {
611 SYSERROR("Failed to remove isolated cpus");
612 free(clonechildrenpath
);
617 /* Already set for us by someone else. */
619 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
620 free(clonechildrenpath
);
625 /* copy parent's settings */
626 if (!copy_parent_file(cgpath
, "cpuset.mems")) {
627 SYSERROR("Failed to copy \"cpuset.mems\" settings");
629 free(clonechildrenpath
);
634 ret
= lxc_write_to_file(clonechildrenpath
, "1", 1, false, 0666);
636 /* Set clone_children so children inherit our settings */
637 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath
);
638 free(clonechildrenpath
);
641 free(clonechildrenpath
);
645 /* Given two null-terminated lists of strings, return true if any string is in
648 static bool controller_lists_intersect(char **l1
, char **l2
)
655 for (i
= 0; l1
[i
]; i
++) {
656 if (string_in_list(l2
, l1
[i
]))
663 /* For a null-terminated list of controllers @clist, return true if any of those
664 * controllers is already listed the null-terminated list of hierarchies @hlist.
665 * Realistically, if one is present, all must be present.
667 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
674 for (i
= 0; hlist
[i
]; i
++)
675 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
681 /* Return true if the controller @entry is found in the null-terminated list of
682 * hierarchies @hlist.
684 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
691 for (i
= 0; hlist
[i
]; i
++)
692 if (string_in_list(hlist
[i
]->controllers
, entry
))
698 /* Return true if all of the controllers which we require have been found. The
699 * required list is freezer and anything in lxc.cgroup.use.
701 static bool all_controllers_found(struct cgroup_ops
*ops
)
704 struct hierarchy
**hlist
= ops
->hierarchies
;
706 if (!controller_found(hlist
, "freezer")) {
707 ERROR("No freezer controller mountpoint found");
711 if (!ops
->cgroup_use
)
714 for (cur
= ops
->cgroup_use
; cur
&& *cur
; cur
++)
715 if (!controller_found(hlist
, *cur
)) {
716 ERROR("No %s controller mountpoint found", *cur
);
723 /* Get the controllers from a mountinfo line There are other ways we could get
724 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
725 * could parse the mount options. But we simply assume that the mountpoint must
726 * be /sys/fs/cgroup/controller-list
728 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
731 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
732 * for legacy hierarchies.
735 char *dup
, *p2
, *tok
;
736 char *p
= line
, *sep
= ",";
739 for (i
= 0; i
< 4; i
++) {
746 /* Note, if we change how mountinfo works, then our caller will need to
747 * verify /sys/fs/cgroup/ in this field.
749 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0) {
750 ERROR("Found hierarchy not under /sys/fs/cgroup: \"%s\"", p
);
757 ERROR("Corrupt mountinfo");
762 if (type
== CGROUP_SUPER_MAGIC
) {
763 /* strdup() here for v1 hierarchies. Otherwise
764 * lxc_iterate_parts() will destroy mountpoints such as
765 * "/sys/fs/cgroup/cpu,cpuacct".
771 lxc_iterate_parts(tok
, dup
, sep
) {
772 must_append_controller(klist
, nlist
, &aret
, tok
);
782 static char **cg_unified_make_empty_controller(void)
787 newentry
= append_null_to_list((void ***)&aret
);
788 aret
[newentry
] = NULL
;
792 static char **cg_unified_get_controllers(const char *file
)
798 buf
= read_file(file
);
802 lxc_iterate_parts(tok
, buf
, sep
) {
806 newentry
= append_null_to_list((void ***)&aret
);
807 copy
= must_copy_string(tok
);
808 aret
[newentry
] = copy
;
815 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
816 char *container_base_path
, int type
)
818 struct hierarchy
*new;
821 new = must_realloc(NULL
, sizeof(*new));
822 new->controllers
= clist
;
823 new->mountpoint
= mountpoint
;
824 new->container_base_path
= container_base_path
;
825 new->container_full_path
= NULL
;
826 new->monitor_full_path
= NULL
;
829 newentry
= append_null_to_list((void ***)h
);
830 (*h
)[newentry
] = new;
834 /* Get a copy of the mountpoint from @line, which is a line from
835 * /proc/self/mountinfo.
837 static char *cg_hybrid_get_mountpoint(char *line
)
842 char *p
= line
, *sret
= NULL
;
844 for (i
= 0; i
< 4; i
++) {
851 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
854 p2
= strchr(p
+ 15, ' ');
860 sret
= must_realloc(NULL
, len
+ 1);
861 memcpy(sret
, p
, len
);
866 /* Given a multi-line string, return a null-terminated copy of the current line. */
867 static char *copy_to_eol(char *p
)
869 char *p2
= strchr(p
, '\n'), *sret
;
876 sret
= must_realloc(NULL
, len
+ 1);
877 memcpy(sret
, p
, len
);
882 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
883 * /proc/self/cgroup file. Check whether controller c is present.
885 static bool controller_in_clist(char *cgline
, char *c
)
887 char *tok
, *eol
, *tmp
;
890 eol
= strchr(cgline
, ':');
895 tmp
= alloca(len
+ 1);
896 memcpy(tmp
, cgline
, len
);
899 lxc_iterate_parts(tok
, tmp
, ",") {
900 if (strcmp(tok
, c
) == 0)
907 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
910 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
913 char *p
= basecginfo
;
916 bool is_cgv2_base_cgroup
= false;
918 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
919 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
920 is_cgv2_base_cgroup
= true;
927 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
932 return copy_to_eol(p
);
942 static void must_append_string(char ***list
, char *entry
)
947 newentry
= append_null_to_list((void ***)list
);
948 copy
= must_copy_string(entry
);
949 (*list
)[newentry
] = copy
;
952 static int get_existing_subsystems(char ***klist
, char ***nlist
)
958 f
= fopen("/proc/self/cgroup", "r");
962 while (getline(&line
, &len
, f
) != -1) {
964 p
= strchr(line
, ':');
973 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
974 * contains an entry of the form:
978 * In this case we use "cgroup2" as controller name.
981 must_append_string(klist
, "cgroup2");
985 lxc_iterate_parts(tok
, p
, ",") {
986 if (strncmp(tok
, "name=", 5) == 0)
987 must_append_string(nlist
, tok
);
989 must_append_string(klist
, tok
);
998 static void trim(char *s
)
1003 while ((len
> 1) && (s
[len
- 1] == '\n'))
1007 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
1010 struct hierarchy
**it
;
1012 if (!ops
->hierarchies
) {
1013 TRACE(" No hierarchies found");
1017 TRACE(" Hierarchies:");
1018 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
1022 TRACE(" %d: base_cgroup: %s", i
, (*it
)->container_base_path
? (*it
)->container_base_path
: "(null)");
1023 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
1024 TRACE(" controllers:");
1025 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
1026 TRACE(" %d: %s", j
, *cit
);
1030 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
1036 TRACE("basecginfo is:");
1037 TRACE("%s", basecginfo
);
1039 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
1040 TRACE("kernel subsystem %d: %s", k
, *it
);
1042 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
1043 TRACE("named subsystem %d: %s", k
, *it
);
1046 static int cgroup_rmdir(struct hierarchy
**hierarchies
,
1047 const char *container_cgroup
)
1051 if (!container_cgroup
|| !hierarchies
)
1054 for (i
= 0; hierarchies
[i
]; i
++) {
1056 struct hierarchy
*h
= hierarchies
[i
];
1058 if (!h
->container_full_path
)
1061 ret
= recursive_destroy(h
->container_full_path
);
1063 WARN("Failed to destroy \"%s\"", h
->container_full_path
);
1065 free(h
->container_full_path
);
1066 h
->container_full_path
= NULL
;
1072 struct generic_userns_exec_data
{
1073 struct hierarchy
**hierarchies
;
1074 const char *container_cgroup
;
1075 struct lxc_conf
*conf
;
1076 uid_t origuid
; /* target uid in parent namespace */
1080 static int cgroup_rmdir_wrapper(void *data
)
1083 struct generic_userns_exec_data
*arg
= data
;
1084 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1085 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1087 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1089 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid
,
1090 (int)nsgid
, (int)nsgid
);
1094 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1096 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid
,
1097 (int)nsuid
, (int)nsuid
);
1101 ret
= setgroups(0, NULL
);
1102 if (ret
< 0 && errno
!= EPERM
) {
1103 SYSERROR("Failed to setgroups(0, NULL)");
1107 return cgroup_rmdir(arg
->hierarchies
, arg
->container_cgroup
);
1110 __cgfsng_ops
static void cgfsng_payload_destroy(struct cgroup_ops
*ops
,
1111 struct lxc_handler
*handler
)
1114 struct generic_userns_exec_data wrap
;
1117 wrap
.container_cgroup
= ops
->container_cgroup
;
1118 wrap
.hierarchies
= ops
->hierarchies
;
1119 wrap
.conf
= handler
->conf
;
1121 if (handler
->conf
&& !lxc_list_empty(&handler
->conf
->id_map
))
1122 ret
= userns_exec_1(handler
->conf
, cgroup_rmdir_wrapper
, &wrap
,
1123 "cgroup_rmdir_wrapper");
1125 ret
= cgroup_rmdir(ops
->hierarchies
, ops
->container_cgroup
);
1127 WARN("Failed to destroy cgroups");
1132 __cgfsng_ops
static void cgfsng_monitor_destroy(struct cgroup_ops
*ops
,
1133 struct lxc_handler
*handler
)
1137 struct lxc_conf
*conf
= handler
->conf
;
1138 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1140 if (!ops
->hierarchies
)
1143 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", handler
->monitor_pid
);
1144 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
1147 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1150 char pivot_cgroup
[] = PIVOT_CGROUP
;
1151 struct hierarchy
*h
= ops
->hierarchies
[i
];
1153 if (!h
->monitor_full_path
)
1156 if (conf
&& conf
->cgroup_meta
.dir
)
1157 pivot_path
= must_make_path(h
->mountpoint
,
1158 h
->container_base_path
,
1159 conf
->cgroup_meta
.dir
,
1161 "cgroup.procs", NULL
);
1163 pivot_path
= must_make_path(h
->mountpoint
,
1164 h
->container_base_path
,
1166 "cgroup.procs", NULL
);
1168 chop
= strrchr(pivot_path
, '/');
1173 * Make sure not to pass in the ro string literal PIVOT_CGROUP
1176 if (!cg_legacy_handle_cpuset_hierarchy(h
, pivot_cgroup
)) {
1177 WARN("Failed to handle legacy cpuset controller");
1181 ret
= mkdir_p(pivot_path
, 0755);
1182 if (ret
< 0 && errno
!= EEXIST
) {
1183 SYSWARN("Failed to create cgroup \"%s\"\n", pivot_path
);
1190 /* Move ourselves into the pivot cgroup to delete our own
1193 ret
= lxc_write_to_file(pivot_path
, pidstr
, len
, false, 0666);
1195 SYSWARN("Failed to move monitor %s to \"%s\"\n", pidstr
, pivot_path
);
1199 ret
= recursive_destroy(h
->monitor_full_path
);
1201 WARN("Failed to destroy \"%s\"", h
->monitor_full_path
);
1208 static bool cg_unified_create_cgroup(struct hierarchy
*h
, char *cgname
)
1210 size_t i
, parts_len
;
1212 size_t full_len
= 0;
1213 char *add_controllers
= NULL
, *cgroup
= NULL
;
1214 char **parts
= NULL
;
1217 if (h
->version
!= CGROUP2_SUPER_MAGIC
)
1220 if (!h
->controllers
)
1223 /* For now we simply enable all controllers that we have detected by
1224 * creating a string like "+memory +pids +cpu +io".
1225 * TODO: In the near future we might want to support "-<controller>"
1226 * etc. but whether supporting semantics like this make sense will need
1229 for (it
= h
->controllers
; it
&& *it
; it
++) {
1230 full_len
+= strlen(*it
) + 2;
1231 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
1233 if (h
->controllers
[0] == *it
)
1234 add_controllers
[0] = '\0';
1236 (void)strlcat(add_controllers
, "+", full_len
+ 1);
1237 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
1239 if ((it
+ 1) && *(it
+ 1))
1240 (void)strlcat(add_controllers
, " ", full_len
+ 1);
1243 parts
= lxc_string_split(cgname
, '/');
1247 parts_len
= lxc_array_len((void **)parts
);
1251 cgroup
= must_make_path(h
->mountpoint
, h
->container_base_path
, NULL
);
1252 for (i
= 0; i
< parts_len
; i
++) {
1256 cgroup
= must_append_path(cgroup
, parts
[i
], NULL
);
1257 target
= must_make_path(cgroup
, "cgroup.subtree_control", NULL
);
1258 ret
= lxc_write_to_file(target
, add_controllers
, full_len
, false, 0666);
1261 SYSERROR("Could not enable \"%s\" controllers in the "
1262 "unified cgroup \"%s\"", add_controllers
, cgroup
);
1270 lxc_free_array((void **)parts
, free
);
1271 free(add_controllers
);
1276 static int mkdir_eexist_on_last(const char *dir
, mode_t mode
)
1278 const char *tmp
= dir
;
1279 const char *orig
= dir
;
1282 orig_len
= strlen(dir
);
1288 dir
= tmp
+ strspn(tmp
, "/");
1289 tmp
= dir
+ strcspn(dir
, "/");
1292 cur_len
= dir
- orig
;
1293 makeme
= strndup(orig
, cur_len
);
1297 ret
= mkdir(makeme
, mode
);
1299 if ((errno
!= EEXIST
) || (orig_len
== cur_len
)) {
1300 SYSERROR("Failed to create directory \"%s\"", makeme
);
1307 } while (tmp
!= dir
);
1312 static bool monitor_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1316 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1317 ERROR("Failed to handle legacy cpuset controller");
1321 h
->monitor_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1322 ret
= mkdir_eexist_on_last(h
->monitor_full_path
, 0755);
1324 ERROR("Failed to create cgroup \"%s\"", h
->monitor_full_path
);
1328 return cg_unified_create_cgroup(h
, cgname
);
1331 static bool container_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1335 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1336 ERROR("Failed to handle legacy cpuset controller");
1340 h
->container_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1341 ret
= mkdir_eexist_on_last(h
->container_full_path
, 0755);
1343 ERROR("Failed to create cgroup \"%s\"", h
->container_full_path
);
1347 return cg_unified_create_cgroup(h
, cgname
);
1350 static void remove_path_for_hierarchy(struct hierarchy
*h
, char *cgname
, bool monitor
)
1356 full_path
= h
->monitor_full_path
;
1358 full_path
= h
->container_full_path
;
1360 ret
= rmdir(full_path
);
1362 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", full_path
);
1367 h
->monitor_full_path
= NULL
;
1369 h
->container_full_path
= NULL
;
1372 __cgfsng_ops
static inline bool cgfsng_monitor_create(struct cgroup_ops
*ops
,
1373 struct lxc_handler
*handler
)
1375 char *monitor_cgroup
, *offset
, *tmp
;
1379 struct lxc_conf
*conf
= handler
->conf
;
1384 if (conf
->cgroup_meta
.dir
)
1385 tmp
= lxc_string_join("/",
1386 (const char *[]){conf
->cgroup_meta
.dir
,
1387 ops
->monitor_pattern
,
1388 handler
->name
, NULL
},
1391 tmp
= must_make_path(ops
->monitor_pattern
, handler
->name
, NULL
);
1395 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1396 monitor_cgroup
= must_realloc(tmp
, len
);
1397 offset
= monitor_cgroup
+ len
- 5;
1402 int ret
= snprintf(offset
, 5, "-%d", idx
);
1403 if (ret
< 0 || (size_t)ret
>= 5)
1407 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1408 if (!monitor_create_path_for_hierarchy(ops
->hierarchies
[i
], monitor_cgroup
)) {
1409 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->monitor_full_path
);
1410 free(ops
->hierarchies
[i
]->container_full_path
);
1411 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1413 for (int j
= 0; j
< i
; j
++)
1414 remove_path_for_hierarchy(ops
->hierarchies
[j
], monitor_cgroup
, true);
1420 } while (ops
->hierarchies
[i
] && idx
> 0 && idx
< 1000);
1424 INFO("The monitor process uses \"%s\" as cgroup", monitor_cgroup
);
1428 free(monitor_cgroup
);
1433 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1434 * next cgroup_pattern-1, -2, ..., -999.
1436 __cgfsng_ops
static inline bool cgfsng_payload_create(struct cgroup_ops
*ops
,
1437 struct lxc_handler
*handler
)
1441 char *container_cgroup
, *offset
, *tmp
;
1443 struct lxc_conf
*conf
= handler
->conf
;
1445 if (ops
->container_cgroup
) {
1446 WARN("cgfsng_create called a second time: %s", ops
->container_cgroup
);
1453 if (conf
->cgroup_meta
.dir
)
1454 tmp
= lxc_string_join("/", (const char *[]){conf
->cgroup_meta
.dir
, handler
->name
, NULL
}, false);
1456 tmp
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1458 ERROR("Failed expanding cgroup name pattern");
1462 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1463 container_cgroup
= must_realloc(NULL
, len
);
1464 (void)strlcpy(container_cgroup
, tmp
, len
);
1466 offset
= container_cgroup
+ len
- 5;
1470 ERROR("Too many conflicting cgroup names");
1477 ret
= snprintf(offset
, 5, "-%d", idx
);
1478 if (ret
< 0 || (size_t)ret
>= 5) {
1479 FILE *f
= fopen("/dev/null", "w");
1481 fprintf(f
, "Workaround for GCC7 bug: "
1482 "https://gcc.gnu.org/bugzilla/"
1483 "show_bug.cgi?id=78969");
1489 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1490 if (!container_create_path_for_hierarchy(ops
->hierarchies
[i
], container_cgroup
)) {
1491 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->container_full_path
);
1492 free(ops
->hierarchies
[i
]->container_full_path
);
1493 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1494 for (int j
= 0; j
< i
; j
++)
1495 remove_path_for_hierarchy(ops
->hierarchies
[j
], container_cgroup
, false);
1501 ops
->container_cgroup
= container_cgroup
;
1502 INFO("The container uses \"%s\" as cgroup", container_cgroup
);
1507 free(container_cgroup
);
1512 __cgfsng_ops
static bool __do_cgroup_enter(struct cgroup_ops
*ops
, pid_t pid
,
1516 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1518 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", pid
);
1519 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
1522 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1527 path
= must_make_path(ops
->hierarchies
[i
]->monitor_full_path
,
1528 "cgroup.procs", NULL
);
1530 path
= must_make_path(ops
->hierarchies
[i
]->container_full_path
,
1531 "cgroup.procs", NULL
);
1532 ret
= lxc_write_to_file(path
, pidstr
, len
, false, 0666);
1534 SYSERROR("Failed to enter cgroup \"%s\"", path
);
1544 __cgfsng_ops
static bool cgfsng_monitor_enter(struct cgroup_ops
*ops
, pid_t pid
)
1546 return __do_cgroup_enter(ops
, pid
, true);
1549 static bool cgfsng_payload_enter(struct cgroup_ops
*ops
, pid_t pid
)
1551 return __do_cgroup_enter(ops
, pid
, false);
1554 static int chowmod(char *path
, uid_t chown_uid
, gid_t chown_gid
,
1559 ret
= chown(path
, chown_uid
, chown_gid
);
1561 SYSWARN("Failed to chown(%s, %d, %d)", path
, (int)chown_uid
, (int)chown_gid
);
1565 ret
= chmod(path
, chmod_mode
);
1567 SYSWARN("Failed to chmod(%s, %d)", path
, (int)chmod_mode
);
1574 /* chgrp the container cgroups to container group. We leave
1575 * the container owner as cgroup owner. So we must make the
1576 * directories 775 so that the container can create sub-cgroups.
1578 * Also chown the tasks and cgroup.procs files. Those may not
1579 * exist depending on kernel version.
1581 static int chown_cgroup_wrapper(void *data
)
1585 struct generic_userns_exec_data
*arg
= data
;
1586 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1587 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1589 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1591 SYSERROR("Failed to setresgid(%d, %d, %d)",
1592 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1596 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1598 SYSERROR("Failed to setresuid(%d, %d, %d)",
1599 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1603 ret
= setgroups(0, NULL
);
1604 if (ret
< 0 && errno
!= EPERM
) {
1605 SYSERROR("Failed to setgroups(0, NULL)");
1609 destuid
= get_ns_uid(arg
->origuid
);
1610 if (destuid
== LXC_INVALID_UID
)
1613 for (i
= 0; arg
->hierarchies
[i
]; i
++) {
1615 char *path
= arg
->hierarchies
[i
]->container_full_path
;
1617 ret
= chowmod(path
, destuid
, nsgid
, 0775);
1621 /* Failures to chown() these are inconvenient but not
1622 * detrimental We leave these owned by the container launcher,
1623 * so that container root can write to the files to attach. We
1624 * chmod() them 664 so that container systemd can write to the
1625 * files (which systemd in wily insists on doing).
1628 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
) {
1629 fullpath
= must_make_path(path
, "tasks", NULL
);
1630 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1634 fullpath
= must_make_path(path
, "cgroup.procs", NULL
);
1635 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1638 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1641 fullpath
= must_make_path(path
, "cgroup.subtree_control", NULL
);
1642 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1645 fullpath
= must_make_path(path
, "cgroup.threads", NULL
);
1646 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1653 __cgfsng_ops
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1654 struct lxc_conf
*conf
)
1656 struct generic_userns_exec_data wrap
;
1658 if (lxc_list_empty(&conf
->id_map
))
1661 wrap
.origuid
= geteuid();
1663 wrap
.hierarchies
= ops
->hierarchies
;
1666 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
,
1667 "chown_cgroup_wrapper") < 0) {
1668 ERROR("Error requesting cgroup chown in new user namespace");
1675 /* cgroup-full:* is done, no need to create subdirs */
1676 static bool cg_mount_needs_subdirs(int type
)
1678 if (type
>= LXC_AUTO_CGROUP_FULL_RO
)
1684 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1685 * remount controller ro if needed and bindmount the cgroupfs onto
1686 * control/the/cg/path.
1688 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1689 char *controllerpath
, char *cgpath
,
1690 const char *container_cgroup
)
1692 int ret
, remount_flags
;
1694 int flags
= MS_BIND
;
1696 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1697 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1699 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
1700 controllerpath
, controllerpath
);
1704 remount_flags
= add_required_remount_flags(controllerpath
,
1706 flags
| MS_REMOUNT
);
1707 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1708 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1711 SYSERROR("Failed to remount \"%s\" ro", controllerpath
);
1715 INFO("Remounted %s read-only", controllerpath
);
1718 sourcepath
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1719 container_cgroup
, NULL
);
1720 if (type
== LXC_AUTO_CGROUP_RO
)
1723 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1725 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1729 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1731 if (flags
& MS_RDONLY
) {
1732 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1733 flags
| MS_REMOUNT
);
1734 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1736 SYSERROR("Failed to remount \"%s\" ro", cgpath
);
1740 INFO("Remounted %s read-only", cgpath
);
1744 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1748 /* __cg_mount_direct
1750 * Mount cgroup hierarchies directly without using bind-mounts. The main
1751 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1752 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1754 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1755 const char *controllerpath
)
1758 char *controllers
= NULL
;
1759 char *fstype
= "cgroup2";
1760 unsigned long flags
= 0;
1765 flags
|= MS_RELATIME
;
1767 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1770 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1771 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1777 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1780 SYSERROR("Failed to mount \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1784 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1788 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1789 const char *controllerpath
)
1791 return __cg_mount_direct(type
, h
, controllerpath
);
1794 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1795 const char *controllerpath
)
1797 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1800 return __cg_mount_direct(type
, h
, controllerpath
);
1803 __cgfsng_ops
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1804 struct lxc_handler
*handler
,
1805 const char *root
, int type
)
1808 char *tmpfspath
= NULL
;
1809 bool has_cgns
= false, retval
= false, wants_force_mount
= false;
1811 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1814 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1815 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1816 wants_force_mount
= true;
1819 if (!wants_force_mount
){
1820 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1821 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1823 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1826 has_cgns
= cgns_supported();
1827 if (has_cgns
&& !wants_force_mount
)
1830 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1831 type
= LXC_AUTO_CGROUP_MIXED
;
1832 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1833 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1836 tmpfspath
= must_make_path(root
, "/sys/fs/cgroup", NULL
);
1837 ret
= safe_mount(NULL
, tmpfspath
, "tmpfs",
1838 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1839 "size=10240k,mode=755", root
);
1843 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1844 char *controllerpath
, *path2
;
1845 struct hierarchy
*h
= ops
->hierarchies
[i
];
1846 char *controller
= strrchr(h
->mountpoint
, '/');
1852 controllerpath
= must_make_path(tmpfspath
, controller
, NULL
);
1853 if (dir_exists(controllerpath
)) {
1854 free(controllerpath
);
1858 ret
= mkdir(controllerpath
, 0755);
1860 SYSERROR("Error creating cgroup path: %s", controllerpath
);
1861 free(controllerpath
);
1865 if (has_cgns
&& wants_force_mount
) {
1866 /* If cgroup namespaces are supported but the container
1867 * will not have CAP_SYS_ADMIN after it has started we
1868 * need to mount the cgroups manually.
1870 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1871 free(controllerpath
);
1878 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1880 free(controllerpath
);
1884 if (!cg_mount_needs_subdirs(type
)) {
1885 free(controllerpath
);
1889 path2
= must_make_path(controllerpath
, h
->container_base_path
,
1890 ops
->container_cgroup
, NULL
);
1891 ret
= mkdir_p(path2
, 0755);
1893 free(controllerpath
);
1898 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1899 path2
, ops
->container_cgroup
);
1900 free(controllerpath
);
1912 static int recursive_count_nrtasks(char *dirname
)
1914 struct dirent
*direntp
;
1919 dir
= opendir(dirname
);
1923 while ((direntp
= readdir(dir
))) {
1926 if (!strcmp(direntp
->d_name
, ".") ||
1927 !strcmp(direntp
->d_name
, ".."))
1930 path
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1932 if (lstat(path
, &mystat
))
1935 if (!S_ISDIR(mystat
.st_mode
))
1938 count
+= recursive_count_nrtasks(path
);
1943 path
= must_make_path(dirname
, "cgroup.procs", NULL
);
1944 ret
= lxc_count_file_lines(path
);
1949 (void)closedir(dir
);
1954 __cgfsng_ops
static int cgfsng_nrtasks(struct cgroup_ops
*ops
)
1959 if (!ops
->container_cgroup
|| !ops
->hierarchies
)
1962 path
= must_make_path(ops
->hierarchies
[0]->container_full_path
, NULL
);
1963 count
= recursive_count_nrtasks(path
);
1968 /* Only root needs to escape to the cgroup of its init. */
1969 __cgfsng_ops
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1970 struct lxc_conf
*conf
)
1974 if (conf
->cgroup_meta
.relative
|| geteuid())
1977 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1981 fullpath
= must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1982 ops
->hierarchies
[i
]->container_base_path
,
1983 "cgroup.procs", NULL
);
1984 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1986 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath
);
1996 __cgfsng_ops
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
2000 for (i
= 0; ops
->hierarchies
[i
]; i
++)
2006 __cgfsng_ops
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
, char ***out
)
2010 /* sanity check n */
2011 for (i
= 0; i
< n
; i
++)
2012 if (!ops
->hierarchies
[i
])
2015 *out
= ops
->hierarchies
[i
]->controllers
;
2020 #define THAWED "THAWED"
2021 #define THAWED_LEN (strlen(THAWED))
2023 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
2026 __cgfsng_ops
static bool cgfsng_unfreeze(struct cgroup_ops
*ops
)
2030 struct hierarchy
*h
;
2032 h
= get_hierarchy(ops
, "freezer");
2036 fullpath
= must_make_path(h
->container_full_path
, "freezer.state", NULL
);
2037 ret
= lxc_write_to_file(fullpath
, THAWED
, THAWED_LEN
, false, 0666);
2045 __cgfsng_ops
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
2046 const char *controller
)
2048 struct hierarchy
*h
;
2050 h
= get_hierarchy(ops
, controller
);
2052 WARN("Failed to find hierarchy for controller \"%s\"",
2053 controller
? controller
: "(null)");
2057 return h
->container_full_path
? h
->container_full_path
+ strlen(h
->mountpoint
) : NULL
;
2060 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2061 * which must be freed by the caller.
2063 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
2065 const char *filename
)
2067 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
2070 /* Technically, we're always at a delegation boundary here (This is especially
2071 * true when cgroup namespaces are available.). The reasoning is that in order
2072 * for us to have been able to start a container in the first place the root
2073 * cgroup must have been a leaf node. Now, either the container's init system
2074 * has populated the cgroup and kept it as a leaf node or it has created
2075 * subtrees. In the former case we will simply attach to the leaf node we
2076 * created when we started the container in the latter case we create our own
2077 * cgroup for the attaching process.
2079 static int __cg_unified_attach(const struct hierarchy
*h
, const char *name
,
2080 const char *lxcpath
, const char *pidstr
,
2081 size_t pidstr_len
, const char *controller
)
2085 int fret
= -1, idx
= 0;
2086 char *base_path
= NULL
, *container_cgroup
= NULL
, *full_path
= NULL
;
2088 container_cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2090 if (!container_cgroup
)
2093 base_path
= must_make_path(h
->mountpoint
, container_cgroup
, NULL
);
2094 full_path
= must_make_path(base_path
, "cgroup.procs", NULL
);
2095 /* cgroup is populated */
2096 ret
= lxc_write_to_file(full_path
, pidstr
, pidstr_len
, false, 0666);
2097 if (ret
< 0 && errno
!= EBUSY
)
2105 len
= strlen(base_path
) + STRLITERALLEN("/lxc-1000") +
2106 STRLITERALLEN("/cgroup-procs");
2107 full_path
= must_realloc(NULL
, len
+ 1);
2110 ret
= snprintf(full_path
, len
+ 1, "%s/lxc-%d",
2113 ret
= snprintf(full_path
, len
+ 1, "%s/lxc", base_path
);
2114 if (ret
< 0 || (size_t)ret
>= len
+ 1)
2117 ret
= mkdir_p(full_path
, 0755);
2118 if (ret
< 0 && errno
!= EEXIST
)
2121 (void)strlcat(full_path
, "/cgroup.procs", len
+ 1);
2122 ret
= lxc_write_to_file(full_path
, pidstr
, len
, false, 0666);
2126 /* this is a non-leaf node */
2131 } while (idx
< 1000);
2139 free(container_cgroup
);
2145 __cgfsng_ops
static bool cgfsng_attach(struct cgroup_ops
*ops
, const char *name
,
2146 const char *lxcpath
, pid_t pid
)
2149 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
2151 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", pid
);
2152 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
2155 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
2157 char *fullpath
= NULL
;
2158 struct hierarchy
*h
= ops
->hierarchies
[i
];
2160 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2161 ret
= __cg_unified_attach(h
, name
, lxcpath
, pidstr
, len
,
2169 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2174 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2176 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2178 SYSERROR("Failed to attach %d to %s", (int)pid
, fullpath
);
2188 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2189 * don't have a cgroup_data set up, so we ask the running container through the
2190 * commands API for the cgroup path.
2192 __cgfsng_ops
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
2193 char *value
, size_t len
, const char *name
,
2194 const char *lxcpath
)
2197 size_t controller_len
;
2198 char *controller
, *p
, *path
;
2199 struct hierarchy
*h
;
2201 controller_len
= strlen(filename
);
2202 controller
= alloca(controller_len
+ 1);
2203 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2205 p
= strchr(controller
, '.');
2209 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2214 h
= get_hierarchy(ops
, controller
);
2218 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2219 ret
= lxc_read_from_file(fullpath
, value
, len
);
2227 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2228 * don't have a cgroup_data set up, so we ask the running container through the
2229 * commands API for the cgroup path.
2231 __cgfsng_ops
static int cgfsng_set(struct cgroup_ops
*ops
,
2232 const char *filename
, const char *value
,
2233 const char *name
, const char *lxcpath
)
2236 size_t controller_len
;
2237 char *controller
, *p
, *path
;
2238 struct hierarchy
*h
;
2240 controller_len
= strlen(filename
);
2241 controller
= alloca(controller_len
+ 1);
2242 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2244 p
= strchr(controller
, '.');
2248 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2253 h
= get_hierarchy(ops
, controller
);
2257 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2258 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2266 /* take devices cgroup line
2268 * and convert it to a valid
2269 * type major:minor mode
2270 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2273 static int convert_devpath(const char *invalue
, char *dest
)
2276 char *p
, *path
, type
;
2277 unsigned long minor
, major
;
2282 path
= must_copy_string(invalue
);
2284 /* Read path followed by mode. Ignore any trailing text.
2285 * A ' # comment' would be legal. Technically other text is not
2286 * legal, we could check for that if we cared to.
2288 for (n_parts
= 1, p
= path
; *p
&& n_parts
< 3; p
++) {
2310 ret
= stat(path
, &sb
);
2314 mode_t m
= sb
.st_mode
& S_IFMT
;
2323 ERROR("Unsupported device type %i for \"%s\"", m
, path
);
2328 major
= MAJOR(sb
.st_rdev
);
2329 minor
= MINOR(sb
.st_rdev
);
2330 ret
= snprintf(dest
, 50, "%c %lu:%lu %s", type
, major
, minor
, mode
);
2331 if (ret
< 0 || ret
>= 50) {
2332 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2333 "chars)", type
, major
, minor
, mode
);
2334 ret
= -ENAMETOOLONG
;
2344 /* Called from setup_limits - here we have the container's cgroup_data because
2345 * we created the cgroups.
2347 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2352 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2353 char converted_value
[50];
2354 struct hierarchy
*h
;
2356 char *controller
= NULL
;
2358 len
= strlen(filename
);
2359 controller
= alloca(len
+ 1);
2360 (void)strlcpy(controller
, filename
, len
+ 1);
2362 p
= strchr(controller
, '.');
2366 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2367 ret
= convert_devpath(value
, converted_value
);
2370 value
= converted_value
;
2373 h
= get_hierarchy(ops
, controller
);
2375 ERROR("Failed to setup limits for the \"%s\" controller. "
2376 "The controller seems to be unused by \"cgfsng\" cgroup "
2377 "driver or not enabled on the cgroup hierarchy",
2383 fullpath
= must_make_path(h
->container_full_path
, filename
, NULL
);
2384 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2389 static bool __cg_legacy_setup_limits(struct cgroup_ops
*ops
,
2390 struct lxc_list
*cgroup_settings
,
2393 struct lxc_list
*iterator
, *next
, *sorted_cgroup_settings
;
2394 struct lxc_cgroup
*cg
;
2397 if (lxc_list_empty(cgroup_settings
))
2400 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2401 if (!sorted_cgroup_settings
)
2404 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2405 cg
= iterator
->elem
;
2407 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2408 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
)) {
2409 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2410 WARN("Failed to set \"%s\" to \"%s\"",
2411 cg
->subsystem
, cg
->value
);
2414 WARN("Failed to set \"%s\" to \"%s\"",
2415 cg
->subsystem
, cg
->value
);
2418 DEBUG("Set controller \"%s\" set to \"%s\"",
2419 cg
->subsystem
, cg
->value
);
2424 INFO("Limits for the legacy cgroup hierarchies have been setup");
2426 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2427 lxc_list_del(iterator
);
2430 free(sorted_cgroup_settings
);
2434 static bool __cg_unified_setup_limits(struct cgroup_ops
*ops
,
2435 struct lxc_list
*cgroup_settings
)
2437 struct lxc_list
*iterator
;
2438 struct hierarchy
*h
= ops
->unified
;
2440 if (lxc_list_empty(cgroup_settings
))
2446 lxc_list_for_each(iterator
, cgroup_settings
) {
2449 struct lxc_cgroup
*cg
= iterator
->elem
;
2451 fullpath
= must_make_path(h
->container_full_path
, cg
->subsystem
, NULL
);
2452 ret
= lxc_write_to_file(fullpath
, cg
->value
, strlen(cg
->value
), false, 0666);
2455 SYSERROR("Failed to set \"%s\" to \"%s\"",
2456 cg
->subsystem
, cg
->value
);
2459 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2462 INFO("Limits for the unified cgroup hierarchy have been setup");
2466 __cgfsng_ops
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2467 struct lxc_conf
*conf
,
2472 bret
= __cg_legacy_setup_limits(ops
, &conf
->cgroup
, do_devices
);
2476 return __cg_unified_setup_limits(ops
, &conf
->cgroup2
);
2479 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
2482 char **cur_ctrl
, **cur_use
;
2484 if (!ops
->cgroup_use
)
2487 for (cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
2490 for (cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
2491 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
2507 /* At startup, parse_hierarchies finds all the info we need about cgroup
2508 * mountpoints and current cgroups, and stores it in @d.
2510 static bool cg_hybrid_init(struct cgroup_ops
*ops
, bool relative
)
2517 char **klist
= NULL
, **nlist
= NULL
;
2519 /* Root spawned containers escape the current cgroup, so use init's
2520 * cgroups as our base in that case.
2522 if (!relative
&& (geteuid() == 0))
2523 basecginfo
= read_file("/proc/1/cgroup");
2525 basecginfo
= read_file("/proc/self/cgroup");
2529 ret
= get_existing_subsystems(&klist
, &nlist
);
2531 ERROR("Failed to retrieve available legacy cgroup controllers");
2536 f
= fopen("/proc/self/mountinfo", "r");
2538 ERROR("Failed to open \"/proc/self/mountinfo\"");
2543 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
2545 while (getline(&line
, &len
, f
) != -1) {
2548 struct hierarchy
*new;
2549 char *base_cgroup
= NULL
, *mountpoint
= NULL
;
2550 char **controller_list
= NULL
;
2552 type
= get_cgroup_version(line
);
2556 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
2559 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
2560 if (type
== CGROUP2_SUPER_MAGIC
)
2561 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2562 else if (type
== CGROUP_SUPER_MAGIC
)
2563 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
2564 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
2565 if (type
== CGROUP_SUPER_MAGIC
)
2566 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2567 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
2568 if (type
== CGROUP2_SUPER_MAGIC
)
2569 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2572 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
2573 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
2576 if (type
== CGROUP_SUPER_MAGIC
)
2577 if (controller_list_is_dup(ops
->hierarchies
, controller_list
))
2580 mountpoint
= cg_hybrid_get_mountpoint(line
);
2582 ERROR("Failed parsing mountpoint from \"%s\"", line
);
2586 if (type
== CGROUP_SUPER_MAGIC
)
2587 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
2589 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
2591 ERROR("Failed to find current cgroup");
2596 prune_init_scope(base_cgroup
);
2597 if (type
== CGROUP2_SUPER_MAGIC
)
2598 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
2600 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
2604 if (type
== CGROUP2_SUPER_MAGIC
) {
2605 char *cgv2_ctrl_path
;
2607 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
2608 "cgroup.controllers",
2611 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
2612 free(cgv2_ctrl_path
);
2613 if (!controller_list
) {
2614 controller_list
= cg_unified_make_empty_controller();
2615 TRACE("No controllers are enabled for "
2616 "delegation in the unified hierarchy");
2620 /* Exclude all controllers that cgroup use does not want. */
2621 if (!cgroup_use_wants_controllers(ops
, controller_list
))
2624 new = add_hierarchy(&ops
->hierarchies
, controller_list
, mountpoint
, base_cgroup
, type
);
2625 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
)
2631 free_string_list(controller_list
);
2636 free_string_list(klist
);
2637 free_string_list(nlist
);
2644 TRACE("Writable cgroup hierarchies:");
2645 lxc_cgfsng_print_hierarchies(ops
);
2647 /* verify that all controllers in cgroup.use and all crucial
2648 * controllers are accounted for
2650 if (!all_controllers_found(ops
))
2656 static int cg_is_pure_unified(void)
2662 ret
= statfs("/sys/fs/cgroup", &fs
);
2666 if (is_fs_type(&fs
, CGROUP2_SUPER_MAGIC
))
2667 return CGROUP2_SUPER_MAGIC
;
2672 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
2673 static char *cg_unified_get_current_cgroup(bool relative
)
2675 char *basecginfo
, *base_cgroup
;
2678 if (!relative
&& (geteuid() == 0))
2679 basecginfo
= read_file("/proc/1/cgroup");
2681 basecginfo
= read_file("/proc/self/cgroup");
2685 base_cgroup
= strstr(basecginfo
, "0::/");
2687 goto cleanup_on_err
;
2689 base_cgroup
= base_cgroup
+ 3;
2690 copy
= copy_to_eol(base_cgroup
);
2692 goto cleanup_on_err
;
2702 static int cg_unified_init(struct cgroup_ops
*ops
, bool relative
)
2705 char *mountpoint
, *subtree_path
;
2707 char *base_cgroup
= NULL
;
2709 ret
= cg_is_pure_unified();
2710 if (ret
== -ENOMEDIUM
)
2713 if (ret
!= CGROUP2_SUPER_MAGIC
)
2716 base_cgroup
= cg_unified_get_current_cgroup(relative
);
2719 prune_init_scope(base_cgroup
);
2721 /* We assume that we have already been given controllers to delegate
2722 * further down the hierarchy. If not it is up to the user to delegate
2725 mountpoint
= must_copy_string("/sys/fs/cgroup");
2726 subtree_path
= must_make_path(mountpoint
, base_cgroup
,
2727 "cgroup.subtree_control", NULL
);
2728 delegatable
= cg_unified_get_controllers(subtree_path
);
2731 delegatable
= cg_unified_make_empty_controller();
2732 if (!delegatable
[0])
2733 TRACE("No controllers are enabled for delegation");
2735 /* TODO: If the user requested specific controllers via lxc.cgroup.use
2736 * we should verify here. The reason I'm not doing it right is that I'm
2737 * not convinced that lxc.cgroup.use will be the future since it is a
2738 * global property. I much rather have an option that lets you request
2739 * controllers per container.
2742 add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
2744 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2745 return CGROUP2_SUPER_MAGIC
;
2748 static bool cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
2752 bool relative
= conf
->cgroup_meta
.relative
;
2754 tmp
= lxc_global_config_value("lxc.cgroup.use");
2756 char *chop
, *cur
, *pin
;
2758 pin
= must_copy_string(tmp
);
2761 lxc_iterate_parts(cur
, chop
, ",") {
2762 must_append_string(&ops
->cgroup_use
, cur
);
2768 ret
= cg_unified_init(ops
, relative
);
2772 if (ret
== CGROUP2_SUPER_MAGIC
)
2775 return cg_hybrid_init(ops
, relative
);
2778 __cgfsng_ops
static bool cgfsng_data_init(struct cgroup_ops
*ops
)
2780 const char *cgroup_pattern
;
2782 /* copy system-wide cgroup information */
2783 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
2784 if (!cgroup_pattern
) {
2785 /* lxc.cgroup.pattern is only NULL on error. */
2786 ERROR("Failed to retrieve cgroup pattern");
2789 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
2790 ops
->monitor_pattern
= MONITOR_CGROUP
;
2795 struct cgroup_ops
*cgfsng_ops_init(struct lxc_conf
*conf
)
2797 struct cgroup_ops
*cgfsng_ops
;
2799 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
2803 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
2804 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
2806 if (!cg_init(cgfsng_ops
, conf
)) {
2811 cgfsng_ops
->data_init
= cgfsng_data_init
;
2812 cgfsng_ops
->payload_destroy
= cgfsng_payload_destroy
;
2813 cgfsng_ops
->monitor_destroy
= cgfsng_monitor_destroy
;
2814 cgfsng_ops
->monitor_create
= cgfsng_monitor_create
;
2815 cgfsng_ops
->monitor_enter
= cgfsng_monitor_enter
;
2816 cgfsng_ops
->payload_create
= cgfsng_payload_create
;
2817 cgfsng_ops
->payload_enter
= cgfsng_payload_enter
;
2818 cgfsng_ops
->escape
= cgfsng_escape
;
2819 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
2820 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
2821 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
2822 cgfsng_ops
->get
= cgfsng_get
;
2823 cgfsng_ops
->set
= cgfsng_set
;
2824 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
2825 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
2826 cgfsng_ops
->driver
= "cgfsng";
2827 cgfsng_ops
->version
= "1.0.0";
2828 cgfsng_ops
->attach
= cgfsng_attach
;
2829 cgfsng_ops
->chown
= cgfsng_chown
;
2830 cgfsng_ops
->mount
= cgfsng_mount
;
2831 cgfsng_ops
->nrtasks
= cgfsng_nrtasks
;