3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
11 #define __STDC_FORMAT_MACROS
28 #include <linux/magic.h>
29 #include <linux/sched.h>
30 #include <sys/epoll.h>
32 #include <sys/mount.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/sysinfo.h>
40 #include "config.h" // for VERSION
42 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
43 #define LXCFS_NUMSTRLEN64 21
45 /* Define pivot_root() if missing from the C library */
46 #ifndef HAVE_PIVOT_ROOT
47 static int pivot_root(const char * new_root
, const char * put_old
)
49 #ifdef __NR_pivot_root
50 return syscall(__NR_pivot_root
, new_root
, put_old
);
57 extern int pivot_root(const char * new_root
, const char * put_old
);
63 LXC_TYPE_PROC_MEMINFO
,
64 LXC_TYPE_PROC_CPUINFO
,
67 LXC_TYPE_PROC_DISKSTATS
,
69 LXC_TYPE_PROC_LOADAVG
,
77 char *buf
; // unused as of yet
79 int size
; //actual data size
83 /* The function of hash table.*/
84 #define LOAD_SIZE 100 /*the size of hash_table */
85 #define FLUSH_TIME 5 /*the flush rate */
86 #define DEPTH_DIR 3 /*the depth of per cgroup */
87 /* The function of calculate loadavg .*/
88 #define FSHIFT 11 /* nr of bits of precision */
89 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
90 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
91 #define EXP_5 2014 /* 1/exp(5sec/5min) */
92 #define EXP_15 2037 /* 1/exp(5sec/15min) */
93 #define LOAD_INT(x) ((x) >> FSHIFT)
94 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
96 * This parameter is used for proc_loadavg_read().
97 * 1 means use loadavg, 0 means not use.
99 static int loadavg
= 0;
100 static int calc_hash(char *name
)
102 unsigned int hash
= 0;
104 /* ELFHash algorithm. */
106 hash
= (hash
<< 4) + *name
++;
107 x
= hash
& 0xf0000000;
112 return ((hash
& 0x7fffffff) % LOAD_SIZE
);
117 unsigned long avenrun
[3]; /* Load averages */
118 unsigned int run_pid
;
119 unsigned int total_pid
;
120 unsigned int last_pid
;
121 int cfd
; /* The file descriptor of the mounted cgroup */
122 struct load_node
*next
;
123 struct load_node
**pre
;
128 * The lock is about insert load_node and refresh load_node.To the first
129 * load_node of each hash bucket, insert and refresh in this hash bucket is
130 * mutually exclusive.
132 pthread_mutex_t lock
;
134 * The rdlock is about read loadavg and delete load_node.To each hash
135 * bucket, read and delete is mutually exclusive. But at the same time, we
136 * allow paratactic read operation. This rdlock is at list level.
138 pthread_rwlock_t rdlock
;
140 * The rilock is about read loadavg and insert load_node.To the first
141 * load_node of each hash bucket, read and insert is mutually exclusive.
142 * But at the same time, we allow paratactic read operation.
144 pthread_rwlock_t rilock
;
145 struct load_node
*next
;
148 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
150 * init_load initialize the hash table.
151 * Return 0 on success, return -1 on failure.
153 static int init_load(void)
158 for (i
= 0; i
< LOAD_SIZE
; i
++) {
159 load_hash
[i
].next
= NULL
;
160 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
162 lxcfs_error("%s\n", "Failed to initialize lock");
165 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
167 lxcfs_error("%s\n", "Failed to initialize rdlock");
170 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
172 lxcfs_error("%s\n", "Failed to initialize rilock");
178 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
180 pthread_mutex_destroy(&load_hash
[i
].lock
);
184 pthread_mutex_destroy(&load_hash
[i
].lock
);
185 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
186 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
191 static void insert_node(struct load_node
**n
, int locate
)
195 pthread_mutex_lock(&load_hash
[locate
].lock
);
196 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
197 f
= load_hash
[locate
].next
;
198 load_hash
[locate
].next
= *n
;
200 (*n
)->pre
= &(load_hash
[locate
].next
);
202 f
->pre
= &((*n
)->next
);
204 pthread_mutex_unlock(&load_hash
[locate
].lock
);
205 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
208 * locate_node() finds special node. Not return NULL means success.
209 * It should be noted that rdlock isn't unlocked at the end of code
210 * because this function is used to read special node. Delete is not
211 * allowed before read has ended.
212 * unlock rdlock only in proc_loadavg_read().
214 static struct load_node
*locate_node(char *cg
, int locate
)
216 struct load_node
*f
= NULL
;
219 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
220 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
221 if (load_hash
[locate
].next
== NULL
) {
222 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
225 f
= load_hash
[locate
].next
;
226 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
227 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
231 /* Delete the load_node n and return the next node of it. */
232 static struct load_node
*del_node(struct load_node
*n
, int locate
)
236 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
237 if (n
->next
== NULL
) {
241 n
->next
->pre
= n
->pre
;
246 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
250 /* Reserve buffer size to account for file size changes. */
251 #define BUF_RESERVE_SIZE 512
254 * A table caching which pid is init for a pid namespace.
255 * When looking up which pid is init for $qpid, we first
256 * 1. Stat /proc/$qpid/ns/pid.
257 * 2. Check whether the ino_t is in our store.
258 * a. if not, fork a child in qpid's ns to send us
259 * ucred.pid = 1, and read the initpid. Cache
260 * initpid and creation time for /proc/initpid
261 * in a new store entry.
262 * b. if so, verify that /proc/initpid still matches
263 * what we have saved. If not, clear the store
264 * entry and go back to a. If so, return the
267 struct pidns_init_store
{
268 ino_t ino
; // inode number for /proc/$pid/ns/pid
269 pid_t initpid
; // the pid of nit in that ns
270 long int ctime
; // the time at which /proc/$initpid was created
271 struct pidns_init_store
*next
;
275 /* lol - look at how they are allocated in the kernel */
276 #define PIDNS_HASH_SIZE 4096
277 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
279 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
280 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
281 static void lock_mutex(pthread_mutex_t
*l
)
285 if ((ret
= pthread_mutex_lock(l
)) != 0) {
286 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
291 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
292 * Number of hierarchies mounted. */
293 static int num_hierarchies
;
295 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
296 * Hierachies mounted {cpuset, blkio, ...}:
297 * Initialized via __constructor__ collect_and_mount_subsystems(). */
298 static char **hierarchies
;
300 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
301 * Open file descriptors:
302 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
303 * private mount namespace.
304 * Initialized via __constructor__ collect_and_mount_subsystems().
305 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
306 * mounts and respective files in the private namespace even when located in
307 * another namespace using the *at() family of functions
308 * {openat(), fchownat(), ...}. */
309 static int *fd_hierarchies
;
310 static int cgroup_mount_ns_fd
= -1;
312 static void unlock_mutex(pthread_mutex_t
*l
)
316 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
317 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
322 static void store_lock(void)
324 lock_mutex(&pidns_store_mutex
);
327 static void store_unlock(void)
329 unlock_mutex(&pidns_store_mutex
);
332 /* Must be called under store_lock */
333 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
338 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
339 if (stat(fnam
, &initsb
) < 0)
342 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
343 initsb
.st_ctime
, e
->initpid
);
345 if (e
->ctime
!= initsb
.st_ctime
)
350 /* Must be called under store_lock */
351 static void remove_initpid(struct pidns_init_store
*e
)
353 struct pidns_init_store
*tmp
;
356 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
359 if (pidns_hash_table
[h
] == e
) {
360 pidns_hash_table
[h
] = e
->next
;
365 tmp
= pidns_hash_table
[h
];
367 if (tmp
->next
== e
) {
377 /* Must be called under store_lock */
378 static void prune_initpid_store(void)
380 static long int last_prune
= 0;
381 struct pidns_init_store
*e
, *prev
, *delme
;
382 long int now
, threshold
;
386 last_prune
= time(NULL
);
390 if (now
< last_prune
+ PURGE_SECS
)
393 lxcfs_debug("%s\n", "Pruning.");
396 threshold
= now
- 2 * PURGE_SECS
;
398 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
399 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
400 if (e
->lastcheck
< threshold
) {
402 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
406 prev
->next
= e
->next
;
408 pidns_hash_table
[i
] = e
->next
;
419 /* Must be called under store_lock */
420 static void save_initpid(struct stat
*sb
, pid_t pid
)
422 struct pidns_init_store
*e
;
427 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
429 snprintf(fpath
, 100, "/proc/%d", pid
);
430 if (stat(fpath
, &procsb
) < 0)
433 e
= malloc(sizeof(*e
));
437 e
->ctime
= procsb
.st_ctime
;
439 e
->next
= pidns_hash_table
[h
];
440 e
->lastcheck
= time(NULL
);
441 pidns_hash_table
[h
] = e
;
445 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
446 * entry for the inode number and creation time. Verify that the init pid
447 * is still valid. If not, remove it. Return the entry if valid, NULL
449 * Must be called under store_lock
451 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
453 int h
= HASH(sb
->st_ino
);
454 struct pidns_init_store
*e
= pidns_hash_table
[h
];
457 if (e
->ino
== sb
->st_ino
) {
458 if (initpid_still_valid(e
, sb
)) {
459 e
->lastcheck
= time(NULL
);
471 static int is_dir(const char *path
, int fd
)
474 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
475 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
480 static char *must_copy_string(const char *str
)
492 static inline void drop_trailing_newlines(char *s
)
496 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
500 #define BATCH_SIZE 50
501 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
503 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
504 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
506 if (!*mem
|| newbatches
> oldbatches
) {
509 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
514 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
516 size_t newlen
= *len
+ linelen
;
517 dorealloc(contents
, *len
, newlen
+ 1);
518 memcpy(*contents
+ *len
, line
, linelen
+1);
522 static char *slurp_file(const char *from
, int fd
)
525 char *contents
= NULL
;
526 FILE *f
= fdopen(fd
, "r");
527 size_t len
= 0, fulllen
= 0;
533 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
534 append_line(&contents
, &fulllen
, line
, linelen
);
539 drop_trailing_newlines(contents
);
544 static bool write_string(const char *fnam
, const char *string
, int fd
)
549 if (!(f
= fdopen(fd
, "w")))
551 len
= strlen(string
);
552 ret
= fwrite(string
, 1, len
, f
);
554 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
559 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
572 static bool store_hierarchy(char *stridx
, char *h
)
574 if (num_hierarchies
% ALLOC_NUM
== 0) {
575 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
577 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
579 lxcfs_error("%s\n", strerror(errno
));
585 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
589 static void print_subsystems(void)
593 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
594 fprintf(stderr
, "hierarchies:\n");
595 for (i
= 0; i
< num_hierarchies
; i
++) {
597 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
598 fd_hierarchies
[i
], hierarchies
[i
]);
602 static bool in_comma_list(const char *needle
, const char *haystack
)
604 const char *s
= haystack
, *e
;
605 size_t nlen
= strlen(needle
);
607 while (*s
&& (e
= strchr(s
, ','))) {
612 if (strncmp(needle
, s
, nlen
) == 0)
616 if (strcmp(needle
, s
) == 0)
621 /* do we need to do any massaging here? I'm not sure... */
622 /* Return the mounted controller and store the corresponding open file descriptor
623 * referring to the controller mountpoint in the private lxcfs namespace in
626 static char *find_mounted_controller(const char *controller
, int *cfd
)
630 for (i
= 0; i
< num_hierarchies
; i
++) {
633 if (strcmp(hierarchies
[i
], controller
) == 0) {
634 *cfd
= fd_hierarchies
[i
];
635 return hierarchies
[i
];
637 if (in_comma_list(controller
, hierarchies
[i
])) {
638 *cfd
= fd_hierarchies
[i
];
639 return hierarchies
[i
];
646 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
653 tmpc
= find_mounted_controller(controller
, &cfd
);
657 /* Make sure we pass a relative path to *at() family of functions.
658 * . + /cgroup + / + file + \0
660 len
= strlen(cgroup
) + strlen(file
) + 3;
662 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
663 if (ret
< 0 || (size_t)ret
>= len
)
666 fd
= openat(cfd
, fnam
, O_WRONLY
);
670 return write_string(fnam
, value
, fd
);
673 // Chown all the files in the cgroup directory. We do this when we create
674 // a cgroup on behalf of a user.
675 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
677 struct dirent
*direntp
;
678 char path
[MAXPATHLEN
];
683 len
= strlen(dirname
);
684 if (len
>= MAXPATHLEN
) {
685 lxcfs_error("Pathname too long: %s\n", dirname
);
689 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
695 lxcfs_error("Failed to open %s\n", dirname
);
699 while ((direntp
= readdir(d
))) {
700 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
702 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
703 if (ret
< 0 || ret
>= MAXPATHLEN
) {
704 lxcfs_error("Pathname too long under %s\n", dirname
);
707 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
708 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
713 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
719 tmpc
= find_mounted_controller(controller
, &cfd
);
723 /* Make sure we pass a relative path to *at() family of functions.
726 len
= strlen(cg
) + 2;
727 dirnam
= alloca(len
);
728 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
730 if (mkdirat(cfd
, dirnam
, 0755) < 0)
733 if (uid
== 0 && gid
== 0)
736 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
739 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
744 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
746 struct dirent
*direntp
;
749 char pathname
[MAXPATHLEN
];
752 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
756 dir
= fdopendir(dupfd
);
758 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
763 while ((direntp
= readdir(dir
))) {
767 if (!strcmp(direntp
->d_name
, ".") ||
768 !strcmp(direntp
->d_name
, ".."))
771 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
772 if (rc
< 0 || rc
>= MAXPATHLEN
) {
773 lxcfs_error("%s\n", "Pathname too long.");
777 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
779 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
782 if (S_ISDIR(mystat
.st_mode
))
783 if (!recursive_rmdir(pathname
, fd
, cfd
))
784 lxcfs_debug("Error removing %s.\n", pathname
);
788 if (closedir(dir
) < 0) {
789 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
793 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
794 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
803 bool cgfs_remove(const char *controller
, const char *cg
)
810 tmpc
= find_mounted_controller(controller
, &cfd
);
814 /* Make sure we pass a relative path to *at() family of functions.
817 len
= strlen(cg
) + 2;
818 dirnam
= alloca(len
);
819 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
821 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
825 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
830 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
834 char *pathname
, *tmpc
;
836 tmpc
= find_mounted_controller(controller
, &cfd
);
840 /* Make sure we pass a relative path to *at() family of functions.
843 len
= strlen(file
) + 2;
844 pathname
= alloca(len
);
845 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
846 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
851 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
856 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
858 snprintf(fname
, len
, "%s/tasks", dirname
);
859 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
861 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
862 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
867 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
871 char *pathname
, *tmpc
;
873 tmpc
= find_mounted_controller(controller
, &cfd
);
877 /* Make sure we pass a relative path to *at() family of functions.
880 len
= strlen(file
) + 2;
881 pathname
= alloca(len
);
882 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
883 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
886 if (is_dir(pathname
, cfd
))
887 // like cgmanager did, we want to chown the tasks file as well
888 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
893 FILE *open_pids_file(const char *controller
, const char *cgroup
)
897 char *pathname
, *tmpc
;
899 tmpc
= find_mounted_controller(controller
, &cfd
);
903 /* Make sure we pass a relative path to *at() family of functions.
904 * . + /cgroup + / "cgroup.procs" + \0
906 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
907 pathname
= alloca(len
);
908 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
910 fd
= openat(cfd
, pathname
, O_WRONLY
);
914 return fdopen(fd
, "w");
917 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
918 void ***list
, size_t typesize
,
919 void* (*iterator
)(const char*, const char*, const char*))
924 char pathname
[MAXPATHLEN
];
925 size_t sz
= 0, asz
= 0;
926 struct dirent
*dirent
;
929 tmpc
= find_mounted_controller(controller
, &cfd
);
934 /* Make sure we pass a relative path to *at() family of functions. */
935 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
937 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
938 if (ret
< 0 || (size_t)ret
>= len
) {
939 lxcfs_error("Pathname too long under %s\n", cgroup
);
943 fd
= openat(cfd
, cg
, O_DIRECTORY
);
951 while ((dirent
= readdir(dir
))) {
954 if (!strcmp(dirent
->d_name
, ".") ||
955 !strcmp(dirent
->d_name
, ".."))
958 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
959 if (ret
< 0 || ret
>= MAXPATHLEN
) {
960 lxcfs_error("Pathname too long under %s\n", cg
);
964 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
966 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
969 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
970 (directories
&& !S_ISDIR(mystat
.st_mode
)))
977 tmp
= realloc(*list
, asz
* typesize
);
981 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
982 (*list
)[sz
+1] = NULL
;
985 if (closedir(dir
) < 0) {
986 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
992 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
996 dup
= strdup(dir_entry
);
1001 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1003 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1006 void free_key(struct cgfs_files
*k
)
1014 void free_keys(struct cgfs_files
**keys
)
1020 for (i
= 0; keys
[i
]; i
++) {
1026 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1032 tmpc
= find_mounted_controller(controller
, &cfd
);
1036 /* Make sure we pass a relative path to *at() family of functions.
1037 * . + /cgroup + / + file + \0
1039 len
= strlen(cgroup
) + strlen(file
) + 3;
1041 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1042 if (ret
< 0 || (size_t)ret
>= len
)
1045 fd
= openat(cfd
, fnam
, O_RDONLY
);
1049 *value
= slurp_file(fnam
, fd
);
1050 return *value
!= NULL
;
1053 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1059 struct cgfs_files
*newkey
;
1061 tmpc
= find_mounted_controller(controller
, &cfd
);
1065 if (file
&& *file
== '/')
1068 if (file
&& strchr(file
, '/'))
1071 /* Make sure we pass a relative path to *at() family of functions.
1072 * . + /cgroup + / + file + \0
1074 len
= strlen(cgroup
) + 3;
1076 len
+= strlen(file
) + 1;
1078 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1079 file
? "/" : "", file
? file
: "");
1081 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1086 newkey
= malloc(sizeof(struct cgfs_files
));
1089 newkey
->name
= must_copy_string(file
);
1090 else if (strrchr(cgroup
, '/'))
1091 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1093 newkey
->name
= must_copy_string(cgroup
);
1094 newkey
->uid
= sb
.st_uid
;
1095 newkey
->gid
= sb
.st_gid
;
1096 newkey
->mode
= sb
.st_mode
;
1101 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1103 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1105 lxcfs_error("Error getting files under %s:%s\n", controller
,
1111 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1113 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1116 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1124 tmpc
= find_mounted_controller(controller
, &cfd
);
1128 /* Make sure we pass a relative path to *at() family of functions.
1129 * . + /cgroup + / + f + \0
1131 len
= strlen(cgroup
) + strlen(f
) + 3;
1133 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1134 if (ret
< 0 || (size_t)ret
>= len
)
1137 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1138 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1144 #define SEND_CREDS_OK 0
1145 #define SEND_CREDS_NOTSK 1
1146 #define SEND_CREDS_FAIL 2
1147 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1148 static int wait_for_pid(pid_t pid
);
1149 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1150 static int send_creds_clone_wrapper(void *arg
);
1153 * clone a task which switches to @task's namespace and writes '1'.
1154 * over a unix sock so we can read the task's reaper's pid in our
1157 * Note: glibc's fork() does not respect pidns, which can lead to failed
1158 * assertions inside glibc (and thus failed forks) if the child's pid in
1159 * the pidns and the parent pid outside are identical. Using clone prevents
1162 static void write_task_init_pid_exit(int sock
, pid_t target
)
1167 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1168 void *stack
= alloca(stack_size
);
1170 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1171 if (ret
< 0 || ret
>= sizeof(fnam
))
1174 fd
= open(fnam
, O_RDONLY
);
1176 perror("write_task_init_pid_exit open of ns/pid");
1180 perror("write_task_init_pid_exit setns 1");
1184 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1188 if (!wait_for_pid(pid
))
1194 static int send_creds_clone_wrapper(void *arg
) {
1197 int sock
= *(int *)arg
;
1199 /* we are the child */
1204 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1209 static pid_t
get_init_pid_for_task(pid_t task
)
1217 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1218 perror("socketpair");
1227 write_task_init_pid_exit(sock
[0], task
);
1231 if (!recv_creds(sock
[1], &cred
, &v
))
1243 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1247 struct pidns_init_store
*e
;
1250 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1252 if (stat(fnam
, &sb
) < 0)
1254 e
= lookup_verify_initpid(&sb
);
1256 answer
= e
->initpid
;
1259 answer
= get_init_pid_for_task(qpid
);
1261 save_initpid(&sb
, answer
);
1264 /* we prune at end in case we are returning
1265 * the value we were about to return */
1266 prune_initpid_store();
1271 static int wait_for_pid(pid_t pid
)
1279 ret
= waitpid(pid
, &status
, 0);
1287 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1294 * append pid to *src.
1295 * src: a pointer to a char* in which ot append the pid.
1296 * sz: the number of characters printed so far, minus trailing \0.
1297 * asz: the allocated size so far
1298 * pid: the pid to append
1300 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1304 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1306 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1309 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1312 *asz
+= BUF_RESERVE_SIZE
;
1314 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1319 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1320 * valid in the caller's namespace, return the id mapped into
1322 * Returns the mapped id, or -1 on error.
1325 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1327 unsigned int nsuid
, // base id for a range in the idfile's namespace
1328 hostuid
, // base id for a range in the caller's namespace
1329 count
; // number of ids in this range
1333 fseek(idfile
, 0L, SEEK_SET
);
1334 while (fgets(line
, 400, idfile
)) {
1335 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1338 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1340 * uids wrapped around - unexpected as this is a procfile,
1343 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1344 nsuid
, hostuid
, count
, line
);
1347 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1349 * now since hostuid <= in_id < hostuid+count, and
1350 * hostuid+count and nsuid+count do not wrap around,
1351 * we know that nsuid+(in_id-hostuid) which must be
1352 * less that nsuid+(count) must not wrap around
1354 return (in_id
- hostuid
) + nsuid
;
1363 * for is_privileged_over,
1364 * specify whether we require the calling uid to be root in his
1367 #define NS_ROOT_REQD true
1368 #define NS_ROOT_OPT false
1372 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1374 char fpath
[PROCLEN
];
1376 bool answer
= false;
1379 if (victim
== -1 || uid
== -1)
1383 * If the request is one not requiring root in the namespace,
1384 * then having the same uid suffices. (i.e. uid 1000 has write
1385 * access to files owned by uid 1000
1387 if (!req_ns_root
&& uid
== victim
)
1390 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1391 if (ret
< 0 || ret
>= PROCLEN
)
1393 FILE *f
= fopen(fpath
, "r");
1397 /* if caller's not root in his namespace, reject */
1398 nsuid
= convert_id_to_ns(f
, uid
);
1403 * If victim is not mapped into caller's ns, reject.
1404 * XXX I'm not sure this check is needed given that fuse
1405 * will be sending requests where the vfs has converted
1407 nsuid
= convert_id_to_ns(f
, victim
);
1418 static bool perms_include(int fmode
, mode_t req_mode
)
1422 switch (req_mode
& O_ACCMODE
) {
1430 r
= S_IROTH
| S_IWOTH
;
1435 return ((fmode
& r
) == r
);
1441 * querycg is /a/b/c/d/e
1444 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1448 if (strlen(taskcg
) <= strlen(querycg
)) {
1449 lxcfs_error("%s\n", "I was fed bad input.");
1453 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1454 start
= strdup(taskcg
+ 1);
1456 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1459 end
= strchr(start
, '/');
1465 static void stripnewline(char *x
)
1467 size_t l
= strlen(x
);
1468 if (l
&& x
[l
-1] == '\n')
1472 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1477 char *answer
= NULL
;
1481 const char *h
= find_mounted_controller(contrl
, &cfd
);
1485 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1486 if (ret
< 0 || ret
>= PROCLEN
)
1488 if (!(f
= fopen(fnam
, "r")))
1491 while (getline(&line
, &len
, f
) != -1) {
1495 c1
= strchr(line
, ':');
1499 c2
= strchr(c1
, ':');
1503 if (strcmp(c1
, h
) != 0)
1508 answer
= strdup(c2
);
1520 * check whether a fuse context may access a cgroup dir or file
1522 * If file is not null, it is a cgroup file to check under cg.
1523 * If file is null, then we are checking perms on cg itself.
1525 * For files we can check the mode of the list_keys result.
1526 * For cgroups, we must make assumptions based on the files under the
1527 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1530 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1532 struct cgfs_files
*k
= NULL
;
1535 k
= cgfs_get_key(contrl
, cg
, file
);
1539 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1540 if (perms_include(k
->mode
>> 6, mode
)) {
1545 if (fc
->gid
== k
->gid
) {
1546 if (perms_include(k
->mode
>> 3, mode
)) {
1551 ret
= perms_include(k
->mode
, mode
);
1558 #define INITSCOPE "/init.scope"
1559 static void prune_init_slice(char *cg
)
1562 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1564 if (cg_len
< initscope_len
)
1567 point
= cg
+ cg_len
- initscope_len
;
1568 if (strcmp(point
, INITSCOPE
) == 0) {
1577 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1578 * If pid is in /a, he may act on /a/b, but not on /b.
1579 * if the answer is false and nextcg is not NULL, then *nextcg will point
1580 * to a string containing the next cgroup directory under cg, which must be
1581 * freed by the caller.
1583 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1585 bool answer
= false;
1586 char *c2
= get_pid_cgroup(pid
, contrl
);
1591 prune_init_slice(c2
);
1594 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1595 * they pass in a cgroup without leading '/'
1597 * The original line here was:
1598 * linecmp = *cg == '/' ? c2 : c2+1;
1599 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1600 * Serge, do you know?
1602 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1606 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1608 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1620 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1622 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1624 bool answer
= false;
1626 size_t target_len
, task_len
;
1628 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1631 c2
= get_pid_cgroup(pid
, contrl
);
1634 prune_init_slice(c2
);
1637 target_len
= strlen(cg
);
1638 task_len
= strlen(task_cg
);
1639 if (task_len
== 0) {
1640 /* Task is in the root cg, it can see everything. This case is
1641 * not handled by the strmcps below, since they test for the
1642 * last /, but that is the first / that we've chopped off
1648 if (strcmp(cg
, task_cg
) == 0) {
1652 if (target_len
< task_len
) {
1653 /* looking up a parent dir */
1654 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1658 if (target_len
> task_len
) {
1659 /* looking up a child dir */
1660 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1671 * given /cgroup/freezer/a/b, return "freezer".
1672 * the returned char* should NOT be freed.
1674 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1677 char *contr
, *slash
;
1679 if (strlen(path
) < 9) {
1683 if (*(path
+ 7) != '/') {
1688 contr
= strdupa(p1
);
1693 slash
= strstr(contr
, "/");
1698 for (i
= 0; i
< num_hierarchies
; i
++) {
1699 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1700 return hierarchies
[i
];
1707 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1708 * Note that the returned value may include files (keynames) etc
1710 static const char *find_cgroup_in_path(const char *path
)
1714 if (strlen(path
) < 9) {
1718 p1
= strstr(path
+ 8, "/");
1728 * split the last path element from the path in @cg.
1729 * @dir is newly allocated and should be freed, @last not
1731 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1738 *last
= strrchr(cg
, '/');
1743 p
= strrchr(*dir
, '/');
1748 * FUSE ops for /cgroup
1751 int cg_getattr(const char *path
, struct stat
*sb
)
1753 struct timespec now
;
1754 struct fuse_context
*fc
= fuse_get_context();
1755 char * cgdir
= NULL
;
1756 char *last
= NULL
, *path1
, *path2
;
1757 struct cgfs_files
*k
= NULL
;
1759 const char *controller
= NULL
;
1766 memset(sb
, 0, sizeof(struct stat
));
1768 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1771 sb
->st_uid
= sb
->st_gid
= 0;
1772 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1775 if (strcmp(path
, "/cgroup") == 0) {
1776 sb
->st_mode
= S_IFDIR
| 00755;
1781 controller
= pick_controller_from_path(fc
, path
);
1784 cgroup
= find_cgroup_in_path(path
);
1786 /* this is just /cgroup/controller, return it as a dir */
1787 sb
->st_mode
= S_IFDIR
| 00755;
1792 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1802 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1805 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1806 * Then check that caller's cgroup is under path if last is a child
1807 * cgroup, or cgdir if last is a file */
1809 if (is_child_cgroup(controller
, path1
, path2
)) {
1810 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1814 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1815 /* this is just /cgroup/controller, return it as a dir */
1816 sb
->st_mode
= S_IFDIR
| 00555;
1821 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1826 // get uid, gid, from '/tasks' file and make up a mode
1827 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1828 sb
->st_mode
= S_IFDIR
| 00755;
1829 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1831 sb
->st_uid
= sb
->st_gid
= 0;
1833 sb
->st_uid
= k
->uid
;
1834 sb
->st_gid
= k
->gid
;
1842 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1843 sb
->st_mode
= S_IFREG
| k
->mode
;
1845 sb
->st_uid
= k
->uid
;
1846 sb
->st_gid
= k
->gid
;
1849 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1861 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1863 struct fuse_context
*fc
= fuse_get_context();
1865 struct file_info
*dir_info
;
1866 char *controller
= NULL
;
1871 if (strcmp(path
, "/cgroup") == 0) {
1875 // return list of keys for the controller, and list of child cgroups
1876 controller
= pick_controller_from_path(fc
, path
);
1880 cgroup
= find_cgroup_in_path(path
);
1882 /* this is just /cgroup/controller, return its contents */
1887 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1891 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1893 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1897 /* we'll free this at cg_releasedir */
1898 dir_info
= malloc(sizeof(*dir_info
));
1901 dir_info
->controller
= must_copy_string(controller
);
1902 dir_info
->cgroup
= must_copy_string(cgroup
);
1903 dir_info
->type
= LXC_TYPE_CGDIR
;
1904 dir_info
->buf
= NULL
;
1905 dir_info
->file
= NULL
;
1906 dir_info
->buflen
= 0;
1908 fi
->fh
= (unsigned long)dir_info
;
1912 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1913 struct fuse_file_info
*fi
)
1915 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1916 struct cgfs_files
**list
= NULL
;
1918 char *nextcg
= NULL
;
1919 struct fuse_context
*fc
= fuse_get_context();
1920 char **clist
= NULL
;
1922 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1925 if (d
->type
!= LXC_TYPE_CGDIR
) {
1926 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1929 if (!d
->cgroup
&& !d
->controller
) {
1930 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1933 for (i
= 0; i
< num_hierarchies
; i
++) {
1934 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1941 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1942 // not a valid cgroup
1947 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1950 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1952 ret
= filler(buf
, nextcg
, NULL
, 0);
1963 for (i
= 0; list
[i
]; i
++) {
1964 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1970 // now get the list of child cgroups
1972 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1977 for (i
= 0; clist
[i
]; i
++) {
1978 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1989 for (i
= 0; clist
[i
]; i
++)
1996 static void do_release_file_info(struct fuse_file_info
*fi
)
1998 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2005 free(f
->controller
);
2006 f
->controller
= NULL
;
2016 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2018 do_release_file_info(fi
);
2022 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2025 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2026 struct cgfs_files
*k
= NULL
;
2027 struct file_info
*file_info
;
2028 struct fuse_context
*fc
= fuse_get_context();
2034 controller
= pick_controller_from_path(fc
, path
);
2037 cgroup
= find_cgroup_in_path(path
);
2041 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2050 k
= cgfs_get_key(controller
, path1
, path2
);
2057 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2060 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2064 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2069 /* we'll free this at cg_release */
2070 file_info
= malloc(sizeof(*file_info
));
2075 file_info
->controller
= must_copy_string(controller
);
2076 file_info
->cgroup
= must_copy_string(path1
);
2077 file_info
->file
= must_copy_string(path2
);
2078 file_info
->type
= LXC_TYPE_CGFILE
;
2079 file_info
->buf
= NULL
;
2080 file_info
->buflen
= 0;
2082 fi
->fh
= (unsigned long)file_info
;
2090 int cg_access(const char *path
, int mode
)
2094 char *path1
, *path2
, *controller
;
2095 char *last
= NULL
, *cgdir
= NULL
;
2096 struct cgfs_files
*k
= NULL
;
2097 struct fuse_context
*fc
= fuse_get_context();
2099 if (strcmp(path
, "/cgroup") == 0)
2105 controller
= pick_controller_from_path(fc
, path
);
2108 cgroup
= find_cgroup_in_path(path
);
2110 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2111 if ((mode
& W_OK
) == 0)
2116 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2125 k
= cgfs_get_key(controller
, path1
, path2
);
2127 if ((mode
& W_OK
) == 0)
2135 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2138 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2142 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2154 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2156 do_release_file_info(fi
);
2160 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2162 static bool wait_for_sock(int sock
, int timeout
)
2164 struct epoll_event ev
;
2165 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2167 if ((starttime
= time(NULL
)) < 0)
2170 if ((epfd
= epoll_create(1)) < 0) {
2171 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2175 ev
.events
= POLLIN_SET
;
2177 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2178 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2184 if ((now
= time(NULL
)) < 0) {
2189 deltatime
= (starttime
+ timeout
) - now
;
2190 if (deltatime
< 0) { // timeout
2195 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2196 if (ret
< 0 && errno
== EINTR
)
2198 saved_errno
= errno
;
2202 errno
= saved_errno
;
2208 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2210 if (!wait_for_sock(sockfd
, 2))
2212 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2215 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2217 struct msghdr msg
= { 0 };
2219 struct cmsghdr
*cmsg
;
2220 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2225 if (msgrecv(sock
, buf
, 1) != 1) {
2226 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2227 return SEND_CREDS_FAIL
;
2231 msg
.msg_control
= cmsgbuf
;
2232 msg
.msg_controllen
= sizeof(cmsgbuf
);
2234 cmsg
= CMSG_FIRSTHDR(&msg
);
2235 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2236 cmsg
->cmsg_level
= SOL_SOCKET
;
2237 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2238 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2240 msg
.msg_name
= NULL
;
2241 msg
.msg_namelen
= 0;
2245 iov
.iov_len
= sizeof(buf
);
2249 if (sendmsg(sock
, &msg
, 0) < 0) {
2250 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2252 return SEND_CREDS_NOTSK
;
2253 return SEND_CREDS_FAIL
;
2256 return SEND_CREDS_OK
;
2259 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2261 struct msghdr msg
= { 0 };
2263 struct cmsghdr
*cmsg
;
2264 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2275 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2276 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2280 if (write(sock
, buf
, 1) != 1) {
2281 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2285 msg
.msg_name
= NULL
;
2286 msg
.msg_namelen
= 0;
2287 msg
.msg_control
= cmsgbuf
;
2288 msg
.msg_controllen
= sizeof(cmsgbuf
);
2291 iov
.iov_len
= sizeof(buf
);
2295 if (!wait_for_sock(sock
, 2)) {
2296 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2299 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2301 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2305 cmsg
= CMSG_FIRSTHDR(&msg
);
2307 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2308 cmsg
->cmsg_level
== SOL_SOCKET
&&
2309 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2310 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2317 struct pid_ns_clone_args
{
2321 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2325 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2326 * with clone(). This simply writes '1' as ACK back to the parent
2327 * before calling the actual wrapped function.
2329 static int pid_ns_clone_wrapper(void *arg
) {
2330 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2333 close(args
->cpipe
[0]);
2334 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2335 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2336 close(args
->cpipe
[1]);
2337 return args
->wrapped(args
->sock
, args
->tpid
);
2341 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2342 * int value back over the socket. This shifts the pid from the
2343 * sender's pidns into tpid's pidns.
2345 static int pid_to_ns(int sock
, pid_t tpid
)
2350 while (recv_creds(sock
, &cred
, &v
)) {
2353 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2361 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2362 * in your old pidns. Only children which you clone will be in the target
2363 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2364 * actually convert pids.
2366 * Note: glibc's fork() does not respect pidns, which can lead to failed
2367 * assertions inside glibc (and thus failed forks) if the child's pid in
2368 * the pidns and the parent pid outside are identical. Using clone prevents
2371 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2373 int newnsfd
= -1, ret
, cpipe
[2];
2378 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2379 if (ret
< 0 || ret
>= sizeof(fnam
))
2381 newnsfd
= open(fnam
, O_RDONLY
);
2384 if (setns(newnsfd
, 0) < 0)
2388 if (pipe(cpipe
) < 0)
2391 struct pid_ns_clone_args args
= {
2395 .wrapped
= &pid_to_ns
2397 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2398 void *stack
= alloca(stack_size
);
2400 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2404 // give the child 1 second to be done forking and
2406 if (!wait_for_sock(cpipe
[0], 1))
2408 ret
= read(cpipe
[0], &v
, 1);
2409 if (ret
!= sizeof(char) || v
!= '1')
2412 if (!wait_for_pid(cpid
))
2418 * To read cgroup files with a particular pid, we will setns into the child
2419 * pidns, open a pipe, fork a child - which will be the first to really be in
2420 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2422 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2424 int sock
[2] = {-1, -1};
2425 char *tmpdata
= NULL
;
2427 pid_t qpid
, cpid
= -1;
2428 bool answer
= false;
2431 size_t sz
= 0, asz
= 0;
2433 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2437 * Now we read the pids from returned data one by one, pass
2438 * them into a child in the target namespace, read back the
2439 * translated pids, and put them into our to-return data
2442 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2443 perror("socketpair");
2452 if (!cpid
) // child - exits when done
2453 pid_to_ns_wrapper(sock
[1], tpid
);
2455 char *ptr
= tmpdata
;
2458 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2460 ret
= send_creds(sock
[0], &cred
, v
, true);
2462 if (ret
== SEND_CREDS_NOTSK
)
2464 if (ret
== SEND_CREDS_FAIL
)
2467 // read converted results
2468 if (!wait_for_sock(sock
[0], 2)) {
2469 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2472 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2473 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2476 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2478 ptr
= strchr(ptr
, '\n');
2484 cred
.pid
= getpid();
2486 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2487 // failed to ask child to exit
2488 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2498 if (sock
[0] != -1) {
2505 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2506 struct fuse_file_info
*fi
)
2508 struct fuse_context
*fc
= fuse_get_context();
2509 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2510 struct cgfs_files
*k
= NULL
;
2515 if (f
->type
!= LXC_TYPE_CGFILE
) {
2516 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2529 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2535 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2540 if (strcmp(f
->file
, "tasks") == 0 ||
2541 strcmp(f
->file
, "/tasks") == 0 ||
2542 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2543 strcmp(f
->file
, "cgroup.procs") == 0)
2544 // special case - we have to translate the pids
2545 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2547 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2561 memcpy(buf
, data
, s
);
2562 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2572 static int pid_from_ns(int sock
, pid_t tpid
)
2582 if (!wait_for_sock(sock
, 2)) {
2583 lxcfs_error("%s\n", "Timeout reading from parent.");
2586 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2587 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2590 if (vpid
== -1) // done
2594 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2596 cred
.pid
= getpid();
2597 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2604 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2606 int newnsfd
= -1, ret
, cpipe
[2];
2611 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2612 if (ret
< 0 || ret
>= sizeof(fnam
))
2614 newnsfd
= open(fnam
, O_RDONLY
);
2617 if (setns(newnsfd
, 0) < 0)
2621 if (pipe(cpipe
) < 0)
2624 struct pid_ns_clone_args args
= {
2628 .wrapped
= &pid_from_ns
2630 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2631 void *stack
= alloca(stack_size
);
2633 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2637 // give the child 1 second to be done forking and
2639 if (!wait_for_sock(cpipe
[0], 1))
2641 ret
= read(cpipe
[0], &v
, 1);
2642 if (ret
!= sizeof(char) || v
!= '1')
2645 if (!wait_for_pid(cpid
))
2651 * Given host @uid, return the uid to which it maps in
2652 * @pid's user namespace, or -1 if none.
2654 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2659 sprintf(line
, "/proc/%d/uid_map", pid
);
2660 if ((f
= fopen(line
, "r")) == NULL
) {
2664 *answer
= convert_id_to_ns(f
, uid
);
2673 * get_pid_creds: get the real uid and gid of @pid from
2675 * (XXX should we use euid here?)
2677 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2686 sprintf(line
, "/proc/%d/status", pid
);
2687 if ((f
= fopen(line
, "r")) == NULL
) {
2688 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2691 while (fgets(line
, 400, f
)) {
2692 if (strncmp(line
, "Uid:", 4) == 0) {
2693 if (sscanf(line
+4, "%u", &u
) != 1) {
2694 lxcfs_error("bad uid line for pid %u\n", pid
);
2699 } else if (strncmp(line
, "Gid:", 4) == 0) {
2700 if (sscanf(line
+4, "%u", &g
) != 1) {
2701 lxcfs_error("bad gid line for pid %u\n", pid
);
2712 * May the requestor @r move victim @v to a new cgroup?
2713 * This is allowed if
2714 * . they are the same task
2715 * . they are ownedy by the same uid
2716 * . @r is root on the host, or
2717 * . @v's uid is mapped into @r's where @r is root.
2719 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2721 uid_t v_uid
, tmpuid
;
2728 get_pid_creds(v
, &v_uid
, &v_gid
);
2731 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2732 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2737 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2738 const char *file
, const char *buf
)
2740 int sock
[2] = {-1, -1};
2741 pid_t qpid
, cpid
= -1;
2742 FILE *pids_file
= NULL
;
2743 bool answer
= false, fail
= false;
2745 pids_file
= open_pids_file(contrl
, cg
);
2750 * write the pids to a socket, have helper in writer's pidns
2751 * call movepid for us
2753 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2754 perror("socketpair");
2762 if (!cpid
) { // child
2764 pid_from_ns_wrapper(sock
[1], tpid
);
2767 const char *ptr
= buf
;
2768 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2772 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2773 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2777 if (recv_creds(sock
[0], &cred
, &v
)) {
2779 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2783 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2788 ptr
= strchr(ptr
, '\n');
2794 /* All good, write the value */
2796 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2797 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2805 if (sock
[0] != -1) {
2810 if (fclose(pids_file
) != 0)
2816 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2817 struct fuse_file_info
*fi
)
2819 struct fuse_context
*fc
= fuse_get_context();
2820 char *localbuf
= NULL
;
2821 struct cgfs_files
*k
= NULL
;
2822 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2825 if (f
->type
!= LXC_TYPE_CGFILE
) {
2826 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2836 localbuf
= alloca(size
+1);
2837 localbuf
[size
] = '\0';
2838 memcpy(localbuf
, buf
, size
);
2840 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2845 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2850 if (strcmp(f
->file
, "tasks") == 0 ||
2851 strcmp(f
->file
, "/tasks") == 0 ||
2852 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2853 strcmp(f
->file
, "cgroup.procs") == 0)
2854 // special case - we have to translate the pids
2855 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2857 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2867 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2869 struct fuse_context
*fc
= fuse_get_context();
2870 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2871 struct cgfs_files
*k
= NULL
;
2878 if (strcmp(path
, "/cgroup") == 0)
2881 controller
= pick_controller_from_path(fc
, path
);
2883 return errno
== ENOENT
? -EPERM
: -errno
;
2885 cgroup
= find_cgroup_in_path(path
);
2887 /* this is just /cgroup/controller */
2890 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2900 if (is_child_cgroup(controller
, path1
, path2
)) {
2901 // get uid, gid, from '/tasks' file and make up a mode
2902 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2903 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2906 k
= cgfs_get_key(controller
, path1
, path2
);
2914 * This being a fuse request, the uid and gid must be valid
2915 * in the caller's namespace. So we can just check to make
2916 * sure that the caller is root in his uid, and privileged
2917 * over the file's current owner.
2919 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2924 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2933 int cg_chmod(const char *path
, mode_t mode
)
2935 struct fuse_context
*fc
= fuse_get_context();
2936 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2937 struct cgfs_files
*k
= NULL
;
2944 if (strcmp(path
, "/cgroup") == 0)
2947 controller
= pick_controller_from_path(fc
, path
);
2949 return errno
== ENOENT
? -EPERM
: -errno
;
2951 cgroup
= find_cgroup_in_path(path
);
2953 /* this is just /cgroup/controller */
2956 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2966 if (is_child_cgroup(controller
, path1
, path2
)) {
2967 // get uid, gid, from '/tasks' file and make up a mode
2968 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2969 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2972 k
= cgfs_get_key(controller
, path1
, path2
);
2980 * This being a fuse request, the uid and gid must be valid
2981 * in the caller's namespace. So we can just check to make
2982 * sure that the caller is root in his uid, and privileged
2983 * over the file's current owner.
2985 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2990 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3002 int cg_mkdir(const char *path
, mode_t mode
)
3004 struct fuse_context
*fc
= fuse_get_context();
3005 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3012 controller
= pick_controller_from_path(fc
, path
);
3014 return errno
== ENOENT
? -EPERM
: -errno
;
3016 cgroup
= find_cgroup_in_path(path
);
3020 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3026 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3029 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3032 else if (last
&& strcmp(next
, last
) == 0)
3039 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3043 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3048 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3056 int cg_rmdir(const char *path
)
3058 struct fuse_context
*fc
= fuse_get_context();
3059 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3066 controller
= pick_controller_from_path(fc
, path
);
3067 if (!controller
) /* Someone's trying to delete "/cgroup". */
3070 cgroup
= find_cgroup_in_path(path
);
3071 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3074 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3076 /* Someone's trying to delete a cgroup on the same level as the
3077 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3078 * rmdir "/cgroup/blkio/init.slice".
3084 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3087 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3088 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3095 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3099 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3104 if (!cgfs_remove(controller
, cgroup
)) {
3117 static bool startswith(const char *line
, const char *pref
)
3119 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3124 static void parse_memstat(char *memstat
, unsigned long *cached
,
3125 unsigned long *active_anon
, unsigned long *inactive_anon
,
3126 unsigned long *active_file
, unsigned long *inactive_file
,
3127 unsigned long *unevictable
)
3132 if (startswith(memstat
, "total_cache")) {
3133 sscanf(memstat
+ 11, "%lu", cached
);
3135 } else if (startswith(memstat
, "total_active_anon")) {
3136 sscanf(memstat
+ 17, "%lu", active_anon
);
3137 *active_anon
/= 1024;
3138 } else if (startswith(memstat
, "total_inactive_anon")) {
3139 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3140 *inactive_anon
/= 1024;
3141 } else if (startswith(memstat
, "total_active_file")) {
3142 sscanf(memstat
+ 17, "%lu", active_file
);
3143 *active_file
/= 1024;
3144 } else if (startswith(memstat
, "total_inactive_file")) {
3145 sscanf(memstat
+ 19, "%lu", inactive_file
);
3146 *inactive_file
/= 1024;
3147 } else if (startswith(memstat
, "total_unevictable")) {
3148 sscanf(memstat
+ 17, "%lu", unevictable
);
3149 *unevictable
/= 1024;
3151 eol
= strchr(memstat
, '\n');
3158 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3164 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3166 size_t len
= strlen(key
);
3170 if (startswith(str
, key
)) {
3171 sscanf(str
+ len
, "%lu", v
);
3174 eol
= strchr(str
, '\n');
3181 static int read_file(const char *path
, char *buf
, size_t size
,
3182 struct file_info
*d
)
3184 size_t linelen
= 0, total_len
= 0, rv
= 0;
3186 char *cache
= d
->buf
;
3187 size_t cache_size
= d
->buflen
;
3188 FILE *f
= fopen(path
, "r");
3192 while (getline(&line
, &linelen
, f
) != -1) {
3193 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3195 perror("Error writing to cache");
3199 if (l
>= cache_size
) {
3200 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3209 d
->size
= total_len
;
3210 if (total_len
> size
)
3213 /* read from off 0 */
3214 memcpy(buf
, d
->buf
, total_len
);
3223 * FUSE ops for /proc
3226 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3228 char *memlimit_str
= NULL
;
3229 unsigned long memlimit
= -1;
3231 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3232 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3239 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3241 char *copy
= strdupa(cgroup
);
3242 unsigned long memlimit
= 0, retlimit
;
3244 retlimit
= get_memlimit(copy
, file
);
3246 while (strcmp(copy
, "/") != 0) {
3247 copy
= dirname(copy
);
3248 memlimit
= get_memlimit(copy
, file
);
3249 if (memlimit
!= -1 && memlimit
< retlimit
)
3250 retlimit
= memlimit
;
3256 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3257 struct fuse_file_info
*fi
)
3259 struct fuse_context
*fc
= fuse_get_context();
3260 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3262 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3263 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3264 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3265 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3266 active_file
= 0, inactive_file
= 0, unevictable
= 0,
3269 size_t linelen
= 0, total_len
= 0, rv
= 0;
3270 char *cache
= d
->buf
;
3271 size_t cache_size
= d
->buflen
;
3275 if (offset
> d
->size
)
3279 int left
= d
->size
- offset
;
3280 total_len
= left
> size
? size
: left
;
3281 memcpy(buf
, cache
+ offset
, total_len
);
3285 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3288 cg
= get_pid_cgroup(initpid
, "memory");
3290 return read_file("/proc/meminfo", buf
, size
, d
);
3291 prune_init_slice(cg
);
3293 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3294 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3296 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3299 // Following values are allowed to fail, because swapaccount might be turned
3300 // off for current kernel
3301 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3302 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3304 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3305 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3307 memswlimit
= memswlimit
/ 1024;
3308 memswusage
= memswusage
/ 1024;
3311 memusage
= strtoul(memusage_str
, NULL
, 10);
3315 parse_memstat(memstat_str
, &cached
, &active_anon
,
3316 &inactive_anon
, &active_file
, &inactive_file
,
3319 f
= fopen("/proc/meminfo", "r");
3323 while (getline(&line
, &linelen
, f
) != -1) {
3325 char *printme
, lbuf
[100];
3327 memset(lbuf
, 0, 100);
3328 if (startswith(line
, "MemTotal:")) {
3329 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3330 if (hosttotal
< memlimit
)
3331 memlimit
= hosttotal
;
3332 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3334 } else if (startswith(line
, "MemFree:")) {
3335 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3337 } else if (startswith(line
, "MemAvailable:")) {
3338 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3340 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3341 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3342 if (hostswtotal
< memswlimit
)
3343 memswlimit
= hostswtotal
;
3344 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3346 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3347 unsigned long swaptotal
= memswlimit
,
3348 swapusage
= memswusage
- memusage
,
3349 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3350 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3352 } else if (startswith(line
, "Slab:")) {
3353 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3355 } else if (startswith(line
, "Buffers:")) {
3356 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3358 } else if (startswith(line
, "Cached:")) {
3359 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3361 } else if (startswith(line
, "SwapCached:")) {
3362 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3364 } else if (startswith(line
, "Active:")) {
3365 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3366 active_anon
+ active_file
);
3368 } else if (startswith(line
, "Inactive:")) {
3369 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3370 inactive_anon
+ inactive_file
);
3372 } else if (startswith(line
, "Active(anon)")) {
3373 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3375 } else if (startswith(line
, "Inactive(anon)")) {
3376 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3378 } else if (startswith(line
, "Active(file)")) {
3379 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3381 } else if (startswith(line
, "Inactive(file)")) {
3382 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3384 } else if (startswith(line
, "Unevictable")) {
3385 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3387 } else if (startswith(line
, "SReclaimable")) {
3388 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3390 } else if (startswith(line
, "SUnreclaim")) {
3391 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3396 l
= snprintf(cache
, cache_size
, "%s", printme
);
3398 perror("Error writing to cache");
3403 if (l
>= cache_size
) {
3404 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3415 d
->size
= total_len
;
3416 if (total_len
> size
) total_len
= size
;
3417 memcpy(buf
, d
->buf
, total_len
);
3426 free(memswlimit_str
);
3427 free(memswusage_str
);
3433 * Read the cpuset.cpus for cg
3434 * Return the answer in a newly allocated string which must be freed
3436 static char *get_cpuset(const char *cg
)
3440 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3445 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3447 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3451 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3453 return cpu_in_cpuset(cpu
, cpuset
);
3457 * check whether this is a '^processor" line in /proc/cpuinfo
3459 static bool is_processor_line(const char *line
)
3463 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3468 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3469 struct fuse_file_info
*fi
)
3471 struct fuse_context
*fc
= fuse_get_context();
3472 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3474 char *cpuset
= NULL
;
3476 size_t linelen
= 0, total_len
= 0, rv
= 0;
3477 bool am_printing
= false, firstline
= true, is_s390x
= false;
3478 int curcpu
= -1, cpu
;
3479 char *cache
= d
->buf
;
3480 size_t cache_size
= d
->buflen
;
3484 if (offset
> d
->size
)
3488 int left
= d
->size
- offset
;
3489 total_len
= left
> size
? size
: left
;
3490 memcpy(buf
, cache
+ offset
, total_len
);
3494 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3497 cg
= get_pid_cgroup(initpid
, "cpuset");
3499 return read_file("proc/cpuinfo", buf
, size
, d
);
3500 prune_init_slice(cg
);
3502 cpuset
= get_cpuset(cg
);
3506 f
= fopen("/proc/cpuinfo", "r");
3510 while (getline(&line
, &linelen
, f
) != -1) {
3514 if (strstr(line
, "IBM/S390") != NULL
) {
3520 if (strncmp(line
, "# processors:", 12) == 0)
3522 if (is_processor_line(line
)) {
3523 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3526 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3528 perror("Error writing to cache");
3532 if (l
>= cache_size
) {
3533 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3542 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3544 if (!cpu_in_cpuset(cpu
, cpuset
))
3547 p
= strchr(line
, ':');
3551 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3553 perror("Error writing to cache");
3557 if (l
>= cache_size
) {
3558 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3569 l
= snprintf(cache
, cache_size
, "%s", line
);
3571 perror("Error writing to cache");
3575 if (l
>= cache_size
) {
3576 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3587 char *origcache
= d
->buf
;
3590 d
->buf
= malloc(d
->buflen
);
3593 cache_size
= d
->buflen
;
3595 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3596 if (l
< 0 || l
>= cache_size
) {
3603 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3604 if (l
< 0 || l
>= cache_size
) {
3611 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3613 if (l
< 0 || l
>= cache_size
)
3619 d
->size
= total_len
;
3620 if (total_len
> size
) total_len
= size
;
3622 /* read from off 0 */
3623 memcpy(buf
, d
->buf
, total_len
);
3634 static uint64_t get_reaper_start_time(pid_t pid
)
3639 /* strlen("/proc/") = 6
3643 * strlen("/stat") = 5
3647 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3648 char path
[__PROC_PID_STAT_LEN
];
3651 qpid
= lookup_initpid_in_store(pid
);
3653 /* Caller can check for EINVAL on 0. */
3658 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3659 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3660 /* Caller can check for EINVAL on 0. */
3665 f
= fopen(path
, "r");
3667 /* Caller can check for EINVAL on 0. */
3672 /* Note that the *scanf() argument supression requires that length
3673 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3674 * at us. It's like telling someone you're not married and then asking
3675 * if you can bring your wife to the party.
3677 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3678 "%*s " /* (2) comm %s */
3679 "%*c " /* (3) state %c */
3680 "%*d " /* (4) ppid %d */
3681 "%*d " /* (5) pgrp %d */
3682 "%*d " /* (6) session %d */
3683 "%*d " /* (7) tty_nr %d */
3684 "%*d " /* (8) tpgid %d */
3685 "%*u " /* (9) flags %u */
3686 "%*u " /* (10) minflt %lu */
3687 "%*u " /* (11) cminflt %lu */
3688 "%*u " /* (12) majflt %lu */
3689 "%*u " /* (13) cmajflt %lu */
3690 "%*u " /* (14) utime %lu */
3691 "%*u " /* (15) stime %lu */
3692 "%*d " /* (16) cutime %ld */
3693 "%*d " /* (17) cstime %ld */
3694 "%*d " /* (18) priority %ld */
3695 "%*d " /* (19) nice %ld */
3696 "%*d " /* (20) num_threads %ld */
3697 "%*d " /* (21) itrealvalue %ld */
3698 "%" PRIu64
, /* (22) starttime %llu */
3702 /* Caller can check for EINVAL on 0. */
3713 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3715 uint64_t clockticks
;
3716 int64_t ticks_per_sec
;
3718 clockticks
= get_reaper_start_time(pid
);
3719 if (clockticks
== 0 && errno
== EINVAL
) {
3720 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3724 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3725 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3728 "failed to determine number of clock ticks in a second");
3732 return (clockticks
/= ticks_per_sec
);
3735 static uint64_t get_reaper_age(pid_t pid
)
3737 uint64_t procstart
, uptime
, procage
;
3739 /* We need to substract the time the process has started since system
3740 * boot minus the time when the system has started to get the actual
3743 procstart
= get_reaper_start_time_in_sec(pid
);
3744 procage
= procstart
;
3745 if (procstart
> 0) {
3747 struct timespec spec
;
3749 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3752 /* We could make this more precise here by using the tv_nsec
3753 * field in the timespec struct and convert it to milliseconds
3754 * and then create a double for the seconds and milliseconds but
3755 * that seems more work than it is worth.
3757 uptime
= spec
.tv_sec
;
3758 procage
= uptime
- procstart
;
3764 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
3765 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3766 struct fuse_file_info
*fi
)
3768 struct fuse_context
*fc
= fuse_get_context();
3769 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3771 char *cpuset
= NULL
;
3773 size_t linelen
= 0, total_len
= 0, rv
= 0;
3774 int curcpu
= -1; /* cpu numbering starts at 0 */
3775 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
3776 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3777 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
3778 char cpuall
[CPUALL_MAX_SIZE
];
3779 /* reserve for cpu all */
3780 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3781 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3785 if (offset
> d
->size
)
3789 int left
= d
->size
- offset
;
3790 total_len
= left
> size
? size
: left
;
3791 memcpy(buf
, d
->buf
+ offset
, total_len
);
3795 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3798 cg
= get_pid_cgroup(initpid
, "cpuset");
3800 return read_file("/proc/stat", buf
, size
, d
);
3801 prune_init_slice(cg
);
3803 cpuset
= get_cpuset(cg
);
3807 f
= fopen("/proc/stat", "r");
3812 if (getline(&line
, &linelen
, f
) < 0) {
3813 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3817 while (getline(&line
, &linelen
, f
) != -1) {
3820 char cpu_char
[10]; /* That's a lot of cores */
3823 if (strlen(line
) == 0)
3825 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3826 /* not a ^cpuN line containing a number N, just print it */
3827 l
= snprintf(cache
, cache_size
, "%s", line
);
3829 perror("Error writing to cache");
3833 if (l
>= cache_size
) {
3834 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3844 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3846 if (!cpu_in_cpuset(cpu
, cpuset
))
3850 c
= strchr(line
, ' ');
3853 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3855 perror("Error writing to cache");
3860 if (l
>= cache_size
) {
3861 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3870 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
3884 system_sum
+= system
;
3886 iowait_sum
+= iowait
;
3888 softirq_sum
+= softirq
;
3891 guest_nice_sum
+= guest_nice
;
3896 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3907 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
3908 memcpy(cache
, cpuall
, cpuall_len
);
3909 cache
+= cpuall_len
;
3911 /* shouldn't happen */
3912 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
3916 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3917 total_len
+= cpuall_len
;
3919 d
->size
= total_len
;
3920 if (total_len
> size
)
3923 memcpy(buf
, d
->buf
, total_len
);
3935 /* This function retrieves the busy time of a group of tasks by looking at
3936 * cpuacct.usage. Unfortunately, this only makes sense when the container has
3937 * been given it's own cpuacct cgroup. If not, this function will take the busy
3938 * time of all other taks that do not actually belong to the container into
3939 * account as well. If someone has a clever solution for this please send a
3942 static unsigned long get_reaper_busy(pid_t task
)
3944 pid_t initpid
= lookup_initpid_in_store(task
);
3945 char *cgroup
= NULL
, *usage_str
= NULL
;
3946 unsigned long usage
= 0;
3951 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3954 prune_init_slice(cgroup
);
3955 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3957 usage
= strtoul(usage_str
, NULL
, 10);
3958 usage
/= 1000000000;
3971 fd
= creat("/tmp/lxcfs-iwashere", 0644);
3978 * We read /proc/uptime and reuse its second field.
3979 * For the first field, we use the mtime for the reaper for
3980 * the calling pid as returned by getreaperage
3982 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
3983 struct fuse_file_info
*fi
)
3985 struct fuse_context
*fc
= fuse_get_context();
3986 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3987 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
3988 char *cache
= d
->buf
;
3989 ssize_t total_len
= 0;
3990 uint64_t idletime
, reaperage
;
3999 if (offset
> d
->size
)
4001 int left
= d
->size
- offset
;
4002 total_len
= left
> size
? size
: left
;
4003 memcpy(buf
, cache
+ offset
, total_len
);
4007 reaperage
= get_reaper_age(fc
->pid
);
4008 /* To understand why this is done, please read the comment to the
4009 * get_reaper_busy() function.
4011 idletime
= reaperage
;
4012 if (reaperage
>= busytime
)
4013 idletime
= reaperage
- busytime
;
4015 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
4016 if (total_len
< 0 || total_len
>= d
->buflen
){
4017 lxcfs_error("%s\n", "failed to write to cache");
4021 d
->size
= (int)total_len
;
4024 if (total_len
> size
) total_len
= size
;
4026 memcpy(buf
, d
->buf
, total_len
);
4030 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
4031 struct fuse_file_info
*fi
)
4034 struct fuse_context
*fc
= fuse_get_context();
4035 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4037 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
4038 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
4039 unsigned long read
= 0, write
= 0;
4040 unsigned long read_merged
= 0, write_merged
= 0;
4041 unsigned long read_sectors
= 0, write_sectors
= 0;
4042 unsigned long read_ticks
= 0, write_ticks
= 0;
4043 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
4044 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
4045 char *cache
= d
->buf
;
4046 size_t cache_size
= d
->buflen
;
4048 size_t linelen
= 0, total_len
= 0, rv
= 0;
4049 unsigned int major
= 0, minor
= 0;
4054 if (offset
> d
->size
)
4058 int left
= d
->size
- offset
;
4059 total_len
= left
> size
? size
: left
;
4060 memcpy(buf
, cache
+ offset
, total_len
);
4064 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4067 cg
= get_pid_cgroup(initpid
, "blkio");
4069 return read_file("/proc/diskstats", buf
, size
, d
);
4070 prune_init_slice(cg
);
4072 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
4074 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
4076 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
4078 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
4080 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
4084 f
= fopen("/proc/diskstats", "r");
4088 while (getline(&line
, &linelen
, f
) != -1) {
4092 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
4096 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
4097 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
4098 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
4099 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
4100 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
4101 read_sectors
= read_sectors
/512;
4102 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
4103 write_sectors
= write_sectors
/512;
4105 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
4106 rd_svctm
= rd_svctm
/1000000;
4107 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
4108 rd_wait
= rd_wait
/1000000;
4109 read_ticks
= rd_svctm
+ rd_wait
;
4111 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
4112 wr_svctm
= wr_svctm
/1000000;
4113 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
4114 wr_wait
= wr_wait
/1000000;
4115 write_ticks
= wr_svctm
+ wr_wait
;
4117 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
4118 tot_ticks
= tot_ticks
/1000000;
4120 memset(lbuf
, 0, 256);
4121 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
4122 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4123 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
4124 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
4128 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
4130 perror("Error writing to fuse buf");
4134 if (l
>= cache_size
) {
4135 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4145 d
->size
= total_len
;
4146 if (total_len
> size
) total_len
= size
;
4147 memcpy(buf
, d
->buf
, total_len
);
4155 free(io_serviced_str
);
4156 free(io_merged_str
);
4157 free(io_service_bytes_str
);
4158 free(io_wait_time_str
);
4159 free(io_service_time_str
);
4163 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
4164 struct fuse_file_info
*fi
)
4166 struct fuse_context
*fc
= fuse_get_context();
4167 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4169 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
4170 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
4171 ssize_t total_len
= 0, rv
= 0;
4173 char *cache
= d
->buf
;
4176 if (offset
> d
->size
)
4180 int left
= d
->size
- offset
;
4181 total_len
= left
> size
? size
: left
;
4182 memcpy(buf
, cache
+ offset
, total_len
);
4186 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4189 cg
= get_pid_cgroup(initpid
, "memory");
4191 return read_file("/proc/swaps", buf
, size
, d
);
4192 prune_init_slice(cg
);
4194 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
4196 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
4199 memusage
= strtoul(memusage_str
, NULL
, 10);
4201 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
4202 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
4204 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
4205 memswusage
= strtoul(memswusage_str
, NULL
, 10);
4207 swap_total
= (memswlimit
- memlimit
) / 1024;
4208 swap_free
= (memswusage
- memusage
) / 1024;
4211 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
4213 /* When no mem + swap limit is specified or swapaccount=0*/
4217 FILE *f
= fopen("/proc/meminfo", "r");
4222 while (getline(&line
, &linelen
, f
) != -1) {
4223 if (startswith(line
, "SwapTotal:")) {
4224 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
4225 } else if (startswith(line
, "SwapFree:")) {
4226 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
4234 if (swap_total
> 0) {
4235 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
4236 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
4237 swap_total
, swap_free
);
4241 if (total_len
< 0 || l
< 0) {
4242 perror("Error writing to cache");
4248 d
->size
= (int)total_len
;
4250 if (total_len
> size
) total_len
= size
;
4251 memcpy(buf
, d
->buf
, total_len
);
4256 free(memswlimit_str
);
4259 free(memswusage_str
);
4263 * Find the process pid from cgroup path.
4264 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
4265 * @pid_buf : put pid to pid_buf.
4266 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
4267 * @depth : the depth of cgroup in container.
4268 * @sum : return the number of pid.
4269 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
4271 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
4275 struct dirent
*file
;
4280 char *path_dir
, *path
;
4283 /* path = dpath + "/cgroup.procs" + /0 */
4285 path
= malloc(strlen(dpath
) + 20);
4288 strcpy(path
, dpath
);
4289 fd
= openat(cfd
, path
, O_RDONLY
);
4293 dir
= fdopendir(fd
);
4299 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
4300 if (strncmp(file
->d_name
, ".", 1) == 0)
4302 if (strncmp(file
->d_name
, "..", 1) == 0)
4304 if (file
->d_type
== DT_DIR
) {
4305 /* path + '/' + d_name +/0 */
4307 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
4308 } while (!path_dir
);
4309 strcpy(path_dir
, path
);
4310 strcat(path_dir
, "/");
4311 strcat(path_dir
, file
->d_name
);
4313 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
4319 strcat(path
, "/cgroup.procs");
4320 fd
= openat(cfd
, path
, O_RDONLY
);
4324 f
= fdopen(fd
, "r");
4330 while (getline(&line
, &linelen
, f
) != -1) {
4332 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
4336 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
4337 } while (*(*pid_buf
+ sum
) == NULL
);
4338 strcpy(*(*pid_buf
+ sum
), line
);
4347 * calc_load calculates the load according to the following formula:
4348 * load1 = load0 * exp + active * (1 - exp)
4350 * @load1: the new loadavg.
4351 * @load0: the former loadavg.
4352 * @active: the total number of running pid at this moment.
4353 * @exp: the fixed-point defined in the beginning.
4355 static unsigned long
4356 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
4358 unsigned long newload
;
4360 active
= active
> 0 ? active
* FIXED_1
: 0;
4361 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
4363 newload
+= FIXED_1
- 1;
4365 return newload
/ FIXED_1
;
4369 * Return 0 means that container p->cg is closed.
4370 * Return -1 means that error occurred in refresh.
4371 * Positive num equals the total number of pid.
4373 static int refresh_load(struct load_node
*p
, char *path
)
4377 char proc_path
[256];
4378 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
4383 struct dirent
*file
;
4386 idbuf
= malloc(sizeof(char *));
4388 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
4393 for (i
= 0; i
< sum
; i
++) {
4395 length
= strlen(idbuf
[i
])-1;
4396 idbuf
[i
][length
] = '\0';
4397 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
4398 if (ret
< 0 || ret
> 255) {
4399 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4405 dp
= opendir(proc_path
);
4407 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
4410 while ((file
= readdir(dp
)) != NULL
) {
4411 if (strncmp(file
->d_name
, ".", 1) == 0)
4413 if (strncmp(file
->d_name
, "..", 1) == 0)
4416 /* We make the biggest pid become last_pid.*/
4417 ret
= atof(file
->d_name
);
4418 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
4420 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
4421 if (ret
< 0 || ret
> 255) {
4422 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4428 f
= fopen(proc_path
, "r");
4430 while (getline(&line
, &linelen
, f
) != -1) {
4432 if ((line
[0] == 'S') && (line
[1] == 't'))
4435 if ((line
[7] == 'R') || (line
[7] == 'D'))
4442 /*Calculate the loadavg.*/
4443 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
4444 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
4445 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
4446 p
->run_pid
= run_pid
;
4447 p
->total_pid
= total_pid
;
4448 p
->last_pid
= last_pid
;
4459 * Traverse the hash table and update it.
4461 void *load_begin(void *arg
)
4465 int i
, sum
, length
, ret
;
4466 struct load_node
*f
;
4468 clock_t time1
, time2
;
4472 for (i
= 0; i
< LOAD_SIZE
; i
++) {
4473 pthread_mutex_lock(&load_hash
[i
].lock
);
4474 if (load_hash
[i
].next
== NULL
) {
4475 pthread_mutex_unlock(&load_hash
[i
].lock
);
4478 f
= load_hash
[i
].next
;
4481 length
= strlen(f
->cg
) + 2;
4483 /* strlen(f->cg) + '.' or '' + \0 */
4484 path
= malloc(length
);
4487 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
4488 if (ret
< 0 || ret
> length
- 1) {
4489 /* snprintf failed, ignore the node.*/
4490 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
4493 sum
= refresh_load(f
, path
);
4500 /* load_hash[i].lock locks only on the first node.*/
4501 if (first_node
== 1) {
4503 pthread_mutex_unlock(&load_hash
[i
].lock
);
4508 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
4512 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
4513 struct fuse_file_info
*fi
)
4515 struct fuse_context
*fc
= fuse_get_context();
4516 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4519 size_t total_len
= 0;
4520 char *cache
= d
->buf
;
4521 struct load_node
*n
;
4524 unsigned long a
, b
, c
;
4527 if (offset
> d
->size
)
4531 int left
= d
->size
- offset
;
4532 total_len
= left
> size
? size
: left
;
4533 memcpy(buf
, cache
+ offset
, total_len
);
4537 return read_file("/proc/loadavg", buf
, size
, d
);
4539 initpid
= lookup_initpid_in_store(fc
->pid
);
4542 cg
= get_pid_cgroup(initpid
, "cpu");
4544 return read_file("/proc/loadavg", buf
, size
, d
);
4546 prune_init_slice(cg
);
4547 hash
= calc_hash(cg
);
4548 n
= locate_node(cg
, hash
);
4552 if (!find_mounted_controller("cpu", &cfd
)) {
4554 * In locate_node() above, pthread_rwlock_unlock() isn't used
4555 * because delete is not allowed before read has ended.
4557 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4561 n
= malloc(sizeof(struct load_node
));
4565 n
->cg
= malloc(strlen(cg
)+1);
4573 n
->last_pid
= initpid
;
4575 insert_node(&n
, hash
);
4577 a
= n
->avenrun
[0] + (FIXED_1
/200);
4578 b
= n
->avenrun
[1] + (FIXED_1
/200);
4579 c
= n
->avenrun
[2] + (FIXED_1
/200);
4580 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
4581 LOAD_INT(a
), LOAD_FRAC(a
),
4582 LOAD_INT(b
), LOAD_FRAC(b
),
4583 LOAD_INT(c
), LOAD_FRAC(c
),
4584 n
->run_pid
, n
->total_pid
, n
->last_pid
);
4585 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4586 if (total_len
< 0 || total_len
>= d
->buflen
) {
4587 lxcfs_error("%s\n", "Failed to write to cache");
4590 d
->size
= (int)total_len
;
4593 if (total_len
> size
)
4595 memcpy(buf
, d
->buf
, total_len
);
4598 /* Return a positive number on success, return 0 on failure.*/
4599 pthread_t
load_daemon(int load_use
)
4606 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
4609 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
4611 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
4615 /* use loadavg, here loadavg = 1*/
4620 static off_t
get_procfile_size(const char *which
)
4622 FILE *f
= fopen(which
, "r");
4625 ssize_t sz
, answer
= 0;
4629 while ((sz
= getline(&line
, &len
, f
)) != -1)
4637 int proc_getattr(const char *path
, struct stat
*sb
)
4639 struct timespec now
;
4641 memset(sb
, 0, sizeof(struct stat
));
4642 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
4644 sb
->st_uid
= sb
->st_gid
= 0;
4645 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4646 if (strcmp(path
, "/proc") == 0) {
4647 sb
->st_mode
= S_IFDIR
| 00555;
4651 if (strcmp(path
, "/proc/meminfo") == 0 ||
4652 strcmp(path
, "/proc/cpuinfo") == 0 ||
4653 strcmp(path
, "/proc/uptime") == 0 ||
4654 strcmp(path
, "/proc/stat") == 0 ||
4655 strcmp(path
, "/proc/diskstats") == 0 ||
4656 strcmp(path
, "/proc/swaps") == 0 ||
4657 strcmp(path
, "/proc/loadavg") == 0) {
4659 sb
->st_mode
= S_IFREG
| 00444;
4667 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4668 struct fuse_file_info
*fi
)
4670 if (filler(buf
, ".", NULL
, 0) != 0 ||
4671 filler(buf
, "..", NULL
, 0) != 0 ||
4672 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4673 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4674 filler(buf
, "stat", NULL
, 0) != 0 ||
4675 filler(buf
, "uptime", NULL
, 0) != 0 ||
4676 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4677 filler(buf
, "swaps", NULL
, 0) != 0 ||
4678 filler(buf
, "loadavg", NULL
, 0) != 0)
4683 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4686 struct file_info
*info
;
4688 if (strcmp(path
, "/proc/meminfo") == 0)
4689 type
= LXC_TYPE_PROC_MEMINFO
;
4690 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4691 type
= LXC_TYPE_PROC_CPUINFO
;
4692 else if (strcmp(path
, "/proc/uptime") == 0)
4693 type
= LXC_TYPE_PROC_UPTIME
;
4694 else if (strcmp(path
, "/proc/stat") == 0)
4695 type
= LXC_TYPE_PROC_STAT
;
4696 else if (strcmp(path
, "/proc/diskstats") == 0)
4697 type
= LXC_TYPE_PROC_DISKSTATS
;
4698 else if (strcmp(path
, "/proc/swaps") == 0)
4699 type
= LXC_TYPE_PROC_SWAPS
;
4700 else if (strcmp(path
, "/proc/loadavg") == 0)
4701 type
= LXC_TYPE_PROC_LOADAVG
;
4705 info
= malloc(sizeof(*info
));
4709 memset(info
, 0, sizeof(*info
));
4712 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4714 info
->buf
= malloc(info
->buflen
);
4715 } while (!info
->buf
);
4716 memset(info
->buf
, 0, info
->buflen
);
4717 /* set actual size to buffer size */
4718 info
->size
= info
->buflen
;
4720 fi
->fh
= (unsigned long)info
;
4724 int proc_access(const char *path
, int mask
)
4726 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4729 /* these are all read-only */
4730 if ((mask
& ~R_OK
) != 0)
4735 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4737 do_release_file_info(fi
);
4741 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4742 struct fuse_file_info
*fi
)
4744 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4747 case LXC_TYPE_PROC_MEMINFO
:
4748 return proc_meminfo_read(buf
, size
, offset
, fi
);
4749 case LXC_TYPE_PROC_CPUINFO
:
4750 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4751 case LXC_TYPE_PROC_UPTIME
:
4752 return proc_uptime_read(buf
, size
, offset
, fi
);
4753 case LXC_TYPE_PROC_STAT
:
4754 return proc_stat_read(buf
, size
, offset
, fi
);
4755 case LXC_TYPE_PROC_DISKSTATS
:
4756 return proc_diskstats_read(buf
, size
, offset
, fi
);
4757 case LXC_TYPE_PROC_SWAPS
:
4758 return proc_swaps_read(buf
, size
, offset
, fi
);
4759 case LXC_TYPE_PROC_LOADAVG
:
4760 return proc_loadavg_read(buf
, size
, offset
, fi
);
4767 * Functions needed to setup cgroups in the __constructor__.
4770 static bool mkdir_p(const char *dir
, mode_t mode
)
4772 const char *tmp
= dir
;
4773 const char *orig
= dir
;
4777 dir
= tmp
+ strspn(tmp
, "/");
4778 tmp
= dir
+ strcspn(dir
, "/");
4779 makeme
= strndup(orig
, dir
- orig
);
4782 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4783 lxcfs_error("Failed to create directory '%s': %s.\n",
4784 makeme
, strerror(errno
));
4789 } while(tmp
!= dir
);
4794 static bool umount_if_mounted(void)
4796 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
4797 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
4803 /* __typeof__ should be safe to use with all compilers. */
4804 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
4805 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
4807 return (fs
->f_type
== (fs_type_magic
)magic_val
);
4811 * looking at fs/proc_namespace.c, it appears we can
4812 * actually expect the rootfs entry to very specifically contain
4813 * " - rootfs rootfs "
4814 * IIUC, so long as we've chrooted so that rootfs is not our root,
4815 * the rootfs entry should always be skipped in mountinfo contents.
4817 static bool is_on_ramfs(void)
4825 f
= fopen("/proc/self/mountinfo", "r");
4829 while (getline(&line
, &len
, f
) != -1) {
4830 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
4831 p
= strchr(p
+ 1, ' ');
4834 p2
= strchr(p
+ 1, ' ');
4838 if (strcmp(p
+ 1, "/") == 0) {
4839 // this is '/'. is it the ramfs?
4840 p
= strchr(p2
+ 1, '-');
4841 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
4853 static int pivot_enter()
4855 int ret
= -1, oldroot
= -1, newroot
= -1;
4857 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
4859 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
4863 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
4865 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
4869 /* change into new root fs */
4870 if (fchdir(newroot
) < 0) {
4871 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
4875 /* pivot_root into our new root fs */
4876 if (pivot_root(".", ".") < 0) {
4877 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
4882 * At this point the old-root is mounted on top of our new-root.
4883 * To unmounted it we must not be chdir'd into it, so escape back
4886 if (fchdir(oldroot
) < 0) {
4887 lxcfs_error("%s\n", "Failed to enter old root.");
4891 if (umount2(".", MNT_DETACH
) < 0) {
4892 lxcfs_error("%s\n", "Failed to detach old root.");
4896 if (fchdir(newroot
) < 0) {
4897 lxcfs_error("%s\n", "Failed to re-enter new root.");
4912 static int chroot_enter()
4914 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
4915 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
4919 if (chroot(".") < 0) {
4920 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
4924 if (chdir("/") < 0) {
4925 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
4932 static int permute_and_enter(void)
4936 if (statfs("/", &sb
) < 0) {
4937 lxcfs_error("%s\n", "Could not stat / mountpoint.");
4941 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
4942 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
4943 * /proc/1/mountinfo. */
4944 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
4945 return chroot_enter();
4947 if (pivot_enter() < 0) {
4948 lxcfs_error("%s\n", "Could not perform pivot root.");
4955 /* Prepare our new clean root. */
4956 static int permute_prepare(void)
4958 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
4959 lxcfs_error("%s\n", "Failed to create directory for new root.");
4963 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
4964 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
4968 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
4969 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
4973 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
4974 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
4981 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
4982 static bool permute_root(void)
4984 /* Prepare new root. */
4985 if (permute_prepare() < 0)
4988 /* Pivot into new root. */
4989 if (permute_and_enter() < 0)
4995 static int preserve_mnt_ns(int pid
)
4998 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
5001 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
5002 if (ret
< 0 || (size_t)ret
>= len
)
5005 return open(path
, O_RDONLY
| O_CLOEXEC
);
5008 static bool cgfs_prepare_mounts(void)
5010 if (!mkdir_p(BASEDIR
, 0700)) {
5011 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
5015 if (!umount_if_mounted()) {
5016 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
5020 if (unshare(CLONE_NEWNS
) < 0) {
5021 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
5025 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
5026 if (cgroup_mount_ns_fd
< 0) {
5027 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
5031 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
5032 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
5036 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
5037 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
5044 static bool cgfs_mount_hierarchies(void)
5050 for (i
= 0; i
< num_hierarchies
; i
++) {
5051 char *controller
= hierarchies
[i
];
5053 clen
= strlen(controller
);
5054 len
= strlen(BASEDIR
) + clen
+ 2;
5055 target
= malloc(len
);
5059 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
5060 if (ret
< 0 || ret
>= len
) {
5064 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
5068 if (!strcmp(controller
, "unified"))
5069 ret
= mount("none", target
, "cgroup2", 0, NULL
);
5071 ret
= mount(controller
, target
, "cgroup", 0, controller
);
5073 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
5078 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
5079 if (fd_hierarchies
[i
] < 0) {
5088 static bool cgfs_setup_controllers(void)
5090 if (!cgfs_prepare_mounts())
5093 if (!cgfs_mount_hierarchies()) {
5094 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
5098 if (!permute_root())
5104 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
5107 char *cret
, *line
= NULL
;
5108 char cwd
[MAXPATHLEN
];
5110 int i
, init_ns
= -1;
5111 bool found_unified
= false;
5113 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
5114 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
5118 while (getline(&line
, &len
, f
) != -1) {
5121 p
= strchr(line
, ':');
5127 p2
= strrchr(p
, ':');
5132 /* With cgroupv2 /proc/self/cgroup can contain entries of the
5133 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
5134 * because it parses out the empty string "" and later on passes
5135 * it to mount(). Let's skip such entries.
5137 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
5138 found_unified
= true;
5142 if (!store_hierarchy(line
, p
))
5146 /* Preserve initial namespace. */
5147 init_ns
= preserve_mnt_ns(getpid());
5149 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
5153 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
5154 if (!fd_hierarchies
) {
5155 lxcfs_error("%s\n", strerror(errno
));
5159 for (i
= 0; i
< num_hierarchies
; i
++)
5160 fd_hierarchies
[i
] = -1;
5162 cret
= getcwd(cwd
, MAXPATHLEN
);
5164 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
5166 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
5167 * to privately mount lxcfs cgroups. */
5168 if (!cgfs_setup_controllers()) {
5169 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
5173 if (setns(init_ns
, 0) < 0) {
5174 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
5178 if (!cret
|| chdir(cwd
) < 0)
5179 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
5190 static void __attribute__((destructor
)) free_subsystems(void)
5194 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
5196 for (i
= 0; i
< num_hierarchies
; i
++) {
5198 free(hierarchies
[i
]);
5199 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
5200 close(fd_hierarchies
[i
]);
5203 free(fd_hierarchies
);
5205 if (cgroup_mount_ns_fd
>= 0)
5206 close(cgroup_mount_ns_fd
);