2 * lxc: linux Container library
4 * Copyright © 2016 Canonical Ltd.
7 * Serge Hallyn <serge.hallyn@ubuntu.com>
8 * Christian Brauner <christian.brauner@ubuntu.com>
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
27 * cgroup backend. The original cgfs.c was designed to be as flexible
28 * as possible. It would try to find cgroup filesystems no matter where
29 * or how you had them mounted, and deduce the most usable mount for
32 * This new implementation assumes that cgroup filesystems are mounted
33 * under /sys/fs/cgroup/clist where clist is either the controller, or
34 * a comman-separated list of controllers.
48 #include <linux/kdev_t.h>
49 #include <linux/types.h>
50 #include <sys/types.h>
54 #include "cgroup_utils.h"
59 #include "storage/storage.h"
63 #include "include/strlcpy.h"
67 #include "include/strlcat.h"
70 lxc_log_define(cgfsng
, cgroup
);
72 static void free_string_list(char **clist
)
79 for (i
= 0; clist
[i
]; i
++)
85 /* Allocate a pointer, do not fail. */
86 static void *must_alloc(size_t sz
)
88 return must_realloc(NULL
, sz
);
91 /* Given a pointer to a null-terminated array of pointers, realloc to add one
92 * entry, and point the new entry to NULL. Do not fail. Return the index to the
93 * second-to-last entry - that is, the one which is now available for use
94 * (keeping the list null-terminated).
96 static int append_null_to_list(void ***list
)
101 for (; (*list
)[newentry
]; newentry
++)
104 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
105 (*list
)[newentry
+ 1] = NULL
;
109 /* Given a null-terminated array of strings, check whether @entry is one of the
112 static bool string_in_list(char **list
, const char *entry
)
119 for (i
= 0; list
[i
]; i
++)
120 if (strcmp(list
[i
], entry
) == 0)
126 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
127 * "name=systemd". Do not fail.
129 static char *cg_legacy_must_prefix_named(char *entry
)
135 prefixed
= must_alloc(len
+ 6);
138 memcpy(prefixed
, "name=", STRLITERALLEN("name="));
139 memcpy(prefixed
+ STRLITERALLEN("name="), entry
, len
);
140 prefixed
[len
+ 5] = '\0';
144 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
147 * We also handle named subsystems here. Any controller which is not a kernel
148 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
149 * we refuse to use because we're not sure which we have here.
150 * (TODO: We could work around this in some cases by just remounting to be
151 * unambiguous, or by comparing mountpoint contents with current cgroup.)
153 * The last entry will always be NULL.
155 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
161 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
162 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
163 ERROR("It is both a named and kernel subsystem");
167 newentry
= append_null_to_list((void ***)clist
);
169 if (strncmp(entry
, "name=", 5) == 0)
170 copy
= must_copy_string(entry
);
171 else if (string_in_list(klist
, entry
))
172 copy
= must_copy_string(entry
);
174 copy
= cg_legacy_must_prefix_named(entry
);
176 (*clist
)[newentry
] = copy
;
179 /* Given a handler's cgroup data, return the struct hierarchy for the controller
180 * @c, or NULL if there is none.
182 struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *controller
)
188 if (!ops
->hierarchies
) {
189 TRACE("There are no useable cgroup controllers");
193 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
195 /* This is the empty unified hierarchy. */
196 if (ops
->hierarchies
[i
]->controllers
&&
197 !ops
->hierarchies
[i
]->controllers
[0])
198 return ops
->hierarchies
[i
];
203 if (string_in_list(ops
->hierarchies
[i
]->controllers
, controller
))
204 return ops
->hierarchies
[i
];
208 WARN("There is no useable %s controller", controller
);
210 WARN("There is no empty unified cgroup hierarchy");
215 #define BATCH_SIZE 50
216 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
218 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
219 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
221 if (!*mem
|| newbatches
> oldbatches
) {
222 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
226 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
228 size_t full
= oldlen
+ newlen
;
230 batch_realloc(dest
, oldlen
, full
+ 1);
232 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
235 /* Slurp in a whole file */
236 static char *read_file(const char *fnam
)
239 char *line
= NULL
, *buf
= NULL
;
240 size_t len
= 0, fulllen
= 0;
243 f
= fopen(fnam
, "r");
246 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
247 append_line(&buf
, fulllen
, line
, linelen
);
255 /* Taken over modified from the kernel sources. */
256 #define NBITS 32 /* bits in uint32_t */
257 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
258 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
260 static void set_bit(unsigned bit
, uint32_t *bitarr
)
262 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
265 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
267 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
270 static bool is_set(unsigned bit
, uint32_t *bitarr
)
272 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
275 /* Create cpumask from cpulist aka turn:
283 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
289 arrlen
= BITS_TO_LONGS(nbits
);
290 bitarr
= calloc(arrlen
, sizeof(uint32_t));
294 lxc_iterate_parts(token
, buf
, ",") {
299 start
= strtoul(token
, NULL
, 0);
301 range
= strchr(token
, '-');
303 end
= strtoul(range
+ 1, NULL
, 0);
305 if (!(start
<= end
)) {
316 set_bit(start
++, bitarr
);
322 /* Turn cpumask into simple, comma-separated cpulist. */
323 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
327 char **cpulist
= NULL
;
328 char numstr
[INTTYPE_TO_STRLEN(size_t)] = {0};
330 for (i
= 0; i
<= nbits
; i
++) {
331 if (!is_set(i
, bitarr
))
334 ret
= snprintf(numstr
, sizeof(numstr
), "%zu", i
);
335 if (ret
< 0 || (size_t)ret
>= sizeof(numstr
)) {
336 lxc_free_array((void **)cpulist
, free
);
340 ret
= lxc_append_string(&cpulist
, numstr
);
342 lxc_free_array((void **)cpulist
, free
);
350 return lxc_string_join(",", (const char **)cpulist
, false);
353 static ssize_t
get_max_cpus(char *cpulist
)
356 char *maxcpus
= cpulist
;
359 c1
= strrchr(maxcpus
, ',');
363 c2
= strrchr(maxcpus
, '-');
377 cpus
= strtoul(c1
, NULL
, 0);
384 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
385 static bool cg_legacy_filter_and_set_cpus(char *path
, bool am_initialized
)
389 char *lastslash
, *fpath
, oldv
;
390 ssize_t maxisol
= 0, maxposs
= 0;
391 char *cpulist
= NULL
, *isolcpus
= NULL
, *posscpus
= NULL
;
392 uint32_t *isolmask
= NULL
, *possmask
= NULL
;
393 bool bret
= false, flipped_bit
= false;
395 lastslash
= strrchr(path
, '/');
397 ERROR("Failed to detect \"/\" in \"%s\"", path
);
402 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
403 posscpus
= read_file(fpath
);
405 SYSERROR("Failed to read file \"%s\"", fpath
);
409 /* Get maximum number of cpus found in possible cpuset. */
410 maxposs
= get_max_cpus(posscpus
);
411 if (maxposs
< 0 || maxposs
>= INT_MAX
- 1)
414 if (!file_exists(__ISOL_CPUS
)) {
415 /* This system doesn't expose isolated cpus. */
416 DEBUG("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
418 /* No isolated cpus but we weren't already initialized by
419 * someone. We should simply copy the parents cpuset.cpus
422 if (!am_initialized
) {
423 DEBUG("Copying cpu settings of parent cgroup");
426 /* No isolated cpus but we were already initialized by someone.
427 * Nothing more to do for us.
432 isolcpus
= read_file(__ISOL_CPUS
);
434 SYSERROR("Failed to read file \""__ISOL_CPUS
"\"");
437 if (!isdigit(isolcpus
[0])) {
438 TRACE("No isolated cpus detected");
440 /* No isolated cpus but we weren't already initialized by
441 * someone. We should simply copy the parents cpuset.cpus
444 if (!am_initialized
) {
445 DEBUG("Copying cpu settings of parent cgroup");
448 /* No isolated cpus but we were already initialized by someone.
449 * Nothing more to do for us.
454 /* Get maximum number of cpus found in isolated cpuset. */
455 maxisol
= get_max_cpus(isolcpus
);
456 if (maxisol
< 0 || maxisol
>= INT_MAX
- 1)
459 if (maxposs
< maxisol
)
463 possmask
= lxc_cpumask(posscpus
, maxposs
);
465 ERROR("Failed to create cpumask for possible cpus");
469 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
471 ERROR("Failed to create cpumask for isolated cpus");
475 for (i
= 0; i
<= maxposs
; i
++) {
476 if (!is_set(i
, isolmask
) || !is_set(i
, possmask
))
480 clear_bit(i
, possmask
);
484 DEBUG("No isolated cpus present in cpuset");
487 DEBUG("Removed isolated cpus from cpuset");
489 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
491 ERROR("Failed to create cpu list");
498 fpath
= must_make_path(path
, "cpuset.cpus", NULL
);
499 ret
= lxc_write_to_file(fpath
, cpulist
, strlen(cpulist
), false, 0666);
501 SYSERROR("Failed to write cpu list to \"%s\"", fpath
);
514 if (posscpus
!= cpulist
)
522 /* Copy contents of parent(@path)/@file to @path/@file */
523 static bool copy_parent_file(char *path
, char *file
)
526 char *fpath
, *lastslash
, oldv
;
530 lastslash
= strrchr(path
, '/');
532 ERROR("Failed to detect \"/\" in \"%s\"", path
);
537 fpath
= must_make_path(path
, file
, NULL
);
538 len
= lxc_read_from_file(fpath
, NULL
, 0);
542 value
= must_alloc(len
+ 1);
543 ret
= lxc_read_from_file(fpath
, value
, len
);
549 fpath
= must_make_path(path
, file
, NULL
);
550 ret
= lxc_write_to_file(fpath
, value
, len
, false, 0666);
552 SYSERROR("Failed to write \"%s\" to file \"%s\"", value
, fpath
);
558 SYSERROR("Failed to read file \"%s\"", fpath
);
564 /* Initialize the cpuset hierarchy in first directory of @gname and set
565 * cgroup.clone_children so that children inherit settings. Since the
566 * h->base_path is populated by init or ourselves, we know it is already
569 static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
, char *cgname
)
573 char *cgpath
, *clonechildrenpath
, *slash
;
575 if (!string_in_list(h
->controllers
, "cpuset"))
580 slash
= strchr(cgname
, '/');
584 cgpath
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
588 ret
= mkdir(cgpath
, 0755);
590 if (errno
!= EEXIST
) {
591 SYSERROR("Failed to create directory \"%s\"", cgpath
);
597 clonechildrenpath
= must_make_path(cgpath
, "cgroup.clone_children", NULL
);
598 /* unified hierarchy doesn't have clone_children */
599 if (!file_exists(clonechildrenpath
)) {
600 free(clonechildrenpath
);
605 ret
= lxc_read_from_file(clonechildrenpath
, &v
, 1);
607 SYSERROR("Failed to read file \"%s\"", clonechildrenpath
);
608 free(clonechildrenpath
);
613 /* Make sure any isolated cpus are removed from cpuset.cpus. */
614 if (!cg_legacy_filter_and_set_cpus(cgpath
, v
== '1')) {
615 SYSERROR("Failed to remove isolated cpus");
616 free(clonechildrenpath
);
621 /* Already set for us by someone else. */
623 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
624 free(clonechildrenpath
);
629 /* copy parent's settings */
630 if (!copy_parent_file(cgpath
, "cpuset.mems")) {
631 SYSERROR("Failed to copy \"cpuset.mems\" settings");
633 free(clonechildrenpath
);
638 ret
= lxc_write_to_file(clonechildrenpath
, "1", 1, false, 0666);
640 /* Set clone_children so children inherit our settings */
641 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath
);
642 free(clonechildrenpath
);
645 free(clonechildrenpath
);
649 /* Given two null-terminated lists of strings, return true if any string is in
652 static bool controller_lists_intersect(char **l1
, char **l2
)
659 for (i
= 0; l1
[i
]; i
++) {
660 if (string_in_list(l2
, l1
[i
]))
667 /* For a null-terminated list of controllers @clist, return true if any of those
668 * controllers is already listed the null-terminated list of hierarchies @hlist.
669 * Realistically, if one is present, all must be present.
671 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
678 for (i
= 0; hlist
[i
]; i
++)
679 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
685 /* Return true if the controller @entry is found in the null-terminated list of
686 * hierarchies @hlist.
688 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
695 for (i
= 0; hlist
[i
]; i
++)
696 if (string_in_list(hlist
[i
]->controllers
, entry
))
702 /* Return true if all of the controllers which we require have been found. The
703 * required list is freezer and anything in lxc.cgroup.use.
705 static bool all_controllers_found(struct cgroup_ops
*ops
)
708 struct hierarchy
**hlist
= ops
->hierarchies
;
710 if (!controller_found(hlist
, "freezer")) {
711 ERROR("No freezer controller mountpoint found");
715 if (!ops
->cgroup_use
)
718 for (cur
= ops
->cgroup_use
; cur
&& *cur
; cur
++)
719 if (!controller_found(hlist
, *cur
)) {
720 ERROR("No %s controller mountpoint found", *cur
);
727 /* Get the controllers from a mountinfo line There are other ways we could get
728 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
729 * could parse the mount options. But we simply assume that the mountpoint must
730 * be /sys/fs/cgroup/controller-list
732 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
735 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
736 * for legacy hierarchies.
739 char *dup
, *p2
, *tok
;
740 char *p
= line
, *sep
= ",";
743 for (i
= 0; i
< 4; i
++) {
750 /* Note, if we change how mountinfo works, then our caller will need to
751 * verify /sys/fs/cgroup/ in this field.
753 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0) {
754 ERROR("Found hierarchy not under /sys/fs/cgroup: \"%s\"", p
);
761 ERROR("Corrupt mountinfo");
766 if (type
== CGROUP_SUPER_MAGIC
) {
767 /* strdup() here for v1 hierarchies. Otherwise
768 * lxc_iterate_parts() will destroy mountpoints such as
769 * "/sys/fs/cgroup/cpu,cpuacct".
775 lxc_iterate_parts(tok
, dup
, sep
) {
776 must_append_controller(klist
, nlist
, &aret
, tok
);
786 static char **cg_unified_make_empty_controller(void)
791 newentry
= append_null_to_list((void ***)&aret
);
792 aret
[newentry
] = NULL
;
796 static char **cg_unified_get_controllers(const char *file
)
802 buf
= read_file(file
);
806 lxc_iterate_parts(tok
, buf
, sep
) {
810 newentry
= append_null_to_list((void ***)&aret
);
811 copy
= must_copy_string(tok
);
812 aret
[newentry
] = copy
;
819 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
820 char *container_base_path
, int type
)
822 struct hierarchy
*new;
825 new = must_alloc(sizeof(*new));
826 new->controllers
= clist
;
827 new->mountpoint
= mountpoint
;
828 new->container_base_path
= container_base_path
;
829 new->container_full_path
= NULL
;
830 new->monitor_full_path
= NULL
;
833 newentry
= append_null_to_list((void ***)h
);
834 (*h
)[newentry
] = new;
838 /* Get a copy of the mountpoint from @line, which is a line from
839 * /proc/self/mountinfo.
841 static char *cg_hybrid_get_mountpoint(char *line
)
846 char *p
= line
, *sret
= NULL
;
848 for (i
= 0; i
< 4; i
++) {
855 if (strncmp(p
, "/sys/fs/cgroup/", 15) != 0)
858 p2
= strchr(p
+ 15, ' ');
864 sret
= must_alloc(len
+ 1);
865 memcpy(sret
, p
, len
);
870 /* Given a multi-line string, return a null-terminated copy of the current line. */
871 static char *copy_to_eol(char *p
)
873 char *p2
= strchr(p
, '\n'), *sret
;
880 sret
= must_alloc(len
+ 1);
881 memcpy(sret
, p
, len
);
886 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
887 * /proc/self/cgroup file. Check whether controller c is present.
889 static bool controller_in_clist(char *cgline
, char *c
)
891 char *tok
, *eol
, *tmp
;
894 eol
= strchr(cgline
, ':');
899 tmp
= alloca(len
+ 1);
900 memcpy(tmp
, cgline
, len
);
903 lxc_iterate_parts(tok
, tmp
, ",") {
904 if (strcmp(tok
, c
) == 0)
911 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
914 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
917 char *p
= basecginfo
;
920 bool is_cgv2_base_cgroup
= false;
922 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
923 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
924 is_cgv2_base_cgroup
= true;
931 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
936 return copy_to_eol(p
);
946 static void must_append_string(char ***list
, char *entry
)
951 newentry
= append_null_to_list((void ***)list
);
952 copy
= must_copy_string(entry
);
953 (*list
)[newentry
] = copy
;
956 static int get_existing_subsystems(char ***klist
, char ***nlist
)
962 f
= fopen("/proc/self/cgroup", "r");
966 while (getline(&line
, &len
, f
) != -1) {
968 p
= strchr(line
, ':');
977 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
978 * contains an entry of the form:
982 * In this case we use "cgroup2" as controller name.
985 must_append_string(klist
, "cgroup2");
989 lxc_iterate_parts(tok
, p
, ",") {
990 if (strncmp(tok
, "name=", 5) == 0)
991 must_append_string(nlist
, tok
);
993 must_append_string(klist
, tok
);
1002 static void trim(char *s
)
1007 while ((len
> 1) && (s
[len
- 1] == '\n'))
1011 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
1014 struct hierarchy
**it
;
1016 if (!ops
->hierarchies
) {
1017 TRACE(" No hierarchies found");
1021 TRACE(" Hierarchies:");
1022 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
1026 TRACE(" %d: base_cgroup: %s", i
, (*it
)->container_base_path
? (*it
)->container_base_path
: "(null)");
1027 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
1028 TRACE(" controllers:");
1029 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
1030 TRACE(" %d: %s", j
, *cit
);
1034 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
1040 TRACE("basecginfo is:");
1041 TRACE("%s", basecginfo
);
1043 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
1044 TRACE("kernel subsystem %d: %s", k
, *it
);
1046 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
1047 TRACE("named subsystem %d: %s", k
, *it
);
1050 static int cgroup_rmdir(struct hierarchy
**hierarchies
,
1051 const char *container_cgroup
)
1055 if (!container_cgroup
|| !hierarchies
)
1058 for (i
= 0; hierarchies
[i
]; i
++) {
1060 struct hierarchy
*h
= hierarchies
[i
];
1062 if (!h
->container_full_path
)
1065 ret
= recursive_destroy(h
->container_full_path
);
1067 WARN("Failed to destroy \"%s\"", h
->container_full_path
);
1069 free(h
->container_full_path
);
1070 h
->container_full_path
= NULL
;
1076 struct generic_userns_exec_data
{
1077 struct hierarchy
**hierarchies
;
1078 const char *container_cgroup
;
1079 struct lxc_conf
*conf
;
1080 uid_t origuid
; /* target uid in parent namespace */
1084 static int cgroup_rmdir_wrapper(void *data
)
1087 struct generic_userns_exec_data
*arg
= data
;
1088 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1089 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1091 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1093 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid
,
1094 (int)nsgid
, (int)nsgid
);
1098 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1100 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid
,
1101 (int)nsuid
, (int)nsuid
);
1105 ret
= setgroups(0, NULL
);
1106 if (ret
< 0 && errno
!= EPERM
) {
1107 SYSERROR("Failed to setgroups(0, NULL)");
1111 return cgroup_rmdir(arg
->hierarchies
, arg
->container_cgroup
);
1114 __cgfsng_ops
static void cgfsng_payload_destroy(struct cgroup_ops
*ops
,
1115 struct lxc_handler
*handler
)
1118 struct generic_userns_exec_data wrap
;
1121 wrap
.container_cgroup
= ops
->container_cgroup
;
1122 wrap
.hierarchies
= ops
->hierarchies
;
1123 wrap
.conf
= handler
->conf
;
1125 if (handler
->conf
&& !lxc_list_empty(&handler
->conf
->id_map
))
1126 ret
= userns_exec_1(handler
->conf
, cgroup_rmdir_wrapper
, &wrap
,
1127 "cgroup_rmdir_wrapper");
1129 ret
= cgroup_rmdir(ops
->hierarchies
, ops
->container_cgroup
);
1131 WARN("Failed to destroy cgroups");
1136 __cgfsng_ops
static void cgfsng_monitor_destroy(struct cgroup_ops
*ops
,
1137 struct lxc_handler
*handler
)
1141 struct lxc_conf
*conf
= handler
->conf
;
1142 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1144 if (!ops
->hierarchies
)
1147 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", handler
->monitor_pid
);
1148 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
1151 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1153 struct hierarchy
*h
= ops
->hierarchies
[i
];
1155 if (!h
->monitor_full_path
)
1158 if (conf
&& conf
->cgroup_meta
.dir
)
1159 pivot_path
= must_make_path(h
->mountpoint
,
1160 h
->container_base_path
,
1161 conf
->cgroup_meta
.dir
,
1163 "cgroup.procs", NULL
);
1165 pivot_path
= must_make_path(h
->mountpoint
,
1166 h
->container_base_path
,
1168 "cgroup.procs", NULL
);
1170 ret
= mkdir_p(pivot_path
, 0755);
1171 if (ret
< 0 && errno
!= EEXIST
)
1174 /* Move ourselves into the pivot cgroup to delete our own
1177 ret
= lxc_write_to_file(pivot_path
, pidstr
, len
, false, 0666);
1181 ret
= recursive_destroy(h
->monitor_full_path
);
1183 WARN("Failed to destroy \"%s\"", h
->monitor_full_path
);
1190 static bool cg_unified_create_cgroup(struct hierarchy
*h
, char *cgname
)
1192 size_t i
, parts_len
;
1194 size_t full_len
= 0;
1195 char *add_controllers
= NULL
, *cgroup
= NULL
;
1196 char **parts
= NULL
;
1199 if (h
->version
!= CGROUP2_SUPER_MAGIC
)
1202 if (!h
->controllers
)
1205 /* For now we simply enable all controllers that we have detected by
1206 * creating a string like "+memory +pids +cpu +io".
1207 * TODO: In the near future we might want to support "-<controller>"
1208 * etc. but whether supporting semantics like this make sense will need
1211 for (it
= h
->controllers
; it
&& *it
; it
++) {
1212 full_len
+= strlen(*it
) + 2;
1213 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
1215 if (h
->controllers
[0] == *it
)
1216 add_controllers
[0] = '\0';
1218 (void)strlcat(add_controllers
, "+", full_len
+ 1);
1219 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
1221 if ((it
+ 1) && *(it
+ 1))
1222 (void)strlcat(add_controllers
, " ", full_len
+ 1);
1225 parts
= lxc_string_split(cgname
, '/');
1229 parts_len
= lxc_array_len((void **)parts
);
1233 cgroup
= must_make_path(h
->mountpoint
, h
->container_base_path
, NULL
);
1234 for (i
= 0; i
< parts_len
; i
++) {
1238 cgroup
= must_append_path(cgroup
, parts
[i
], NULL
);
1239 target
= must_make_path(cgroup
, "cgroup.subtree_control", NULL
);
1240 ret
= lxc_write_to_file(target
, add_controllers
, full_len
, false, 0666);
1243 SYSERROR("Could not enable \"%s\" controllers in the "
1244 "unified cgroup \"%s\"", add_controllers
, cgroup
);
1252 lxc_free_array((void **)parts
, free
);
1253 free(add_controllers
);
1258 static bool monitor_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1262 h
->monitor_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1263 if (dir_exists(h
->monitor_full_path
))
1266 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1267 ERROR("Failed to handle legacy cpuset controller");
1271 ret
= mkdir_p(h
->monitor_full_path
, 0755);
1273 ERROR("Failed to create cgroup \"%s\"", h
->monitor_full_path
);
1277 return cg_unified_create_cgroup(h
, cgname
);
1280 static bool container_create_path_for_hierarchy(struct hierarchy
*h
, char *cgname
)
1284 h
->container_full_path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgname
, NULL
);
1285 if (dir_exists(h
->container_full_path
)) {
1286 ERROR("The cgroup \"%s\" already existed", h
->container_full_path
);
1290 if (!cg_legacy_handle_cpuset_hierarchy(h
, cgname
)) {
1291 ERROR("Failed to handle legacy cpuset controller");
1295 ret
= mkdir_p(h
->container_full_path
, 0755);
1297 ERROR("Failed to create cgroup \"%s\"", h
->container_full_path
);
1301 return cg_unified_create_cgroup(h
, cgname
);
1304 static void remove_path_for_hierarchy(struct hierarchy
*h
, char *cgname
, bool monitor
)
1310 full_path
= h
->monitor_full_path
;
1312 full_path
= h
->container_full_path
;
1314 ret
= rmdir(full_path
);
1316 SYSERROR("Failed to rmdir(\"%s\") from failed creation attempt", full_path
);
1321 h
->monitor_full_path
= NULL
;
1323 h
->container_full_path
= NULL
;
1326 __cgfsng_ops
static inline bool cgfsng_monitor_create(struct cgroup_ops
*ops
,
1327 struct lxc_handler
*handler
)
1329 char *monitor_cgroup
, *offset
, *tmp
;
1333 struct lxc_conf
*conf
= handler
->conf
;
1338 if (conf
->cgroup_meta
.dir
)
1339 tmp
= lxc_string_join("/",
1340 (const char *[]){conf
->cgroup_meta
.dir
,
1341 ops
->monitor_pattern
,
1342 handler
->name
, NULL
},
1345 tmp
= must_make_path(ops
->monitor_pattern
, handler
->name
, NULL
);
1349 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1350 monitor_cgroup
= must_alloc(len
);
1351 (void)strlcpy(monitor_cgroup
, tmp
, len
);
1353 offset
= monitor_cgroup
+ len
- 5;
1357 int ret
= snprintf(offset
, 5, "-%d", idx
);
1358 if (ret
< 0 || (size_t)ret
>= 5)
1362 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1363 if (!monitor_create_path_for_hierarchy(ops
->hierarchies
[i
], monitor_cgroup
)) {
1364 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->monitor_full_path
);
1365 free(ops
->hierarchies
[i
]->container_full_path
);
1366 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1368 for (int j
= 0; j
< i
; j
++)
1369 remove_path_for_hierarchy(ops
->hierarchies
[j
], monitor_cgroup
, true);
1375 } while (idx
> 0 && idx
< 1000);
1381 free(monitor_cgroup
);
1386 /* Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1387 * next cgroup_pattern-1, -2, ..., -999.
1389 __cgfsng_ops
static inline bool cgfsng_payload_create(struct cgroup_ops
*ops
,
1390 struct lxc_handler
*handler
)
1394 char *container_cgroup
, *offset
, *tmp
;
1396 struct lxc_conf
*conf
= handler
->conf
;
1398 if (ops
->container_cgroup
) {
1399 WARN("cgfsng_create called a second time: %s", ops
->container_cgroup
);
1406 if (conf
->cgroup_meta
.dir
)
1407 tmp
= lxc_string_join("/", (const char *[]){conf
->cgroup_meta
.dir
, handler
->name
, NULL
}, false);
1409 tmp
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1411 ERROR("Failed expanding cgroup name pattern");
1415 len
= strlen(tmp
) + 5; /* leave room for -NNN\0 */
1416 container_cgroup
= must_alloc(len
);
1417 (void)strlcpy(container_cgroup
, tmp
, len
);
1419 offset
= container_cgroup
+ len
- 5;
1423 ERROR("Too many conflicting cgroup names");
1430 ret
= snprintf(offset
, 5, "-%d", idx
);
1431 if (ret
< 0 || (size_t)ret
>= 5) {
1432 FILE *f
= fopen("/dev/null", "w");
1434 fprintf(f
, "Workaround for GCC7 bug: "
1435 "https://gcc.gnu.org/bugzilla/"
1436 "show_bug.cgi?id=78969");
1442 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1443 if (!container_create_path_for_hierarchy(ops
->hierarchies
[i
], container_cgroup
)) {
1444 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->container_full_path
);
1445 free(ops
->hierarchies
[i
]->container_full_path
);
1446 ops
->hierarchies
[i
]->container_full_path
= NULL
;
1447 for (int j
= 0; j
< i
; j
++)
1448 remove_path_for_hierarchy(ops
->hierarchies
[j
], container_cgroup
, false);
1454 ops
->container_cgroup
= container_cgroup
;
1459 free(container_cgroup
);
1464 __cgfsng_ops
static bool __do_cgroup_enter(struct cgroup_ops
*ops
, pid_t pid
,
1470 len
= snprintf(pidstr
, 25, "%d", pid
);
1471 if (len
< 0 || len
>= 25)
1474 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1479 path
= must_make_path(ops
->hierarchies
[i
]->monitor_full_path
,
1480 "cgroup.procs", NULL
);
1482 path
= must_make_path(ops
->hierarchies
[i
]->container_full_path
,
1483 "cgroup.procs", NULL
);
1484 ret
= lxc_write_to_file(path
, pidstr
, len
, false, 0666);
1486 SYSERROR("Failed to enter cgroup \"%s\"", path
);
1496 __cgfsng_ops
static bool cgfsng_monitor_enter(struct cgroup_ops
*ops
, pid_t pid
)
1498 return __do_cgroup_enter(ops
, pid
, true);
1501 static bool cgfsng_payload_enter(struct cgroup_ops
*ops
, pid_t pid
)
1503 return __do_cgroup_enter(ops
, pid
, false);
1506 static int chowmod(char *path
, uid_t chown_uid
, gid_t chown_gid
,
1511 ret
= chown(path
, chown_uid
, chown_gid
);
1513 SYSWARN("Failed to chown(%s, %d, %d)", path
, (int)chown_uid
, (int)chown_gid
);
1517 ret
= chmod(path
, chmod_mode
);
1519 SYSWARN("Failed to chmod(%s, %d)", path
, (int)chmod_mode
);
1526 /* chgrp the container cgroups to container group. We leave
1527 * the container owner as cgroup owner. So we must make the
1528 * directories 775 so that the container can create sub-cgroups.
1530 * Also chown the tasks and cgroup.procs files. Those may not
1531 * exist depending on kernel version.
1533 static int chown_cgroup_wrapper(void *data
)
1537 struct generic_userns_exec_data
*arg
= data
;
1538 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1539 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1541 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1543 SYSERROR("Failed to setresgid(%d, %d, %d)",
1544 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1548 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1550 SYSERROR("Failed to setresuid(%d, %d, %d)",
1551 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1555 ret
= setgroups(0, NULL
);
1556 if (ret
< 0 && errno
!= EPERM
) {
1557 SYSERROR("Failed to setgroups(0, NULL)");
1561 destuid
= get_ns_uid(arg
->origuid
);
1562 if (destuid
== LXC_INVALID_UID
)
1565 for (i
= 0; arg
->hierarchies
[i
]; i
++) {
1567 char *path
= arg
->hierarchies
[i
]->container_full_path
;
1569 ret
= chowmod(path
, destuid
, nsgid
, 0775);
1573 /* Failures to chown() these are inconvenient but not
1574 * detrimental We leave these owned by the container launcher,
1575 * so that container root can write to the files to attach. We
1576 * chmod() them 664 so that container systemd can write to the
1577 * files (which systemd in wily insists on doing).
1580 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
) {
1581 fullpath
= must_make_path(path
, "tasks", NULL
);
1582 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1586 fullpath
= must_make_path(path
, "cgroup.procs", NULL
);
1587 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1590 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1593 fullpath
= must_make_path(path
, "cgroup.subtree_control", NULL
);
1594 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1597 fullpath
= must_make_path(path
, "cgroup.threads", NULL
);
1598 (void)chowmod(fullpath
, destuid
, nsgid
, 0664);
1605 __cgfsng_ops
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1606 struct lxc_conf
*conf
)
1608 struct generic_userns_exec_data wrap
;
1610 if (lxc_list_empty(&conf
->id_map
))
1613 wrap
.origuid
= geteuid();
1615 wrap
.hierarchies
= ops
->hierarchies
;
1618 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
,
1619 "chown_cgroup_wrapper") < 0) {
1620 ERROR("Error requesting cgroup chown in new user namespace");
1627 /* cgroup-full:* is done, no need to create subdirs */
1628 static bool cg_mount_needs_subdirs(int type
)
1630 if (type
>= LXC_AUTO_CGROUP_FULL_RO
)
1636 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1637 * remount controller ro if needed and bindmount the cgroupfs onto
1638 * controll/the/cg/path.
1640 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1641 char *controllerpath
, char *cgpath
,
1642 const char *container_cgroup
)
1644 int ret
, remount_flags
;
1646 int flags
= MS_BIND
;
1648 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1649 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1651 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
1652 controllerpath
, controllerpath
);
1656 remount_flags
= add_required_remount_flags(controllerpath
,
1658 flags
| MS_REMOUNT
);
1659 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1660 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1663 SYSERROR("Failed to remount \"%s\" ro", controllerpath
);
1667 INFO("Remounted %s read-only", controllerpath
);
1670 sourcepath
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1671 container_cgroup
, NULL
);
1672 if (type
== LXC_AUTO_CGROUP_RO
)
1675 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1677 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1681 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1683 if (flags
& MS_RDONLY
) {
1684 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1685 flags
| MS_REMOUNT
);
1686 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1688 SYSERROR("Failed to remount \"%s\" ro", cgpath
);
1692 INFO("Remounted %s read-only", cgpath
);
1696 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1700 /* __cg_mount_direct
1702 * Mount cgroup hierarchies directly without using bind-mounts. The main
1703 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1704 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1706 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1707 const char *controllerpath
)
1710 char *controllers
= NULL
;
1711 char *fstype
= "cgroup2";
1712 unsigned long flags
= 0;
1717 flags
|= MS_RELATIME
;
1719 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1722 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1723 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1729 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1732 SYSERROR("Failed to mount \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1736 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1740 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1741 const char *controllerpath
)
1743 return __cg_mount_direct(type
, h
, controllerpath
);
1746 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1747 const char *controllerpath
)
1749 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1752 return __cg_mount_direct(type
, h
, controllerpath
);
1755 __cgfsng_ops
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1756 struct lxc_handler
*handler
,
1757 const char *root
, int type
)
1760 char *tmpfspath
= NULL
;
1761 bool has_cgns
= false, retval
= false, wants_force_mount
= false;
1763 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1766 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1767 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1768 wants_force_mount
= true;
1771 if (!wants_force_mount
){
1772 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1773 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1775 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1778 has_cgns
= cgns_supported();
1779 if (has_cgns
&& !wants_force_mount
)
1782 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1783 type
= LXC_AUTO_CGROUP_MIXED
;
1784 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1785 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1788 tmpfspath
= must_make_path(root
, "/sys/fs/cgroup", NULL
);
1789 ret
= safe_mount(NULL
, tmpfspath
, "tmpfs",
1790 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1791 "size=10240k,mode=755", root
);
1795 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1796 char *controllerpath
, *path2
;
1797 struct hierarchy
*h
= ops
->hierarchies
[i
];
1798 char *controller
= strrchr(h
->mountpoint
, '/');
1804 controllerpath
= must_make_path(tmpfspath
, controller
, NULL
);
1805 if (dir_exists(controllerpath
)) {
1806 free(controllerpath
);
1810 ret
= mkdir(controllerpath
, 0755);
1812 SYSERROR("Error creating cgroup path: %s", controllerpath
);
1813 free(controllerpath
);
1817 if (has_cgns
&& wants_force_mount
) {
1818 /* If cgroup namespaces are supported but the container
1819 * will not have CAP_SYS_ADMIN after it has started we
1820 * need to mount the cgroups manually.
1822 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1823 free(controllerpath
);
1830 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1832 free(controllerpath
);
1836 if (!cg_mount_needs_subdirs(type
)) {
1837 free(controllerpath
);
1841 path2
= must_make_path(controllerpath
, h
->container_base_path
,
1842 ops
->container_cgroup
, NULL
);
1843 ret
= mkdir_p(path2
, 0755);
1845 free(controllerpath
);
1850 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1851 path2
, ops
->container_cgroup
);
1852 free(controllerpath
);
1864 static int recursive_count_nrtasks(char *dirname
)
1866 struct dirent
*direntp
;
1871 dir
= opendir(dirname
);
1875 while ((direntp
= readdir(dir
))) {
1878 if (!strcmp(direntp
->d_name
, ".") ||
1879 !strcmp(direntp
->d_name
, ".."))
1882 path
= must_make_path(dirname
, direntp
->d_name
, NULL
);
1884 if (lstat(path
, &mystat
))
1887 if (!S_ISDIR(mystat
.st_mode
))
1890 count
+= recursive_count_nrtasks(path
);
1895 path
= must_make_path(dirname
, "cgroup.procs", NULL
);
1896 ret
= lxc_count_file_lines(path
);
1901 (void)closedir(dir
);
1906 __cgfsng_ops
static int cgfsng_nrtasks(struct cgroup_ops
*ops
)
1911 if (!ops
->container_cgroup
|| !ops
->hierarchies
)
1914 path
= must_make_path(ops
->hierarchies
[0]->container_full_path
, NULL
);
1915 count
= recursive_count_nrtasks(path
);
1920 /* Only root needs to escape to the cgroup of its init. */
1921 __cgfsng_ops
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1922 struct lxc_conf
*conf
)
1926 if (conf
->cgroup_meta
.relative
|| geteuid())
1929 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1933 fullpath
= must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1934 ops
->hierarchies
[i
]->container_base_path
,
1935 "cgroup.procs", NULL
);
1936 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1938 SYSERROR("Failed to escape to cgroup \"%s\"", fullpath
);
1948 __cgfsng_ops
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1952 for (i
= 0; ops
->hierarchies
[i
]; i
++)
1958 __cgfsng_ops
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
, char ***out
)
1962 /* sanity check n */
1963 for (i
= 0; i
< n
; i
++)
1964 if (!ops
->hierarchies
[i
])
1967 *out
= ops
->hierarchies
[i
]->controllers
;
1972 #define THAWED "THAWED"
1973 #define THAWED_LEN (strlen(THAWED))
1975 /* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
1978 __cgfsng_ops
static bool cgfsng_unfreeze(struct cgroup_ops
*ops
)
1982 struct hierarchy
*h
;
1984 h
= get_hierarchy(ops
, "freezer");
1988 fullpath
= must_make_path(h
->container_full_path
, "freezer.state", NULL
);
1989 ret
= lxc_write_to_file(fullpath
, THAWED
, THAWED_LEN
, false, 0666);
1997 __cgfsng_ops
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
1998 const char *controller
)
2000 struct hierarchy
*h
;
2002 h
= get_hierarchy(ops
, controller
);
2004 WARN("Failed to find hierarchy for controller \"%s\"",
2005 controller
? controller
: "(null)");
2009 return h
->container_full_path
? h
->container_full_path
+ strlen(h
->mountpoint
) : NULL
;
2012 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2013 * which must be freed by the caller.
2015 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
2017 const char *filename
)
2019 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
2022 /* Technically, we're always at a delegation boundary here (This is especially
2023 * true when cgroup namespaces are available.). The reasoning is that in order
2024 * for us to have been able to start a container in the first place the root
2025 * cgroup must have been a leaf node. Now, either the container's init system
2026 * has populated the cgroup and kept it as a leaf node or it has created
2027 * subtrees. In the former case we will simply attach to the leaf node we
2028 * created when we started the container in the latter case we create our own
2029 * cgroup for the attaching process.
2031 static int __cg_unified_attach(const struct hierarchy
*h
, const char *name
,
2032 const char *lxcpath
, const char *pidstr
,
2033 size_t pidstr_len
, const char *controller
)
2037 int fret
= -1, idx
= 0;
2038 char *base_path
= NULL
, *container_cgroup
= NULL
, *full_path
= NULL
;
2040 container_cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2042 if (!container_cgroup
)
2045 base_path
= must_make_path(h
->mountpoint
, container_cgroup
, NULL
);
2046 full_path
= must_make_path(base_path
, "cgroup.procs", NULL
);
2047 /* cgroup is populated */
2048 ret
= lxc_write_to_file(full_path
, pidstr
, pidstr_len
, false, 0666);
2049 if (ret
< 0 && errno
!= EBUSY
)
2057 len
= strlen(base_path
) + STRLITERALLEN("/lxc-1000") +
2058 STRLITERALLEN("/cgroup-procs");
2059 full_path
= must_alloc(len
+ 1);
2062 ret
= snprintf(full_path
, len
+ 1, "%s/lxc-%d",
2065 ret
= snprintf(full_path
, len
+ 1, "%s/lxc", base_path
);
2066 if (ret
< 0 || (size_t)ret
>= len
+ 1)
2069 ret
= mkdir_p(full_path
, 0755);
2070 if (ret
< 0 && errno
!= EEXIST
)
2073 (void)strlcat(full_path
, "/cgroup.procs", len
+ 1);
2074 ret
= lxc_write_to_file(full_path
, pidstr
, len
, false, 0666);
2078 /* this is a non-leaf node */
2082 } while (++idx
> 0 && idx
< 1000);
2090 free(container_cgroup
);
2096 __cgfsng_ops
static bool cgfsng_attach(struct cgroup_ops
*ops
, const char *name
,
2097 const char *lxcpath
, pid_t pid
)
2102 len
= snprintf(pidstr
, 25, "%d", pid
);
2103 if (len
< 0 || len
>= 25)
2106 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
2108 char *fullpath
= NULL
;
2109 struct hierarchy
*h
= ops
->hierarchies
[i
];
2111 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2112 ret
= __cg_unified_attach(h
, name
, lxcpath
, pidstr
, len
,
2120 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2125 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2127 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2129 SYSERROR("Failed to attach %d to %s", (int)pid
, fullpath
);
2139 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2140 * don't have a cgroup_data set up, so we ask the running container through the
2141 * commands API for the cgroup path.
2143 __cgfsng_ops
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
2144 char *value
, size_t len
, const char *name
,
2145 const char *lxcpath
)
2148 size_t controller_len
;
2149 char *controller
, *p
, *path
;
2150 struct hierarchy
*h
;
2152 controller_len
= strlen(filename
);
2153 controller
= alloca(controller_len
+ 1);
2154 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2156 p
= strchr(controller
, '.');
2160 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2165 h
= get_hierarchy(ops
, controller
);
2169 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2170 ret
= lxc_read_from_file(fullpath
, value
, len
);
2178 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2179 * don't have a cgroup_data set up, so we ask the running container through the
2180 * commands API for the cgroup path.
2182 __cgfsng_ops
static int cgfsng_set(struct cgroup_ops
*ops
,
2183 const char *filename
, const char *value
,
2184 const char *name
, const char *lxcpath
)
2187 size_t controller_len
;
2188 char *controller
, *p
, *path
;
2189 struct hierarchy
*h
;
2191 controller_len
= strlen(filename
);
2192 controller
= alloca(controller_len
+ 1);
2193 (void)strlcpy(controller
, filename
, controller_len
+ 1);
2195 p
= strchr(controller
, '.');
2199 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2204 h
= get_hierarchy(ops
, controller
);
2208 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2209 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2217 /* take devices cgroup line
2219 * and convert it to a valid
2220 * type major:minor mode
2221 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2224 static int convert_devpath(const char *invalue
, char *dest
)
2227 char *p
, *path
, type
;
2228 unsigned long minor
, major
;
2233 path
= must_copy_string(invalue
);
2235 /* Read path followed by mode. Ignore any trailing text.
2236 * A ' # comment' would be legal. Technically other text is not
2237 * legal, we could check for that if we cared to.
2239 for (n_parts
= 1, p
= path
; *p
&& n_parts
< 3; p
++) {
2261 ret
= stat(path
, &sb
);
2265 mode_t m
= sb
.st_mode
& S_IFMT
;
2274 ERROR("Unsupported device type %i for \"%s\"", m
, path
);
2279 major
= MAJOR(sb
.st_rdev
);
2280 minor
= MINOR(sb
.st_rdev
);
2281 ret
= snprintf(dest
, 50, "%c %lu:%lu %s", type
, major
, minor
, mode
);
2282 if (ret
< 0 || ret
>= 50) {
2283 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2284 "chars)", type
, major
, minor
, mode
);
2285 ret
= -ENAMETOOLONG
;
2295 /* Called from setup_limits - here we have the container's cgroup_data because
2296 * we created the cgroups.
2298 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2303 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2304 char converted_value
[50];
2305 struct hierarchy
*h
;
2307 char *controller
= NULL
;
2309 len
= strlen(filename
);
2310 controller
= alloca(len
+ 1);
2311 (void)strlcpy(controller
, filename
, len
+ 1);
2313 p
= strchr(controller
, '.');
2317 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2318 ret
= convert_devpath(value
, converted_value
);
2321 value
= converted_value
;
2324 h
= get_hierarchy(ops
, controller
);
2326 ERROR("Failed to setup limits for the \"%s\" controller. "
2327 "The controller seems to be unused by \"cgfsng\" cgroup "
2328 "driver or not enabled on the cgroup hierarchy",
2334 fullpath
= must_make_path(h
->container_full_path
, filename
, NULL
);
2335 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2340 static bool __cg_legacy_setup_limits(struct cgroup_ops
*ops
,
2341 struct lxc_list
*cgroup_settings
,
2344 struct lxc_list
*iterator
, *next
, *sorted_cgroup_settings
;
2345 struct lxc_cgroup
*cg
;
2348 if (lxc_list_empty(cgroup_settings
))
2351 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2352 if (!sorted_cgroup_settings
)
2355 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2356 cg
= iterator
->elem
;
2358 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2359 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
)) {
2360 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2361 WARN("Failed to set \"%s\" to \"%s\"",
2362 cg
->subsystem
, cg
->value
);
2365 WARN("Failed to set \"%s\" to \"%s\"",
2366 cg
->subsystem
, cg
->value
);
2369 DEBUG("Set controller \"%s\" set to \"%s\"",
2370 cg
->subsystem
, cg
->value
);
2375 INFO("Limits for the legacy cgroup hierarchies have been setup");
2377 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2378 lxc_list_del(iterator
);
2381 free(sorted_cgroup_settings
);
2385 static bool __cg_unified_setup_limits(struct cgroup_ops
*ops
,
2386 struct lxc_list
*cgroup_settings
)
2388 struct lxc_list
*iterator
;
2389 struct hierarchy
*h
= ops
->unified
;
2391 if (lxc_list_empty(cgroup_settings
))
2397 lxc_list_for_each(iterator
, cgroup_settings
) {
2400 struct lxc_cgroup
*cg
= iterator
->elem
;
2402 fullpath
= must_make_path(h
->container_full_path
, cg
->subsystem
, NULL
);
2403 ret
= lxc_write_to_file(fullpath
, cg
->value
, strlen(cg
->value
), false, 0666);
2406 SYSERROR("Failed to set \"%s\" to \"%s\"",
2407 cg
->subsystem
, cg
->value
);
2410 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2413 INFO("Limits for the unified cgroup hierarchy have been setup");
2417 __cgfsng_ops
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2418 struct lxc_conf
*conf
,
2423 bret
= __cg_legacy_setup_limits(ops
, &conf
->cgroup
, do_devices
);
2427 return __cg_unified_setup_limits(ops
, &conf
->cgroup2
);
2430 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
2433 char **cur_ctrl
, **cur_use
;
2435 if (!ops
->cgroup_use
)
2438 for (cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
2441 for (cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
2442 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
2458 /* At startup, parse_hierarchies finds all the info we need about cgroup
2459 * mountpoints and current cgroups, and stores it in @d.
2461 static bool cg_hybrid_init(struct cgroup_ops
*ops
, bool relative
)
2468 char **klist
= NULL
, **nlist
= NULL
;
2470 /* Root spawned containers escape the current cgroup, so use init's
2471 * cgroups as our base in that case.
2473 if (!relative
&& (geteuid() == 0))
2474 basecginfo
= read_file("/proc/1/cgroup");
2476 basecginfo
= read_file("/proc/self/cgroup");
2480 ret
= get_existing_subsystems(&klist
, &nlist
);
2482 ERROR("Failed to retrieve available legacy cgroup controllers");
2487 f
= fopen("/proc/self/mountinfo", "r");
2489 ERROR("Failed to open \"/proc/self/mountinfo\"");
2494 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
2496 while (getline(&line
, &len
, f
) != -1) {
2499 struct hierarchy
*new;
2500 char *base_cgroup
= NULL
, *mountpoint
= NULL
;
2501 char **controller_list
= NULL
;
2503 type
= get_cgroup_version(line
);
2507 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
2510 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
2511 if (type
== CGROUP2_SUPER_MAGIC
)
2512 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2513 else if (type
== CGROUP_SUPER_MAGIC
)
2514 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
2515 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
2516 if (type
== CGROUP_SUPER_MAGIC
)
2517 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2518 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
2519 if (type
== CGROUP2_SUPER_MAGIC
)
2520 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
2523 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
2524 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
2527 if (type
== CGROUP_SUPER_MAGIC
)
2528 if (controller_list_is_dup(ops
->hierarchies
, controller_list
))
2531 mountpoint
= cg_hybrid_get_mountpoint(line
);
2533 ERROR("Failed parsing mountpoint from \"%s\"", line
);
2537 if (type
== CGROUP_SUPER_MAGIC
)
2538 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
2540 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
2542 ERROR("Failed to find current cgroup");
2547 prune_init_scope(base_cgroup
);
2548 if (type
== CGROUP2_SUPER_MAGIC
)
2549 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
2551 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
2555 if (type
== CGROUP2_SUPER_MAGIC
) {
2556 char *cgv2_ctrl_path
;
2558 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
2559 "cgroup.controllers",
2562 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
2563 free(cgv2_ctrl_path
);
2564 if (!controller_list
) {
2565 controller_list
= cg_unified_make_empty_controller();
2566 TRACE("No controllers are enabled for "
2567 "delegation in the unified hierarchy");
2571 /* Exclude all controllers that cgroup use does not want. */
2572 if (!cgroup_use_wants_controllers(ops
, controller_list
))
2575 new = add_hierarchy(&ops
->hierarchies
, controller_list
, mountpoint
, base_cgroup
, type
);
2576 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
)
2582 free_string_list(controller_list
);
2587 free_string_list(klist
);
2588 free_string_list(nlist
);
2595 TRACE("Writable cgroup hierarchies:");
2596 lxc_cgfsng_print_hierarchies(ops
);
2598 /* verify that all controllers in cgroup.use and all crucial
2599 * controllers are accounted for
2601 if (!all_controllers_found(ops
))
2607 static int cg_is_pure_unified(void)
2613 ret
= statfs("/sys/fs/cgroup", &fs
);
2617 if (is_fs_type(&fs
, CGROUP2_SUPER_MAGIC
))
2618 return CGROUP2_SUPER_MAGIC
;
2623 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
2624 static char *cg_unified_get_current_cgroup(bool relative
)
2626 char *basecginfo
, *base_cgroup
;
2629 if (!relative
&& (geteuid() == 0))
2630 basecginfo
= read_file("/proc/1/cgroup");
2632 basecginfo
= read_file("/proc/self/cgroup");
2636 base_cgroup
= strstr(basecginfo
, "0::/");
2638 goto cleanup_on_err
;
2640 base_cgroup
= base_cgroup
+ 3;
2641 copy
= copy_to_eol(base_cgroup
);
2643 goto cleanup_on_err
;
2653 static int cg_unified_init(struct cgroup_ops
*ops
, bool relative
)
2656 char *mountpoint
, *subtree_path
;
2658 char *base_cgroup
= NULL
;
2660 ret
= cg_is_pure_unified();
2661 if (ret
== -ENOMEDIUM
)
2664 if (ret
!= CGROUP2_SUPER_MAGIC
)
2667 base_cgroup
= cg_unified_get_current_cgroup(relative
);
2670 prune_init_scope(base_cgroup
);
2672 /* We assume that we have already been given controllers to delegate
2673 * further down the hierarchy. If not it is up to the user to delegate
2676 mountpoint
= must_copy_string("/sys/fs/cgroup");
2677 subtree_path
= must_make_path(mountpoint
, base_cgroup
,
2678 "cgroup.subtree_control", NULL
);
2679 delegatable
= cg_unified_get_controllers(subtree_path
);
2682 delegatable
= cg_unified_make_empty_controller();
2683 if (!delegatable
[0])
2684 TRACE("No controllers are enabled for delegation");
2686 /* TODO: If the user requested specific controllers via lxc.cgroup.use
2687 * we should verify here. The reason I'm not doing it right is that I'm
2688 * not convinced that lxc.cgroup.use will be the future since it is a
2689 * global property. I much rather have an option that lets you request
2690 * controllers per container.
2693 add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
2695 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
2696 return CGROUP2_SUPER_MAGIC
;
2699 static bool cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
2703 bool relative
= conf
->cgroup_meta
.relative
;
2705 tmp
= lxc_global_config_value("lxc.cgroup.use");
2707 char *chop
, *cur
, *pin
;
2709 pin
= must_copy_string(tmp
);
2712 lxc_iterate_parts(cur
, chop
, ",") {
2713 must_append_string(&ops
->cgroup_use
, cur
);
2719 ret
= cg_unified_init(ops
, relative
);
2723 if (ret
== CGROUP2_SUPER_MAGIC
)
2726 return cg_hybrid_init(ops
, relative
);
2729 __cgfsng_ops
static bool cgfsng_data_init(struct cgroup_ops
*ops
)
2731 const char *cgroup_pattern
;
2733 /* copy system-wide cgroup information */
2734 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
2735 if (!cgroup_pattern
) {
2736 /* lxc.cgroup.pattern is only NULL on error. */
2737 ERROR("Failed to retrieve cgroup pattern");
2740 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
2741 ops
->monitor_pattern
= MONITOR_CGROUP
;
2746 struct cgroup_ops
*cgfsng_ops_init(struct lxc_conf
*conf
)
2748 struct cgroup_ops
*cgfsng_ops
;
2750 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
2754 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
2755 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
2757 if (!cg_init(cgfsng_ops
, conf
)) {
2762 cgfsng_ops
->data_init
= cgfsng_data_init
;
2763 cgfsng_ops
->payload_destroy
= cgfsng_payload_destroy
;
2764 cgfsng_ops
->monitor_destroy
= cgfsng_monitor_destroy
;
2765 cgfsng_ops
->monitor_create
= cgfsng_monitor_create
;
2766 cgfsng_ops
->monitor_enter
= cgfsng_monitor_enter
;
2767 cgfsng_ops
->payload_create
= cgfsng_payload_create
;
2768 cgfsng_ops
->payload_enter
= cgfsng_payload_enter
;
2769 cgfsng_ops
->escape
= cgfsng_escape
;
2770 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
2771 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
2772 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
2773 cgfsng_ops
->get
= cgfsng_get
;
2774 cgfsng_ops
->set
= cgfsng_set
;
2775 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
2776 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
2777 cgfsng_ops
->driver
= "cgfsng";
2778 cgfsng_ops
->version
= "1.0.0";
2779 cgfsng_ops
->attach
= cgfsng_attach
;
2780 cgfsng_ops
->chown
= cgfsng_chown
;
2781 cgfsng_ops
->mount
= cgfsng_mount
;
2782 cgfsng_ops
->nrtasks
= cgfsng_nrtasks
;