]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/cgfs.c
Merge pull request #751 from jirutka/alpine-tmpl
[mirror_lxc.git] / src / lxc / cgfs.c
CommitLineData
576f946d 1/*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
9afe19d6 7 * Daniel Lezcano <daniel.lezcano at free.fr>
576f946d 8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
250b1eec 21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
576f946d 22 */
d06245b8
NC
23#include "config.h"
24
576f946d 25#include <stdio.h>
576f946d 26#include <stdlib.h>
27#include <errno.h>
576f946d 28#include <unistd.h>
29#include <string.h>
341a9bd8 30#include <dirent.h>
576f946d 31#include <fcntl.h>
8b276860 32#include <grp.h>
b98f7d6e 33#include <ctype.h>
576f946d 34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/param.h>
37#include <sys/inotify.h>
aae1f3c4 38#include <sys/mount.h>
576f946d 39#include <netinet/in.h>
40#include <net/if.h>
41
e2bcd7db 42#include "error.h"
ae5c8b8e 43#include "commands.h"
b98f7d6e
SH
44#include "list.h"
45#include "conf.h"
33ad9f1a 46#include "utils.h"
4ec31c52 47#include "bdev/bdev.h"
f2363e38
ÇO
48#include "log.h"
49#include "cgroup.h"
50#include "start.h"
484ed030 51#include "state.h"
36eb9bde 52
edaf8b1b
SG
53#if IS_BIONIC
54#include <../include/lxcmntent.h>
55#else
56#include <mntent.h>
57#endif
58
4fb3cba5
DE
59struct cgroup_hierarchy;
60struct cgroup_meta_data;
61struct cgroup_mount_point;
62
63/*
64 * cgroup_meta_data: the metadata about the cgroup infrastructure on this
65 * host
66 */
67struct cgroup_meta_data {
68 ptrdiff_t ref; /* simple refcount */
69 struct cgroup_hierarchy **hierarchies;
70 struct cgroup_mount_point **mount_points;
71 int maximum_hierarchy;
72};
73
74/*
75 * cgroup_hierarchy: describes a single cgroup hierarchy
76 * (may have multiple mount points)
77 */
78struct cgroup_hierarchy {
79 int index;
80 bool used; /* false if the hierarchy should be ignored by lxc */
81 char **subsystems;
82 struct cgroup_mount_point *rw_absolute_mount_point;
83 struct cgroup_mount_point *ro_absolute_mount_point;
84 struct cgroup_mount_point **all_mount_points;
85 size_t all_mount_point_capacity;
86};
87
88/*
89 * cgroup_mount_point: a mount point to where a hierarchy
90 * is mounted to
91 */
92struct cgroup_mount_point {
93 struct cgroup_hierarchy *hierarchy;
94 char *mount_point;
95 char *mount_prefix;
96 bool read_only;
97 bool need_cpuset_init;
98};
99
100/*
101 * cgroup_process_info: describes the membership of a
102 * process to the different cgroup
103 * hierarchies
104 *
105 * Note this is the per-process info tracked by the cgfs_ops.
106 * This is not used with cgmanager.
107 */
108struct cgroup_process_info {
109 struct cgroup_process_info *next;
110 struct cgroup_meta_data *meta_ref;
111 struct cgroup_hierarchy *hierarchy;
112 char *cgroup_path;
113 char *cgroup_path_sub;
114 char **created_paths;
115 size_t created_paths_capacity;
116 size_t created_paths_count;
117 struct cgroup_mount_point *designated_mount_point;
118};
119
120struct cgfs_data {
121 char *name;
122 const char *cgroup_pattern;
123 struct cgroup_meta_data *meta;
124 struct cgroup_process_info *info;
125};
126
127lxc_log_define(lxc_cgfs, lxc);
576f946d 128
33ad9f1a
CS
129static struct cgroup_process_info *lxc_cgroup_process_info_getx(const char *proc_pid_cgroup_str, struct cgroup_meta_data *meta);
130static char **subsystems_from_mount_options(const char *mount_options, char **kernel_list);
131static void lxc_cgroup_mount_point_free(struct cgroup_mount_point *mp);
132static void lxc_cgroup_hierarchy_free(struct cgroup_hierarchy *h);
133static bool is_valid_cgroup(const char *name);
33ad9f1a 134static int create_cgroup(struct cgroup_mount_point *mp, const char *path);
603c64c2 135static int remove_cgroup(struct cgroup_mount_point *mp, const char *path, bool recurse);
33ad9f1a
CS
136static char *cgroup_to_absolute_path(struct cgroup_mount_point *mp, const char *path, const char *suffix);
137static struct cgroup_process_info *find_info_for_subsystem(struct cgroup_process_info *info, const char *subsystem);
138static int do_cgroup_get(const char *cgroup_path, const char *sub_filename, char *value, size_t len);
139static int do_cgroup_set(const char *cgroup_path, const char *sub_filename, const char *value);
4fb3cba5
DE
140static bool cgroup_devices_has_allow_or_deny(struct cgfs_data *d, char *v, bool for_allow);
141static int do_setup_cgroup_limits(struct cgfs_data *d, struct lxc_list *cgroup_settings, bool do_devices);
33ad9f1a
CS
142static int cgroup_recursive_task_count(const char *cgroup_path);
143static int count_lines(const char *fn);
1ea59ad2 144static int handle_cgroup_settings(struct cgroup_mount_point *mp, char *cgroup_path);
d703c2b1 145static bool init_cpuset_if_needed(struct cgroup_mount_point *mp, const char *path);
33ad9f1a 146
4fb3cba5
DE
147static struct cgroup_meta_data *lxc_cgroup_load_meta2(const char **subsystem_whitelist);
148static struct cgroup_meta_data *lxc_cgroup_get_meta(struct cgroup_meta_data *meta_data);
149static struct cgroup_meta_data *lxc_cgroup_put_meta(struct cgroup_meta_data *meta_data);
150
151/* free process membership information */
152static void lxc_cgroup_process_info_free(struct cgroup_process_info *info);
153static void lxc_cgroup_process_info_free_and_remove(struct cgroup_process_info *info);
154
d4ef7c50 155static struct cgroup_ops cgfs_ops;
d4ef7c50 156
603c64c2
SH
157static int cgroup_rmdir(char *dirname)
158{
159 struct dirent dirent, *direntp;
160 int saved_errno = 0;
161 DIR *dir;
162 int ret, failed=0;
163 char pathname[MAXPATHLEN];
164
165 dir = opendir(dirname);
166 if (!dir) {
167 ERROR("%s: failed to open %s", __func__, dirname);
168 return -1;
169 }
170
171 while (!readdir_r(dir, &dirent, &direntp)) {
172 struct stat mystat;
173 int rc;
174
175 if (!direntp)
176 break;
177
178 if (!strcmp(direntp->d_name, ".") ||
179 !strcmp(direntp->d_name, ".."))
180 continue;
181
182 rc = snprintf(pathname, MAXPATHLEN, "%s/%s", dirname, direntp->d_name);
183 if (rc < 0 || rc >= MAXPATHLEN) {
184 ERROR("pathname too long");
185 failed=1;
186 if (!saved_errno)
187 saved_errno = -ENOMEM;
188 continue;
189 }
190 ret = lstat(pathname, &mystat);
191 if (ret) {
192 SYSERROR("%s: failed to stat %s", __func__, pathname);
193 failed=1;
194 if (!saved_errno)
195 saved_errno = errno;
196 continue;
197 }
198 if (S_ISDIR(mystat.st_mode)) {
199 if (cgroup_rmdir(pathname) < 0) {
200 if (!saved_errno)
201 saved_errno = errno;
202 failed=1;
203 }
204 }
205 }
206
207 if (rmdir(dirname) < 0) {
208 SYSERROR("%s: failed to delete %s", __func__, dirname);
209 if (!saved_errno)
210 saved_errno = errno;
211 failed=1;
212 }
213
214 ret = closedir(dir);
215 if (ret) {
216 SYSERROR("%s: failed to close directory %s", __func__, dirname);
217 if (!saved_errno)
218 saved_errno = errno;
219 failed=1;
220 }
221
222 errno = saved_errno;
223 return failed ? -1 : 0;
224}
225
4fb3cba5 226static struct cgroup_meta_data *lxc_cgroup_load_meta()
33ad9f1a
CS
227{
228 const char *cgroup_use = NULL;
229 char **cgroup_use_list = NULL;
230 struct cgroup_meta_data *md = NULL;
231 int saved_errno;
232
233 errno = 0;
593e8478 234 cgroup_use = lxc_global_config_value("lxc.cgroup.use");
33ad9f1a
CS
235 if (!cgroup_use && errno != 0)
236 return NULL;
237 if (cgroup_use) {
238 cgroup_use_list = lxc_string_split_and_trim(cgroup_use, ',');
239 if (!cgroup_use_list)
240 return NULL;
241 }
576f946d 242
33ad9f1a
CS
243 md = lxc_cgroup_load_meta2((const char **)cgroup_use_list);
244 saved_errno = errno;
245 lxc_free_array((void **)cgroup_use_list, free);
246 errno = saved_errno;
247 return md;
248}
fd37327f 249
b653309a 250/* Step 1: determine all kernel subsystems */
4fb3cba5 251static bool find_cgroup_subsystems(char ***kernel_subsystems)
1d39a065 252{
b653309a
SH
253 FILE *proc_cgroups;
254 bool bret = false;
33ad9f1a
CS
255 char *line = NULL;
256 size_t sz = 0;
b653309a
SH
257 size_t kernel_subsystems_count = 0;
258 size_t kernel_subsystems_capacity = 0;
259 int r;
1d39a065 260
33ad9f1a
CS
261 proc_cgroups = fopen_cloexec("/proc/cgroups", "r");
262 if (!proc_cgroups)
b653309a 263 return false;
1d39a065 264
33ad9f1a
CS
265 while (getline(&line, &sz, proc_cgroups) != -1) {
266 char *tab1;
267 char *tab2;
268 int hierarchy_number;
1d39a065 269
33ad9f1a
CS
270 if (line[0] == '#')
271 continue;
272 if (!line[0])
273 continue;
1d39a065 274
33ad9f1a
CS
275 tab1 = strchr(line, '\t');
276 if (!tab1)
8900b9eb 277 continue;
33ad9f1a
CS
278 *tab1++ = '\0';
279 tab2 = strchr(tab1, '\t');
280 if (!tab2)
281 continue;
282 *tab2 = '\0';
fd37327f 283
33ad9f1a
CS
284 tab2 = NULL;
285 hierarchy_number = strtoul(tab1, &tab2, 10);
286 if (!tab2 || *tab2)
287 continue;
288 (void)hierarchy_number;
289
b653309a 290 r = lxc_grow_array((void ***)kernel_subsystems, &kernel_subsystems_capacity, kernel_subsystems_count + 1, 12);
33ad9f1a 291 if (r < 0)
b653309a
SH
292 goto out;
293 (*kernel_subsystems)[kernel_subsystems_count] = strdup(line);
294 if (!(*kernel_subsystems)[kernel_subsystems_count])
295 goto out;
33ad9f1a 296 kernel_subsystems_count++;
bcbd102c 297 }
b653309a 298 bret = true;
0d9f8e18 299
b653309a 300out:
33ad9f1a 301 fclose(proc_cgroups);
0ccf7c2a 302 free(line);
b653309a
SH
303 return bret;
304}
305
306/* Step 2: determine all hierarchies (by reading /proc/self/cgroup),
307 * since mount points don't specify hierarchy number and
308 * /proc/cgroups does not contain named hierarchies
309 */
310static bool find_cgroup_hierarchies(struct cgroup_meta_data *meta_data,
311 bool all_kernel_subsystems, bool all_named_subsystems,
312 const char **subsystem_whitelist)
313{
314 FILE *proc_self_cgroup;
315 char *line = NULL;
316 size_t sz = 0;
317 int r;
318 bool bret = false;
319 size_t hierarchy_capacity = 0;
ef6e34ee 320
33ad9f1a
CS
321 proc_self_cgroup = fopen_cloexec("/proc/self/cgroup", "r");
322 /* if for some reason (because of setns() and pid namespace for example),
323 * /proc/self is not valid, we try /proc/1/cgroup... */
324 if (!proc_self_cgroup)
325 proc_self_cgroup = fopen_cloexec("/proc/1/cgroup", "r");
326 if (!proc_self_cgroup)
b653309a 327 return false;
33ad9f1a
CS
328
329 while (getline(&line, &sz, proc_self_cgroup) != -1) {
330 /* file format: hierarchy:subsystems:group,
331 * we only extract hierarchy and subsystems
332 * here */
333 char *colon1;
334 char *colon2;
335 int hierarchy_number;
336 struct cgroup_hierarchy *h = NULL;
337 char **p;
338
339 if (!line[0])
340 continue;
ad08bbb7 341
33ad9f1a
CS
342 colon1 = strchr(line, ':');
343 if (!colon1)
8900b9eb 344 continue;
33ad9f1a
CS
345 *colon1++ = '\0';
346 colon2 = strchr(colon1, ':');
347 if (!colon2)
348 continue;
349 *colon2 = '\0';
ad08bbb7 350
33ad9f1a
CS
351 colon2 = NULL;
352 hierarchy_number = strtoul(line, &colon2, 10);
353 if (!colon2 || *colon2)
354 continue;
576f946d 355
33ad9f1a
CS
356 if (hierarchy_number > meta_data->maximum_hierarchy) {
357 /* lxc_grow_array will never shrink, so even if we find a lower
358 * hierarchy number here, the array will never be smaller
359 */
360 r = lxc_grow_array((void ***)&meta_data->hierarchies, &hierarchy_capacity, hierarchy_number + 1, 12);
361 if (r < 0)
b653309a 362 goto out;
5193cc3d 363
33ad9f1a
CS
364 meta_data->maximum_hierarchy = hierarchy_number;
365 }
fd37327f 366
33ad9f1a
CS
367 /* this shouldn't happen, we had this already */
368 if (meta_data->hierarchies[hierarchy_number])
b653309a 369 goto out;
33ad9f1a
CS
370
371 h = calloc(1, sizeof(struct cgroup_hierarchy));
372 if (!h)
b653309a 373 goto out;
33ad9f1a
CS
374
375 meta_data->hierarchies[hierarchy_number] = h;
376
377 h->index = hierarchy_number;
378 h->subsystems = lxc_string_split_and_trim(colon1, ',');
379 if (!h->subsystems)
b653309a 380 goto out;
33ad9f1a
CS
381 /* see if this hierarchy should be considered */
382 if (!all_kernel_subsystems || !all_named_subsystems) {
383 for (p = h->subsystems; *p; p++) {
384 if (!strncmp(*p, "name=", 5)) {
385 if (all_named_subsystems || (subsystem_whitelist && lxc_string_in_array(*p, subsystem_whitelist))) {
386 h->used = true;
387 break;
388 }
389 } else {
390 if (all_kernel_subsystems || (subsystem_whitelist && lxc_string_in_array(*p, subsystem_whitelist))) {
391 h->used = true;
392 break;
393 }
394 }
395 }
396 } else {
397 /* we want all hierarchy anyway */
398 h->used = true;
ae5c8b8e 399 }
ae5c8b8e 400 }
b653309a 401 bret = true;
0b9c21ab 402
b653309a 403out:
33ad9f1a 404 fclose(proc_self_cgroup);
0ccf7c2a 405 free(line);
b653309a
SH
406 return bret;
407}
408
409/* Step 3: determine all mount points of each hierarchy */
410static bool find_hierarchy_mountpts( struct cgroup_meta_data *meta_data, char **kernel_subsystems)
411{
412 bool bret = false;
413 FILE *proc_self_mountinfo;
414 char *line = NULL;
415 size_t sz = 0;
416 char **tokens = NULL;
417 size_t mount_point_count = 0;
418 size_t mount_point_capacity = 0;
419 size_t token_capacity = 0;
420 int r;
421
33ad9f1a
CS
422 proc_self_mountinfo = fopen_cloexec("/proc/self/mountinfo", "r");
423 /* if for some reason (because of setns() and pid namespace for example),
424 * /proc/self is not valid, we try /proc/1/cgroup... */
425 if (!proc_self_mountinfo)
426 proc_self_mountinfo = fopen_cloexec("/proc/1/mountinfo", "r");
427 if (!proc_self_mountinfo)
b653309a 428 return false;
33ad9f1a
CS
429
430 while (getline(&line, &sz, proc_self_mountinfo) != -1) {
178938fe 431 char *token, *line_tok, *saveptr = NULL;
33ad9f1a
CS
432 size_t i, j, k;
433 struct cgroup_mount_point *mount_point;
434 struct cgroup_hierarchy *h;
435 char **subsystems;
836514a8 436 bool is_lxcfs = false;
33ad9f1a
CS
437
438 if (line[0] && line[strlen(line) - 1] == '\n')
439 line[strlen(line) - 1] = '\0';
440
178938fe 441 for (i = 0, line_tok = line; (token = strtok_r(line_tok, " ", &saveptr)); line_tok = NULL) {
33ad9f1a
CS
442 r = lxc_grow_array((void ***)&tokens, &token_capacity, i + 1, 64);
443 if (r < 0)
b653309a 444 goto out;
33ad9f1a
CS
445 tokens[i++] = token;
446 }
b98f7d6e 447
33ad9f1a
CS
448 /* layout of /proc/self/mountinfo:
449 * 0: id
450 * 1: parent id
451 * 2: device major:minor
452 * 3: mount prefix
8900b9eb 453 * 4: mount point
33ad9f1a
CS
454 * 5: per-mount options
455 * [optional X]: additional data
456 * X+7: "-"
457 * X+8: type
458 * X+9: source
459 * X+10: per-superblock options
460 */
461 for (j = 6; j < i && tokens[j]; j++)
462 if (!strcmp(tokens[j], "-"))
463 break;
fd4f5a56 464
33ad9f1a
CS
465 /* could not find separator */
466 if (j >= i || !tokens[j])
467 continue;
468 /* there should be exactly three fields after
469 * the separator
470 */
471 if (i != j + 4)
472 continue;
fd4f5a56 473
33ad9f1a 474 /* not a cgroup filesystem */
836514a8
U
475 if (strcmp(tokens[j + 1], "cgroup") != 0) {
476 if (strcmp(tokens[j + 1], "fuse.lxcfs") != 0)
477 continue;
478 if (strncmp(tokens[4], "/sys/fs/cgroup/", 15) != 0)
479 continue;
480 is_lxcfs = true;
481 char *curtok = tokens[4] + 15;
482 subsystems = subsystems_from_mount_options(curtok,
483 kernel_subsystems);
484 } else
485 subsystems = subsystems_from_mount_options(tokens[j + 3],
486 kernel_subsystems);
33ad9f1a 487 if (!subsystems)
b653309a 488 goto out;
33ad9f1a
CS
489
490 h = NULL;
491 for (k = 1; k <= meta_data->maximum_hierarchy; k++) {
492 if (meta_data->hierarchies[k] &&
493 meta_data->hierarchies[k]->subsystems[0] &&
494 lxc_string_in_array(meta_data->hierarchies[k]->subsystems[0], (const char **)subsystems)) {
495 /* TODO: we could also check if the lists really match completely,
496 * just to have an additional sanity check */
497 h = meta_data->hierarchies[k];
b98f7d6e 498 break;
33ad9f1a 499 }
b98f7d6e 500 }
33ad9f1a
CS
501 lxc_free_array((void **)subsystems, free);
502
503 r = lxc_grow_array((void ***)&meta_data->mount_points, &mount_point_capacity, mount_point_count + 1, 12);
504 if (r < 0)
b653309a 505 goto out;
33ad9f1a
CS
506
507 /* create mount point object */
508 mount_point = calloc(1, sizeof(*mount_point));
509 if (!mount_point)
b653309a 510 goto out;
33ad9f1a
CS
511
512 meta_data->mount_points[mount_point_count++] = mount_point;
513
514 mount_point->hierarchy = h;
836514a8
U
515 if (is_lxcfs)
516 mount_point->mount_prefix = strdup("/");
517 else
518 mount_point->mount_prefix = strdup(tokens[3]);
33ad9f1a 519 mount_point->mount_point = strdup(tokens[4]);
33ad9f1a 520 if (!mount_point->mount_point || !mount_point->mount_prefix)
b653309a 521 goto out;
33ad9f1a
CS
522 mount_point->read_only = !lxc_string_in_list("rw", tokens[5], ',');
523
524 if (!strcmp(mount_point->mount_prefix, "/")) {
525 if (mount_point->read_only) {
526 if (!h->ro_absolute_mount_point)
527 h->ro_absolute_mount_point = mount_point;
528 } else {
529 if (!h->rw_absolute_mount_point)
530 h->rw_absolute_mount_point = mount_point;
531 }
b98f7d6e 532 }
ae5c8b8e 533
33ad9f1a
CS
534 k = lxc_array_len((void **)h->all_mount_points);
535 r = lxc_grow_array((void ***)&h->all_mount_points, &h->all_mount_point_capacity, k + 1, 4);
536 if (r < 0)
b653309a 537 goto out;
33ad9f1a 538 h->all_mount_points[k] = mount_point;
fd4f5a56 539 }
b653309a
SH
540 bret = true;
541
542out:
b653309a 543 fclose(proc_self_mountinfo);
b653309a 544 free(tokens);
2cdafc54 545 free(line);
b653309a
SH
546 return bret;
547}
548
4fb3cba5 549static struct cgroup_meta_data *lxc_cgroup_load_meta2(const char **subsystem_whitelist)
b653309a
SH
550{
551 bool all_kernel_subsystems = true;
552 bool all_named_subsystems = false;
553 struct cgroup_meta_data *meta_data = NULL;
554 char **kernel_subsystems = NULL;
555 int saved_errno = 0;
556
557 /* if the subsystem whitelist is not specified, include all
558 * hierarchies that contain kernel subsystems by default but
559 * no hierarchies that only contain named subsystems
560 *
561 * if it is specified, the specifier @all will select all
562 * hierarchies, @kernel will select all hierarchies with
563 * kernel subsystems and @named will select all named
564 * hierarchies
565 */
566 all_kernel_subsystems = subsystem_whitelist ?
567 (lxc_string_in_array("@kernel", subsystem_whitelist) || lxc_string_in_array("@all", subsystem_whitelist)) :
568 true;
569 all_named_subsystems = subsystem_whitelist ?
570 (lxc_string_in_array("@named", subsystem_whitelist) || lxc_string_in_array("@all", subsystem_whitelist)) :
79c59e6b 571 true;
b653309a
SH
572
573 meta_data = calloc(1, sizeof(struct cgroup_meta_data));
574 if (!meta_data)
575 return NULL;
576 meta_data->ref = 1;
577
578 if (!find_cgroup_subsystems(&kernel_subsystems))
579 goto out_error;
580
581 if (!find_cgroup_hierarchies(meta_data, all_kernel_subsystems,
582 all_named_subsystems, subsystem_whitelist))
583 goto out_error;
584
585 if (!find_hierarchy_mountpts(meta_data, kernel_subsystems))
586 goto out_error;
fd4f5a56 587
33ad9f1a
CS
588 /* oops, we couldn't find anything */
589 if (!meta_data->hierarchies || !meta_data->mount_points) {
590 errno = EINVAL;
591 goto out_error;
ae5c8b8e 592 }
fd4f5a56 593
3a0abb3a 594 lxc_free_array((void **)kernel_subsystems, free);
33ad9f1a
CS
595 return meta_data;
596
597out_error:
598 saved_errno = errno;
33ad9f1a
CS
599 lxc_free_array((void **)kernel_subsystems, free);
600 lxc_cgroup_put_meta(meta_data);
601 errno = saved_errno;
602 return NULL;
fd4f5a56
DL
603}
604
4fb3cba5 605static struct cgroup_meta_data *lxc_cgroup_get_meta(struct cgroup_meta_data *meta_data)
e14f67a7 606{
33ad9f1a
CS
607 meta_data->ref++;
608 return meta_data;
609}
e14f67a7 610
4fb3cba5 611static struct cgroup_meta_data *lxc_cgroup_put_meta(struct cgroup_meta_data *meta_data)
33ad9f1a
CS
612{
613 size_t i;
614 if (!meta_data)
615 return NULL;
616 if (--meta_data->ref > 0)
617 return meta_data;
618 lxc_free_array((void **)meta_data->mount_points, (lxc_free_fn)lxc_cgroup_mount_point_free);
619 if (meta_data->hierarchies) {
620 for (i = 0; i <= meta_data->maximum_hierarchy; i++)
621 lxc_cgroup_hierarchy_free(meta_data->hierarchies[i]);
e14f67a7 622 }
33ad9f1a 623 free(meta_data->hierarchies);
178938fe 624 free(meta_data);
33ad9f1a 625 return NULL;
e14f67a7
U
626}
627
4fb3cba5 628static struct cgroup_hierarchy *lxc_cgroup_find_hierarchy(struct cgroup_meta_data *meta_data, const char *subsystem)
e14f67a7 629{
33ad9f1a
CS
630 size_t i;
631 for (i = 0; i <= meta_data->maximum_hierarchy; i++) {
632 struct cgroup_hierarchy *h = meta_data->hierarchies[i];
633 if (h && lxc_string_in_array(subsystem, (const char **)h->subsystems))
634 return h;
e14f67a7 635 }
e14f67a7
U
636 return NULL;
637}
638
d3f99e96
SH
639static bool mountpoint_is_accessible(struct cgroup_mount_point *mp)
640{
641 return mp && access(mp->mount_point, F_OK) == 0;
642}
643
4fb3cba5 644static struct cgroup_mount_point *lxc_cgroup_find_mount_point(struct cgroup_hierarchy *hierarchy, const char *group, bool should_be_writable)
b98f7d6e 645{
33ad9f1a
CS
646 struct cgroup_mount_point **mps;
647 struct cgroup_mount_point *current_result = NULL;
648 ssize_t quality = -1;
b98f7d6e 649
33ad9f1a 650 /* trivial case */
d3f99e96 651 if (mountpoint_is_accessible(hierarchy->rw_absolute_mount_point))
33ad9f1a 652 return hierarchy->rw_absolute_mount_point;
d3f99e96 653 if (!should_be_writable && mountpoint_is_accessible(hierarchy->ro_absolute_mount_point))
33ad9f1a 654 return hierarchy->ro_absolute_mount_point;
b98f7d6e 655
33ad9f1a
CS
656 for (mps = hierarchy->all_mount_points; mps && *mps; mps++) {
657 struct cgroup_mount_point *mp = *mps;
658 size_t prefix_len = mp->mount_prefix ? strlen(mp->mount_prefix) : 0;
b98f7d6e 659
33ad9f1a
CS
660 if (prefix_len == 1 && mp->mount_prefix[0] == '/')
661 prefix_len = 0;
b98f7d6e 662
d3f99e96
SH
663 if (!mountpoint_is_accessible(mp))
664 continue;
665
33ad9f1a
CS
666 if (should_be_writable && mp->read_only)
667 continue;
668
669 if (!prefix_len ||
670 (strncmp(group, mp->mount_prefix, prefix_len) == 0 &&
671 (group[prefix_len] == '\0' || group[prefix_len] == '/'))) {
672 /* search for the best quality match, i.e. the match with the
673 * shortest prefix where this group is still contained
674 */
675 if (quality == -1 || prefix_len < quality) {
676 current_result = mp;
677 quality = prefix_len;
678 }
b98f7d6e
SH
679 }
680 }
681
33ad9f1a
CS
682 if (!current_result)
683 errno = ENOENT;
684 return current_result;
b98f7d6e
SH
685}
686
4fb3cba5 687static char *lxc_cgroup_find_abs_path(const char *subsystem, const char *group, bool should_be_writable, const char *suffix)
b98f7d6e 688{
33ad9f1a
CS
689 struct cgroup_meta_data *meta_data;
690 struct cgroup_hierarchy *h;
691 struct cgroup_mount_point *mp;
692 char *result;
693 int saved_errno;
694
695 meta_data = lxc_cgroup_load_meta();
696 if (!meta_data)
697 return NULL;
b98f7d6e 698
33ad9f1a
CS
699 h = lxc_cgroup_find_hierarchy(meta_data, subsystem);
700 if (!h)
701 goto out_error;
b98f7d6e 702
33ad9f1a
CS
703 mp = lxc_cgroup_find_mount_point(h, group, should_be_writable);
704 if (!mp)
705 goto out_error;
b98f7d6e 706
33ad9f1a
CS
707 result = cgroup_to_absolute_path(mp, group, suffix);
708 if (!result)
709 goto out_error;
b98f7d6e 710
33ad9f1a
CS
711 lxc_cgroup_put_meta(meta_data);
712 return result;
b98f7d6e 713
33ad9f1a
CS
714out_error:
715 saved_errno = errno;
716 lxc_cgroup_put_meta(meta_data);
717 errno = saved_errno;
718 return NULL;
b98f7d6e
SH
719}
720
4fb3cba5 721static struct cgroup_process_info *lxc_cgroup_process_info_get(pid_t pid, struct cgroup_meta_data *meta)
fd4f5a56 722{
33ad9f1a
CS
723 char pid_buf[32];
724 snprintf(pid_buf, 32, "/proc/%lu/cgroup", (unsigned long)pid);
725 return lxc_cgroup_process_info_getx(pid_buf, meta);
c8f7c563
CS
726}
727
4fb3cba5 728static struct cgroup_process_info *lxc_cgroup_process_info_get_init(struct cgroup_meta_data *meta)
c8f7c563 729{
33ad9f1a
CS
730 return lxc_cgroup_process_info_get(1, meta);
731}
b98f7d6e 732
4fb3cba5 733static struct cgroup_process_info *lxc_cgroup_process_info_get_self(struct cgroup_meta_data *meta)
33ad9f1a
CS
734{
735 struct cgroup_process_info *i;
736 i = lxc_cgroup_process_info_getx("/proc/self/cgroup", meta);
737 if (!i)
738 i = lxc_cgroup_process_info_get(getpid(), meta);
739 return i;
740}
ae5c8b8e 741
692ba18f
SH
742/*
743 * If a controller has ns cgroup mounted, then in that cgroup the handler->pid
744 * is already in a new cgroup named after the pid. 'mnt' is passed in as
745 * the full current cgroup. Say that is /sys/fs/cgroup/lxc/2975 and the container
746 * name is c1. . We want to rename the cgroup directory to /sys/fs/cgroup/lxc/c1,
747 * and return the string /sys/fs/cgroup/lxc/c1.
748 */
cea0552e 749static char *cgroup_rename_nsgroup(const char *mountpath, const char *oldname, pid_t pid, const char *name)
692ba18f
SH
750{
751 char *dir, *fulloldpath;
752 char *newname, *fullnewpath;
cea0552e 753 int len, newlen, ret;
692ba18f
SH
754
755 /*
756 * if cgroup is mounted at /cgroup and task is in cgroup /ab/, pid 2375 and
757 * name is c1,
758 * dir: /ab
759 * fulloldpath = /cgroup/ab/2375
760 * fullnewpath = /cgroup/ab/c1
761 * newname = /ab/c1
762 */
763 dir = alloca(strlen(oldname) + 1);
764 strcpy(dir, oldname);
765
cea0552e
SH
766 len = strlen(oldname) + strlen(mountpath) + 22;
767 fulloldpath = alloca(len);
768 ret = snprintf(fulloldpath, len, "%s/%s/%ld", mountpath, oldname, (unsigned long)pid);
769 if (ret < 0 || ret >= len)
770 return NULL;
692ba18f
SH
771
772 len = strlen(dir) + strlen(name) + 2;
773 newname = malloc(len);
774 if (!newname) {
775 SYSERROR("Out of memory");
776 return NULL;
777 }
cea0552e
SH
778 ret = snprintf(newname, len, "%s/%s", dir, name);
779 if (ret < 0 || ret >= len) {
780 free(newname);
781 return NULL;
782 }
692ba18f 783
cea0552e
SH
784 newlen = strlen(mountpath) + len + 2;
785 fullnewpath = alloca(newlen);
786 ret = snprintf(fullnewpath, newlen, "%s/%s", mountpath, newname);
787 if (ret < 0 || ret >= newlen) {
788 free(newname);
789 return NULL;
790 }
692ba18f
SH
791
792 if (access(fullnewpath, F_OK) == 0) {
793 if (rmdir(fullnewpath) != 0) {
794 SYSERROR("container cgroup %s already exists.", fullnewpath);
795 free(newname);
796 return NULL;
797 }
798 }
799 if (rename(fulloldpath, fullnewpath)) {
800 SYSERROR("failed to rename cgroup %s->%s", fulloldpath, fullnewpath);
801 free(newname);
802 return NULL;
803 }
804
805 DEBUG("'%s' renamed to '%s'", oldname, newname);
806
807 return newname;
808}
809
33ad9f1a 810/* create a new cgroup */
4fb3cba5 811static struct cgroup_process_info *lxc_cgroupfs_create(const char *name, const char *path_pattern, struct cgroup_meta_data *meta_data, const char *sub_pattern)
33ad9f1a 812{
001b026e 813 char **cgroup_path_components = NULL;
33ad9f1a
CS
814 char **p = NULL;
815 char *path_so_far = NULL;
816 char **new_cgroup_paths = NULL;
817 char **new_cgroup_paths_sub = NULL;
818 struct cgroup_mount_point *mp;
819 struct cgroup_hierarchy *h;
820 struct cgroup_process_info *base_info = NULL;
821 struct cgroup_process_info *info_ptr;
822 int saved_errno;
823 int r;
824 unsigned suffix = 0;
825 bool had_sub_pattern = false;
826 size_t i;
ae5c8b8e 827
33ad9f1a
CS
828 if (!is_valid_cgroup(name)) {
829 ERROR("Invalid cgroup name: '%s'", name);
830 errno = EINVAL;
831 return NULL;
ae5c8b8e
SH
832 }
833
33ad9f1a
CS
834 if (!strstr(path_pattern, "%n")) {
835 ERROR("Invalid cgroup path pattern: '%s'; contains no %%n for specifying container name", path_pattern);
836 errno = EINVAL;
837 return NULL;
838 }
fd37327f 839
33ad9f1a
CS
840 /* we will modify the result of this operation directly,
841 * so we don't have to copy the data structure
842 */
843 base_info = (path_pattern[0] == '/') ?
844 lxc_cgroup_process_info_get_init(meta_data) :
845 lxc_cgroup_process_info_get_self(meta_data);
846 if (!base_info)
847 return NULL;
c8f7c563 848
33ad9f1a
CS
849 new_cgroup_paths = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *));
850 if (!new_cgroup_paths)
851 goto out_initial_error;
852
853 new_cgroup_paths_sub = calloc(meta_data->maximum_hierarchy + 1, sizeof(char *));
854 if (!new_cgroup_paths_sub)
855 goto out_initial_error;
856
857 /* find mount points we can use */
858 for (info_ptr = base_info; info_ptr; info_ptr = info_ptr->next) {
859 h = info_ptr->hierarchy;
860 mp = lxc_cgroup_find_mount_point(h, info_ptr->cgroup_path, true);
861 if (!mp) {
862 ERROR("Could not find writable mount point for cgroup hierarchy %d while trying to create cgroup.", h->index);
863 goto out_initial_error;
864 }
865 info_ptr->designated_mount_point = mp;
460a1cf0 866
692ba18f
SH
867 if (lxc_string_in_array("ns", (const char **)h->subsystems))
868 continue;
2edb53c7
SH
869 if (handle_cgroup_settings(mp, info_ptr->cgroup_path) < 0) {
870 ERROR("Could not set clone_children to 1 for cpuset hierarchy in parent cgroup.");
33ad9f1a 871 goto out_initial_error;
2edb53c7 872 }
33ad9f1a 873 }
b98f7d6e 874
33ad9f1a
CS
875 /* normalize the path */
876 cgroup_path_components = lxc_normalize_path(path_pattern);
877 if (!cgroup_path_components)
878 goto out_initial_error;
879
880 /* go through the path components to see if we can create them */
881 for (p = cgroup_path_components; *p || (sub_pattern && !had_sub_pattern); p++) {
882 /* we only want to create the same component with -1, -2, etc.
883 * if the component contains the container name itself, otherwise
884 * it's not an error if it already exists
885 */
886 char *p_eff = *p ? *p : (char *)sub_pattern;
887 bool contains_name = strstr(p_eff, "%n");
888 char *current_component = NULL;
889 char *current_subpath = NULL;
890 char *current_entire_path = NULL;
891 char *parts[3];
892 size_t j = 0;
893 i = 0;
894
895 /* if we are processing the subpattern, we want to make sure
896 * loop is ended the next time around
897 */
898 if (!*p) {
899 had_sub_pattern = true;
900 p--;
901 }
b98f7d6e 902
33ad9f1a 903 goto find_name_on_this_level;
4fb3cba5 904
33ad9f1a
CS
905 cleanup_name_on_this_level:
906 /* This is reached if we found a name clash.
907 * In that case, remove the cgroup from all previous hierarchies
908 */
909 for (j = 0, info_ptr = base_info; j < i && info_ptr; info_ptr = info_ptr->next, j++) {
603c64c2 910 r = remove_cgroup(info_ptr->designated_mount_point, info_ptr->created_paths[info_ptr->created_paths_count - 1], false);
33ad9f1a
CS
911 if (r < 0)
912 WARN("could not clean up cgroup we created when trying to create container");
913 free(info_ptr->created_paths[info_ptr->created_paths_count - 1]);
914 info_ptr->created_paths[--info_ptr->created_paths_count] = NULL;
915 }
916 if (current_component != current_subpath)
917 free(current_subpath);
918 if (current_component != p_eff)
919 free(current_component);
920 current_component = current_subpath = NULL;
921 /* try again with another suffix */
922 ++suffix;
4fb3cba5 923
33ad9f1a
CS
924 find_name_on_this_level:
925 /* determine name of the path component we should create */
926 if (contains_name && suffix > 0) {
927 char *buf = calloc(strlen(name) + 32, 1);
928 if (!buf)
929 goto out_initial_error;
930 snprintf(buf, strlen(name) + 32, "%s-%u", name, suffix);
931 current_component = lxc_string_replace("%n", buf, p_eff);
932 free(buf);
933 } else {
934 current_component = contains_name ? lxc_string_replace("%n", name, p_eff) : p_eff;
935 }
936 parts[0] = path_so_far;
937 parts[1] = current_component;
938 parts[2] = NULL;
939 current_subpath = path_so_far ? lxc_string_join("/", (const char **)parts, false) : current_component;
940
941 /* Now go through each hierarchy and try to create the
942 * corresponding cgroup
943 */
944 for (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) {
945 char *parts2[3];
692ba18f
SH
946
947 if (lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems))
948 continue;
33ad9f1a
CS
949 current_entire_path = NULL;
950
951 parts2[0] = !strcmp(info_ptr->cgroup_path, "/") ? "" : info_ptr->cgroup_path;
952 parts2[1] = current_subpath;
953 parts2[2] = NULL;
954 current_entire_path = lxc_string_join("/", (const char **)parts2, false);
955
956 if (!*p) {
957 /* we are processing the subpath, so only update that one */
958 free(new_cgroup_paths_sub[i]);
959 new_cgroup_paths_sub[i] = strdup(current_entire_path);
960 if (!new_cgroup_paths_sub[i])
961 goto cleanup_from_error;
962 } else {
963 /* remember which path was used on this controller */
964 free(new_cgroup_paths[i]);
965 new_cgroup_paths[i] = strdup(current_entire_path);
966 if (!new_cgroup_paths[i])
967 goto cleanup_from_error;
968 }
fd4f5a56 969
33ad9f1a
CS
970 r = create_cgroup(info_ptr->designated_mount_point, current_entire_path);
971 if (r < 0 && errno == EEXIST && contains_name) {
972 /* name clash => try new name with new suffix */
973 free(current_entire_path);
974 current_entire_path = NULL;
975 goto cleanup_name_on_this_level;
976 } else if (r < 0 && errno != EEXIST) {
b38b62a6 977 SYSERROR("Could not create cgroup '%s' in '%s'.", current_entire_path, info_ptr->designated_mount_point->mount_point);
33ad9f1a
CS
978 goto cleanup_from_error;
979 } else if (r == 0) {
980 /* successfully created */
981 r = lxc_grow_array((void ***)&info_ptr->created_paths, &info_ptr->created_paths_capacity, info_ptr->created_paths_count + 1, 8);
982 if (r < 0)
983 goto cleanup_from_error;
d703c2b1 984 if (!init_cpuset_if_needed(info_ptr->designated_mount_point, current_entire_path)) {
b38b62a6 985 ERROR("Failed to initialize cpuset for '%s' in '%s'.", current_entire_path, info_ptr->designated_mount_point->mount_point);
d703c2b1
RV
986 goto cleanup_from_error;
987 }
33ad9f1a
CS
988 info_ptr->created_paths[info_ptr->created_paths_count++] = current_entire_path;
989 } else {
990 /* if we didn't create the cgroup, then we have to make sure that
991 * further cgroups will be created properly
992 */
d703c2b1 993 if (handle_cgroup_settings(info_ptr->designated_mount_point, info_ptr->cgroup_path) < 0) {
f6ac3b9e 994 ERROR("Could not set clone_children to 1 for cpuset hierarchy in pre-existing cgroup.");
33ad9f1a 995 goto cleanup_from_error;
f6ac3b9e 996 }
d703c2b1
RV
997 if (!init_cpuset_if_needed(info_ptr->designated_mount_point, info_ptr->cgroup_path)) {
998 ERROR("Failed to initialize cpuset in pre-existing '%s'.", info_ptr->cgroup_path);
999 goto cleanup_from_error;
1000 }
33ad9f1a
CS
1001
1002 /* already existed but path component of pattern didn't contain '%n',
1003 * so this is not an error; but then we don't need current_entire_path
1004 * anymore...
1005 */
1006 free(current_entire_path);
1007 current_entire_path = NULL;
1008 }
1009 }
fd4f5a56 1010
33ad9f1a
CS
1011 /* save path so far */
1012 free(path_so_far);
1013 path_so_far = strdup(current_subpath);
1014 if (!path_so_far)
1015 goto cleanup_from_error;
1016
1017 /* cleanup */
1018 if (current_component != current_subpath)
1019 free(current_subpath);
1020 if (current_component != p_eff)
1021 free(current_component);
1022 current_component = current_subpath = NULL;
1023 continue;
4fb3cba5 1024
33ad9f1a 1025 cleanup_from_error:
ec64264d 1026 /* called if an error occurred in the loop, so we
33ad9f1a
CS
1027 * do some additional cleanup here
1028 */
1029 saved_errno = errno;
1030 if (current_component != current_subpath)
1031 free(current_subpath);
1032 if (current_component != p_eff)
1033 free(current_component);
1034 free(current_entire_path);
1035 errno = saved_errno;
1036 goto out_initial_error;
fd4f5a56
DL
1037 }
1038
33ad9f1a
CS
1039 /* we're done, now update the paths */
1040 for (i = 0, info_ptr = base_info; info_ptr; info_ptr = info_ptr->next, i++) {
47d8fb3b
CS
1041 /* ignore legacy 'ns' subsystem here, lxc_cgroup_create_legacy
1042 * will take care of it
1043 * Since we do a continue in above loop, new_cgroup_paths[i] is
1044 * unset anyway, as is new_cgroup_paths_sub[i]
692ba18f 1045 */
47d8fb3b
CS
1046 if (lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems))
1047 continue;
1048 free(info_ptr->cgroup_path);
1049 info_ptr->cgroup_path = new_cgroup_paths[i];
1050 info_ptr->cgroup_path_sub = new_cgroup_paths_sub[i];
fd4f5a56 1051 }
33ad9f1a
CS
1052 /* don't use lxc_free_array since we used the array members
1053 * to store them in our result...
1054 */
1055 free(new_cgroup_paths);
1056 free(new_cgroup_paths_sub);
1057 free(path_so_far);
1058 lxc_free_array((void **)cgroup_path_components, free);
1059 return base_info;
1060
1061out_initial_error:
1062 saved_errno = errno;
1063 free(path_so_far);
1064 lxc_cgroup_process_info_free_and_remove(base_info);
1065 lxc_free_array((void **)new_cgroup_paths, free);
1066 lxc_free_array((void **)new_cgroup_paths_sub, free);
1067 lxc_free_array((void **)cgroup_path_components, free);
1068 errno = saved_errno;
1069 return NULL;
c8f7c563
CS
1070}
1071
4fb3cba5 1072static int lxc_cgroup_create_legacy(struct cgroup_process_info *base_info, const char *name, pid_t pid)
47d8fb3b
CS
1073{
1074 struct cgroup_process_info *info_ptr;
1075 int r;
1076
1077 for (info_ptr = base_info; info_ptr; info_ptr = info_ptr->next) {
1078 if (!lxc_string_in_array("ns", (const char **)info_ptr->hierarchy->subsystems))
1079 continue;
1080 /*
1081 * For any path which has ns cgroup mounted, handler->pid is already
1082 * moved into a container called '%d % (handler->pid)'. Rename it to
1083 * the cgroup name and record that.
1084 */
1085 char *tmp = cgroup_rename_nsgroup((const char *)info_ptr->designated_mount_point->mount_point,
1086 info_ptr->cgroup_path, pid, name);
1087 if (!tmp)
1088 return -1;
1089 free(info_ptr->cgroup_path);
1090 info_ptr->cgroup_path = tmp;
1091 r = lxc_grow_array((void ***)&info_ptr->created_paths, &info_ptr->created_paths_capacity, info_ptr->created_paths_count + 1, 8);
1092 if (r < 0)
1093 return -1;
1094 tmp = strdup(tmp);
1095 if (!tmp)
1096 return -1;
1097 info_ptr->created_paths[info_ptr->created_paths_count++] = tmp;
1098 }
1099 return 0;
1100}
1101
33ad9f1a 1102/* get the cgroup membership of a given container */
4fb3cba5 1103static struct cgroup_process_info *lxc_cgroup_get_container_info(const char *name, const char *lxcpath, struct cgroup_meta_data *meta_data)
c8f7c563 1104{
33ad9f1a
CS
1105 struct cgroup_process_info *result = NULL;
1106 int saved_errno = 0;
1107 size_t i;
1108 struct cgroup_process_info **cptr = &result;
1109 struct cgroup_process_info *entry = NULL;
1110 char *path = NULL;
1111
1112 for (i = 0; i <= meta_data->maximum_hierarchy; i++) {
1113 struct cgroup_hierarchy *h = meta_data->hierarchies[i];
1114 if (!h || !h->used)
1115 continue;
c8f7c563 1116
33ad9f1a
CS
1117 /* use the command interface to look for the cgroup */
1118 path = lxc_cmd_get_cgroup_path(name, lxcpath, h->subsystems[0]);
c661b0a8
DE
1119 if (!path) {
1120 h->used = false;
1121 WARN("Not attaching to cgroup %s unknown to %s %s", h->subsystems[0], lxcpath, name);
1122 continue;
1123 }
33ad9f1a
CS
1124
1125 entry = calloc(1, sizeof(struct cgroup_process_info));
1126 if (!entry)
1127 goto out_error;
1128 entry->meta_ref = lxc_cgroup_get_meta(meta_data);
1129 entry->hierarchy = h;
1130 entry->cgroup_path = path;
1131 path = NULL;
1132
1133 /* it is not an error if we don't find anything here,
1134 * it is up to the caller to decide what to do in that
1135 * case */
1136 entry->designated_mount_point = lxc_cgroup_find_mount_point(h, entry->cgroup_path, true);
1137
1138 *cptr = entry;
1139 cptr = &entry->next;
1140 entry = NULL;
c8f7c563
CS
1141 }
1142
33ad9f1a
CS
1143 return result;
1144out_error:
1145 saved_errno = errno;
1146 free(path);
1147 lxc_cgroup_process_info_free(result);
1148 lxc_cgroup_process_info_free(entry);
1149 errno = saved_errno;
1150 return NULL;
fd4f5a56
DL
1151}
1152
33ad9f1a 1153/* move a processs to the cgroups specified by the membership */
4fb3cba5 1154static int lxc_cgroupfs_enter(struct cgroup_process_info *info, pid_t pid, bool enter_sub)
4f17323e 1155{
33ad9f1a
CS
1156 char pid_buf[32];
1157 char *cgroup_tasks_fn;
1158 int r;
1159 struct cgroup_process_info *info_ptr;
1160
1161 snprintf(pid_buf, 32, "%lu", (unsigned long)pid);
1162 for (info_ptr = info; info_ptr; info_ptr = info_ptr->next) {
1163 char *cgroup_path = (enter_sub && info_ptr->cgroup_path_sub) ?
1164 info_ptr->cgroup_path_sub :
1165 info_ptr->cgroup_path;
1166
1167 if (!info_ptr->designated_mount_point) {
1168 info_ptr->designated_mount_point = lxc_cgroup_find_mount_point(info_ptr->hierarchy, cgroup_path, true);
1169 if (!info_ptr->designated_mount_point) {
1170 SYSERROR("Could not add pid %lu to cgroup %s: internal error (couldn't find any writable mountpoint to cgroup filesystem)", (unsigned long)pid, cgroup_path);
1171 return -1;
1172 }
1173 }
4f17323e 1174
33ad9f1a
CS
1175 cgroup_tasks_fn = cgroup_to_absolute_path(info_ptr->designated_mount_point, cgroup_path, "/tasks");
1176 if (!cgroup_tasks_fn) {
1177 SYSERROR("Could not add pid %lu to cgroup %s: internal error", (unsigned long)pid, cgroup_path);
1178 return -1;
1179 }
4f17323e 1180
33ad9f1a 1181 r = lxc_write_to_file(cgroup_tasks_fn, pid_buf, strlen(pid_buf), false);
5903da82 1182 free(cgroup_tasks_fn);
33ad9f1a
CS
1183 if (r < 0) {
1184 SYSERROR("Could not add pid %lu to cgroup %s: internal error", (unsigned long)pid, cgroup_path);
1185 return -1;
1186 }
4f17323e
CS
1187 }
1188
33ad9f1a 1189 return 0;
4f17323e
CS
1190}
1191
33ad9f1a
CS
1192/* free process membership information */
1193void lxc_cgroup_process_info_free(struct cgroup_process_info *info)
fc7de561 1194{
33ad9f1a
CS
1195 struct cgroup_process_info *next;
1196 if (!info)
b98f7d6e 1197 return;
33ad9f1a
CS
1198 next = info->next;
1199 lxc_cgroup_put_meta(info->meta_ref);
1200 free(info->cgroup_path);
1201 free(info->cgroup_path_sub);
1202 lxc_free_array((void **)info->created_paths, free);
1203 free(info);
1204 lxc_cgroup_process_info_free(next);
fc7de561
SH
1205}
1206
33ad9f1a
CS
1207/* free process membership information and remove cgroups that were created */
1208void lxc_cgroup_process_info_free_and_remove(struct cgroup_process_info *info)
b98f7d6e 1209{
33ad9f1a
CS
1210 struct cgroup_process_info *next;
1211 char **pp;
1212 if (!info)
1213 return;
1214 next = info->next;
603c64c2 1215 {
33ad9f1a
CS
1216 struct cgroup_mount_point *mp = info->designated_mount_point;
1217 if (!mp)
1218 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
1219 if (mp)
1220 /* ignore return value here, perhaps we created the
1221 * '/lxc' cgroup in this container but another container
1222 * is still running (for example)
1223 */
603c64c2
SH
1224 (void)remove_cgroup(mp, info->cgroup_path, true);
1225 }
1226 for (pp = info->created_paths; pp && *pp; pp++);
1227 for ((void)(pp && --pp); info->created_paths && pp >= info->created_paths; --pp) {
33ad9f1a 1228 free(*pp);
b98f7d6e 1229 }
33ad9f1a
CS
1230 free(info->created_paths);
1231 lxc_cgroup_put_meta(info->meta_ref);
1232 free(info->cgroup_path);
1233 free(info->cgroup_path_sub);
1234 free(info);
9431aa65 1235 lxc_cgroup_process_info_free_and_remove(next);
33ad9f1a 1236}
b98f7d6e 1237
4fb3cba5 1238static char *lxc_cgroup_get_hierarchy_path_data(const char *subsystem, struct cgfs_data *d)
33ad9f1a 1239{
d4ef7c50
SH
1240 struct cgroup_process_info *info = d->info;
1241 info = find_info_for_subsystem(info, subsystem);
33ad9f1a
CS
1242 if (!info)
1243 return NULL;
f348e47c 1244 prune_init_scope(info->cgroup_path);
33ad9f1a 1245 return info->cgroup_path;
b98f7d6e
SH
1246}
1247
4fb3cba5 1248static char *lxc_cgroup_get_hierarchy_abs_path_data(const char *subsystem, struct cgfs_data *d)
b98f7d6e 1249{
d4ef7c50 1250 struct cgroup_process_info *info = d->info;
33ad9f1a 1251 struct cgroup_mount_point *mp = NULL;
d4ef7c50
SH
1252
1253 info = find_info_for_subsystem(info, subsystem);
33ad9f1a
CS
1254 if (!info)
1255 return NULL;
1256 if (info->designated_mount_point) {
8900b9eb 1257 mp = info->designated_mount_point;
33ad9f1a
CS
1258 } else {
1259 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
1260 if (!mp)
1261 return NULL;
b98f7d6e 1262 }
33ad9f1a 1263 return cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
b98f7d6e 1264}
55c76589 1265
4fb3cba5 1266static char *lxc_cgroup_get_hierarchy_abs_path(const char *subsystem, const char *name, const char *lxcpath)
9a93d992 1267{
33ad9f1a
CS
1268 struct cgroup_meta_data *meta;
1269 struct cgroup_process_info *base_info, *info;
1270 struct cgroup_mount_point *mp;
1271 char *result = NULL;
33ad9f1a
CS
1272
1273 meta = lxc_cgroup_load_meta();
1274 if (!meta)
9a93d992 1275 return NULL;
33ad9f1a
CS
1276 base_info = lxc_cgroup_get_container_info(name, lxcpath, meta);
1277 if (!base_info)
178938fe 1278 goto out1;
33ad9f1a
CS
1279 info = find_info_for_subsystem(base_info, subsystem);
1280 if (!info)
178938fe 1281 goto out2;
33ad9f1a 1282 if (info->designated_mount_point) {
8900b9eb 1283 mp = info->designated_mount_point;
33ad9f1a
CS
1284 } else {
1285 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
1286 if (!mp)
178938fe 1287 goto out3;
33ad9f1a
CS
1288 }
1289 result = cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
178938fe 1290out3:
178938fe 1291out2:
33ad9f1a 1292 lxc_cgroup_process_info_free(base_info);
178938fe 1293out1:
33ad9f1a 1294 lxc_cgroup_put_meta(meta);
33ad9f1a
CS
1295 return result;
1296}
9a93d992 1297
4fb3cba5 1298static int lxc_cgroup_set_data(const char *filename, const char *value, struct cgfs_data *d)
33ad9f1a
CS
1299{
1300 char *subsystem = NULL, *p, *path;
1301 int ret = -1;
9a93d992 1302
33ad9f1a
CS
1303 subsystem = alloca(strlen(filename) + 1);
1304 strcpy(subsystem, filename);
46cd2845 1305 if ((p = strchr(subsystem, '.')) != NULL)
33ad9f1a 1306 *p = '\0';
9a93d992 1307
4f875f70 1308 errno = ENOENT;
4fb3cba5 1309 path = lxc_cgroup_get_hierarchy_abs_path_data(subsystem, d);
33ad9f1a
CS
1310 if (path) {
1311 ret = do_cgroup_set(path, filename, value);
4f875f70 1312 int saved_errno = errno;
33ad9f1a 1313 free(path);
4f875f70 1314 errno = saved_errno;
9a93d992 1315 }
33ad9f1a
CS
1316 return ret;
1317}
9a93d992 1318
4fb3cba5 1319static int lxc_cgroupfs_set(const char *filename, const char *value, const char *name, const char *lxcpath)
9a93d992 1320{
33ad9f1a
CS
1321 char *subsystem = NULL, *p, *path;
1322 int ret = -1;
9a93d992 1323
33ad9f1a
CS
1324 subsystem = alloca(strlen(filename) + 1);
1325 strcpy(subsystem, filename);
46cd2845 1326 if ((p = strchr(subsystem, '.')) != NULL)
33ad9f1a 1327 *p = '\0';
9a93d992 1328
33ad9f1a
CS
1329 path = lxc_cgroup_get_hierarchy_abs_path(subsystem, name, lxcpath);
1330 if (path) {
1331 ret = do_cgroup_set(path, filename, value);
1332 free(path);
1333 }
b98f7d6e 1334 return ret;
9a93d992
SH
1335}
1336
4fb3cba5 1337static int lxc_cgroupfs_get(const char *filename, char *value, size_t len, const char *name, const char *lxcpath)
9a93d992 1338{
33ad9f1a
CS
1339 char *subsystem = NULL, *p, *path;
1340 int ret = -1;
1341
1342 subsystem = alloca(strlen(filename) + 1);
1343 strcpy(subsystem, filename);
46cd2845 1344 if ((p = strchr(subsystem, '.')) != NULL)
33ad9f1a
CS
1345 *p = '\0';
1346
1347 path = lxc_cgroup_get_hierarchy_abs_path(subsystem, name, lxcpath);
1348 if (path) {
1349 ret = do_cgroup_get(path, filename, value, len);
1350 free(path);
9a93d992 1351 }
33ad9f1a 1352 return ret;
9a93d992
SH
1353}
1354
4fb3cba5 1355static bool cgroupfs_mount_cgroup(void *hdata, const char *root, int type)
aae1f3c4
CS
1356{
1357 size_t bufsz = strlen(root) + sizeof("/sys/fs/cgroup");
1358 char *path = NULL;
1359 char **parts = NULL;
1360 char *dirname = NULL;
1361 char *abs_path = NULL;
1362 char *abs_path2 = NULL;
d4ef7c50
SH
1363 struct cgfs_data *cgfs_d;
1364 struct cgroup_process_info *info, *base_info;
aae1f3c4
CS
1365 int r, saved_errno = 0;
1366
4608594e
SH
1367 if (cgns_supported())
1368 return true;
1369
4fb3cba5
DE
1370 cgfs_d = hdata;
1371 if (!cgfs_d)
1372 return false;
d4ef7c50
SH
1373 base_info = cgfs_d->info;
1374
0769b82a
CS
1375 /* If we get passed the _NOSPEC types, we default to _MIXED, since we don't
1376 * have access to the lxc_conf object at this point. It really should be up
1377 * to the caller to fix this, but this doesn't really hurt.
1378 */
1379 if (type == LXC_AUTO_CGROUP_FULL_NOSPEC)
1380 type = LXC_AUTO_CGROUP_FULL_MIXED;
1381 else if (type == LXC_AUTO_CGROUP_NOSPEC)
1382 type = LXC_AUTO_CGROUP_MIXED;
1383
7997d7da
CS
1384 if (type < LXC_AUTO_CGROUP_RO || type > LXC_AUTO_CGROUP_FULL_MIXED) {
1385 ERROR("could not mount cgroups into container: invalid type specified internally");
1386 errno = EINVAL;
c476bdce 1387 return false;
7997d7da
CS
1388 }
1389
aae1f3c4
CS
1390 path = calloc(1, bufsz);
1391 if (!path)
c476bdce 1392 return false;
aae1f3c4 1393 snprintf(path, bufsz, "%s/sys/fs/cgroup", root);
592fd47a
SH
1394 r = safe_mount("cgroup_root", path, "tmpfs",
1395 MS_NOSUID|MS_NODEV|MS_NOEXEC|MS_RELATIME,
1396 "size=10240k,mode=755",
1397 root);
aae1f3c4
CS
1398 if (r < 0) {
1399 SYSERROR("could not mount tmpfs to /sys/fs/cgroup in the container");
c476bdce 1400 return false;
aae1f3c4
CS
1401 }
1402
1403 /* now mount all the hierarchies we care about */
1404 for (info = base_info; info; info = info->next) {
1405 size_t subsystem_count, i;
1406 struct cgroup_mount_point *mp = info->designated_mount_point;
d3f99e96 1407 if (!mountpoint_is_accessible(mp))
aae1f3c4 1408 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, true);
d3f99e96 1409
aae1f3c4
CS
1410 if (!mp) {
1411 SYSERROR("could not find original mount point for cgroup hierarchy while trying to mount cgroup filesystem");
1412 goto out_error;
1413 }
1414
1415 subsystem_count = lxc_array_len((void **)info->hierarchy->subsystems);
1416 parts = calloc(subsystem_count + 1, sizeof(char *));
1417 if (!parts)
1418 goto out_error;
1419
1420 for (i = 0; i < subsystem_count; i++) {
1421 if (!strncmp(info->hierarchy->subsystems[i], "name=", 5))
1422 parts[i] = info->hierarchy->subsystems[i] + 5;
1423 else
1424 parts[i] = info->hierarchy->subsystems[i];
1425 }
1426 dirname = lxc_string_join(",", (const char **)parts, false);
1427 if (!dirname)
1428 goto out_error;
1429
1430 /* create subsystem directory */
1431 abs_path = lxc_append_paths(path, dirname);
1432 if (!abs_path)
1433 goto out_error;
1434 r = mkdir_p(abs_path, 0755);
1435 if (r < 0 && errno != EEXIST) {
1436 SYSERROR("could not create cgroup subsystem directory /sys/fs/cgroup/%s", dirname);
1437 goto out_error;
1438 }
1439
aae1f3c4
CS
1440 abs_path2 = lxc_append_paths(abs_path, info->cgroup_path);
1441 if (!abs_path2)
1442 goto out_error;
aae1f3c4 1443
7997d7da
CS
1444 if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_RW || type == LXC_AUTO_CGROUP_FULL_MIXED) {
1445 /* bind-mount the cgroup entire filesystem there */
1446 if (strcmp(mp->mount_prefix, "/") != 0) {
1447 /* FIXME: maybe we should just try to remount the entire hierarchy
1448 * with a regular mount command? may that works? */
1449 ERROR("could not automatically mount cgroup-full to /sys/fs/cgroup/%s: host has no mount point for this cgroup filesystem that has access to the root cgroup", dirname);
1450 goto out_error;
1451 }
1452 r = mount(mp->mount_point, abs_path, "none", MS_BIND, 0);
1453 if (r < 0) {
1454 SYSERROR("error bind-mounting %s to %s", mp->mount_point, abs_path);
1455 goto out_error;
1456 }
f8f3c3c0
SG
1457 /* main cgroup path should be read-only */
1458 if (type == LXC_AUTO_CGROUP_FULL_RO || type == LXC_AUTO_CGROUP_FULL_MIXED) {
1459 r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1460 if (r < 0) {
1461 SYSERROR("error re-mounting %s readonly", abs_path);
1462 goto out_error;
1463 }
1464 }
7997d7da
CS
1465 /* own cgroup should be read-write */
1466 if (type == LXC_AUTO_CGROUP_FULL_MIXED) {
1467 r = mount(abs_path2, abs_path2, NULL, MS_BIND, NULL);
1468 if (r < 0) {
1469 SYSERROR("error bind-mounting %s onto itself", abs_path2);
1470 goto out_error;
1471 }
1472 r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND, NULL);
1473 if (r < 0) {
1474 SYSERROR("error re-mounting %s readwrite", abs_path2);
1475 goto out_error;
1476 }
1477 }
1478 } else {
1479 /* create path for container's cgroup */
1480 r = mkdir_p(abs_path2, 0755);
1481 if (r < 0 && errno != EEXIST) {
1482 SYSERROR("could not create cgroup directory /sys/fs/cgroup/%s%s", dirname, info->cgroup_path);
1483 goto out_error;
1484 }
aae1f3c4 1485
b46f0553
CS
1486 /* for read-only and mixed cases, we have to bind-mount the tmpfs directory
1487 * that points to the hierarchy itself (i.e. /sys/fs/cgroup/cpu etc.) onto
1488 * itself and then bind-mount it read-only, since we keep the tmpfs itself
1489 * read-write (see comment below)
1490 */
1491 if (type == LXC_AUTO_CGROUP_MIXED || type == LXC_AUTO_CGROUP_RO) {
1492 r = mount(abs_path, abs_path, NULL, MS_BIND, NULL);
1493 if (r < 0) {
1494 SYSERROR("error bind-mounting %s onto itself", abs_path);
1495 goto out_error;
1496 }
1497 r = mount(NULL, abs_path, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1498 if (r < 0) {
1499 SYSERROR("error re-mounting %s readonly", abs_path);
1500 goto out_error;
1501 }
1502 }
1503
7997d7da
CS
1504 free(abs_path);
1505 abs_path = NULL;
1506
1507 /* bind-mount container's cgroup to that directory */
1508 abs_path = cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
1509 if (!abs_path)
1510 goto out_error;
1511 r = mount(abs_path, abs_path2, "none", MS_BIND, 0);
1512 if (r < 0) {
1513 SYSERROR("error bind-mounting %s to %s", abs_path, abs_path2);
1514 goto out_error;
1515 }
1516 if (type == LXC_AUTO_CGROUP_RO) {
1517 r = mount(NULL, abs_path2, NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL);
1518 if (r < 0) {
1519 SYSERROR("error re-mounting %s readonly", abs_path2);
1520 goto out_error;
1521 }
1522 }
aae1f3c4
CS
1523 }
1524
1525 free(abs_path);
1526 free(abs_path2);
1527 abs_path = NULL;
1528 abs_path2 = NULL;
1529
1530 /* add symlinks for every single subsystem */
1531 if (subsystem_count > 1) {
1532 for (i = 0; i < subsystem_count; i++) {
1533 abs_path = lxc_append_paths(path, parts[i]);
1534 if (!abs_path)
1535 goto out_error;
1536 r = symlink(dirname, abs_path);
1537 if (r < 0)
1538 WARN("could not create symlink %s -> %s in /sys/fs/cgroup of container", parts[i], dirname);
1539 free(abs_path);
1540 abs_path = NULL;
1541 }
1542 }
1543 free(dirname);
1544 free(parts);
1545 dirname = NULL;
1546 parts = NULL;
1547 }
1548
b46f0553
CS
1549 /* We used to remount the entire tmpfs readonly if any :ro or
1550 * :mixed mode was specified. However, Ubuntu's mountall has the
1551 * unfortunate behavior to block bootup if /sys/fs/cgroup is
1552 * mounted read-only and cannot be remounted read-write.
1553 * (mountall reads /lib/init/fstab and tries to (re-)mount all of
1554 * these if they are not already mounted with the right options;
1555 * it contains an entry for /sys/fs/cgroup. In case it can't do
1556 * that, it prompts for the user to either manually fix it or
1557 * boot anyway. But without user input, booting of the container
1558 * hangs.)
1559 *
1560 * Instead of remounting the entire tmpfs readonly, we only
1561 * remount the paths readonly that are part of the cgroup
1562 * hierarchy.
f8f3c3c0 1563 */
f8f3c3c0 1564
aae1f3c4
CS
1565 free(path);
1566
c476bdce 1567 return true;
aae1f3c4
CS
1568
1569out_error:
1570 saved_errno = errno;
1571 free(path);
1572 free(dirname);
1573 free(parts);
1574 free(abs_path);
1575 free(abs_path2);
1576 errno = saved_errno;
c476bdce 1577 return false;
aae1f3c4
CS
1578}
1579
4fb3cba5 1580static int cgfs_nrtasks(void *hdata)
33ad9f1a 1581{
4fb3cba5
DE
1582 struct cgfs_data *d = hdata;
1583 struct cgroup_process_info *info;
33ad9f1a
CS
1584 struct cgroup_mount_point *mp = NULL;
1585 char *abs_path = NULL;
1586 int ret;
460a1cf0 1587
4fb3cba5
DE
1588 if (!d) {
1589 errno = ENOENT;
1590 return -1;
1591 }
1592
1593 info = d->info;
33ad9f1a
CS
1594 if (!info) {
1595 errno = ENOENT;
1596 return -1;
b98f7d6e 1597 }
c8f7c563 1598
33ad9f1a 1599 if (info->designated_mount_point) {
8900b9eb 1600 mp = info->designated_mount_point;
33ad9f1a
CS
1601 } else {
1602 mp = lxc_cgroup_find_mount_point(info->hierarchy, info->cgroup_path, false);
1603 if (!mp)
1604 return -1;
c8f7c563
CS
1605 }
1606
33ad9f1a
CS
1607 abs_path = cgroup_to_absolute_path(mp, info->cgroup_path, NULL);
1608 if (!abs_path)
1609 return -1;
1610
1611 ret = cgroup_recursive_task_count(abs_path);
1612 free(abs_path);
1613 return ret;
c8f7c563
CS
1614}
1615
574c4428
QH
1616static struct cgroup_process_info *
1617lxc_cgroup_process_info_getx(const char *proc_pid_cgroup_str,
1618 struct cgroup_meta_data *meta)
d08ba6ec 1619{
33ad9f1a
CS
1620 struct cgroup_process_info *result = NULL;
1621 FILE *proc_pid_cgroup = NULL;
1622 char *line = NULL;
1623 size_t sz = 0;
1624 int saved_errno = 0;
1625 struct cgroup_process_info **cptr = &result;
1626 struct cgroup_process_info *entry = NULL;
1627
1628 proc_pid_cgroup = fopen_cloexec(proc_pid_cgroup_str, "r");
1629 if (!proc_pid_cgroup)
b98f7d6e 1630 return NULL;
1ac470c0 1631
33ad9f1a
CS
1632 while (getline(&line, &sz, proc_pid_cgroup) != -1) {
1633 /* file format: hierarchy:subsystems:group */
1634 char *colon1;
1635 char *colon2;
1636 char *endptr;
1637 int hierarchy_number;
1638 struct cgroup_hierarchy *h = NULL;
fd4f5a56 1639
33ad9f1a 1640 if (!line[0])
ae5c8b8e 1641 continue;
b98f7d6e 1642
33ad9f1a
CS
1643 if (line[strlen(line) - 1] == '\n')
1644 line[strlen(line) - 1] = '\0';
1645
1646 colon1 = strchr(line, ':');
1647 if (!colon1)
8900b9eb 1648 continue;
33ad9f1a
CS
1649 *colon1++ = '\0';
1650 colon2 = strchr(colon1, ':');
1651 if (!colon2)
ae5c8b8e 1652 continue;
33ad9f1a 1653 *colon2++ = '\0';
e4659536 1654
33ad9f1a
CS
1655 endptr = NULL;
1656 hierarchy_number = strtoul(line, &endptr, 10);
1657 if (!endptr || *endptr)
9a93d992 1658 continue;
9a93d992 1659
33ad9f1a
CS
1660 if (hierarchy_number > meta->maximum_hierarchy) {
1661 /* we encountered a hierarchy we didn't have before,
1662 * so probably somebody remounted some stuff in the
1663 * mean time...
1664 */
1665 errno = EAGAIN;
1666 goto out_error;
b98f7d6e 1667 }
33ad9f1a
CS
1668
1669 h = meta->hierarchies[hierarchy_number];
1670 if (!h) {
1671 /* we encountered a hierarchy that was thought to be
1672 * dead before, so probably somebody remounted some
1673 * stuff in the mean time...
1674 */
1675 errno = EAGAIN;
1676 goto out_error;
b98f7d6e 1677 }
33ad9f1a
CS
1678
1679 /* we are told that we should ignore this hierarchy */
1680 if (!h->used)
b98f7d6e 1681 continue;
5193cc3d 1682
33ad9f1a
CS
1683 entry = calloc(1, sizeof(struct cgroup_process_info));
1684 if (!entry)
1685 goto out_error;
fd4f5a56 1686
33ad9f1a
CS
1687 entry->meta_ref = lxc_cgroup_get_meta(meta);
1688 entry->hierarchy = h;
1689 entry->cgroup_path = strdup(colon2);
1690 if (!entry->cgroup_path)
1691 goto out_error;
3939a22a 1692 prune_init_scope(entry->cgroup_path);
d08ba6ec 1693
33ad9f1a
CS
1694 *cptr = entry;
1695 cptr = &entry->next;
1696 entry = NULL;
b98f7d6e 1697 }
b98f7d6e 1698
33ad9f1a
CS
1699 fclose(proc_pid_cgroup);
1700 free(line);
1701 return result;
1702
1703out_error:
1704 saved_errno = errno;
1705 if (proc_pid_cgroup)
1706 fclose(proc_pid_cgroup);
1707 lxc_cgroup_process_info_free(result);
1708 lxc_cgroup_process_info_free(entry);
1709 free(line);
1710 errno = saved_errno;
ae5c8b8e 1711 return NULL;
36b86299
DL
1712}
1713
574c4428
QH
1714static char **subsystems_from_mount_options(const char *mount_options,
1715 char **kernel_list)
36b86299 1716{
33ad9f1a
CS
1717 char *token, *str, *saveptr = NULL;
1718 char **result = NULL;
1719 size_t result_capacity = 0;
8900b9eb 1720 size_t result_count = 0;
33ad9f1a
CS
1721 int saved_errno;
1722 int r;
ef342abb 1723
33ad9f1a
CS
1724 str = alloca(strlen(mount_options)+1);
1725 strcpy(str, mount_options);
1726 for (; (token = strtok_r(str, ",", &saveptr)); str = NULL) {
1727 /* we have a subsystem if it's either in the list of
1728 * subsystems provided by the kernel OR if it starts
1729 * with name= for named hierarchies
1730 */
836514a8
U
1731 r = lxc_grow_array((void ***)&result, &result_capacity, result_count + 1, 12);
1732 if (r < 0)
1733 goto out_free;
1734 result[result_count + 1] = NULL;
1735 if (strncmp(token, "name=", 5) && !lxc_string_in_array(token, (const char **)kernel_list)) {
1736 // this is eg 'systemd' but the mount will be 'name=systemd'
1737 result[result_count] = malloc(strlen(token) + 6);
1738 if (result[result_count])
1739 sprintf(result[result_count], "name=%s", token);
1740 } else
33ad9f1a 1741 result[result_count] = strdup(token);
836514a8
U
1742 if (!result[result_count])
1743 goto out_free;
1744 result_count++;
ae5c8b8e 1745 }
f0e64b8b 1746
33ad9f1a
CS
1747 return result;
1748
1749out_free:
1750 saved_errno = errno;
1751 lxc_free_array((void**)result, free);
1752 errno = saved_errno;
1753 return NULL;
b98f7d6e
SH
1754}
1755
574c4428 1756static void lxc_cgroup_mount_point_free(struct cgroup_mount_point *mp)
b98f7d6e 1757{
33ad9f1a
CS
1758 if (!mp)
1759 return;
1760 free(mp->mount_point);
1761 free(mp->mount_prefix);
1762 free(mp);
bcbd102c
SH
1763}
1764
574c4428 1765static void lxc_cgroup_hierarchy_free(struct cgroup_hierarchy *h)
341a9bd8 1766{
33ad9f1a
CS
1767 if (!h)
1768 return;
1769 lxc_free_array((void **)h->subsystems, free);
8bfcb981 1770 free(h->all_mount_points);
33ad9f1a
CS
1771 free(h);
1772}
341a9bd8 1773
574c4428 1774static bool is_valid_cgroup(const char *name)
33ad9f1a
CS
1775{
1776 const char *p;
1777 for (p = name; *p; p++) {
28bb9321
QH
1778 /* Use the ASCII printable characters range(32 - 127)
1779 * is reasonable, we kick out 32(SPACE) because it'll
1780 * break legacy lxc-ls
1781 */
1782 if (*p <= 32 || *p >= 127 || *p == '/')
33ad9f1a 1783 return false;
341a9bd8 1784 }
33ad9f1a
CS
1785 return strcmp(name, ".") != 0 && strcmp(name, "..") != 0;
1786}
341a9bd8 1787
574c4428
QH
1788static int create_or_remove_cgroup(bool do_remove,
1789 struct cgroup_mount_point *mp, const char *path, int recurse)
33ad9f1a
CS
1790{
1791 int r, saved_errno = 0;
1792 char *buf = cgroup_to_absolute_path(mp, path, NULL);
1793 if (!buf)
1794 return -1;
341a9bd8 1795
33ad9f1a 1796 /* create or remove directory */
603c64c2
SH
1797 if (do_remove) {
1798 if (recurse)
1799 r = cgroup_rmdir(buf);
1800 else
1801 r = rmdir(buf);
1802 } else
1803 r = mkdir(buf, 0777);
33ad9f1a
CS
1804 saved_errno = errno;
1805 free(buf);
1806 errno = saved_errno;
1807 return r;
341a9bd8 1808}
bcbd102c 1809
574c4428 1810static int create_cgroup(struct cgroup_mount_point *mp, const char *path)
a6ddef61 1811{
603c64c2 1812 return create_or_remove_cgroup(false, mp, path, false);
a6ddef61
MN
1813}
1814
574c4428
QH
1815static int remove_cgroup(struct cgroup_mount_point *mp,
1816 const char *path, bool recurse)
576f946d 1817{
603c64c2 1818 return create_or_remove_cgroup(true, mp, path, recurse);
33ad9f1a 1819}
576f946d 1820
574c4428
QH
1821static char *cgroup_to_absolute_path(struct cgroup_mount_point *mp,
1822 const char *path, const char *suffix)
33ad9f1a
CS
1823{
1824 /* first we have to make sure we subtract the mount point's prefix */
1825 char *prefix = mp->mount_prefix;
1826 char *buf;
1827 ssize_t len, rv;
1828
1829 /* we want to make sure only absolute paths to cgroups are passed to us */
1830 if (path[0] != '/') {
1831 errno = EINVAL;
1832 return NULL;
1833 }
b98f7d6e 1834
33ad9f1a
CS
1835 if (prefix && !strcmp(prefix, "/"))
1836 prefix = NULL;
b98f7d6e 1837
33ad9f1a
CS
1838 /* prefix doesn't match */
1839 if (prefix && strncmp(prefix, path, strlen(prefix)) != 0) {
1840 errno = EINVAL;
1841 return NULL;
1842 }
1843 /* if prefix is /foo and path is /foobar */
1844 if (prefix && path[strlen(prefix)] != '/' && path[strlen(prefix)] != '\0') {
1845 errno = EINVAL;
1846 return NULL;
1847 }
b98f7d6e 1848
33ad9f1a
CS
1849 /* remove prefix from path */
1850 path += prefix ? strlen(prefix) : 0;
b98f7d6e 1851
33ad9f1a
CS
1852 len = strlen(mp->mount_point) + strlen(path) + (suffix ? strlen(suffix) : 0);
1853 buf = calloc(len + 1, 1);
50266dc6
DE
1854 if (!buf)
1855 return NULL;
33ad9f1a 1856 rv = snprintf(buf, len + 1, "%s%s%s", mp->mount_point, path, suffix ? suffix : "");
8900b9eb 1857 if (rv > len) {
33ad9f1a
CS
1858 free(buf);
1859 errno = ENOMEM;
8900b9eb 1860 return NULL;
8b92dc3a 1861 }
576f946d 1862
33ad9f1a 1863 return buf;
e0f888d9 1864}
283678ed 1865
574c4428
QH
1866static struct cgroup_process_info *
1867find_info_for_subsystem(struct cgroup_process_info *info, const char *subsystem)
283678ed 1868{
33ad9f1a
CS
1869 struct cgroup_process_info *info_ptr;
1870 for (info_ptr = info; info_ptr; info_ptr = info_ptr->next) {
1871 struct cgroup_hierarchy *h = info_ptr->hierarchy;
1872 if (lxc_string_in_array(subsystem, (const char **)h->subsystems))
1873 return info_ptr;
b98f7d6e 1874 }
33ad9f1a
CS
1875 errno = ENOENT;
1876 return NULL;
1877}
283678ed 1878
574c4428
QH
1879static int do_cgroup_get(const char *cgroup_path, const char *sub_filename,
1880 char *value, size_t len)
33ad9f1a
CS
1881{
1882 const char *parts[3] = {
1883 cgroup_path,
1884 sub_filename,
1885 NULL
1886 };
1887 char *filename;
1888 int ret, saved_errno;
1889
1890 filename = lxc_string_join("/", parts, false);
1891 if (!filename)
1892 return -1;
1893
1894 ret = lxc_read_from_file(filename, value, len);
1895 saved_errno = errno;
1896 free(filename);
1897 errno = saved_errno;
1898 return ret;
283678ed 1899}
b113383b 1900
574c4428
QH
1901static int do_cgroup_set(const char *cgroup_path, const char *sub_filename,
1902 const char *value)
b113383b 1903{
33ad9f1a
CS
1904 const char *parts[3] = {
1905 cgroup_path,
1906 sub_filename,
1907 NULL
1908 };
1909 char *filename;
1910 int ret, saved_errno;
b113383b 1911
33ad9f1a
CS
1912 filename = lxc_string_join("/", parts, false);
1913 if (!filename)
1914 return -1;
b113383b 1915
33ad9f1a
CS
1916 ret = lxc_write_to_file(filename, value, strlen(value), false);
1917 saved_errno = errno;
1918 free(filename);
1919 errno = saved_errno;
1920 return ret;
b98f7d6e
SH
1921}
1922
4fb3cba5 1923static int do_setup_cgroup_limits(struct cgfs_data *d,
574c4428 1924 struct lxc_list *cgroup_settings, bool do_devices)
b98f7d6e 1925{
365d180a 1926 struct lxc_list *iterator, *sorted_cgroup_settings, *next;
b98f7d6e
SH
1927 struct lxc_cgroup *cg;
1928 int ret = -1;
1929
33ad9f1a 1930 if (lxc_list_empty(cgroup_settings))
b98f7d6e
SH
1931 return 0;
1932
aaf26830 1933 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
fac7c663
KT
1934 if (!sorted_cgroup_settings) {
1935 return -1;
1936 }
aaf26830
KT
1937
1938 lxc_list_for_each(iterator, sorted_cgroup_settings) {
b98f7d6e
SH
1939 cg = iterator->elem;
1940
33ad9f1a 1941 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
b98f7d6e 1942 if (strcmp(cg->subsystem, "devices.deny") == 0 &&
4fb3cba5 1943 cgroup_devices_has_allow_or_deny(d, cg->value, false))
b98f7d6e
SH
1944 continue;
1945 if (strcmp(cg->subsystem, "devices.allow") == 0 &&
4fb3cba5 1946 cgroup_devices_has_allow_or_deny(d, cg->value, true))
b98f7d6e 1947 continue;
4fb3cba5 1948 if (lxc_cgroup_set_data(cg->subsystem, cg->value, d)) {
dddf7c5b 1949 if (do_devices && (errno == EACCES || errno == EPERM)) {
4f875f70
SH
1950 WARN("Error setting %s to %s for %s",
1951 cg->subsystem, cg->value, d->name);
1952 continue;
1953 }
dddf7c5b 1954 SYSERROR("Error setting %s to %s for %s",
4fb3cba5 1955 cg->subsystem, cg->value, d->name);
b98f7d6e
SH
1956 goto out;
1957 }
b113383b 1958 }
b98f7d6e
SH
1959
1960 DEBUG("cgroup '%s' set to '%s'", cg->subsystem, cg->value);
b113383b
SH
1961 }
1962
b98f7d6e
SH
1963 ret = 0;
1964 INFO("cgroup has been setup");
1965out:
365d180a 1966 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
aaf26830
KT
1967 lxc_list_del(iterator);
1968 free(iterator);
1969 }
365d180a 1970 free(sorted_cgroup_settings);
b113383b
SH
1971 return ret;
1972}
b98f7d6e 1973
4fb3cba5 1974static bool cgroup_devices_has_allow_or_deny(struct cgfs_data *d,
574c4428 1975 char *v, bool for_allow)
33ad9f1a
CS
1976{
1977 char *path;
1978 FILE *devices_list;
8900b9eb 1979 char *line = NULL;
33ad9f1a
CS
1980 size_t sz = 0;
1981 bool ret = !for_allow;
1982 const char *parts[3] = {
1983 NULL,
1984 "devices.list",
1985 NULL
1986 };
1987
1988 // XXX FIXME if users could use something other than 'lxc.devices.deny = a'.
1989 // not sure they ever do, but they *could*
1990 // right now, I'm assuming they do NOT
1991 if (!for_allow && strcmp(v, "a") != 0 && strcmp(v, "a *:* rwm") != 0)
1992 return false;
1993
4fb3cba5 1994 parts[0] = (const char *)lxc_cgroup_get_hierarchy_abs_path_data("devices", d);
33ad9f1a
CS
1995 if (!parts[0])
1996 return false;
1997 path = lxc_string_join("/", parts, false);
1998 if (!path) {
1999 free((void *)parts[0]);
2000 return false;
2001 }
2002
2003 devices_list = fopen_cloexec(path, "r");
2004 if (!devices_list) {
2005 free(path);
2006 return false;
2007 }
2008
2009 while (getline(&line, &sz, devices_list) != -1) {
2010 size_t len = strlen(line);
2011 if (len > 0 && line[len-1] == '\n')
2012 line[len-1] = '\0';
2013 if (strcmp(line, "a *:* rwm") == 0) {
2014 ret = for_allow;
2015 goto out;
2016 } else if (for_allow && strcmp(line, v) == 0) {
2017 ret = true;
8900b9eb 2018 goto out;
33ad9f1a
CS
2019 }
2020 }
2021
2022out:
2023 fclose(devices_list);
2024 free(line);
2025 free(path);
2026 return ret;
2027}
2028
574c4428 2029static int cgroup_recursive_task_count(const char *cgroup_path)
b98f7d6e 2030{
33ad9f1a
CS
2031 DIR *d;
2032 struct dirent *dent_buf;
2033 struct dirent *dent;
8900b9eb 2034 ssize_t name_max;
33ad9f1a
CS
2035 int n = 0, r;
2036
2037 /* see man readdir_r(3) */
2038 name_max = pathconf(cgroup_path, _PC_NAME_MAX);
2039 if (name_max <= 0)
2040 name_max = 255;
2041 dent_buf = malloc(offsetof(struct dirent, d_name) + name_max + 1);
2042 if (!dent_buf)
2043 return -1;
2044
2045 d = opendir(cgroup_path);
034ef75d
SH
2046 if (!d) {
2047 free(dent_buf);
33ad9f1a 2048 return 0;
034ef75d 2049 }
33ad9f1a
CS
2050
2051 while (readdir_r(d, dent_buf, &dent) == 0 && dent) {
2052 const char *parts[3] = {
2053 cgroup_path,
2054 dent->d_name,
2055 NULL
2056 };
2057 char *sub_path;
2058 struct stat st;
2059
2060 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
2061 continue;
2062 sub_path = lxc_string_join("/", parts, false);
2063 if (!sub_path) {
2064 closedir(d);
2065 free(dent_buf);
2066 return -1;
2067 }
2068 r = stat(sub_path, &st);
2069 if (r < 0) {
2070 closedir(d);
2071 free(dent_buf);
2072 free(sub_path);
2073 return -1;
2074 }
2075 if (S_ISDIR(st.st_mode)) {
2076 r = cgroup_recursive_task_count(sub_path);
2077 if (r >= 0)
2078 n += r;
2079 } else if (!strcmp(dent->d_name, "tasks")) {
2080 r = count_lines(sub_path);
2081 if (r >= 0)
2082 n += r;
2083 }
2084 free(sub_path);
2085 }
2086 closedir(d);
2087 free(dent_buf);
2088
2089 return n;
2090}
2091
574c4428 2092static int count_lines(const char *fn)
33ad9f1a
CS
2093{
2094 FILE *f;
2095 char *line = NULL;
2096 size_t sz = 0;
2097 int n = 0;
2098
2099 f = fopen_cloexec(fn, "r");
2100 if (!f)
2101 return -1;
2102
2103 while (getline(&line, &sz, f) != -1) {
2104 n++;
2105 }
2106 free(line);
2107 fclose(f);
2108 return n;
b98f7d6e
SH
2109}
2110
574c4428
QH
2111static int handle_cgroup_settings(struct cgroup_mount_point *mp,
2112 char *cgroup_path)
b98f7d6e 2113{
33ad9f1a 2114 int r, saved_errno = 0;
7e7243e1 2115 char buf[2];
1ea59ad2 2116
934b1673
SH
2117 mp->need_cpuset_init = false;
2118
1ea59ad2
SH
2119 /* If this is the memory cgroup, we want to enforce hierarchy.
2120 * But don't fail if for some reason we can't.
2121 */
2edb53c7
SH
2122 if (lxc_string_in_array("memory", (const char **)mp->hierarchy->subsystems)) {
2123 char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/memory.use_hierarchy");
2124 if (cc_path) {
2125 r = lxc_read_from_file(cc_path, buf, 1);
2126 if (r < 1 || buf[0] != '1') {
2127 r = lxc_write_to_file(cc_path, "1", 1, false);
2128 if (r < 0)
a8916143 2129 SYSERROR("failed to set memory.use_hierarchy to 1; continuing");
2edb53c7 2130 }
1ea59ad2
SH
2131 free(cc_path);
2132 }
2edb53c7 2133 }
1ea59ad2 2134
33ad9f1a
CS
2135 /* if this is a cpuset hierarchy, we have to set cgroup.clone_children in
2136 * the base cgroup, otherwise containers will start with an empty cpuset.mems
2137 * and cpuset.cpus and then
2138 */
2edb53c7
SH
2139 if (lxc_string_in_array("cpuset", (const char **)mp->hierarchy->subsystems)) {
2140 char *cc_path = cgroup_to_absolute_path(mp, cgroup_path, "/cgroup.clone_children");
d703c2b1
RV
2141 struct stat sb;
2142
33ad9f1a 2143 if (!cc_path)
2edb53c7 2144 return -1;
d703c2b1
RV
2145 /* cgroup.clone_children is not available when running under
2146 * older kernel versions; in this case, we'll initialize
2147 * cpuset.cpus and cpuset.mems later, after the new cgroup
2148 * was created
2149 */
2150 if (stat(cc_path, &sb) != 0 && errno == ENOENT) {
934b1673 2151 mp->need_cpuset_init = true;
d703c2b1
RV
2152 free(cc_path);
2153 return 0;
2154 }
7e7243e1
SH
2155 r = lxc_read_from_file(cc_path, buf, 1);
2156 if (r == 1 && buf[0] == '1') {
2157 free(cc_path);
2edb53c7 2158 return 0;
7e7243e1 2159 }
33ad9f1a 2160 r = lxc_write_to_file(cc_path, "1", 1, false);
2edb53c7
SH
2161 saved_errno = errno;
2162 free(cc_path);
2163 errno = saved_errno;
2164 return r < 0 ? -1 : 0;
33ad9f1a
CS
2165 }
2166 return 0;
b98f7d6e 2167}
484ed030 2168
934b1673 2169static int cgroup_read_from_file(const char *fn, char buf[], size_t bufsize)
d703c2b1
RV
2170{
2171 int ret = lxc_read_from_file(fn, buf, bufsize);
2172 if (ret < 0) {
2173 SYSERROR("failed to read %s", fn);
934b1673 2174 return ret;
d703c2b1
RV
2175 }
2176 if (ret == bufsize) {
934b1673
SH
2177 if (bufsize > 0) {
2178 /* obviously this wasn't empty */
2179 buf[bufsize-1] = '\0';
2180 return ret;
2181 }
2182 /* Callers don't do this, but regression/sanity check */
2183 ERROR("%s: was not expecting 0 bufsize", __func__);
2184 return -1;
d703c2b1
RV
2185 }
2186 buf[ret] = '\0';
934b1673 2187 return ret;
d703c2b1
RV
2188}
2189
2190static bool do_init_cpuset_file(struct cgroup_mount_point *mp,
2191 const char *path, const char *name)
2192{
934b1673
SH
2193 char value[1024];
2194 char *childfile, *parentfile = NULL, *tmp;
2195 int ret;
2196 bool ok = false;
2197
d703c2b1
RV
2198 childfile = cgroup_to_absolute_path(mp, path, name);
2199 if (!childfile)
2200 return false;
2201
2202 /* don't overwrite a non-empty value in the file */
934b1673
SH
2203 ret = cgroup_read_from_file(childfile, value, sizeof(value));
2204 if (ret < 0)
2205 goto out;
d703c2b1 2206 if (value[0] != '\0' && value[0] != '\n') {
934b1673
SH
2207 ok = true;
2208 goto out;
d703c2b1
RV
2209 }
2210
2211 /* path to the same name in the parent cgroup */
2212 parentfile = strdup(path);
2213 if (!parentfile)
934b1673
SH
2214 goto out;
2215
d703c2b1 2216 tmp = strrchr(parentfile, '/');
934b1673
SH
2217 if (!tmp)
2218 goto out;
d703c2b1
RV
2219 if (tmp == parentfile)
2220 tmp++; /* keep the '/' at the start */
2221 *tmp = '\0';
2222 tmp = parentfile;
2223 parentfile = cgroup_to_absolute_path(mp, tmp, name);
2224 free(tmp);
934b1673
SH
2225 if (!parentfile)
2226 goto out;
d703c2b1
RV
2227
2228 /* copy from parent to child cgroup */
934b1673
SH
2229 ret = cgroup_read_from_file(parentfile, value, sizeof(value));
2230 if (ret < 0)
2231 goto out;
2232 if (ret == sizeof(value)) {
2233 /* If anyone actually sees this error, we can address it */
2234 ERROR("parent cpuset value too long");
2235 goto out;
d703c2b1
RV
2236 }
2237 ok = (lxc_write_to_file(childfile, value, strlen(value), false) >= 0);
2238 if (!ok)
2239 SYSERROR("failed writing %s", childfile);
b1dad6f6
RV
2240
2241out:
f10fad2f 2242 free(parentfile);
d703c2b1 2243 free(childfile);
d703c2b1
RV
2244 return ok;
2245}
2246
2247static bool init_cpuset_if_needed(struct cgroup_mount_point *mp,
2248 const char *path)
2249{
2250 /* the files we have to handle here are only in cpuset hierarchies */
2251 if (!lxc_string_in_array("cpuset",
2252 (const char **)mp->hierarchy->subsystems))
2253 return true;
2254
b1dad6f6
RV
2255 if (!mp->need_cpuset_init)
2256 return true;
2257
d703c2b1
RV
2258 return (do_init_cpuset_file(mp, path, "/cpuset.cpus") &&
2259 do_init_cpuset_file(mp, path, "/cpuset.mems") );
2260}
2261
4fb3cba5 2262struct cgroup_ops *cgfs_ops_init(void)
484ed030 2263{
4fb3cba5 2264 return &cgfs_ops;
d4ef7c50 2265}
484ed030 2266
4fb3cba5 2267static void *cgfs_init(const char *name)
d4ef7c50 2268{
4fb3cba5 2269 struct cgfs_data *d;
484ed030 2270
4fb3cba5
DE
2271 d = malloc(sizeof(*d));
2272 if (!d)
2273 return NULL;
484ed030 2274
4fb3cba5
DE
2275 memset(d, 0, sizeof(*d));
2276 d->name = strdup(name);
2277 if (!d->name)
2278 goto err1;
2279
5e1c5795 2280 d->cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern");
4fb3cba5
DE
2281
2282 d->meta = lxc_cgroup_load_meta();
2283 if (!d->meta) {
2284 ERROR("cgroupfs failed to detect cgroup metadata");
2285 goto err2;
2286 }
2287 return d;
2288
2289err2:
2290 free(d->name);
2291err1:
2292 free(d);
2293 return NULL;
d4ef7c50 2294}
484ed030 2295
4fb3cba5 2296static void cgfs_destroy(void *hdata)
d4ef7c50 2297{
4fb3cba5
DE
2298 struct cgfs_data *d = hdata;
2299
d4ef7c50
SH
2300 if (!d)
2301 return;
f10fad2f 2302 free(d->name);
c55d4505
ME
2303 lxc_cgroup_process_info_free_and_remove(d->info);
2304 lxc_cgroup_put_meta(d->meta);
d4ef7c50 2305 free(d);
d4ef7c50 2306}
484ed030 2307
4fb3cba5 2308static inline bool cgfs_create(void *hdata)
d4ef7c50 2309{
4fb3cba5
DE
2310 struct cgfs_data *d = hdata;
2311 struct cgroup_process_info *i;
2312 struct cgroup_meta_data *md;
484ed030 2313
4fb3cba5 2314 if (!d)
d4ef7c50 2315 return false;
4fb3cba5
DE
2316 md = d->meta;
2317 i = lxc_cgroupfs_create(d->name, d->cgroup_pattern, md, NULL);
d4ef7c50
SH
2318 if (!i)
2319 return false;
2320 d->info = i;
2321 return true;
2322}
484ed030 2323
4fb3cba5 2324static inline bool cgfs_enter(void *hdata, pid_t pid)
d4ef7c50 2325{
4fb3cba5
DE
2326 struct cgfs_data *d = hdata;
2327 struct cgroup_process_info *i;
d4ef7c50 2328 int ret;
4fb3cba5
DE
2329
2330 if (!d)
2331 return false;
2332 i = d->info;
2333 ret = lxc_cgroupfs_enter(i, pid, false);
484ed030 2334
d4ef7c50
SH
2335 return ret == 0;
2336}
2337
4fb3cba5 2338static inline bool cgfs_create_legacy(void *hdata, pid_t pid)
d4ef7c50 2339{
4fb3cba5
DE
2340 struct cgfs_data *d = hdata;
2341 struct cgroup_process_info *i;
2342
2343 if (!d)
2344 return false;
2345 i = d->info;
2346 if (lxc_cgroup_create_legacy(i, d->name, pid) < 0) {
2347 ERROR("failed to create legacy ns cgroups for '%s'", d->name);
d4ef7c50 2348 return false;
484ed030 2349 }
d4ef7c50
SH
2350 return true;
2351}
484ed030 2352
4fb3cba5 2353static const char *cgfs_get_cgroup(void *hdata, const char *subsystem)
d4ef7c50 2354{
4fb3cba5
DE
2355 struct cgfs_data *d = hdata;
2356
2357 if (!d)
2358 return NULL;
2359 return lxc_cgroup_get_hierarchy_path_data(subsystem, d);
484ed030
SH
2360}
2361
2ba7a429
TA
2362static const char *cgfs_canonical_path(void *hdata)
2363{
2364 struct cgfs_data *d = hdata;
2365 struct cgroup_process_info *info_ptr;
2366 char *path = NULL;
2367
2368 if (!d)
2369 return NULL;
2370
2371 for (info_ptr = d->info; info_ptr; info_ptr = info_ptr->next) {
2372 if (!path)
2373 path = info_ptr->cgroup_path;
2374 else if (strcmp(path, info_ptr->cgroup_path) != 0) {
2375 ERROR("not all paths match %s, %s has path %s", path,
2376 info_ptr->hierarchy->subsystems[0], info_ptr->cgroup_path);
2377 return NULL;
2378 }
2379 }
2380
2381 return path;
2382}
2383
06078509
TA
2384static bool cgfs_escape(void)
2385{
2386 struct cgroup_meta_data *md;
2387 int i;
2388 bool ret = false;
2389
2390 md = lxc_cgroup_load_meta();
2391 if (!md)
2392 return false;
2393
2394 for (i = 1; i <= md->maximum_hierarchy; i++) {
2395 struct cgroup_hierarchy *h = md->hierarchies[i];
2396 struct cgroup_mount_point *mp;
2397 char *tasks;
2398 FILE *f;
2399 int written;
2400
2401 if (!h) {
2402 WARN("not escaping hierarchy %d", i);
2403 continue;
2404 }
2405
2406 mp = lxc_cgroup_find_mount_point(h, "/", true);
2407 if (!mp)
2408 goto out;
2409
2410 tasks = cgroup_to_absolute_path(mp, "/", "tasks");
2411 if (!tasks)
2412 goto out;
2413
2414 f = fopen(tasks, "a");
2415 free(tasks);
2416 if (!f)
2417 goto out;
2418
2419 written = fprintf(f, "%d\n", getpid());
2420 fclose(f);
2421 if (written < 0) {
2422 SYSERROR("writing tasks failed\n");
2423 goto out;
2424 }
2425 }
2426
2427 ret = true;
2428out:
2429 lxc_cgroup_put_meta(md);
2430 return ret;
2431}
2432
4fb3cba5 2433static bool cgfs_unfreeze(void *hdata)
0086f499 2434{
4fb3cba5 2435 struct cgfs_data *d = hdata;
0086f499
SH
2436 char *cgabspath, *cgrelpath;
2437 int ret;
2438
4fb3cba5
DE
2439 if (!d)
2440 return false;
2441
2442 cgrelpath = lxc_cgroup_get_hierarchy_path_data("freezer", d);
0086f499
SH
2443 cgabspath = lxc_cgroup_find_abs_path("freezer", cgrelpath, true, NULL);
2444 if (!cgabspath)
ecfcb3f0 2445 return false;
0086f499
SH
2446
2447 ret = do_cgroup_set(cgabspath, "freezer.state", "THAWED");
2448 free(cgabspath);
ecfcb3f0 2449 return ret == 0;
0086f499
SH
2450}
2451
4fb3cba5
DE
2452static bool cgroupfs_setup_limits(void *hdata, struct lxc_list *cgroup_conf,
2453 bool with_devices)
9daf6f5d 2454{
4fb3cba5
DE
2455 struct cgfs_data *d = hdata;
2456
2457 if (!d)
2458 return false;
2459 return do_setup_cgroup_limits(d, cgroup_conf, with_devices) == 0;
9daf6f5d
SH
2460}
2461
4fb3cba5 2462static bool lxc_cgroupfs_attach(const char *name, const char *lxcpath, pid_t pid)
5d897655
SH
2463{
2464 struct cgroup_meta_data *meta_data;
2465 struct cgroup_process_info *container_info;
2466 int ret;
2467
2468 meta_data = lxc_cgroup_load_meta();
2469 if (!meta_data) {
2470 ERROR("could not move attached process %d to cgroup of container", pid);
2471 return false;
2472 }
2473
2474 container_info = lxc_cgroup_get_container_info(name, lxcpath, meta_data);
2475 lxc_cgroup_put_meta(meta_data);
2476 if (!container_info) {
2477 ERROR("could not move attached process %d to cgroup of container", pid);
2478 return false;
2479 }
2480
2481 ret = lxc_cgroupfs_enter(container_info, pid, false);
2482 lxc_cgroup_process_info_free(container_info);
2483 if (ret < 0) {
2484 ERROR("could not move attached process %d to cgroup of container", pid);
2485 return false;
2486 }
2487 return true;
2488}
2489
8b276860
SH
2490struct chown_data {
2491 const char *cgroup_path;
2492 uid_t origuid;
2493};
2494
2495/*
2496 * TODO - someone should refactor this to unshare once passing all the paths
2497 * to be chowned in one go
2498 */
2499static int chown_cgroup_wrapper(void *data)
2500{
2501 struct chown_data *arg = data;
2502 uid_t destuid;
2503 char *fpath;
2504
2505
2506 if (setresgid(0,0,0) < 0)
2507 SYSERROR("Failed to setgid to 0");
2508 if (setresuid(0,0,0) < 0)
2509 SYSERROR("Failed to setuid to 0");
2510 if (setgroups(0, NULL) < 0)
2511 SYSERROR("Failed to clear groups");
2512 destuid = get_ns_uid(arg->origuid);
2513
2514 if (chown(arg->cgroup_path, destuid, 0) < 0)
2515 SYSERROR("Failed chowning %s to %d", arg->cgroup_path, (int)destuid);
2516
2517 fpath = lxc_append_paths(arg->cgroup_path, "tasks");
2518 if (!fpath)
2519 return -1;
2520 if (chown(fpath, destuid, 0) < 0)
2521 SYSERROR("Error chowning %s\n", fpath);
2522 free(fpath);
2523 fpath = lxc_append_paths(arg->cgroup_path, "cgroup.procs");
2524 if (!fpath)
2525 return -1;
2526 if (chown(fpath, destuid, 0) < 0)
2527 SYSERROR("Error chowning %s", fpath);
2528 free(fpath);
2529
2530 return 0;
2531}
2532
2533static bool do_cgfs_chown(char *cgroup_path, struct lxc_conf *conf)
2534{
2535 struct chown_data data;
2536 char *fpath;
2537
2538 if (lxc_list_empty(&conf->id_map))
2539 /* If there's no mapping then we don't need to chown */
2540 return true;
2541
2542 data.cgroup_path = cgroup_path;
2543 data.origuid = geteuid();
2544
2545 /* Unpriv users can't chown it themselves, so chown from
2546 * a child namespace mapping both our own and the target uid
2547 */
2548 if (userns_exec_1(conf, chown_cgroup_wrapper, &data) < 0) {
2549 ERROR("Error requesting cgroup chown in new namespace");
2550 return false;
2551 }
2552
2553 /*
2554 * Now chmod 775 the directory else the container cannot create cgroups.
2555 * This can't be done in the child namespace because it only group-owns
2556 * the cgroup
2557 */
2558 if (chmod(cgroup_path, 0775) < 0) {
2559 SYSERROR("Error chmoding %s\n", cgroup_path);
2560 return false;
2561 }
2562 fpath = lxc_append_paths(cgroup_path, "tasks");
2563 if (!fpath)
2564 return false;
2565 if (chmod(fpath, 0664) < 0)
2566 SYSERROR("Error chmoding %s\n", fpath);
2567 free(fpath);
2568 fpath = lxc_append_paths(cgroup_path, "cgroup.procs");
2569 if (!fpath)
2570 return false;
2571 if (chmod(fpath, 0664) < 0)
2572 SYSERROR("Error chmoding %s\n", fpath);
2573 free(fpath);
2574
2575 return true;
2576}
2577
2578static bool cgfs_chown(void *hdata, struct lxc_conf *conf)
2579{
2580 struct cgfs_data *d = hdata;
2581 struct cgroup_process_info *info_ptr;
2582 char *cgpath;
2583 bool r = true;
2584
2585 if (!d)
2586 return false;
2587
2588 for (info_ptr = d->info; info_ptr; info_ptr = info_ptr->next) {
2589 if (!info_ptr->designated_mount_point) {
2590 info_ptr->designated_mount_point = lxc_cgroup_find_mount_point(info_ptr->hierarchy, info_ptr->cgroup_path, true);
2591 if (!info_ptr->designated_mount_point) {
2592 SYSERROR("Could not chown cgroup %s: internal error (couldn't find any writable mountpoint to cgroup filesystem)", info_ptr->cgroup_path);
2593 return false;
2594 }
2595 }
2596
2597 cgpath = cgroup_to_absolute_path(info_ptr->designated_mount_point, info_ptr->cgroup_path, NULL);
2598 if (!cgpath) {
2599 SYSERROR("Could not chown cgroup %s: internal error", info_ptr->cgroup_path);
2600 continue;
2601 }
2602 r = do_cgfs_chown(cgpath, conf);
2603 if (!r) {
2604 ERROR("Failed chowning %s\n", cgpath);
2605 free(cgpath);
2606 return false;
2607 }
2608 free(cgpath);
2609 }
2610
2611 return true;
2612}
2613
d4ef7c50 2614static struct cgroup_ops cgfs_ops = {
d4ef7c50 2615 .init = cgfs_init,
4fb3cba5 2616 .destroy = cgfs_destroy,
d4ef7c50
SH
2617 .create = cgfs_create,
2618 .enter = cgfs_enter,
2619 .create_legacy = cgfs_create_legacy,
2620 .get_cgroup = cgfs_get_cgroup,
2ba7a429 2621 .canonical_path = cgfs_canonical_path,
06078509 2622 .escape = cgfs_escape,
d4ef7c50
SH
2623 .get = lxc_cgroupfs_get,
2624 .set = lxc_cgroupfs_set,
4fb3cba5 2625 .unfreeze = cgfs_unfreeze,
9daf6f5d 2626 .setup_limits = cgroupfs_setup_limits,
d4ef7c50 2627 .name = "cgroupfs",
5d897655 2628 .attach = lxc_cgroupfs_attach,
8b276860 2629 .chown = cgfs_chown,
c476bdce 2630 .mount_cgroup = cgroupfs_mount_cgroup,
4fb3cba5 2631 .nrtasks = cgfs_nrtasks,
23befb18 2632 .driver = CGFS,
d4ef7c50 2633};