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 struct cpuacct_usage
{
88 /* The function of hash table.*/
89 #define LOAD_SIZE 100 /*the size of hash_table */
90 #define FLUSH_TIME 5 /*the flush rate */
91 #define DEPTH_DIR 3 /*the depth of per cgroup */
92 /* The function of calculate loadavg .*/
93 #define FSHIFT 11 /* nr of bits of precision */
94 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
95 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
96 #define EXP_5 2014 /* 1/exp(5sec/5min) */
97 #define EXP_15 2037 /* 1/exp(5sec/15min) */
98 #define LOAD_INT(x) ((x) >> FSHIFT)
99 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
101 * This parameter is used for proc_loadavg_read().
102 * 1 means use loadavg, 0 means not use.
104 static int loadavg
= 0;
105 static volatile sig_atomic_t loadavg_stop
= 0;
106 static int calc_hash(char *name
)
108 unsigned int hash
= 0;
110 /* ELFHash algorithm. */
112 hash
= (hash
<< 4) + *name
++;
113 x
= hash
& 0xf0000000;
118 return ((hash
& 0x7fffffff) % LOAD_SIZE
);
123 unsigned long avenrun
[3]; /* Load averages */
124 unsigned int run_pid
;
125 unsigned int total_pid
;
126 unsigned int last_pid
;
127 int cfd
; /* The file descriptor of the mounted cgroup */
128 struct load_node
*next
;
129 struct load_node
**pre
;
134 * The lock is about insert load_node and refresh load_node.To the first
135 * load_node of each hash bucket, insert and refresh in this hash bucket is
136 * mutually exclusive.
138 pthread_mutex_t lock
;
140 * The rdlock is about read loadavg and delete load_node.To each hash
141 * bucket, read and delete is mutually exclusive. But at the same time, we
142 * allow paratactic read operation. This rdlock is at list level.
144 pthread_rwlock_t rdlock
;
146 * The rilock is about read loadavg and insert load_node.To the first
147 * load_node of each hash bucket, read and insert is mutually exclusive.
148 * But at the same time, we allow paratactic read operation.
150 pthread_rwlock_t rilock
;
151 struct load_node
*next
;
154 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
156 * init_load initialize the hash table.
157 * Return 0 on success, return -1 on failure.
159 static int init_load(void)
164 for (i
= 0; i
< LOAD_SIZE
; i
++) {
165 load_hash
[i
].next
= NULL
;
166 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
168 lxcfs_error("%s\n", "Failed to initialize lock");
171 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
173 lxcfs_error("%s\n", "Failed to initialize rdlock");
176 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
178 lxcfs_error("%s\n", "Failed to initialize rilock");
184 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
186 pthread_mutex_destroy(&load_hash
[i
].lock
);
190 pthread_mutex_destroy(&load_hash
[i
].lock
);
191 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
192 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
197 static void insert_node(struct load_node
**n
, int locate
)
201 pthread_mutex_lock(&load_hash
[locate
].lock
);
202 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
203 f
= load_hash
[locate
].next
;
204 load_hash
[locate
].next
= *n
;
206 (*n
)->pre
= &(load_hash
[locate
].next
);
208 f
->pre
= &((*n
)->next
);
210 pthread_mutex_unlock(&load_hash
[locate
].lock
);
211 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
214 * locate_node() finds special node. Not return NULL means success.
215 * It should be noted that rdlock isn't unlocked at the end of code
216 * because this function is used to read special node. Delete is not
217 * allowed before read has ended.
218 * unlock rdlock only in proc_loadavg_read().
220 static struct load_node
*locate_node(char *cg
, int locate
)
222 struct load_node
*f
= NULL
;
225 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
226 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
227 if (load_hash
[locate
].next
== NULL
) {
228 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
231 f
= load_hash
[locate
].next
;
232 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
233 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
237 /* Delete the load_node n and return the next node of it. */
238 static struct load_node
*del_node(struct load_node
*n
, int locate
)
242 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
243 if (n
->next
== NULL
) {
247 n
->next
->pre
= n
->pre
;
252 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
256 static void load_free(void)
259 struct load_node
*f
, *p
;
261 for (i
= 0; i
< LOAD_SIZE
; i
++) {
262 pthread_mutex_lock(&load_hash
[i
].lock
);
263 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
264 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
265 if (load_hash
[i
].next
== NULL
) {
266 pthread_mutex_unlock(&load_hash
[i
].lock
);
267 pthread_mutex_destroy(&load_hash
[i
].lock
);
268 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
269 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
270 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
271 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
274 for (f
= load_hash
[i
].next
; f
; ) {
280 pthread_mutex_unlock(&load_hash
[i
].lock
);
281 pthread_mutex_destroy(&load_hash
[i
].lock
);
282 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
283 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
284 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
285 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
288 /* Reserve buffer size to account for file size changes. */
289 #define BUF_RESERVE_SIZE 512
292 * A table caching which pid is init for a pid namespace.
293 * When looking up which pid is init for $qpid, we first
294 * 1. Stat /proc/$qpid/ns/pid.
295 * 2. Check whether the ino_t is in our store.
296 * a. if not, fork a child in qpid's ns to send us
297 * ucred.pid = 1, and read the initpid. Cache
298 * initpid and creation time for /proc/initpid
299 * in a new store entry.
300 * b. if so, verify that /proc/initpid still matches
301 * what we have saved. If not, clear the store
302 * entry and go back to a. If so, return the
305 struct pidns_init_store
{
306 ino_t ino
; // inode number for /proc/$pid/ns/pid
307 pid_t initpid
; // the pid of nit in that ns
308 long int ctime
; // the time at which /proc/$initpid was created
309 struct pidns_init_store
*next
;
313 /* lol - look at how they are allocated in the kernel */
314 #define PIDNS_HASH_SIZE 4096
315 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
317 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
318 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
319 static void lock_mutex(pthread_mutex_t
*l
)
323 if ((ret
= pthread_mutex_lock(l
)) != 0) {
324 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
329 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
330 * Number of hierarchies mounted. */
331 static int num_hierarchies
;
333 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
334 * Hierachies mounted {cpuset, blkio, ...}:
335 * Initialized via __constructor__ collect_and_mount_subsystems(). */
336 static char **hierarchies
;
338 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
339 * Open file descriptors:
340 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
341 * private mount namespace.
342 * Initialized via __constructor__ collect_and_mount_subsystems().
343 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
344 * mounts and respective files in the private namespace even when located in
345 * another namespace using the *at() family of functions
346 * {openat(), fchownat(), ...}. */
347 static int *fd_hierarchies
;
348 static int cgroup_mount_ns_fd
= -1;
350 static void unlock_mutex(pthread_mutex_t
*l
)
354 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
355 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
360 static void store_lock(void)
362 lock_mutex(&pidns_store_mutex
);
365 static void store_unlock(void)
367 unlock_mutex(&pidns_store_mutex
);
370 /* Must be called under store_lock */
371 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
376 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
377 if (stat(fnam
, &initsb
) < 0)
380 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
381 initsb
.st_ctime
, e
->initpid
);
383 if (e
->ctime
!= initsb
.st_ctime
)
388 /* Must be called under store_lock */
389 static void remove_initpid(struct pidns_init_store
*e
)
391 struct pidns_init_store
*tmp
;
394 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
397 if (pidns_hash_table
[h
] == e
) {
398 pidns_hash_table
[h
] = e
->next
;
403 tmp
= pidns_hash_table
[h
];
405 if (tmp
->next
== e
) {
415 /* Must be called under store_lock */
416 static void prune_initpid_store(void)
418 static long int last_prune
= 0;
419 struct pidns_init_store
*e
, *prev
, *delme
;
420 long int now
, threshold
;
424 last_prune
= time(NULL
);
428 if (now
< last_prune
+ PURGE_SECS
)
431 lxcfs_debug("%s\n", "Pruning.");
434 threshold
= now
- 2 * PURGE_SECS
;
436 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
437 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
438 if (e
->lastcheck
< threshold
) {
440 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
444 prev
->next
= e
->next
;
446 pidns_hash_table
[i
] = e
->next
;
457 /* Must be called under store_lock */
458 static void save_initpid(struct stat
*sb
, pid_t pid
)
460 struct pidns_init_store
*e
;
465 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
467 snprintf(fpath
, 100, "/proc/%d", pid
);
468 if (stat(fpath
, &procsb
) < 0)
471 e
= malloc(sizeof(*e
));
475 e
->ctime
= procsb
.st_ctime
;
477 e
->next
= pidns_hash_table
[h
];
478 e
->lastcheck
= time(NULL
);
479 pidns_hash_table
[h
] = e
;
483 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
484 * entry for the inode number and creation time. Verify that the init pid
485 * is still valid. If not, remove it. Return the entry if valid, NULL
487 * Must be called under store_lock
489 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
491 int h
= HASH(sb
->st_ino
);
492 struct pidns_init_store
*e
= pidns_hash_table
[h
];
495 if (e
->ino
== sb
->st_ino
) {
496 if (initpid_still_valid(e
, sb
)) {
497 e
->lastcheck
= time(NULL
);
509 static int is_dir(const char *path
, int fd
)
512 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
513 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
518 static char *must_copy_string(const char *str
)
530 static inline void drop_trailing_newlines(char *s
)
534 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
538 #define BATCH_SIZE 50
539 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
541 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
542 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
544 if (!*mem
|| newbatches
> oldbatches
) {
547 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
552 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
554 size_t newlen
= *len
+ linelen
;
555 dorealloc(contents
, *len
, newlen
+ 1);
556 memcpy(*contents
+ *len
, line
, linelen
+1);
560 static char *slurp_file(const char *from
, int fd
)
563 char *contents
= NULL
;
564 FILE *f
= fdopen(fd
, "r");
565 size_t len
= 0, fulllen
= 0;
571 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
572 append_line(&contents
, &fulllen
, line
, linelen
);
577 drop_trailing_newlines(contents
);
582 static bool write_string(const char *fnam
, const char *string
, int fd
)
591 len
= strlen(string
);
592 ret
= fwrite(string
, 1, len
, f
);
594 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
595 strerror(errno
), string
, fnam
);
601 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
615 static bool store_hierarchy(char *stridx
, char *h
)
617 if (num_hierarchies
% ALLOC_NUM
== 0) {
618 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
620 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
622 lxcfs_error("%s\n", strerror(errno
));
628 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
632 static void print_subsystems(void)
636 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
637 fprintf(stderr
, "hierarchies:\n");
638 for (i
= 0; i
< num_hierarchies
; i
++) {
640 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
641 fd_hierarchies
[i
], hierarchies
[i
]);
645 static bool in_comma_list(const char *needle
, const char *haystack
)
647 const char *s
= haystack
, *e
;
648 size_t nlen
= strlen(needle
);
650 while (*s
&& (e
= strchr(s
, ','))) {
655 if (strncmp(needle
, s
, nlen
) == 0)
659 if (strcmp(needle
, s
) == 0)
664 /* do we need to do any massaging here? I'm not sure... */
665 /* Return the mounted controller and store the corresponding open file descriptor
666 * referring to the controller mountpoint in the private lxcfs namespace in
669 static char *find_mounted_controller(const char *controller
, int *cfd
)
673 for (i
= 0; i
< num_hierarchies
; i
++) {
676 if (strcmp(hierarchies
[i
], controller
) == 0) {
677 *cfd
= fd_hierarchies
[i
];
678 return hierarchies
[i
];
680 if (in_comma_list(controller
, hierarchies
[i
])) {
681 *cfd
= fd_hierarchies
[i
];
682 return hierarchies
[i
];
689 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
696 tmpc
= find_mounted_controller(controller
, &cfd
);
700 /* Make sure we pass a relative path to *at() family of functions.
701 * . + /cgroup + / + file + \0
703 len
= strlen(cgroup
) + strlen(file
) + 3;
705 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
706 if (ret
< 0 || (size_t)ret
>= len
)
709 fd
= openat(cfd
, fnam
, O_WRONLY
);
713 return write_string(fnam
, value
, fd
);
716 // Chown all the files in the cgroup directory. We do this when we create
717 // a cgroup on behalf of a user.
718 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
720 struct dirent
*direntp
;
721 char path
[MAXPATHLEN
];
726 len
= strlen(dirname
);
727 if (len
>= MAXPATHLEN
) {
728 lxcfs_error("Pathname too long: %s\n", dirname
);
732 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
738 lxcfs_error("Failed to open %s\n", dirname
);
742 while ((direntp
= readdir(d
))) {
743 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
745 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
746 if (ret
< 0 || ret
>= MAXPATHLEN
) {
747 lxcfs_error("Pathname too long under %s\n", dirname
);
750 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
751 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
756 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
762 tmpc
= find_mounted_controller(controller
, &cfd
);
766 /* Make sure we pass a relative path to *at() family of functions.
769 len
= strlen(cg
) + 2;
770 dirnam
= alloca(len
);
771 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
773 if (mkdirat(cfd
, dirnam
, 0755) < 0)
776 if (uid
== 0 && gid
== 0)
779 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
782 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
787 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
789 struct dirent
*direntp
;
792 char pathname
[MAXPATHLEN
];
795 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
799 dir
= fdopendir(dupfd
);
801 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
806 while ((direntp
= readdir(dir
))) {
810 if (!strcmp(direntp
->d_name
, ".") ||
811 !strcmp(direntp
->d_name
, ".."))
814 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
815 if (rc
< 0 || rc
>= MAXPATHLEN
) {
816 lxcfs_error("%s\n", "Pathname too long.");
820 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
822 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
825 if (S_ISDIR(mystat
.st_mode
))
826 if (!recursive_rmdir(pathname
, fd
, cfd
))
827 lxcfs_debug("Error removing %s.\n", pathname
);
831 if (closedir(dir
) < 0) {
832 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
836 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
837 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
846 bool cgfs_remove(const char *controller
, const char *cg
)
853 tmpc
= find_mounted_controller(controller
, &cfd
);
857 /* Make sure we pass a relative path to *at() family of functions.
860 len
= strlen(cg
) + 2;
861 dirnam
= alloca(len
);
862 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
864 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
868 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
873 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
877 char *pathname
, *tmpc
;
879 tmpc
= find_mounted_controller(controller
, &cfd
);
883 /* Make sure we pass a relative path to *at() family of functions.
886 len
= strlen(file
) + 2;
887 pathname
= alloca(len
);
888 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
889 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
894 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
899 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
901 snprintf(fname
, len
, "%s/tasks", dirname
);
902 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
904 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
905 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
910 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
914 char *pathname
, *tmpc
;
916 tmpc
= find_mounted_controller(controller
, &cfd
);
920 /* Make sure we pass a relative path to *at() family of functions.
923 len
= strlen(file
) + 2;
924 pathname
= alloca(len
);
925 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
926 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
929 if (is_dir(pathname
, cfd
))
930 // like cgmanager did, we want to chown the tasks file as well
931 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
936 FILE *open_pids_file(const char *controller
, const char *cgroup
)
940 char *pathname
, *tmpc
;
942 tmpc
= find_mounted_controller(controller
, &cfd
);
946 /* Make sure we pass a relative path to *at() family of functions.
947 * . + /cgroup + / "cgroup.procs" + \0
949 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
950 pathname
= alloca(len
);
951 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
953 fd
= openat(cfd
, pathname
, O_WRONLY
);
957 return fdopen(fd
, "w");
960 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
961 void ***list
, size_t typesize
,
962 void* (*iterator
)(const char*, const char*, const char*))
967 char pathname
[MAXPATHLEN
];
968 size_t sz
= 0, asz
= 0;
969 struct dirent
*dirent
;
972 tmpc
= find_mounted_controller(controller
, &cfd
);
977 /* Make sure we pass a relative path to *at() family of functions. */
978 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
980 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
981 if (ret
< 0 || (size_t)ret
>= len
) {
982 lxcfs_error("Pathname too long under %s\n", cgroup
);
986 fd
= openat(cfd
, cg
, O_DIRECTORY
);
994 while ((dirent
= readdir(dir
))) {
997 if (!strcmp(dirent
->d_name
, ".") ||
998 !strcmp(dirent
->d_name
, ".."))
1001 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1002 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1003 lxcfs_error("Pathname too long under %s\n", cg
);
1007 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1009 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1012 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1013 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1020 tmp
= realloc(*list
, asz
* typesize
);
1024 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1025 (*list
)[sz
+1] = NULL
;
1028 if (closedir(dir
) < 0) {
1029 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1035 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1039 dup
= strdup(dir_entry
);
1044 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1046 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1049 void free_key(struct cgfs_files
*k
)
1057 void free_keys(struct cgfs_files
**keys
)
1063 for (i
= 0; keys
[i
]; i
++) {
1069 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1075 tmpc
= find_mounted_controller(controller
, &cfd
);
1079 /* Make sure we pass a relative path to *at() family of functions.
1080 * . + /cgroup + / + file + \0
1082 len
= strlen(cgroup
) + strlen(file
) + 3;
1084 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1085 if (ret
< 0 || (size_t)ret
>= len
)
1088 fd
= openat(cfd
, fnam
, O_RDONLY
);
1092 *value
= slurp_file(fnam
, fd
);
1093 return *value
!= NULL
;
1096 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1102 struct cgfs_files
*newkey
;
1104 tmpc
= find_mounted_controller(controller
, &cfd
);
1108 if (file
&& *file
== '/')
1111 if (file
&& strchr(file
, '/'))
1114 /* Make sure we pass a relative path to *at() family of functions.
1115 * . + /cgroup + / + file + \0
1117 len
= strlen(cgroup
) + 3;
1119 len
+= strlen(file
) + 1;
1121 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1122 file
? "/" : "", file
? file
: "");
1124 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1129 newkey
= malloc(sizeof(struct cgfs_files
));
1132 newkey
->name
= must_copy_string(file
);
1133 else if (strrchr(cgroup
, '/'))
1134 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1136 newkey
->name
= must_copy_string(cgroup
);
1137 newkey
->uid
= sb
.st_uid
;
1138 newkey
->gid
= sb
.st_gid
;
1139 newkey
->mode
= sb
.st_mode
;
1144 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1146 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1148 lxcfs_error("Error getting files under %s:%s\n", controller
,
1154 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1156 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1159 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1167 tmpc
= find_mounted_controller(controller
, &cfd
);
1171 /* Make sure we pass a relative path to *at() family of functions.
1172 * . + /cgroup + / + f + \0
1174 len
= strlen(cgroup
) + strlen(f
) + 3;
1176 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1177 if (ret
< 0 || (size_t)ret
>= len
)
1180 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1181 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1187 #define SEND_CREDS_OK 0
1188 #define SEND_CREDS_NOTSK 1
1189 #define SEND_CREDS_FAIL 2
1190 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1191 static int wait_for_pid(pid_t pid
);
1192 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1193 static int send_creds_clone_wrapper(void *arg
);
1196 * clone a task which switches to @task's namespace and writes '1'.
1197 * over a unix sock so we can read the task's reaper's pid in our
1200 * Note: glibc's fork() does not respect pidns, which can lead to failed
1201 * assertions inside glibc (and thus failed forks) if the child's pid in
1202 * the pidns and the parent pid outside are identical. Using clone prevents
1205 static void write_task_init_pid_exit(int sock
, pid_t target
)
1210 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1211 void *stack
= alloca(stack_size
);
1213 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1214 if (ret
< 0 || ret
>= sizeof(fnam
))
1217 fd
= open(fnam
, O_RDONLY
);
1219 perror("write_task_init_pid_exit open of ns/pid");
1223 perror("write_task_init_pid_exit setns 1");
1227 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1231 if (!wait_for_pid(pid
))
1237 static int send_creds_clone_wrapper(void *arg
) {
1240 int sock
= *(int *)arg
;
1242 /* we are the child */
1247 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1252 static pid_t
get_init_pid_for_task(pid_t task
)
1260 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1261 perror("socketpair");
1270 write_task_init_pid_exit(sock
[0], task
);
1274 if (!recv_creds(sock
[1], &cred
, &v
))
1286 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1290 struct pidns_init_store
*e
;
1293 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1295 if (stat(fnam
, &sb
) < 0)
1297 e
= lookup_verify_initpid(&sb
);
1299 answer
= e
->initpid
;
1302 answer
= get_init_pid_for_task(qpid
);
1304 save_initpid(&sb
, answer
);
1307 /* we prune at end in case we are returning
1308 * the value we were about to return */
1309 prune_initpid_store();
1314 static int wait_for_pid(pid_t pid
)
1322 ret
= waitpid(pid
, &status
, 0);
1330 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1337 * append pid to *src.
1338 * src: a pointer to a char* in which ot append the pid.
1339 * sz: the number of characters printed so far, minus trailing \0.
1340 * asz: the allocated size so far
1341 * pid: the pid to append
1343 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1347 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1349 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1352 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1355 *asz
+= BUF_RESERVE_SIZE
;
1357 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1362 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1363 * valid in the caller's namespace, return the id mapped into
1365 * Returns the mapped id, or -1 on error.
1368 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1370 unsigned int nsuid
, // base id for a range in the idfile's namespace
1371 hostuid
, // base id for a range in the caller's namespace
1372 count
; // number of ids in this range
1376 fseek(idfile
, 0L, SEEK_SET
);
1377 while (fgets(line
, 400, idfile
)) {
1378 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1381 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1383 * uids wrapped around - unexpected as this is a procfile,
1386 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1387 nsuid
, hostuid
, count
, line
);
1390 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1392 * now since hostuid <= in_id < hostuid+count, and
1393 * hostuid+count and nsuid+count do not wrap around,
1394 * we know that nsuid+(in_id-hostuid) which must be
1395 * less that nsuid+(count) must not wrap around
1397 return (in_id
- hostuid
) + nsuid
;
1406 * for is_privileged_over,
1407 * specify whether we require the calling uid to be root in his
1410 #define NS_ROOT_REQD true
1411 #define NS_ROOT_OPT false
1415 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1417 char fpath
[PROCLEN
];
1419 bool answer
= false;
1422 if (victim
== -1 || uid
== -1)
1426 * If the request is one not requiring root in the namespace,
1427 * then having the same uid suffices. (i.e. uid 1000 has write
1428 * access to files owned by uid 1000
1430 if (!req_ns_root
&& uid
== victim
)
1433 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1434 if (ret
< 0 || ret
>= PROCLEN
)
1436 FILE *f
= fopen(fpath
, "r");
1440 /* if caller's not root in his namespace, reject */
1441 nsuid
= convert_id_to_ns(f
, uid
);
1446 * If victim is not mapped into caller's ns, reject.
1447 * XXX I'm not sure this check is needed given that fuse
1448 * will be sending requests where the vfs has converted
1450 nsuid
= convert_id_to_ns(f
, victim
);
1461 static bool perms_include(int fmode
, mode_t req_mode
)
1465 switch (req_mode
& O_ACCMODE
) {
1473 r
= S_IROTH
| S_IWOTH
;
1478 return ((fmode
& r
) == r
);
1484 * querycg is /a/b/c/d/e
1487 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1491 if (strlen(taskcg
) <= strlen(querycg
)) {
1492 lxcfs_error("%s\n", "I was fed bad input.");
1496 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1497 start
= strdup(taskcg
+ 1);
1499 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1502 end
= strchr(start
, '/');
1508 static void stripnewline(char *x
)
1510 size_t l
= strlen(x
);
1511 if (l
&& x
[l
-1] == '\n')
1515 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1520 char *answer
= NULL
;
1524 const char *h
= find_mounted_controller(contrl
, &cfd
);
1528 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1529 if (ret
< 0 || ret
>= PROCLEN
)
1531 if (!(f
= fopen(fnam
, "r")))
1534 while (getline(&line
, &len
, f
) != -1) {
1538 c1
= strchr(line
, ':');
1542 c2
= strchr(c1
, ':');
1546 if (strcmp(c1
, h
) != 0)
1551 answer
= strdup(c2
);
1563 * check whether a fuse context may access a cgroup dir or file
1565 * If file is not null, it is a cgroup file to check under cg.
1566 * If file is null, then we are checking perms on cg itself.
1568 * For files we can check the mode of the list_keys result.
1569 * For cgroups, we must make assumptions based on the files under the
1570 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1573 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1575 struct cgfs_files
*k
= NULL
;
1578 k
= cgfs_get_key(contrl
, cg
, file
);
1582 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1583 if (perms_include(k
->mode
>> 6, mode
)) {
1588 if (fc
->gid
== k
->gid
) {
1589 if (perms_include(k
->mode
>> 3, mode
)) {
1594 ret
= perms_include(k
->mode
, mode
);
1601 #define INITSCOPE "/init.scope"
1602 static void prune_init_slice(char *cg
)
1605 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1607 if (cg_len
< initscope_len
)
1610 point
= cg
+ cg_len
- initscope_len
;
1611 if (strcmp(point
, INITSCOPE
) == 0) {
1620 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1621 * If pid is in /a, he may act on /a/b, but not on /b.
1622 * if the answer is false and nextcg is not NULL, then *nextcg will point
1623 * to a string containing the next cgroup directory under cg, which must be
1624 * freed by the caller.
1626 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1628 bool answer
= false;
1629 char *c2
= get_pid_cgroup(pid
, contrl
);
1634 prune_init_slice(c2
);
1637 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1638 * they pass in a cgroup without leading '/'
1640 * The original line here was:
1641 * linecmp = *cg == '/' ? c2 : c2+1;
1642 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1643 * Serge, do you know?
1645 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1649 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1651 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1663 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1665 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1667 bool answer
= false;
1669 size_t target_len
, task_len
;
1671 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1674 c2
= get_pid_cgroup(pid
, contrl
);
1677 prune_init_slice(c2
);
1680 target_len
= strlen(cg
);
1681 task_len
= strlen(task_cg
);
1682 if (task_len
== 0) {
1683 /* Task is in the root cg, it can see everything. This case is
1684 * not handled by the strmcps below, since they test for the
1685 * last /, but that is the first / that we've chopped off
1691 if (strcmp(cg
, task_cg
) == 0) {
1695 if (target_len
< task_len
) {
1696 /* looking up a parent dir */
1697 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1701 if (target_len
> task_len
) {
1702 /* looking up a child dir */
1703 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1714 * given /cgroup/freezer/a/b, return "freezer".
1715 * the returned char* should NOT be freed.
1717 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1720 char *contr
, *slash
;
1722 if (strlen(path
) < 9) {
1726 if (*(path
+ 7) != '/') {
1731 contr
= strdupa(p1
);
1736 slash
= strstr(contr
, "/");
1741 for (i
= 0; i
< num_hierarchies
; i
++) {
1742 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1743 return hierarchies
[i
];
1750 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1751 * Note that the returned value may include files (keynames) etc
1753 static const char *find_cgroup_in_path(const char *path
)
1757 if (strlen(path
) < 9) {
1761 p1
= strstr(path
+ 8, "/");
1771 * split the last path element from the path in @cg.
1772 * @dir is newly allocated and should be freed, @last not
1774 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1781 *last
= strrchr(cg
, '/');
1786 p
= strrchr(*dir
, '/');
1791 * FUSE ops for /cgroup
1794 int cg_getattr(const char *path
, struct stat
*sb
)
1796 struct timespec now
;
1797 struct fuse_context
*fc
= fuse_get_context();
1798 char * cgdir
= NULL
;
1799 char *last
= NULL
, *path1
, *path2
;
1800 struct cgfs_files
*k
= NULL
;
1802 const char *controller
= NULL
;
1809 memset(sb
, 0, sizeof(struct stat
));
1811 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1814 sb
->st_uid
= sb
->st_gid
= 0;
1815 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1818 if (strcmp(path
, "/cgroup") == 0) {
1819 sb
->st_mode
= S_IFDIR
| 00755;
1824 controller
= pick_controller_from_path(fc
, path
);
1827 cgroup
= find_cgroup_in_path(path
);
1829 /* this is just /cgroup/controller, return it as a dir */
1830 sb
->st_mode
= S_IFDIR
| 00755;
1835 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1845 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1848 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1849 * Then check that caller's cgroup is under path if last is a child
1850 * cgroup, or cgdir if last is a file */
1852 if (is_child_cgroup(controller
, path1
, path2
)) {
1853 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1857 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1858 /* this is just /cgroup/controller, return it as a dir */
1859 sb
->st_mode
= S_IFDIR
| 00555;
1864 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1869 // get uid, gid, from '/tasks' file and make up a mode
1870 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1871 sb
->st_mode
= S_IFDIR
| 00755;
1872 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1874 sb
->st_uid
= sb
->st_gid
= 0;
1876 sb
->st_uid
= k
->uid
;
1877 sb
->st_gid
= k
->gid
;
1885 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1886 sb
->st_mode
= S_IFREG
| k
->mode
;
1888 sb
->st_uid
= k
->uid
;
1889 sb
->st_gid
= k
->gid
;
1892 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1904 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1906 struct fuse_context
*fc
= fuse_get_context();
1908 struct file_info
*dir_info
;
1909 char *controller
= NULL
;
1914 if (strcmp(path
, "/cgroup") == 0) {
1918 // return list of keys for the controller, and list of child cgroups
1919 controller
= pick_controller_from_path(fc
, path
);
1923 cgroup
= find_cgroup_in_path(path
);
1925 /* this is just /cgroup/controller, return its contents */
1930 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1934 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1936 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1940 /* we'll free this at cg_releasedir */
1941 dir_info
= malloc(sizeof(*dir_info
));
1944 dir_info
->controller
= must_copy_string(controller
);
1945 dir_info
->cgroup
= must_copy_string(cgroup
);
1946 dir_info
->type
= LXC_TYPE_CGDIR
;
1947 dir_info
->buf
= NULL
;
1948 dir_info
->file
= NULL
;
1949 dir_info
->buflen
= 0;
1951 fi
->fh
= (unsigned long)dir_info
;
1955 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1956 struct fuse_file_info
*fi
)
1958 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1959 struct cgfs_files
**list
= NULL
;
1961 char *nextcg
= NULL
;
1962 struct fuse_context
*fc
= fuse_get_context();
1963 char **clist
= NULL
;
1965 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1968 if (d
->type
!= LXC_TYPE_CGDIR
) {
1969 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1972 if (!d
->cgroup
&& !d
->controller
) {
1973 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1976 for (i
= 0; i
< num_hierarchies
; i
++) {
1977 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1984 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1985 // not a valid cgroup
1990 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1993 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1995 ret
= filler(buf
, nextcg
, NULL
, 0);
2006 for (i
= 0; list
[i
]; i
++) {
2007 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2013 // now get the list of child cgroups
2015 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2020 for (i
= 0; clist
[i
]; i
++) {
2021 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2032 for (i
= 0; clist
[i
]; i
++)
2039 static void do_release_file_info(struct fuse_file_info
*fi
)
2041 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2048 free(f
->controller
);
2049 f
->controller
= NULL
;
2060 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2062 do_release_file_info(fi
);
2066 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2069 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2070 struct cgfs_files
*k
= NULL
;
2071 struct file_info
*file_info
;
2072 struct fuse_context
*fc
= fuse_get_context();
2078 controller
= pick_controller_from_path(fc
, path
);
2081 cgroup
= find_cgroup_in_path(path
);
2085 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2094 k
= cgfs_get_key(controller
, path1
, path2
);
2101 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2104 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2108 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2113 /* we'll free this at cg_release */
2114 file_info
= malloc(sizeof(*file_info
));
2119 file_info
->controller
= must_copy_string(controller
);
2120 file_info
->cgroup
= must_copy_string(path1
);
2121 file_info
->file
= must_copy_string(path2
);
2122 file_info
->type
= LXC_TYPE_CGFILE
;
2123 file_info
->buf
= NULL
;
2124 file_info
->buflen
= 0;
2126 fi
->fh
= (unsigned long)file_info
;
2134 int cg_access(const char *path
, int mode
)
2138 char *path1
, *path2
, *controller
;
2139 char *last
= NULL
, *cgdir
= NULL
;
2140 struct cgfs_files
*k
= NULL
;
2141 struct fuse_context
*fc
= fuse_get_context();
2143 if (strcmp(path
, "/cgroup") == 0)
2149 controller
= pick_controller_from_path(fc
, path
);
2152 cgroup
= find_cgroup_in_path(path
);
2154 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2155 if ((mode
& W_OK
) == 0)
2160 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2169 k
= cgfs_get_key(controller
, path1
, path2
);
2171 if ((mode
& W_OK
) == 0)
2179 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2182 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2186 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2198 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2200 do_release_file_info(fi
);
2204 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2206 static bool wait_for_sock(int sock
, int timeout
)
2208 struct epoll_event ev
;
2209 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2211 if ((starttime
= time(NULL
)) < 0)
2214 if ((epfd
= epoll_create(1)) < 0) {
2215 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2219 ev
.events
= POLLIN_SET
;
2221 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2222 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2228 if ((now
= time(NULL
)) < 0) {
2233 deltatime
= (starttime
+ timeout
) - now
;
2234 if (deltatime
< 0) { // timeout
2239 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2240 if (ret
< 0 && errno
== EINTR
)
2242 saved_errno
= errno
;
2246 errno
= saved_errno
;
2252 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2254 if (!wait_for_sock(sockfd
, 2))
2256 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2259 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2261 struct msghdr msg
= { 0 };
2263 struct cmsghdr
*cmsg
;
2264 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2269 if (msgrecv(sock
, buf
, 1) != 1) {
2270 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2271 return SEND_CREDS_FAIL
;
2275 msg
.msg_control
= cmsgbuf
;
2276 msg
.msg_controllen
= sizeof(cmsgbuf
);
2278 cmsg
= CMSG_FIRSTHDR(&msg
);
2279 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2280 cmsg
->cmsg_level
= SOL_SOCKET
;
2281 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2282 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2284 msg
.msg_name
= NULL
;
2285 msg
.msg_namelen
= 0;
2289 iov
.iov_len
= sizeof(buf
);
2293 if (sendmsg(sock
, &msg
, 0) < 0) {
2294 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2296 return SEND_CREDS_NOTSK
;
2297 return SEND_CREDS_FAIL
;
2300 return SEND_CREDS_OK
;
2303 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2305 struct msghdr msg
= { 0 };
2307 struct cmsghdr
*cmsg
;
2308 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2319 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2320 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2324 if (write(sock
, buf
, 1) != 1) {
2325 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2329 msg
.msg_name
= NULL
;
2330 msg
.msg_namelen
= 0;
2331 msg
.msg_control
= cmsgbuf
;
2332 msg
.msg_controllen
= sizeof(cmsgbuf
);
2335 iov
.iov_len
= sizeof(buf
);
2339 if (!wait_for_sock(sock
, 2)) {
2340 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2343 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2345 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2349 cmsg
= CMSG_FIRSTHDR(&msg
);
2351 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2352 cmsg
->cmsg_level
== SOL_SOCKET
&&
2353 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2354 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2361 struct pid_ns_clone_args
{
2365 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2369 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2370 * with clone(). This simply writes '1' as ACK back to the parent
2371 * before calling the actual wrapped function.
2373 static int pid_ns_clone_wrapper(void *arg
) {
2374 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2377 close(args
->cpipe
[0]);
2378 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2379 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2380 close(args
->cpipe
[1]);
2381 return args
->wrapped(args
->sock
, args
->tpid
);
2385 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2386 * int value back over the socket. This shifts the pid from the
2387 * sender's pidns into tpid's pidns.
2389 static int pid_to_ns(int sock
, pid_t tpid
)
2394 while (recv_creds(sock
, &cred
, &v
)) {
2397 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2405 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2406 * in your old pidns. Only children which you clone will be in the target
2407 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2408 * actually convert pids.
2410 * Note: glibc's fork() does not respect pidns, which can lead to failed
2411 * assertions inside glibc (and thus failed forks) if the child's pid in
2412 * the pidns and the parent pid outside are identical. Using clone prevents
2415 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2417 int newnsfd
= -1, ret
, cpipe
[2];
2422 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2423 if (ret
< 0 || ret
>= sizeof(fnam
))
2425 newnsfd
= open(fnam
, O_RDONLY
);
2428 if (setns(newnsfd
, 0) < 0)
2432 if (pipe(cpipe
) < 0)
2435 struct pid_ns_clone_args args
= {
2439 .wrapped
= &pid_to_ns
2441 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2442 void *stack
= alloca(stack_size
);
2444 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2448 // give the child 1 second to be done forking and
2450 if (!wait_for_sock(cpipe
[0], 1))
2452 ret
= read(cpipe
[0], &v
, 1);
2453 if (ret
!= sizeof(char) || v
!= '1')
2456 if (!wait_for_pid(cpid
))
2462 * To read cgroup files with a particular pid, we will setns into the child
2463 * pidns, open a pipe, fork a child - which will be the first to really be in
2464 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2466 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2468 int sock
[2] = {-1, -1};
2469 char *tmpdata
= NULL
;
2471 pid_t qpid
, cpid
= -1;
2472 bool answer
= false;
2475 size_t sz
= 0, asz
= 0;
2477 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2481 * Now we read the pids from returned data one by one, pass
2482 * them into a child in the target namespace, read back the
2483 * translated pids, and put them into our to-return data
2486 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2487 perror("socketpair");
2496 if (!cpid
) // child - exits when done
2497 pid_to_ns_wrapper(sock
[1], tpid
);
2499 char *ptr
= tmpdata
;
2502 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2504 ret
= send_creds(sock
[0], &cred
, v
, true);
2506 if (ret
== SEND_CREDS_NOTSK
)
2508 if (ret
== SEND_CREDS_FAIL
)
2511 // read converted results
2512 if (!wait_for_sock(sock
[0], 2)) {
2513 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2516 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2517 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2520 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2522 ptr
= strchr(ptr
, '\n');
2528 cred
.pid
= getpid();
2530 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2531 // failed to ask child to exit
2532 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2542 if (sock
[0] != -1) {
2549 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2550 struct fuse_file_info
*fi
)
2552 struct fuse_context
*fc
= fuse_get_context();
2553 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2554 struct cgfs_files
*k
= NULL
;
2559 if (f
->type
!= LXC_TYPE_CGFILE
) {
2560 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2573 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2579 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2584 if (strcmp(f
->file
, "tasks") == 0 ||
2585 strcmp(f
->file
, "/tasks") == 0 ||
2586 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2587 strcmp(f
->file
, "cgroup.procs") == 0)
2588 // special case - we have to translate the pids
2589 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2591 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2605 memcpy(buf
, data
, s
);
2606 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2616 static int pid_from_ns(int sock
, pid_t tpid
)
2626 if (!wait_for_sock(sock
, 2)) {
2627 lxcfs_error("%s\n", "Timeout reading from parent.");
2630 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2631 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2634 if (vpid
== -1) // done
2638 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2640 cred
.pid
= getpid();
2641 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2648 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2650 int newnsfd
= -1, ret
, cpipe
[2];
2655 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2656 if (ret
< 0 || ret
>= sizeof(fnam
))
2658 newnsfd
= open(fnam
, O_RDONLY
);
2661 if (setns(newnsfd
, 0) < 0)
2665 if (pipe(cpipe
) < 0)
2668 struct pid_ns_clone_args args
= {
2672 .wrapped
= &pid_from_ns
2674 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2675 void *stack
= alloca(stack_size
);
2677 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2681 // give the child 1 second to be done forking and
2683 if (!wait_for_sock(cpipe
[0], 1))
2685 ret
= read(cpipe
[0], &v
, 1);
2686 if (ret
!= sizeof(char) || v
!= '1')
2689 if (!wait_for_pid(cpid
))
2695 * Given host @uid, return the uid to which it maps in
2696 * @pid's user namespace, or -1 if none.
2698 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2703 sprintf(line
, "/proc/%d/uid_map", pid
);
2704 if ((f
= fopen(line
, "r")) == NULL
) {
2708 *answer
= convert_id_to_ns(f
, uid
);
2717 * get_pid_creds: get the real uid and gid of @pid from
2719 * (XXX should we use euid here?)
2721 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2730 sprintf(line
, "/proc/%d/status", pid
);
2731 if ((f
= fopen(line
, "r")) == NULL
) {
2732 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2735 while (fgets(line
, 400, f
)) {
2736 if (strncmp(line
, "Uid:", 4) == 0) {
2737 if (sscanf(line
+4, "%u", &u
) != 1) {
2738 lxcfs_error("bad uid line for pid %u\n", pid
);
2743 } else if (strncmp(line
, "Gid:", 4) == 0) {
2744 if (sscanf(line
+4, "%u", &g
) != 1) {
2745 lxcfs_error("bad gid line for pid %u\n", pid
);
2756 * May the requestor @r move victim @v to a new cgroup?
2757 * This is allowed if
2758 * . they are the same task
2759 * . they are ownedy by the same uid
2760 * . @r is root on the host, or
2761 * . @v's uid is mapped into @r's where @r is root.
2763 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2765 uid_t v_uid
, tmpuid
;
2772 get_pid_creds(v
, &v_uid
, &v_gid
);
2775 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2776 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2781 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2782 const char *file
, const char *buf
)
2784 int sock
[2] = {-1, -1};
2785 pid_t qpid
, cpid
= -1;
2786 FILE *pids_file
= NULL
;
2787 bool answer
= false, fail
= false;
2789 pids_file
= open_pids_file(contrl
, cg
);
2794 * write the pids to a socket, have helper in writer's pidns
2795 * call movepid for us
2797 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2798 perror("socketpair");
2806 if (!cpid
) { // child
2808 pid_from_ns_wrapper(sock
[1], tpid
);
2811 const char *ptr
= buf
;
2812 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2816 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2817 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2821 if (recv_creds(sock
[0], &cred
, &v
)) {
2823 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2827 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2832 ptr
= strchr(ptr
, '\n');
2838 /* All good, write the value */
2840 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2841 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2849 if (sock
[0] != -1) {
2854 if (fclose(pids_file
) != 0)
2860 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2861 struct fuse_file_info
*fi
)
2863 struct fuse_context
*fc
= fuse_get_context();
2864 char *localbuf
= NULL
;
2865 struct cgfs_files
*k
= NULL
;
2866 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2869 if (f
->type
!= LXC_TYPE_CGFILE
) {
2870 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2880 localbuf
= alloca(size
+1);
2881 localbuf
[size
] = '\0';
2882 memcpy(localbuf
, buf
, size
);
2884 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2889 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2894 if (strcmp(f
->file
, "tasks") == 0 ||
2895 strcmp(f
->file
, "/tasks") == 0 ||
2896 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2897 strcmp(f
->file
, "cgroup.procs") == 0)
2898 // special case - we have to translate the pids
2899 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2901 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2911 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2913 struct fuse_context
*fc
= fuse_get_context();
2914 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2915 struct cgfs_files
*k
= NULL
;
2922 if (strcmp(path
, "/cgroup") == 0)
2925 controller
= pick_controller_from_path(fc
, path
);
2927 return errno
== ENOENT
? -EPERM
: -errno
;
2929 cgroup
= find_cgroup_in_path(path
);
2931 /* this is just /cgroup/controller */
2934 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2944 if (is_child_cgroup(controller
, path1
, path2
)) {
2945 // get uid, gid, from '/tasks' file and make up a mode
2946 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2947 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2950 k
= cgfs_get_key(controller
, path1
, path2
);
2958 * This being a fuse request, the uid and gid must be valid
2959 * in the caller's namespace. So we can just check to make
2960 * sure that the caller is root in his uid, and privileged
2961 * over the file's current owner.
2963 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2968 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2977 int cg_chmod(const char *path
, mode_t mode
)
2979 struct fuse_context
*fc
= fuse_get_context();
2980 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2981 struct cgfs_files
*k
= NULL
;
2988 if (strcmp(path
, "/cgroup") == 0)
2991 controller
= pick_controller_from_path(fc
, path
);
2993 return errno
== ENOENT
? -EPERM
: -errno
;
2995 cgroup
= find_cgroup_in_path(path
);
2997 /* this is just /cgroup/controller */
3000 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3010 if (is_child_cgroup(controller
, path1
, path2
)) {
3011 // get uid, gid, from '/tasks' file and make up a mode
3012 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3013 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3016 k
= cgfs_get_key(controller
, path1
, path2
);
3024 * This being a fuse request, the uid and gid must be valid
3025 * in the caller's namespace. So we can just check to make
3026 * sure that the caller is root in his uid, and privileged
3027 * over the file's current owner.
3029 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3034 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3046 int cg_mkdir(const char *path
, mode_t mode
)
3048 struct fuse_context
*fc
= fuse_get_context();
3049 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3056 controller
= pick_controller_from_path(fc
, path
);
3058 return errno
== ENOENT
? -EPERM
: -errno
;
3060 cgroup
= find_cgroup_in_path(path
);
3064 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3070 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3073 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3076 else if (last
&& strcmp(next
, last
) == 0)
3083 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3087 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3092 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3100 int cg_rmdir(const char *path
)
3102 struct fuse_context
*fc
= fuse_get_context();
3103 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3110 controller
= pick_controller_from_path(fc
, path
);
3111 if (!controller
) /* Someone's trying to delete "/cgroup". */
3114 cgroup
= find_cgroup_in_path(path
);
3115 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3118 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3120 /* Someone's trying to delete a cgroup on the same level as the
3121 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3122 * rmdir "/cgroup/blkio/init.slice".
3128 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3131 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3132 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3139 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3143 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3148 if (!cgfs_remove(controller
, cgroup
)) {
3161 static bool startswith(const char *line
, const char *pref
)
3163 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3168 static void parse_memstat(char *memstat
, unsigned long *cached
,
3169 unsigned long *active_anon
, unsigned long *inactive_anon
,
3170 unsigned long *active_file
, unsigned long *inactive_file
,
3171 unsigned long *unevictable
, unsigned long *shmem
)
3176 if (startswith(memstat
, "total_cache")) {
3177 sscanf(memstat
+ 11, "%lu", cached
);
3179 } else if (startswith(memstat
, "total_active_anon")) {
3180 sscanf(memstat
+ 17, "%lu", active_anon
);
3181 *active_anon
/= 1024;
3182 } else if (startswith(memstat
, "total_inactive_anon")) {
3183 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3184 *inactive_anon
/= 1024;
3185 } else if (startswith(memstat
, "total_active_file")) {
3186 sscanf(memstat
+ 17, "%lu", active_file
);
3187 *active_file
/= 1024;
3188 } else if (startswith(memstat
, "total_inactive_file")) {
3189 sscanf(memstat
+ 19, "%lu", inactive_file
);
3190 *inactive_file
/= 1024;
3191 } else if (startswith(memstat
, "total_unevictable")) {
3192 sscanf(memstat
+ 17, "%lu", unevictable
);
3193 *unevictable
/= 1024;
3194 } else if (startswith(memstat
, "total_shmem")) {
3195 sscanf(memstat
+ 11, "%lu", shmem
);
3198 eol
= strchr(memstat
, '\n');
3205 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3211 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3213 size_t len
= strlen(key
);
3217 if (startswith(str
, key
)) {
3218 sscanf(str
+ len
, "%lu", v
);
3221 eol
= strchr(str
, '\n');
3228 static int read_file(const char *path
, char *buf
, size_t size
,
3229 struct file_info
*d
)
3231 size_t linelen
= 0, total_len
= 0, rv
= 0;
3233 char *cache
= d
->buf
;
3234 size_t cache_size
= d
->buflen
;
3235 FILE *f
= fopen(path
, "r");
3239 while (getline(&line
, &linelen
, f
) != -1) {
3240 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3242 perror("Error writing to cache");
3246 if (l
>= cache_size
) {
3247 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3256 d
->size
= total_len
;
3257 if (total_len
> size
)
3260 /* read from off 0 */
3261 memcpy(buf
, d
->buf
, total_len
);
3270 * FUSE ops for /proc
3273 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3275 char *memlimit_str
= NULL
;
3276 unsigned long memlimit
= -1;
3278 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3279 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3286 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3288 char *copy
= strdupa(cgroup
);
3289 unsigned long memlimit
= 0, retlimit
;
3291 retlimit
= get_memlimit(copy
, file
);
3293 while (strcmp(copy
, "/") != 0) {
3294 copy
= dirname(copy
);
3295 memlimit
= get_memlimit(copy
, file
);
3296 if (memlimit
!= -1 && memlimit
< retlimit
)
3297 retlimit
= memlimit
;
3303 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3304 struct fuse_file_info
*fi
)
3306 struct fuse_context
*fc
= fuse_get_context();
3307 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3309 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3310 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3311 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3312 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3313 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3316 size_t linelen
= 0, total_len
= 0, rv
= 0;
3317 char *cache
= d
->buf
;
3318 size_t cache_size
= d
->buflen
;
3322 if (offset
> d
->size
)
3326 int left
= d
->size
- offset
;
3327 total_len
= left
> size
? size
: left
;
3328 memcpy(buf
, cache
+ offset
, total_len
);
3332 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3335 cg
= get_pid_cgroup(initpid
, "memory");
3337 return read_file("/proc/meminfo", buf
, size
, d
);
3338 prune_init_slice(cg
);
3340 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3341 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3343 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3346 // Following values are allowed to fail, because swapaccount might be turned
3347 // off for current kernel
3348 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3349 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3351 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3352 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3354 memswlimit
= memswlimit
/ 1024;
3355 memswusage
= memswusage
/ 1024;
3358 memusage
= strtoul(memusage_str
, NULL
, 10);
3362 parse_memstat(memstat_str
, &cached
, &active_anon
,
3363 &inactive_anon
, &active_file
, &inactive_file
,
3364 &unevictable
, &shmem
);
3366 f
= fopen("/proc/meminfo", "r");
3370 while (getline(&line
, &linelen
, f
) != -1) {
3372 char *printme
, lbuf
[100];
3374 memset(lbuf
, 0, 100);
3375 if (startswith(line
, "MemTotal:")) {
3376 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3377 if (hosttotal
< memlimit
)
3378 memlimit
= hosttotal
;
3379 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3381 } else if (startswith(line
, "MemFree:")) {
3382 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3384 } else if (startswith(line
, "MemAvailable:")) {
3385 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3387 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3388 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3389 if (hostswtotal
< memswlimit
)
3390 memswlimit
= hostswtotal
;
3391 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3393 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3394 unsigned long swaptotal
= memswlimit
,
3395 swapusage
= memswusage
- memusage
,
3396 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3397 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3399 } else if (startswith(line
, "Slab:")) {
3400 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3402 } else if (startswith(line
, "Buffers:")) {
3403 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3405 } else if (startswith(line
, "Cached:")) {
3406 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3408 } else if (startswith(line
, "SwapCached:")) {
3409 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3411 } else if (startswith(line
, "Active:")) {
3412 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3413 active_anon
+ active_file
);
3415 } else if (startswith(line
, "Inactive:")) {
3416 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3417 inactive_anon
+ inactive_file
);
3419 } else if (startswith(line
, "Active(anon)")) {
3420 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3422 } else if (startswith(line
, "Inactive(anon)")) {
3423 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3425 } else if (startswith(line
, "Active(file)")) {
3426 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3428 } else if (startswith(line
, "Inactive(file)")) {
3429 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3431 } else if (startswith(line
, "Unevictable")) {
3432 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3434 } else if (startswith(line
, "SReclaimable")) {
3435 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3437 } else if (startswith(line
, "SUnreclaim")) {
3438 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3440 } else if (startswith(line
, "Shmem:")) {
3441 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3443 } else if (startswith(line
, "ShmemHugePages")) {
3444 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3446 } else if (startswith(line
, "ShmemPmdMapped")) {
3447 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3452 l
= snprintf(cache
, cache_size
, "%s", printme
);
3454 perror("Error writing to cache");
3459 if (l
>= cache_size
) {
3460 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3471 d
->size
= total_len
;
3472 if (total_len
> size
) total_len
= size
;
3473 memcpy(buf
, d
->buf
, total_len
);
3482 free(memswlimit_str
);
3483 free(memswusage_str
);
3489 * Read the cpuset.cpus for cg
3490 * Return the answer in a newly allocated string which must be freed
3492 static char *get_cpuset(const char *cg
)
3496 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3501 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3503 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3507 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3509 return cpu_in_cpuset(cpu
, cpuset
);
3513 * check whether this is a '^processor" line in /proc/cpuinfo
3515 static bool is_processor_line(const char *line
)
3519 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3524 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3525 struct fuse_file_info
*fi
)
3527 struct fuse_context
*fc
= fuse_get_context();
3528 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3530 char *cpuset
= NULL
;
3532 size_t linelen
= 0, total_len
= 0, rv
= 0;
3533 bool am_printing
= false, firstline
= true, is_s390x
= false;
3534 int curcpu
= -1, cpu
;
3535 char *cache
= d
->buf
;
3536 size_t cache_size
= d
->buflen
;
3540 if (offset
> d
->size
)
3544 int left
= d
->size
- offset
;
3545 total_len
= left
> size
? size
: left
;
3546 memcpy(buf
, cache
+ offset
, total_len
);
3550 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3553 cg
= get_pid_cgroup(initpid
, "cpuset");
3555 return read_file("proc/cpuinfo", buf
, size
, d
);
3556 prune_init_slice(cg
);
3558 cpuset
= get_cpuset(cg
);
3562 f
= fopen("/proc/cpuinfo", "r");
3566 while (getline(&line
, &linelen
, f
) != -1) {
3570 if (strstr(line
, "IBM/S390") != NULL
) {
3576 if (strncmp(line
, "# processors:", 12) == 0)
3578 if (is_processor_line(line
)) {
3579 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3582 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3584 perror("Error writing to cache");
3588 if (l
>= cache_size
) {
3589 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3598 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3600 if (!cpu_in_cpuset(cpu
, cpuset
))
3603 p
= strchr(line
, ':');
3607 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3609 perror("Error writing to cache");
3613 if (l
>= cache_size
) {
3614 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3625 l
= snprintf(cache
, cache_size
, "%s", line
);
3627 perror("Error writing to cache");
3631 if (l
>= cache_size
) {
3632 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3643 char *origcache
= d
->buf
;
3646 d
->buf
= malloc(d
->buflen
);
3649 cache_size
= d
->buflen
;
3651 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3652 if (l
< 0 || l
>= cache_size
) {
3659 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3660 if (l
< 0 || l
>= cache_size
) {
3667 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3669 if (l
< 0 || l
>= cache_size
)
3675 d
->size
= total_len
;
3676 if (total_len
> size
) total_len
= size
;
3678 /* read from off 0 */
3679 memcpy(buf
, d
->buf
, total_len
);
3690 static uint64_t get_reaper_start_time(pid_t pid
)
3695 /* strlen("/proc/") = 6
3699 * strlen("/stat") = 5
3703 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3704 char path
[__PROC_PID_STAT_LEN
];
3707 qpid
= lookup_initpid_in_store(pid
);
3709 /* Caller can check for EINVAL on 0. */
3714 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3715 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3716 /* Caller can check for EINVAL on 0. */
3721 f
= fopen(path
, "r");
3723 /* Caller can check for EINVAL on 0. */
3728 /* Note that the *scanf() argument supression requires that length
3729 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3730 * at us. It's like telling someone you're not married and then asking
3731 * if you can bring your wife to the party.
3733 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3734 "%*s " /* (2) comm %s */
3735 "%*c " /* (3) state %c */
3736 "%*d " /* (4) ppid %d */
3737 "%*d " /* (5) pgrp %d */
3738 "%*d " /* (6) session %d */
3739 "%*d " /* (7) tty_nr %d */
3740 "%*d " /* (8) tpgid %d */
3741 "%*u " /* (9) flags %u */
3742 "%*u " /* (10) minflt %lu */
3743 "%*u " /* (11) cminflt %lu */
3744 "%*u " /* (12) majflt %lu */
3745 "%*u " /* (13) cmajflt %lu */
3746 "%*u " /* (14) utime %lu */
3747 "%*u " /* (15) stime %lu */
3748 "%*d " /* (16) cutime %ld */
3749 "%*d " /* (17) cstime %ld */
3750 "%*d " /* (18) priority %ld */
3751 "%*d " /* (19) nice %ld */
3752 "%*d " /* (20) num_threads %ld */
3753 "%*d " /* (21) itrealvalue %ld */
3754 "%" PRIu64
, /* (22) starttime %llu */
3758 /* Caller can check for EINVAL on 0. */
3769 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3771 uint64_t clockticks
;
3772 int64_t ticks_per_sec
;
3774 clockticks
= get_reaper_start_time(pid
);
3775 if (clockticks
== 0 && errno
== EINVAL
) {
3776 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3780 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3781 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3784 "failed to determine number of clock ticks in a second");
3788 return (clockticks
/= ticks_per_sec
);
3791 static uint64_t get_reaper_age(pid_t pid
)
3793 uint64_t procstart
, uptime
, procage
;
3795 /* We need to substract the time the process has started since system
3796 * boot minus the time when the system has started to get the actual
3799 procstart
= get_reaper_start_time_in_sec(pid
);
3800 procage
= procstart
;
3801 if (procstart
> 0) {
3803 struct timespec spec
;
3805 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3808 /* We could make this more precise here by using the tv_nsec
3809 * field in the timespec struct and convert it to milliseconds
3810 * and then create a double for the seconds and milliseconds but
3811 * that seems more work than it is worth.
3813 uptime
= spec
.tv_sec
;
3814 procage
= uptime
- procstart
;
3821 * Returns 0 on success.
3822 * It is the caller's responsibility to free `return_usage`, unless this
3823 * function returns an error.
3825 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
)
3827 int cpucount
= get_nprocs();
3828 struct cpuacct_usage
*cpu_usage
;
3829 int rv
= 0, i
, j
, ret
, read_pos
= 0, read_cnt
;
3831 uint64_t cg_user
, cg_system
;
3832 int64_t ticks_per_sec
;
3833 char *usage_str
= NULL
;
3835 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3837 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3840 "read_cpuacct_usage_all failed to determine number of clock ticks "
3845 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
3849 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
3854 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
3855 lxcfs_error("read_cpuacct_usage_all reading first line from "
3856 "%s/cpuacct.usage_all failed.\n", cg
);
3861 read_pos
+= read_cnt
;
3863 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
3864 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
3865 &cg_system
, &read_cnt
);
3871 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
3877 read_pos
+= read_cnt
;
3879 if (!cpu_in_cpuset(i
, cpuset
))
3882 /* Convert the time from nanoseconds to USER_HZ */
3883 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3884 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3889 *return_usage
= cpu_usage
;
3897 *return_usage
= NULL
;
3903 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
3904 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3905 struct fuse_file_info
*fi
)
3907 struct fuse_context
*fc
= fuse_get_context();
3908 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3910 char *cpuset
= NULL
;
3912 size_t linelen
= 0, total_len
= 0, rv
= 0;
3913 int curcpu
= -1; /* cpu numbering starts at 0 */
3914 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
3915 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3916 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
3917 char cpuall
[CPUALL_MAX_SIZE
];
3918 /* reserve for cpu all */
3919 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3920 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3922 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
3925 if (offset
> d
->size
)
3929 int left
= d
->size
- offset
;
3930 total_len
= left
> size
? size
: left
;
3931 memcpy(buf
, d
->buf
+ offset
, total_len
);
3935 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3938 cg
= get_pid_cgroup(initpid
, "cpuset");
3940 return read_file("/proc/stat", buf
, size
, d
);
3941 prune_init_slice(cg
);
3943 cpuset
= get_cpuset(cg
);
3948 * Read cpuacct.usage_all for all CPUs.
3949 * If the cpuacct cgroup is present, it is used to calculate the container's
3950 * CPU usage. If not, values from the host's /proc/stat are used.
3952 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
) != 0) {
3953 lxcfs_debug("%s\n", "proc_stat_read failed to read from cpuacct, "
3954 "falling back to the host's /proc/stat");
3957 f
= fopen("/proc/stat", "r");
3962 if (getline(&line
, &linelen
, f
) < 0) {
3963 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3967 while (getline(&line
, &linelen
, f
) != -1) {
3970 char cpu_char
[10]; /* That's a lot of cores */
3972 uint64_t all_used
, cg_used
, new_idle
;
3975 if (strlen(line
) == 0)
3977 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3978 /* not a ^cpuN line containing a number N, just print it */
3979 l
= snprintf(cache
, cache_size
, "%s", line
);
3981 perror("Error writing to cache");
3985 if (l
>= cache_size
) {
3986 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3996 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3998 if (!cpu_in_cpuset(cpu
, cpuset
))
4002 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4014 if (ret
!= 10 || !cg_cpu_usage
) {
4015 c
= strchr(line
, ' ');
4018 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4020 perror("Error writing to cache");
4025 if (l
>= cache_size
) {
4026 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4040 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4041 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4043 if (all_used
>= cg_used
) {
4044 new_idle
= idle
+ (all_used
- cg_used
);
4047 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4048 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4049 curcpu
, cg
, all_used
, cg_used
);
4053 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4054 curcpu
, cg_cpu_usage
[curcpu
].user
, cg_cpu_usage
[curcpu
].system
,
4058 perror("Error writing to cache");
4063 if (l
>= cache_size
) {
4064 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4073 user_sum
+= cg_cpu_usage
[curcpu
].user
;
4074 system_sum
+= cg_cpu_usage
[curcpu
].system
;
4075 idle_sum
+= new_idle
;
4080 system_sum
+= system
;
4082 iowait_sum
+= iowait
;
4084 softirq_sum
+= softirq
;
4087 guest_nice_sum
+= guest_nice
;
4093 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4104 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4105 memcpy(cache
, cpuall
, cpuall_len
);
4106 cache
+= cpuall_len
;
4108 /* shouldn't happen */
4109 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4113 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4114 total_len
+= cpuall_len
;
4116 d
->size
= total_len
;
4117 if (total_len
> size
)
4120 memcpy(buf
, d
->buf
, total_len
);
4134 /* This function retrieves the busy time of a group of tasks by looking at
4135 * cpuacct.usage. Unfortunately, this only makes sense when the container has
4136 * been given it's own cpuacct cgroup. If not, this function will take the busy
4137 * time of all other taks that do not actually belong to the container into
4138 * account as well. If someone has a clever solution for this please send a
4141 static unsigned long get_reaper_busy(pid_t task
)
4143 pid_t initpid
= lookup_initpid_in_store(task
);
4144 char *cgroup
= NULL
, *usage_str
= NULL
;
4145 unsigned long usage
= 0;
4150 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
4153 prune_init_slice(cgroup
);
4154 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
4156 usage
= strtoul(usage_str
, NULL
, 10);
4157 usage
/= 1000000000;
4170 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4177 * We read /proc/uptime and reuse its second field.
4178 * For the first field, we use the mtime for the reaper for
4179 * the calling pid as returned by getreaperage
4181 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4182 struct fuse_file_info
*fi
)
4184 struct fuse_context
*fc
= fuse_get_context();
4185 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4186 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
4187 char *cache
= d
->buf
;
4188 ssize_t total_len
= 0;
4189 uint64_t idletime
, reaperage
;
4198 if (offset
> d
->size
)
4200 int left
= d
->size
- offset
;
4201 total_len
= left
> size
? size
: left
;
4202 memcpy(buf
, cache
+ offset
, total_len
);
4206 reaperage
= get_reaper_age(fc
->pid
);
4207 /* To understand why this is done, please read the comment to the
4208 * get_reaper_busy() function.
4210 idletime
= reaperage
;
4211 if (reaperage
>= busytime
)
4212 idletime
= reaperage
- busytime
;
4214 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
4215 if (total_len
< 0 || total_len
>= d
->buflen
){
4216 lxcfs_error("%s\n", "failed to write to cache");
4220 d
->size
= (int)total_len
;
4223 if (total_len
> size
) total_len
= size
;
4225 memcpy(buf
, d
->buf
, total_len
);
4229 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
4230 struct fuse_file_info
*fi
)
4233 struct fuse_context
*fc
= fuse_get_context();
4234 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4236 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
4237 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
4238 unsigned long read
= 0, write
= 0;
4239 unsigned long read_merged
= 0, write_merged
= 0;
4240 unsigned long read_sectors
= 0, write_sectors
= 0;
4241 unsigned long read_ticks
= 0, write_ticks
= 0;
4242 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
4243 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
4244 char *cache
= d
->buf
;
4245 size_t cache_size
= d
->buflen
;
4247 size_t linelen
= 0, total_len
= 0, rv
= 0;
4248 unsigned int major
= 0, minor
= 0;
4253 if (offset
> d
->size
)
4257 int left
= d
->size
- offset
;
4258 total_len
= left
> size
? size
: left
;
4259 memcpy(buf
, cache
+ offset
, total_len
);
4263 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4266 cg
= get_pid_cgroup(initpid
, "blkio");
4268 return read_file("/proc/diskstats", buf
, size
, d
);
4269 prune_init_slice(cg
);
4271 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
4273 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
4275 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
4277 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
4279 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
4283 f
= fopen("/proc/diskstats", "r");
4287 while (getline(&line
, &linelen
, f
) != -1) {
4291 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
4295 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
4296 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
4297 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
4298 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
4299 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
4300 read_sectors
= read_sectors
/512;
4301 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
4302 write_sectors
= write_sectors
/512;
4304 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
4305 rd_svctm
= rd_svctm
/1000000;
4306 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
4307 rd_wait
= rd_wait
/1000000;
4308 read_ticks
= rd_svctm
+ rd_wait
;
4310 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
4311 wr_svctm
= wr_svctm
/1000000;
4312 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
4313 wr_wait
= wr_wait
/1000000;
4314 write_ticks
= wr_svctm
+ wr_wait
;
4316 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
4317 tot_ticks
= tot_ticks
/1000000;
4319 memset(lbuf
, 0, 256);
4320 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
4321 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4322 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
4323 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
4327 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
4329 perror("Error writing to fuse buf");
4333 if (l
>= cache_size
) {
4334 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4344 d
->size
= total_len
;
4345 if (total_len
> size
) total_len
= size
;
4346 memcpy(buf
, d
->buf
, total_len
);
4354 free(io_serviced_str
);
4355 free(io_merged_str
);
4356 free(io_service_bytes_str
);
4357 free(io_wait_time_str
);
4358 free(io_service_time_str
);
4362 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
4363 struct fuse_file_info
*fi
)
4365 struct fuse_context
*fc
= fuse_get_context();
4366 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4368 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
4369 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
4370 ssize_t total_len
= 0, rv
= 0;
4372 char *cache
= d
->buf
;
4375 if (offset
> d
->size
)
4379 int left
= d
->size
- offset
;
4380 total_len
= left
> size
? size
: left
;
4381 memcpy(buf
, cache
+ offset
, total_len
);
4385 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4388 cg
= get_pid_cgroup(initpid
, "memory");
4390 return read_file("/proc/swaps", buf
, size
, d
);
4391 prune_init_slice(cg
);
4393 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
4395 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
4398 memusage
= strtoul(memusage_str
, NULL
, 10);
4400 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
4401 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
4403 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
4404 memswusage
= strtoul(memswusage_str
, NULL
, 10);
4406 swap_total
= (memswlimit
- memlimit
) / 1024;
4407 swap_free
= (memswusage
- memusage
) / 1024;
4410 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
4412 /* When no mem + swap limit is specified or swapaccount=0*/
4416 FILE *f
= fopen("/proc/meminfo", "r");
4421 while (getline(&line
, &linelen
, f
) != -1) {
4422 if (startswith(line
, "SwapTotal:")) {
4423 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
4424 } else if (startswith(line
, "SwapFree:")) {
4425 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
4433 if (swap_total
> 0) {
4434 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
4435 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
4436 swap_total
, swap_free
);
4440 if (total_len
< 0 || l
< 0) {
4441 perror("Error writing to cache");
4447 d
->size
= (int)total_len
;
4449 if (total_len
> size
) total_len
= size
;
4450 memcpy(buf
, d
->buf
, total_len
);
4455 free(memswlimit_str
);
4458 free(memswusage_str
);
4462 * Find the process pid from cgroup path.
4463 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
4464 * @pid_buf : put pid to pid_buf.
4465 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
4466 * @depth : the depth of cgroup in container.
4467 * @sum : return the number of pid.
4468 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
4470 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
4474 struct dirent
*file
;
4479 char *path_dir
, *path
;
4482 /* path = dpath + "/cgroup.procs" + /0 */
4484 path
= malloc(strlen(dpath
) + 20);
4487 strcpy(path
, dpath
);
4488 fd
= openat(cfd
, path
, O_RDONLY
);
4492 dir
= fdopendir(fd
);
4498 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
4499 if (strncmp(file
->d_name
, ".", 1) == 0)
4501 if (strncmp(file
->d_name
, "..", 1) == 0)
4503 if (file
->d_type
== DT_DIR
) {
4504 /* path + '/' + d_name +/0 */
4506 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
4507 } while (!path_dir
);
4508 strcpy(path_dir
, path
);
4509 strcat(path_dir
, "/");
4510 strcat(path_dir
, file
->d_name
);
4512 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
4518 strcat(path
, "/cgroup.procs");
4519 fd
= openat(cfd
, path
, O_RDONLY
);
4523 f
= fdopen(fd
, "r");
4529 while (getline(&line
, &linelen
, f
) != -1) {
4531 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
4535 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
4536 } while (*(*pid_buf
+ sum
) == NULL
);
4537 strcpy(*(*pid_buf
+ sum
), line
);
4548 * calc_load calculates the load according to the following formula:
4549 * load1 = load0 * exp + active * (1 - exp)
4551 * @load1: the new loadavg.
4552 * @load0: the former loadavg.
4553 * @active: the total number of running pid at this moment.
4554 * @exp: the fixed-point defined in the beginning.
4556 static unsigned long
4557 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
4559 unsigned long newload
;
4561 active
= active
> 0 ? active
* FIXED_1
: 0;
4562 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
4564 newload
+= FIXED_1
- 1;
4566 return newload
/ FIXED_1
;
4570 * Return 0 means that container p->cg is closed.
4571 * Return -1 means that error occurred in refresh.
4572 * Positive num equals the total number of pid.
4574 static int refresh_load(struct load_node
*p
, char *path
)
4578 char proc_path
[256];
4579 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
4584 struct dirent
*file
;
4587 idbuf
= malloc(sizeof(char *));
4589 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
4594 for (i
= 0; i
< sum
; i
++) {
4596 length
= strlen(idbuf
[i
])-1;
4597 idbuf
[i
][length
] = '\0';
4598 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
4599 if (ret
< 0 || ret
> 255) {
4600 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4606 dp
= opendir(proc_path
);
4608 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
4611 while ((file
= readdir(dp
)) != NULL
) {
4612 if (strncmp(file
->d_name
, ".", 1) == 0)
4614 if (strncmp(file
->d_name
, "..", 1) == 0)
4617 /* We make the biggest pid become last_pid.*/
4618 ret
= atof(file
->d_name
);
4619 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
4621 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
4622 if (ret
< 0 || ret
> 255) {
4623 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4629 f
= fopen(proc_path
, "r");
4631 while (getline(&line
, &linelen
, f
) != -1) {
4633 if ((line
[0] == 'S') && (line
[1] == 't'))
4636 if ((line
[7] == 'R') || (line
[7] == 'D'))
4643 /*Calculate the loadavg.*/
4644 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
4645 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
4646 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
4647 p
->run_pid
= run_pid
;
4648 p
->total_pid
= total_pid
;
4649 p
->last_pid
= last_pid
;
4660 * Traverse the hash table and update it.
4662 void *load_begin(void *arg
)
4666 int i
, sum
, length
, ret
;
4667 struct load_node
*f
;
4669 clock_t time1
, time2
;
4672 if (loadavg_stop
== 1)
4676 for (i
= 0; i
< LOAD_SIZE
; i
++) {
4677 pthread_mutex_lock(&load_hash
[i
].lock
);
4678 if (load_hash
[i
].next
== NULL
) {
4679 pthread_mutex_unlock(&load_hash
[i
].lock
);
4682 f
= load_hash
[i
].next
;
4685 length
= strlen(f
->cg
) + 2;
4687 /* strlen(f->cg) + '.' or '' + \0 */
4688 path
= malloc(length
);
4691 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
4692 if (ret
< 0 || ret
> length
- 1) {
4693 /* snprintf failed, ignore the node.*/
4694 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
4697 sum
= refresh_load(f
, path
);
4704 /* load_hash[i].lock locks only on the first node.*/
4705 if (first_node
== 1) {
4707 pthread_mutex_unlock(&load_hash
[i
].lock
);
4712 if (loadavg_stop
== 1)
4716 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
4720 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
4721 struct fuse_file_info
*fi
)
4723 struct fuse_context
*fc
= fuse_get_context();
4724 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4727 size_t total_len
= 0;
4728 char *cache
= d
->buf
;
4729 struct load_node
*n
;
4732 unsigned long a
, b
, c
;
4735 if (offset
> d
->size
)
4739 int left
= d
->size
- offset
;
4740 total_len
= left
> size
? size
: left
;
4741 memcpy(buf
, cache
+ offset
, total_len
);
4745 return read_file("/proc/loadavg", buf
, size
, d
);
4747 initpid
= lookup_initpid_in_store(fc
->pid
);
4750 cg
= get_pid_cgroup(initpid
, "cpu");
4752 return read_file("/proc/loadavg", buf
, size
, d
);
4754 prune_init_slice(cg
);
4755 hash
= calc_hash(cg
);
4756 n
= locate_node(cg
, hash
);
4760 if (!find_mounted_controller("cpu", &cfd
)) {
4762 * In locate_node() above, pthread_rwlock_unlock() isn't used
4763 * because delete is not allowed before read has ended.
4765 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4770 n
= malloc(sizeof(struct load_node
));
4774 n
->cg
= malloc(strlen(cg
)+1);
4782 n
->last_pid
= initpid
;
4784 insert_node(&n
, hash
);
4786 a
= n
->avenrun
[0] + (FIXED_1
/200);
4787 b
= n
->avenrun
[1] + (FIXED_1
/200);
4788 c
= n
->avenrun
[2] + (FIXED_1
/200);
4789 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
4790 LOAD_INT(a
), LOAD_FRAC(a
),
4791 LOAD_INT(b
), LOAD_FRAC(b
),
4792 LOAD_INT(c
), LOAD_FRAC(c
),
4793 n
->run_pid
, n
->total_pid
, n
->last_pid
);
4794 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4795 if (total_len
< 0 || total_len
>= d
->buflen
) {
4796 lxcfs_error("%s\n", "Failed to write to cache");
4800 d
->size
= (int)total_len
;
4803 if (total_len
> size
)
4805 memcpy(buf
, d
->buf
, total_len
);
4812 /* Return a positive number on success, return 0 on failure.*/
4813 pthread_t
load_daemon(int load_use
)
4820 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
4823 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
4825 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
4829 /* use loadavg, here loadavg = 1*/
4834 /* Returns 0 on success. */
4835 int stop_load_daemon(pthread_t pid
)
4839 /* Signal the thread to gracefully stop */
4842 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
4844 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
4854 static off_t
get_procfile_size(const char *which
)
4856 FILE *f
= fopen(which
, "r");
4859 ssize_t sz
, answer
= 0;
4863 while ((sz
= getline(&line
, &len
, f
)) != -1)
4871 int proc_getattr(const char *path
, struct stat
*sb
)
4873 struct timespec now
;
4875 memset(sb
, 0, sizeof(struct stat
));
4876 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
4878 sb
->st_uid
= sb
->st_gid
= 0;
4879 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4880 if (strcmp(path
, "/proc") == 0) {
4881 sb
->st_mode
= S_IFDIR
| 00555;
4885 if (strcmp(path
, "/proc/meminfo") == 0 ||
4886 strcmp(path
, "/proc/cpuinfo") == 0 ||
4887 strcmp(path
, "/proc/uptime") == 0 ||
4888 strcmp(path
, "/proc/stat") == 0 ||
4889 strcmp(path
, "/proc/diskstats") == 0 ||
4890 strcmp(path
, "/proc/swaps") == 0 ||
4891 strcmp(path
, "/proc/loadavg") == 0) {
4893 sb
->st_mode
= S_IFREG
| 00444;
4901 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4902 struct fuse_file_info
*fi
)
4904 if (filler(buf
, ".", NULL
, 0) != 0 ||
4905 filler(buf
, "..", NULL
, 0) != 0 ||
4906 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4907 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4908 filler(buf
, "stat", NULL
, 0) != 0 ||
4909 filler(buf
, "uptime", NULL
, 0) != 0 ||
4910 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4911 filler(buf
, "swaps", NULL
, 0) != 0 ||
4912 filler(buf
, "loadavg", NULL
, 0) != 0)
4917 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4920 struct file_info
*info
;
4922 if (strcmp(path
, "/proc/meminfo") == 0)
4923 type
= LXC_TYPE_PROC_MEMINFO
;
4924 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4925 type
= LXC_TYPE_PROC_CPUINFO
;
4926 else if (strcmp(path
, "/proc/uptime") == 0)
4927 type
= LXC_TYPE_PROC_UPTIME
;
4928 else if (strcmp(path
, "/proc/stat") == 0)
4929 type
= LXC_TYPE_PROC_STAT
;
4930 else if (strcmp(path
, "/proc/diskstats") == 0)
4931 type
= LXC_TYPE_PROC_DISKSTATS
;
4932 else if (strcmp(path
, "/proc/swaps") == 0)
4933 type
= LXC_TYPE_PROC_SWAPS
;
4934 else if (strcmp(path
, "/proc/loadavg") == 0)
4935 type
= LXC_TYPE_PROC_LOADAVG
;
4939 info
= malloc(sizeof(*info
));
4943 memset(info
, 0, sizeof(*info
));
4946 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4948 info
->buf
= malloc(info
->buflen
);
4949 } while (!info
->buf
);
4950 memset(info
->buf
, 0, info
->buflen
);
4951 /* set actual size to buffer size */
4952 info
->size
= info
->buflen
;
4954 fi
->fh
= (unsigned long)info
;
4958 int proc_access(const char *path
, int mask
)
4960 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4963 /* these are all read-only */
4964 if ((mask
& ~R_OK
) != 0)
4969 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4971 do_release_file_info(fi
);
4975 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4976 struct fuse_file_info
*fi
)
4978 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4981 case LXC_TYPE_PROC_MEMINFO
:
4982 return proc_meminfo_read(buf
, size
, offset
, fi
);
4983 case LXC_TYPE_PROC_CPUINFO
:
4984 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4985 case LXC_TYPE_PROC_UPTIME
:
4986 return proc_uptime_read(buf
, size
, offset
, fi
);
4987 case LXC_TYPE_PROC_STAT
:
4988 return proc_stat_read(buf
, size
, offset
, fi
);
4989 case LXC_TYPE_PROC_DISKSTATS
:
4990 return proc_diskstats_read(buf
, size
, offset
, fi
);
4991 case LXC_TYPE_PROC_SWAPS
:
4992 return proc_swaps_read(buf
, size
, offset
, fi
);
4993 case LXC_TYPE_PROC_LOADAVG
:
4994 return proc_loadavg_read(buf
, size
, offset
, fi
);
5001 * Functions needed to setup cgroups in the __constructor__.
5004 static bool mkdir_p(const char *dir
, mode_t mode
)
5006 const char *tmp
= dir
;
5007 const char *orig
= dir
;
5011 dir
= tmp
+ strspn(tmp
, "/");
5012 tmp
= dir
+ strcspn(dir
, "/");
5013 makeme
= strndup(orig
, dir
- orig
);
5016 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
5017 lxcfs_error("Failed to create directory '%s': %s.\n",
5018 makeme
, strerror(errno
));
5023 } while(tmp
!= dir
);
5028 static bool umount_if_mounted(void)
5030 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5031 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5037 /* __typeof__ should be safe to use with all compilers. */
5038 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5039 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5041 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5045 * looking at fs/proc_namespace.c, it appears we can
5046 * actually expect the rootfs entry to very specifically contain
5047 * " - rootfs rootfs "
5048 * IIUC, so long as we've chrooted so that rootfs is not our root,
5049 * the rootfs entry should always be skipped in mountinfo contents.
5051 static bool is_on_ramfs(void)
5059 f
= fopen("/proc/self/mountinfo", "r");
5063 while (getline(&line
, &len
, f
) != -1) {
5064 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5065 p
= strchr(p
+ 1, ' ');
5068 p2
= strchr(p
+ 1, ' ');
5072 if (strcmp(p
+ 1, "/") == 0) {
5073 // this is '/'. is it the ramfs?
5074 p
= strchr(p2
+ 1, '-');
5075 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5087 static int pivot_enter()
5089 int ret
= -1, oldroot
= -1, newroot
= -1;
5091 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5093 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5097 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5099 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5103 /* change into new root fs */
5104 if (fchdir(newroot
) < 0) {
5105 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5109 /* pivot_root into our new root fs */
5110 if (pivot_root(".", ".") < 0) {
5111 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5116 * At this point the old-root is mounted on top of our new-root.
5117 * To unmounted it we must not be chdir'd into it, so escape back
5120 if (fchdir(oldroot
) < 0) {
5121 lxcfs_error("%s\n", "Failed to enter old root.");
5125 if (umount2(".", MNT_DETACH
) < 0) {
5126 lxcfs_error("%s\n", "Failed to detach old root.");
5130 if (fchdir(newroot
) < 0) {
5131 lxcfs_error("%s\n", "Failed to re-enter new root.");
5146 static int chroot_enter()
5148 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
5149 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
5153 if (chroot(".") < 0) {
5154 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
5158 if (chdir("/") < 0) {
5159 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
5166 static int permute_and_enter(void)
5170 if (statfs("/", &sb
) < 0) {
5171 lxcfs_error("%s\n", "Could not stat / mountpoint.");
5175 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
5176 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
5177 * /proc/1/mountinfo. */
5178 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
5179 return chroot_enter();
5181 if (pivot_enter() < 0) {
5182 lxcfs_error("%s\n", "Could not perform pivot root.");
5189 /* Prepare our new clean root. */
5190 static int permute_prepare(void)
5192 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
5193 lxcfs_error("%s\n", "Failed to create directory for new root.");
5197 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
5198 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
5202 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
5203 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
5207 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
5208 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
5215 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
5216 static bool permute_root(void)
5218 /* Prepare new root. */
5219 if (permute_prepare() < 0)
5222 /* Pivot into new root. */
5223 if (permute_and_enter() < 0)
5229 static int preserve_mnt_ns(int pid
)
5232 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
5235 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
5236 if (ret
< 0 || (size_t)ret
>= len
)
5239 return open(path
, O_RDONLY
| O_CLOEXEC
);
5242 static bool cgfs_prepare_mounts(void)
5244 if (!mkdir_p(BASEDIR
, 0700)) {
5245 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
5249 if (!umount_if_mounted()) {
5250 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
5254 if (unshare(CLONE_NEWNS
) < 0) {
5255 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
5259 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
5260 if (cgroup_mount_ns_fd
< 0) {
5261 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
5265 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
5266 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
5270 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
5271 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
5278 static bool cgfs_mount_hierarchies(void)
5284 for (i
= 0; i
< num_hierarchies
; i
++) {
5285 char *controller
= hierarchies
[i
];
5287 clen
= strlen(controller
);
5288 len
= strlen(BASEDIR
) + clen
+ 2;
5289 target
= malloc(len
);
5293 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
5294 if (ret
< 0 || ret
>= len
) {
5298 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
5302 if (!strcmp(controller
, "unified"))
5303 ret
= mount("none", target
, "cgroup2", 0, NULL
);
5305 ret
= mount(controller
, target
, "cgroup", 0, controller
);
5307 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
5312 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
5313 if (fd_hierarchies
[i
] < 0) {
5322 static bool cgfs_setup_controllers(void)
5324 if (!cgfs_prepare_mounts())
5327 if (!cgfs_mount_hierarchies()) {
5328 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
5332 if (!permute_root())
5338 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
5341 char *cret
, *line
= NULL
;
5342 char cwd
[MAXPATHLEN
];
5344 int i
, init_ns
= -1;
5345 bool found_unified
= false;
5347 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
5348 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
5352 while (getline(&line
, &len
, f
) != -1) {
5355 p
= strchr(line
, ':');
5361 p2
= strrchr(p
, ':');
5366 /* With cgroupv2 /proc/self/cgroup can contain entries of the
5367 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
5368 * because it parses out the empty string "" and later on passes
5369 * it to mount(). Let's skip such entries.
5371 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
5372 found_unified
= true;
5376 if (!store_hierarchy(line
, p
))
5380 /* Preserve initial namespace. */
5381 init_ns
= preserve_mnt_ns(getpid());
5383 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
5387 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
5388 if (!fd_hierarchies
) {
5389 lxcfs_error("%s\n", strerror(errno
));
5393 for (i
= 0; i
< num_hierarchies
; i
++)
5394 fd_hierarchies
[i
] = -1;
5396 cret
= getcwd(cwd
, MAXPATHLEN
);
5398 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
5400 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
5401 * to privately mount lxcfs cgroups. */
5402 if (!cgfs_setup_controllers()) {
5403 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
5407 if (setns(init_ns
, 0) < 0) {
5408 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
5412 if (!cret
|| chdir(cwd
) < 0)
5413 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
5424 static void __attribute__((destructor
)) free_subsystems(void)
5428 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
5430 for (i
= 0; i
< num_hierarchies
; i
++) {
5432 free(hierarchies
[i
]);
5433 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
5434 close(fd_hierarchies
[i
]);
5437 free(fd_hierarchies
);
5439 if (cgroup_mount_ns_fd
>= 0)
5440 close(cgroup_mount_ns_fd
);