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
)
587 if (!(f
= fdopen(fd
, "w")))
589 len
= strlen(string
);
590 ret
= fwrite(string
, 1, len
, f
);
592 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
597 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
610 static bool store_hierarchy(char *stridx
, char *h
)
612 if (num_hierarchies
% ALLOC_NUM
== 0) {
613 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
615 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
617 lxcfs_error("%s\n", strerror(errno
));
623 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
627 static void print_subsystems(void)
631 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
632 fprintf(stderr
, "hierarchies:\n");
633 for (i
= 0; i
< num_hierarchies
; i
++) {
635 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
636 fd_hierarchies
[i
], hierarchies
[i
]);
640 static bool in_comma_list(const char *needle
, const char *haystack
)
642 const char *s
= haystack
, *e
;
643 size_t nlen
= strlen(needle
);
645 while (*s
&& (e
= strchr(s
, ','))) {
650 if (strncmp(needle
, s
, nlen
) == 0)
654 if (strcmp(needle
, s
) == 0)
659 /* do we need to do any massaging here? I'm not sure... */
660 /* Return the mounted controller and store the corresponding open file descriptor
661 * referring to the controller mountpoint in the private lxcfs namespace in
664 static char *find_mounted_controller(const char *controller
, int *cfd
)
668 for (i
= 0; i
< num_hierarchies
; i
++) {
671 if (strcmp(hierarchies
[i
], controller
) == 0) {
672 *cfd
= fd_hierarchies
[i
];
673 return hierarchies
[i
];
675 if (in_comma_list(controller
, hierarchies
[i
])) {
676 *cfd
= fd_hierarchies
[i
];
677 return hierarchies
[i
];
684 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
691 tmpc
= find_mounted_controller(controller
, &cfd
);
695 /* Make sure we pass a relative path to *at() family of functions.
696 * . + /cgroup + / + file + \0
698 len
= strlen(cgroup
) + strlen(file
) + 3;
700 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
701 if (ret
< 0 || (size_t)ret
>= len
)
704 fd
= openat(cfd
, fnam
, O_WRONLY
);
708 return write_string(fnam
, value
, fd
);
711 // Chown all the files in the cgroup directory. We do this when we create
712 // a cgroup on behalf of a user.
713 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
715 struct dirent
*direntp
;
716 char path
[MAXPATHLEN
];
721 len
= strlen(dirname
);
722 if (len
>= MAXPATHLEN
) {
723 lxcfs_error("Pathname too long: %s\n", dirname
);
727 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
733 lxcfs_error("Failed to open %s\n", dirname
);
737 while ((direntp
= readdir(d
))) {
738 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
740 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
741 if (ret
< 0 || ret
>= MAXPATHLEN
) {
742 lxcfs_error("Pathname too long under %s\n", dirname
);
745 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
746 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
751 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
757 tmpc
= find_mounted_controller(controller
, &cfd
);
761 /* Make sure we pass a relative path to *at() family of functions.
764 len
= strlen(cg
) + 2;
765 dirnam
= alloca(len
);
766 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
768 if (mkdirat(cfd
, dirnam
, 0755) < 0)
771 if (uid
== 0 && gid
== 0)
774 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
777 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
782 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
784 struct dirent
*direntp
;
787 char pathname
[MAXPATHLEN
];
790 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
794 dir
= fdopendir(dupfd
);
796 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
801 while ((direntp
= readdir(dir
))) {
805 if (!strcmp(direntp
->d_name
, ".") ||
806 !strcmp(direntp
->d_name
, ".."))
809 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
810 if (rc
< 0 || rc
>= MAXPATHLEN
) {
811 lxcfs_error("%s\n", "Pathname too long.");
815 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
817 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
820 if (S_ISDIR(mystat
.st_mode
))
821 if (!recursive_rmdir(pathname
, fd
, cfd
))
822 lxcfs_debug("Error removing %s.\n", pathname
);
826 if (closedir(dir
) < 0) {
827 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
831 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
832 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
841 bool cgfs_remove(const char *controller
, const char *cg
)
848 tmpc
= find_mounted_controller(controller
, &cfd
);
852 /* Make sure we pass a relative path to *at() family of functions.
855 len
= strlen(cg
) + 2;
856 dirnam
= alloca(len
);
857 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
859 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
863 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
868 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
872 char *pathname
, *tmpc
;
874 tmpc
= find_mounted_controller(controller
, &cfd
);
878 /* Make sure we pass a relative path to *at() family of functions.
881 len
= strlen(file
) + 2;
882 pathname
= alloca(len
);
883 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
884 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
889 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
894 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
896 snprintf(fname
, len
, "%s/tasks", dirname
);
897 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
899 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
900 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
905 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
909 char *pathname
, *tmpc
;
911 tmpc
= find_mounted_controller(controller
, &cfd
);
915 /* Make sure we pass a relative path to *at() family of functions.
918 len
= strlen(file
) + 2;
919 pathname
= alloca(len
);
920 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
921 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
924 if (is_dir(pathname
, cfd
))
925 // like cgmanager did, we want to chown the tasks file as well
926 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
931 FILE *open_pids_file(const char *controller
, const char *cgroup
)
935 char *pathname
, *tmpc
;
937 tmpc
= find_mounted_controller(controller
, &cfd
);
941 /* Make sure we pass a relative path to *at() family of functions.
942 * . + /cgroup + / "cgroup.procs" + \0
944 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
945 pathname
= alloca(len
);
946 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
948 fd
= openat(cfd
, pathname
, O_WRONLY
);
952 return fdopen(fd
, "w");
955 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
956 void ***list
, size_t typesize
,
957 void* (*iterator
)(const char*, const char*, const char*))
962 char pathname
[MAXPATHLEN
];
963 size_t sz
= 0, asz
= 0;
964 struct dirent
*dirent
;
967 tmpc
= find_mounted_controller(controller
, &cfd
);
972 /* Make sure we pass a relative path to *at() family of functions. */
973 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
975 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
976 if (ret
< 0 || (size_t)ret
>= len
) {
977 lxcfs_error("Pathname too long under %s\n", cgroup
);
981 fd
= openat(cfd
, cg
, O_DIRECTORY
);
989 while ((dirent
= readdir(dir
))) {
992 if (!strcmp(dirent
->d_name
, ".") ||
993 !strcmp(dirent
->d_name
, ".."))
996 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
997 if (ret
< 0 || ret
>= MAXPATHLEN
) {
998 lxcfs_error("Pathname too long under %s\n", cg
);
1002 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1004 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1007 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1008 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1015 tmp
= realloc(*list
, asz
* typesize
);
1019 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1020 (*list
)[sz
+1] = NULL
;
1023 if (closedir(dir
) < 0) {
1024 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1030 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1034 dup
= strdup(dir_entry
);
1039 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1041 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1044 void free_key(struct cgfs_files
*k
)
1052 void free_keys(struct cgfs_files
**keys
)
1058 for (i
= 0; keys
[i
]; i
++) {
1064 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1070 tmpc
= find_mounted_controller(controller
, &cfd
);
1074 /* Make sure we pass a relative path to *at() family of functions.
1075 * . + /cgroup + / + file + \0
1077 len
= strlen(cgroup
) + strlen(file
) + 3;
1079 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1080 if (ret
< 0 || (size_t)ret
>= len
)
1083 fd
= openat(cfd
, fnam
, O_RDONLY
);
1087 *value
= slurp_file(fnam
, fd
);
1088 return *value
!= NULL
;
1091 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1097 struct cgfs_files
*newkey
;
1099 tmpc
= find_mounted_controller(controller
, &cfd
);
1103 if (file
&& *file
== '/')
1106 if (file
&& strchr(file
, '/'))
1109 /* Make sure we pass a relative path to *at() family of functions.
1110 * . + /cgroup + / + file + \0
1112 len
= strlen(cgroup
) + 3;
1114 len
+= strlen(file
) + 1;
1116 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1117 file
? "/" : "", file
? file
: "");
1119 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1124 newkey
= malloc(sizeof(struct cgfs_files
));
1127 newkey
->name
= must_copy_string(file
);
1128 else if (strrchr(cgroup
, '/'))
1129 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1131 newkey
->name
= must_copy_string(cgroup
);
1132 newkey
->uid
= sb
.st_uid
;
1133 newkey
->gid
= sb
.st_gid
;
1134 newkey
->mode
= sb
.st_mode
;
1139 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1141 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1143 lxcfs_error("Error getting files under %s:%s\n", controller
,
1149 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1151 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1154 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1162 tmpc
= find_mounted_controller(controller
, &cfd
);
1166 /* Make sure we pass a relative path to *at() family of functions.
1167 * . + /cgroup + / + f + \0
1169 len
= strlen(cgroup
) + strlen(f
) + 3;
1171 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1172 if (ret
< 0 || (size_t)ret
>= len
)
1175 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1176 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1182 #define SEND_CREDS_OK 0
1183 #define SEND_CREDS_NOTSK 1
1184 #define SEND_CREDS_FAIL 2
1185 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1186 static int wait_for_pid(pid_t pid
);
1187 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1188 static int send_creds_clone_wrapper(void *arg
);
1191 * clone a task which switches to @task's namespace and writes '1'.
1192 * over a unix sock so we can read the task's reaper's pid in our
1195 * Note: glibc's fork() does not respect pidns, which can lead to failed
1196 * assertions inside glibc (and thus failed forks) if the child's pid in
1197 * the pidns and the parent pid outside are identical. Using clone prevents
1200 static void write_task_init_pid_exit(int sock
, pid_t target
)
1205 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1206 void *stack
= alloca(stack_size
);
1208 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1209 if (ret
< 0 || ret
>= sizeof(fnam
))
1212 fd
= open(fnam
, O_RDONLY
);
1214 perror("write_task_init_pid_exit open of ns/pid");
1218 perror("write_task_init_pid_exit setns 1");
1222 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1226 if (!wait_for_pid(pid
))
1232 static int send_creds_clone_wrapper(void *arg
) {
1235 int sock
= *(int *)arg
;
1237 /* we are the child */
1242 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1247 static pid_t
get_init_pid_for_task(pid_t task
)
1255 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1256 perror("socketpair");
1265 write_task_init_pid_exit(sock
[0], task
);
1269 if (!recv_creds(sock
[1], &cred
, &v
))
1281 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1285 struct pidns_init_store
*e
;
1288 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1290 if (stat(fnam
, &sb
) < 0)
1292 e
= lookup_verify_initpid(&sb
);
1294 answer
= e
->initpid
;
1297 answer
= get_init_pid_for_task(qpid
);
1299 save_initpid(&sb
, answer
);
1302 /* we prune at end in case we are returning
1303 * the value we were about to return */
1304 prune_initpid_store();
1309 static int wait_for_pid(pid_t pid
)
1317 ret
= waitpid(pid
, &status
, 0);
1325 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1332 * append pid to *src.
1333 * src: a pointer to a char* in which ot append the pid.
1334 * sz: the number of characters printed so far, minus trailing \0.
1335 * asz: the allocated size so far
1336 * pid: the pid to append
1338 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1342 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1344 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1347 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1350 *asz
+= BUF_RESERVE_SIZE
;
1352 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1357 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1358 * valid in the caller's namespace, return the id mapped into
1360 * Returns the mapped id, or -1 on error.
1363 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1365 unsigned int nsuid
, // base id for a range in the idfile's namespace
1366 hostuid
, // base id for a range in the caller's namespace
1367 count
; // number of ids in this range
1371 fseek(idfile
, 0L, SEEK_SET
);
1372 while (fgets(line
, 400, idfile
)) {
1373 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1376 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1378 * uids wrapped around - unexpected as this is a procfile,
1381 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1382 nsuid
, hostuid
, count
, line
);
1385 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1387 * now since hostuid <= in_id < hostuid+count, and
1388 * hostuid+count and nsuid+count do not wrap around,
1389 * we know that nsuid+(in_id-hostuid) which must be
1390 * less that nsuid+(count) must not wrap around
1392 return (in_id
- hostuid
) + nsuid
;
1401 * for is_privileged_over,
1402 * specify whether we require the calling uid to be root in his
1405 #define NS_ROOT_REQD true
1406 #define NS_ROOT_OPT false
1410 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1412 char fpath
[PROCLEN
];
1414 bool answer
= false;
1417 if (victim
== -1 || uid
== -1)
1421 * If the request is one not requiring root in the namespace,
1422 * then having the same uid suffices. (i.e. uid 1000 has write
1423 * access to files owned by uid 1000
1425 if (!req_ns_root
&& uid
== victim
)
1428 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1429 if (ret
< 0 || ret
>= PROCLEN
)
1431 FILE *f
= fopen(fpath
, "r");
1435 /* if caller's not root in his namespace, reject */
1436 nsuid
= convert_id_to_ns(f
, uid
);
1441 * If victim is not mapped into caller's ns, reject.
1442 * XXX I'm not sure this check is needed given that fuse
1443 * will be sending requests where the vfs has converted
1445 nsuid
= convert_id_to_ns(f
, victim
);
1456 static bool perms_include(int fmode
, mode_t req_mode
)
1460 switch (req_mode
& O_ACCMODE
) {
1468 r
= S_IROTH
| S_IWOTH
;
1473 return ((fmode
& r
) == r
);
1479 * querycg is /a/b/c/d/e
1482 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1486 if (strlen(taskcg
) <= strlen(querycg
)) {
1487 lxcfs_error("%s\n", "I was fed bad input.");
1491 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1492 start
= strdup(taskcg
+ 1);
1494 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1497 end
= strchr(start
, '/');
1503 static void stripnewline(char *x
)
1505 size_t l
= strlen(x
);
1506 if (l
&& x
[l
-1] == '\n')
1510 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1515 char *answer
= NULL
;
1519 const char *h
= find_mounted_controller(contrl
, &cfd
);
1523 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1524 if (ret
< 0 || ret
>= PROCLEN
)
1526 if (!(f
= fopen(fnam
, "r")))
1529 while (getline(&line
, &len
, f
) != -1) {
1533 c1
= strchr(line
, ':');
1537 c2
= strchr(c1
, ':');
1541 if (strcmp(c1
, h
) != 0)
1546 answer
= strdup(c2
);
1558 * check whether a fuse context may access a cgroup dir or file
1560 * If file is not null, it is a cgroup file to check under cg.
1561 * If file is null, then we are checking perms on cg itself.
1563 * For files we can check the mode of the list_keys result.
1564 * For cgroups, we must make assumptions based on the files under the
1565 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1568 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1570 struct cgfs_files
*k
= NULL
;
1573 k
= cgfs_get_key(contrl
, cg
, file
);
1577 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1578 if (perms_include(k
->mode
>> 6, mode
)) {
1583 if (fc
->gid
== k
->gid
) {
1584 if (perms_include(k
->mode
>> 3, mode
)) {
1589 ret
= perms_include(k
->mode
, mode
);
1596 #define INITSCOPE "/init.scope"
1597 static void prune_init_slice(char *cg
)
1600 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1602 if (cg_len
< initscope_len
)
1605 point
= cg
+ cg_len
- initscope_len
;
1606 if (strcmp(point
, INITSCOPE
) == 0) {
1615 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1616 * If pid is in /a, he may act on /a/b, but not on /b.
1617 * if the answer is false and nextcg is not NULL, then *nextcg will point
1618 * to a string containing the next cgroup directory under cg, which must be
1619 * freed by the caller.
1621 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1623 bool answer
= false;
1624 char *c2
= get_pid_cgroup(pid
, contrl
);
1629 prune_init_slice(c2
);
1632 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1633 * they pass in a cgroup without leading '/'
1635 * The original line here was:
1636 * linecmp = *cg == '/' ? c2 : c2+1;
1637 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1638 * Serge, do you know?
1640 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1644 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1646 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1658 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1660 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1662 bool answer
= false;
1664 size_t target_len
, task_len
;
1666 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1669 c2
= get_pid_cgroup(pid
, contrl
);
1672 prune_init_slice(c2
);
1675 target_len
= strlen(cg
);
1676 task_len
= strlen(task_cg
);
1677 if (task_len
== 0) {
1678 /* Task is in the root cg, it can see everything. This case is
1679 * not handled by the strmcps below, since they test for the
1680 * last /, but that is the first / that we've chopped off
1686 if (strcmp(cg
, task_cg
) == 0) {
1690 if (target_len
< task_len
) {
1691 /* looking up a parent dir */
1692 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1696 if (target_len
> task_len
) {
1697 /* looking up a child dir */
1698 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1709 * given /cgroup/freezer/a/b, return "freezer".
1710 * the returned char* should NOT be freed.
1712 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1715 char *contr
, *slash
;
1717 if (strlen(path
) < 9) {
1721 if (*(path
+ 7) != '/') {
1726 contr
= strdupa(p1
);
1731 slash
= strstr(contr
, "/");
1736 for (i
= 0; i
< num_hierarchies
; i
++) {
1737 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1738 return hierarchies
[i
];
1745 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1746 * Note that the returned value may include files (keynames) etc
1748 static const char *find_cgroup_in_path(const char *path
)
1752 if (strlen(path
) < 9) {
1756 p1
= strstr(path
+ 8, "/");
1766 * split the last path element from the path in @cg.
1767 * @dir is newly allocated and should be freed, @last not
1769 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1776 *last
= strrchr(cg
, '/');
1781 p
= strrchr(*dir
, '/');
1786 * FUSE ops for /cgroup
1789 int cg_getattr(const char *path
, struct stat
*sb
)
1791 struct timespec now
;
1792 struct fuse_context
*fc
= fuse_get_context();
1793 char * cgdir
= NULL
;
1794 char *last
= NULL
, *path1
, *path2
;
1795 struct cgfs_files
*k
= NULL
;
1797 const char *controller
= NULL
;
1804 memset(sb
, 0, sizeof(struct stat
));
1806 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1809 sb
->st_uid
= sb
->st_gid
= 0;
1810 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1813 if (strcmp(path
, "/cgroup") == 0) {
1814 sb
->st_mode
= S_IFDIR
| 00755;
1819 controller
= pick_controller_from_path(fc
, path
);
1822 cgroup
= find_cgroup_in_path(path
);
1824 /* this is just /cgroup/controller, return it as a dir */
1825 sb
->st_mode
= S_IFDIR
| 00755;
1830 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1840 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1843 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1844 * Then check that caller's cgroup is under path if last is a child
1845 * cgroup, or cgdir if last is a file */
1847 if (is_child_cgroup(controller
, path1
, path2
)) {
1848 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1852 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1853 /* this is just /cgroup/controller, return it as a dir */
1854 sb
->st_mode
= S_IFDIR
| 00555;
1859 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1864 // get uid, gid, from '/tasks' file and make up a mode
1865 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1866 sb
->st_mode
= S_IFDIR
| 00755;
1867 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1869 sb
->st_uid
= sb
->st_gid
= 0;
1871 sb
->st_uid
= k
->uid
;
1872 sb
->st_gid
= k
->gid
;
1880 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1881 sb
->st_mode
= S_IFREG
| k
->mode
;
1883 sb
->st_uid
= k
->uid
;
1884 sb
->st_gid
= k
->gid
;
1887 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1899 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1901 struct fuse_context
*fc
= fuse_get_context();
1903 struct file_info
*dir_info
;
1904 char *controller
= NULL
;
1909 if (strcmp(path
, "/cgroup") == 0) {
1913 // return list of keys for the controller, and list of child cgroups
1914 controller
= pick_controller_from_path(fc
, path
);
1918 cgroup
= find_cgroup_in_path(path
);
1920 /* this is just /cgroup/controller, return its contents */
1925 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1929 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1931 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1935 /* we'll free this at cg_releasedir */
1936 dir_info
= malloc(sizeof(*dir_info
));
1939 dir_info
->controller
= must_copy_string(controller
);
1940 dir_info
->cgroup
= must_copy_string(cgroup
);
1941 dir_info
->type
= LXC_TYPE_CGDIR
;
1942 dir_info
->buf
= NULL
;
1943 dir_info
->file
= NULL
;
1944 dir_info
->buflen
= 0;
1946 fi
->fh
= (unsigned long)dir_info
;
1950 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1951 struct fuse_file_info
*fi
)
1953 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1954 struct cgfs_files
**list
= NULL
;
1956 char *nextcg
= NULL
;
1957 struct fuse_context
*fc
= fuse_get_context();
1958 char **clist
= NULL
;
1960 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1963 if (d
->type
!= LXC_TYPE_CGDIR
) {
1964 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1967 if (!d
->cgroup
&& !d
->controller
) {
1968 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1971 for (i
= 0; i
< num_hierarchies
; i
++) {
1972 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1979 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1980 // not a valid cgroup
1985 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1988 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1990 ret
= filler(buf
, nextcg
, NULL
, 0);
2001 for (i
= 0; list
[i
]; i
++) {
2002 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2008 // now get the list of child cgroups
2010 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2015 for (i
= 0; clist
[i
]; i
++) {
2016 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2027 for (i
= 0; clist
[i
]; i
++)
2034 static void do_release_file_info(struct fuse_file_info
*fi
)
2036 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2043 free(f
->controller
);
2044 f
->controller
= NULL
;
2054 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2056 do_release_file_info(fi
);
2060 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2063 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2064 struct cgfs_files
*k
= NULL
;
2065 struct file_info
*file_info
;
2066 struct fuse_context
*fc
= fuse_get_context();
2072 controller
= pick_controller_from_path(fc
, path
);
2075 cgroup
= find_cgroup_in_path(path
);
2079 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2088 k
= cgfs_get_key(controller
, path1
, path2
);
2095 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2098 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2102 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2107 /* we'll free this at cg_release */
2108 file_info
= malloc(sizeof(*file_info
));
2113 file_info
->controller
= must_copy_string(controller
);
2114 file_info
->cgroup
= must_copy_string(path1
);
2115 file_info
->file
= must_copy_string(path2
);
2116 file_info
->type
= LXC_TYPE_CGFILE
;
2117 file_info
->buf
= NULL
;
2118 file_info
->buflen
= 0;
2120 fi
->fh
= (unsigned long)file_info
;
2128 int cg_access(const char *path
, int mode
)
2132 char *path1
, *path2
, *controller
;
2133 char *last
= NULL
, *cgdir
= NULL
;
2134 struct cgfs_files
*k
= NULL
;
2135 struct fuse_context
*fc
= fuse_get_context();
2137 if (strcmp(path
, "/cgroup") == 0)
2143 controller
= pick_controller_from_path(fc
, path
);
2146 cgroup
= find_cgroup_in_path(path
);
2148 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2149 if ((mode
& W_OK
) == 0)
2154 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2163 k
= cgfs_get_key(controller
, path1
, path2
);
2165 if ((mode
& W_OK
) == 0)
2173 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2176 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2180 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2192 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2194 do_release_file_info(fi
);
2198 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2200 static bool wait_for_sock(int sock
, int timeout
)
2202 struct epoll_event ev
;
2203 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2205 if ((starttime
= time(NULL
)) < 0)
2208 if ((epfd
= epoll_create(1)) < 0) {
2209 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2213 ev
.events
= POLLIN_SET
;
2215 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2216 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2222 if ((now
= time(NULL
)) < 0) {
2227 deltatime
= (starttime
+ timeout
) - now
;
2228 if (deltatime
< 0) { // timeout
2233 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2234 if (ret
< 0 && errno
== EINTR
)
2236 saved_errno
= errno
;
2240 errno
= saved_errno
;
2246 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2248 if (!wait_for_sock(sockfd
, 2))
2250 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2253 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2255 struct msghdr msg
= { 0 };
2257 struct cmsghdr
*cmsg
;
2258 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2263 if (msgrecv(sock
, buf
, 1) != 1) {
2264 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2265 return SEND_CREDS_FAIL
;
2269 msg
.msg_control
= cmsgbuf
;
2270 msg
.msg_controllen
= sizeof(cmsgbuf
);
2272 cmsg
= CMSG_FIRSTHDR(&msg
);
2273 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2274 cmsg
->cmsg_level
= SOL_SOCKET
;
2275 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2276 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2278 msg
.msg_name
= NULL
;
2279 msg
.msg_namelen
= 0;
2283 iov
.iov_len
= sizeof(buf
);
2287 if (sendmsg(sock
, &msg
, 0) < 0) {
2288 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2290 return SEND_CREDS_NOTSK
;
2291 return SEND_CREDS_FAIL
;
2294 return SEND_CREDS_OK
;
2297 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2299 struct msghdr msg
= { 0 };
2301 struct cmsghdr
*cmsg
;
2302 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2313 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2314 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2318 if (write(sock
, buf
, 1) != 1) {
2319 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2323 msg
.msg_name
= NULL
;
2324 msg
.msg_namelen
= 0;
2325 msg
.msg_control
= cmsgbuf
;
2326 msg
.msg_controllen
= sizeof(cmsgbuf
);
2329 iov
.iov_len
= sizeof(buf
);
2333 if (!wait_for_sock(sock
, 2)) {
2334 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2337 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2339 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2343 cmsg
= CMSG_FIRSTHDR(&msg
);
2345 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2346 cmsg
->cmsg_level
== SOL_SOCKET
&&
2347 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2348 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2355 struct pid_ns_clone_args
{
2359 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2363 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2364 * with clone(). This simply writes '1' as ACK back to the parent
2365 * before calling the actual wrapped function.
2367 static int pid_ns_clone_wrapper(void *arg
) {
2368 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2371 close(args
->cpipe
[0]);
2372 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2373 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2374 close(args
->cpipe
[1]);
2375 return args
->wrapped(args
->sock
, args
->tpid
);
2379 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2380 * int value back over the socket. This shifts the pid from the
2381 * sender's pidns into tpid's pidns.
2383 static int pid_to_ns(int sock
, pid_t tpid
)
2388 while (recv_creds(sock
, &cred
, &v
)) {
2391 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2399 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2400 * in your old pidns. Only children which you clone will be in the target
2401 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2402 * actually convert pids.
2404 * Note: glibc's fork() does not respect pidns, which can lead to failed
2405 * assertions inside glibc (and thus failed forks) if the child's pid in
2406 * the pidns and the parent pid outside are identical. Using clone prevents
2409 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2411 int newnsfd
= -1, ret
, cpipe
[2];
2416 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2417 if (ret
< 0 || ret
>= sizeof(fnam
))
2419 newnsfd
= open(fnam
, O_RDONLY
);
2422 if (setns(newnsfd
, 0) < 0)
2426 if (pipe(cpipe
) < 0)
2429 struct pid_ns_clone_args args
= {
2433 .wrapped
= &pid_to_ns
2435 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2436 void *stack
= alloca(stack_size
);
2438 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2442 // give the child 1 second to be done forking and
2444 if (!wait_for_sock(cpipe
[0], 1))
2446 ret
= read(cpipe
[0], &v
, 1);
2447 if (ret
!= sizeof(char) || v
!= '1')
2450 if (!wait_for_pid(cpid
))
2456 * To read cgroup files with a particular pid, we will setns into the child
2457 * pidns, open a pipe, fork a child - which will be the first to really be in
2458 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2460 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2462 int sock
[2] = {-1, -1};
2463 char *tmpdata
= NULL
;
2465 pid_t qpid
, cpid
= -1;
2466 bool answer
= false;
2469 size_t sz
= 0, asz
= 0;
2471 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2475 * Now we read the pids from returned data one by one, pass
2476 * them into a child in the target namespace, read back the
2477 * translated pids, and put them into our to-return data
2480 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2481 perror("socketpair");
2490 if (!cpid
) // child - exits when done
2491 pid_to_ns_wrapper(sock
[1], tpid
);
2493 char *ptr
= tmpdata
;
2496 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2498 ret
= send_creds(sock
[0], &cred
, v
, true);
2500 if (ret
== SEND_CREDS_NOTSK
)
2502 if (ret
== SEND_CREDS_FAIL
)
2505 // read converted results
2506 if (!wait_for_sock(sock
[0], 2)) {
2507 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2510 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2511 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2514 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2516 ptr
= strchr(ptr
, '\n');
2522 cred
.pid
= getpid();
2524 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2525 // failed to ask child to exit
2526 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2536 if (sock
[0] != -1) {
2543 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2544 struct fuse_file_info
*fi
)
2546 struct fuse_context
*fc
= fuse_get_context();
2547 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2548 struct cgfs_files
*k
= NULL
;
2553 if (f
->type
!= LXC_TYPE_CGFILE
) {
2554 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2567 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2573 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2578 if (strcmp(f
->file
, "tasks") == 0 ||
2579 strcmp(f
->file
, "/tasks") == 0 ||
2580 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2581 strcmp(f
->file
, "cgroup.procs") == 0)
2582 // special case - we have to translate the pids
2583 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2585 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2599 memcpy(buf
, data
, s
);
2600 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2610 static int pid_from_ns(int sock
, pid_t tpid
)
2620 if (!wait_for_sock(sock
, 2)) {
2621 lxcfs_error("%s\n", "Timeout reading from parent.");
2624 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2625 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2628 if (vpid
== -1) // done
2632 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2634 cred
.pid
= getpid();
2635 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2642 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2644 int newnsfd
= -1, ret
, cpipe
[2];
2649 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2650 if (ret
< 0 || ret
>= sizeof(fnam
))
2652 newnsfd
= open(fnam
, O_RDONLY
);
2655 if (setns(newnsfd
, 0) < 0)
2659 if (pipe(cpipe
) < 0)
2662 struct pid_ns_clone_args args
= {
2666 .wrapped
= &pid_from_ns
2668 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2669 void *stack
= alloca(stack_size
);
2671 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2675 // give the child 1 second to be done forking and
2677 if (!wait_for_sock(cpipe
[0], 1))
2679 ret
= read(cpipe
[0], &v
, 1);
2680 if (ret
!= sizeof(char) || v
!= '1')
2683 if (!wait_for_pid(cpid
))
2689 * Given host @uid, return the uid to which it maps in
2690 * @pid's user namespace, or -1 if none.
2692 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2697 sprintf(line
, "/proc/%d/uid_map", pid
);
2698 if ((f
= fopen(line
, "r")) == NULL
) {
2702 *answer
= convert_id_to_ns(f
, uid
);
2711 * get_pid_creds: get the real uid and gid of @pid from
2713 * (XXX should we use euid here?)
2715 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2724 sprintf(line
, "/proc/%d/status", pid
);
2725 if ((f
= fopen(line
, "r")) == NULL
) {
2726 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2729 while (fgets(line
, 400, f
)) {
2730 if (strncmp(line
, "Uid:", 4) == 0) {
2731 if (sscanf(line
+4, "%u", &u
) != 1) {
2732 lxcfs_error("bad uid line for pid %u\n", pid
);
2737 } else if (strncmp(line
, "Gid:", 4) == 0) {
2738 if (sscanf(line
+4, "%u", &g
) != 1) {
2739 lxcfs_error("bad gid line for pid %u\n", pid
);
2750 * May the requestor @r move victim @v to a new cgroup?
2751 * This is allowed if
2752 * . they are the same task
2753 * . they are ownedy by the same uid
2754 * . @r is root on the host, or
2755 * . @v's uid is mapped into @r's where @r is root.
2757 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2759 uid_t v_uid
, tmpuid
;
2766 get_pid_creds(v
, &v_uid
, &v_gid
);
2769 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2770 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2775 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2776 const char *file
, const char *buf
)
2778 int sock
[2] = {-1, -1};
2779 pid_t qpid
, cpid
= -1;
2780 FILE *pids_file
= NULL
;
2781 bool answer
= false, fail
= false;
2783 pids_file
= open_pids_file(contrl
, cg
);
2788 * write the pids to a socket, have helper in writer's pidns
2789 * call movepid for us
2791 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2792 perror("socketpair");
2800 if (!cpid
) { // child
2802 pid_from_ns_wrapper(sock
[1], tpid
);
2805 const char *ptr
= buf
;
2806 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2810 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2811 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2815 if (recv_creds(sock
[0], &cred
, &v
)) {
2817 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2821 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2826 ptr
= strchr(ptr
, '\n');
2832 /* All good, write the value */
2834 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2835 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2843 if (sock
[0] != -1) {
2848 if (fclose(pids_file
) != 0)
2854 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2855 struct fuse_file_info
*fi
)
2857 struct fuse_context
*fc
= fuse_get_context();
2858 char *localbuf
= NULL
;
2859 struct cgfs_files
*k
= NULL
;
2860 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2863 if (f
->type
!= LXC_TYPE_CGFILE
) {
2864 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2874 localbuf
= alloca(size
+1);
2875 localbuf
[size
] = '\0';
2876 memcpy(localbuf
, buf
, size
);
2878 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2883 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2888 if (strcmp(f
->file
, "tasks") == 0 ||
2889 strcmp(f
->file
, "/tasks") == 0 ||
2890 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2891 strcmp(f
->file
, "cgroup.procs") == 0)
2892 // special case - we have to translate the pids
2893 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2895 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2905 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2907 struct fuse_context
*fc
= fuse_get_context();
2908 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2909 struct cgfs_files
*k
= NULL
;
2916 if (strcmp(path
, "/cgroup") == 0)
2919 controller
= pick_controller_from_path(fc
, path
);
2921 return errno
== ENOENT
? -EPERM
: -errno
;
2923 cgroup
= find_cgroup_in_path(path
);
2925 /* this is just /cgroup/controller */
2928 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2938 if (is_child_cgroup(controller
, path1
, path2
)) {
2939 // get uid, gid, from '/tasks' file and make up a mode
2940 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2941 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2944 k
= cgfs_get_key(controller
, path1
, path2
);
2952 * This being a fuse request, the uid and gid must be valid
2953 * in the caller's namespace. So we can just check to make
2954 * sure that the caller is root in his uid, and privileged
2955 * over the file's current owner.
2957 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2962 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2971 int cg_chmod(const char *path
, mode_t mode
)
2973 struct fuse_context
*fc
= fuse_get_context();
2974 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2975 struct cgfs_files
*k
= NULL
;
2982 if (strcmp(path
, "/cgroup") == 0)
2985 controller
= pick_controller_from_path(fc
, path
);
2987 return errno
== ENOENT
? -EPERM
: -errno
;
2989 cgroup
= find_cgroup_in_path(path
);
2991 /* this is just /cgroup/controller */
2994 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3004 if (is_child_cgroup(controller
, path1
, path2
)) {
3005 // get uid, gid, from '/tasks' file and make up a mode
3006 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3007 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3010 k
= cgfs_get_key(controller
, path1
, path2
);
3018 * This being a fuse request, the uid and gid must be valid
3019 * in the caller's namespace. So we can just check to make
3020 * sure that the caller is root in his uid, and privileged
3021 * over the file's current owner.
3023 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3028 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3040 int cg_mkdir(const char *path
, mode_t mode
)
3042 struct fuse_context
*fc
= fuse_get_context();
3043 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3050 controller
= pick_controller_from_path(fc
, path
);
3052 return errno
== ENOENT
? -EPERM
: -errno
;
3054 cgroup
= find_cgroup_in_path(path
);
3058 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3064 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3067 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3070 else if (last
&& strcmp(next
, last
) == 0)
3077 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3081 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3086 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3094 int cg_rmdir(const char *path
)
3096 struct fuse_context
*fc
= fuse_get_context();
3097 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3104 controller
= pick_controller_from_path(fc
, path
);
3105 if (!controller
) /* Someone's trying to delete "/cgroup". */
3108 cgroup
= find_cgroup_in_path(path
);
3109 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3112 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3114 /* Someone's trying to delete a cgroup on the same level as the
3115 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3116 * rmdir "/cgroup/blkio/init.slice".
3122 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3125 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3126 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3133 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3137 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3142 if (!cgfs_remove(controller
, cgroup
)) {
3155 static bool startswith(const char *line
, const char *pref
)
3157 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3162 static void parse_memstat(char *memstat
, unsigned long *cached
,
3163 unsigned long *active_anon
, unsigned long *inactive_anon
,
3164 unsigned long *active_file
, unsigned long *inactive_file
,
3165 unsigned long *unevictable
, unsigned long *shmem
)
3170 if (startswith(memstat
, "total_cache")) {
3171 sscanf(memstat
+ 11, "%lu", cached
);
3173 } else if (startswith(memstat
, "total_active_anon")) {
3174 sscanf(memstat
+ 17, "%lu", active_anon
);
3175 *active_anon
/= 1024;
3176 } else if (startswith(memstat
, "total_inactive_anon")) {
3177 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3178 *inactive_anon
/= 1024;
3179 } else if (startswith(memstat
, "total_active_file")) {
3180 sscanf(memstat
+ 17, "%lu", active_file
);
3181 *active_file
/= 1024;
3182 } else if (startswith(memstat
, "total_inactive_file")) {
3183 sscanf(memstat
+ 19, "%lu", inactive_file
);
3184 *inactive_file
/= 1024;
3185 } else if (startswith(memstat
, "total_unevictable")) {
3186 sscanf(memstat
+ 17, "%lu", unevictable
);
3187 *unevictable
/= 1024;
3188 } else if (startswith(memstat
, "total_shmem")) {
3189 sscanf(memstat
+ 11, "%lu", shmem
);
3192 eol
= strchr(memstat
, '\n');
3199 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3205 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3207 size_t len
= strlen(key
);
3211 if (startswith(str
, key
)) {
3212 sscanf(str
+ len
, "%lu", v
);
3215 eol
= strchr(str
, '\n');
3222 static int read_file(const char *path
, char *buf
, size_t size
,
3223 struct file_info
*d
)
3225 size_t linelen
= 0, total_len
= 0, rv
= 0;
3227 char *cache
= d
->buf
;
3228 size_t cache_size
= d
->buflen
;
3229 FILE *f
= fopen(path
, "r");
3233 while (getline(&line
, &linelen
, f
) != -1) {
3234 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3236 perror("Error writing to cache");
3240 if (l
>= cache_size
) {
3241 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3250 d
->size
= total_len
;
3251 if (total_len
> size
)
3254 /* read from off 0 */
3255 memcpy(buf
, d
->buf
, total_len
);
3264 * FUSE ops for /proc
3267 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3269 char *memlimit_str
= NULL
;
3270 unsigned long memlimit
= -1;
3272 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3273 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3280 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3282 char *copy
= strdupa(cgroup
);
3283 unsigned long memlimit
= 0, retlimit
;
3285 retlimit
= get_memlimit(copy
, file
);
3287 while (strcmp(copy
, "/") != 0) {
3288 copy
= dirname(copy
);
3289 memlimit
= get_memlimit(copy
, file
);
3290 if (memlimit
!= -1 && memlimit
< retlimit
)
3291 retlimit
= memlimit
;
3297 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3298 struct fuse_file_info
*fi
)
3300 struct fuse_context
*fc
= fuse_get_context();
3301 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3303 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3304 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3305 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3306 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3307 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3310 size_t linelen
= 0, total_len
= 0, rv
= 0;
3311 char *cache
= d
->buf
;
3312 size_t cache_size
= d
->buflen
;
3316 if (offset
> d
->size
)
3320 int left
= d
->size
- offset
;
3321 total_len
= left
> size
? size
: left
;
3322 memcpy(buf
, cache
+ offset
, total_len
);
3326 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3329 cg
= get_pid_cgroup(initpid
, "memory");
3331 return read_file("/proc/meminfo", buf
, size
, d
);
3332 prune_init_slice(cg
);
3334 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3335 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3337 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3340 // Following values are allowed to fail, because swapaccount might be turned
3341 // off for current kernel
3342 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3343 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3345 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3346 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3348 memswlimit
= memswlimit
/ 1024;
3349 memswusage
= memswusage
/ 1024;
3352 memusage
= strtoul(memusage_str
, NULL
, 10);
3356 parse_memstat(memstat_str
, &cached
, &active_anon
,
3357 &inactive_anon
, &active_file
, &inactive_file
,
3358 &unevictable
, &shmem
);
3360 f
= fopen("/proc/meminfo", "r");
3364 while (getline(&line
, &linelen
, f
) != -1) {
3366 char *printme
, lbuf
[100];
3368 memset(lbuf
, 0, 100);
3369 if (startswith(line
, "MemTotal:")) {
3370 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3371 if (hosttotal
< memlimit
)
3372 memlimit
= hosttotal
;
3373 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3375 } else if (startswith(line
, "MemFree:")) {
3376 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3378 } else if (startswith(line
, "MemAvailable:")) {
3379 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3381 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3382 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3383 if (hostswtotal
< memswlimit
)
3384 memswlimit
= hostswtotal
;
3385 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3387 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3388 unsigned long swaptotal
= memswlimit
,
3389 swapusage
= memswusage
- memusage
,
3390 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3391 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3393 } else if (startswith(line
, "Slab:")) {
3394 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3396 } else if (startswith(line
, "Buffers:")) {
3397 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3399 } else if (startswith(line
, "Cached:")) {
3400 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3402 } else if (startswith(line
, "SwapCached:")) {
3403 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3405 } else if (startswith(line
, "Active:")) {
3406 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3407 active_anon
+ active_file
);
3409 } else if (startswith(line
, "Inactive:")) {
3410 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3411 inactive_anon
+ inactive_file
);
3413 } else if (startswith(line
, "Active(anon)")) {
3414 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3416 } else if (startswith(line
, "Inactive(anon)")) {
3417 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3419 } else if (startswith(line
, "Active(file)")) {
3420 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3422 } else if (startswith(line
, "Inactive(file)")) {
3423 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3425 } else if (startswith(line
, "Unevictable")) {
3426 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3428 } else if (startswith(line
, "SReclaimable")) {
3429 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3431 } else if (startswith(line
, "SUnreclaim")) {
3432 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3434 } else if (startswith(line
, "Shmem:")) {
3435 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3437 } else if (startswith(line
, "ShmemHugePages")) {
3438 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3440 } else if (startswith(line
, "ShmemPmdMapped")) {
3441 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3446 l
= snprintf(cache
, cache_size
, "%s", printme
);
3448 perror("Error writing to cache");
3453 if (l
>= cache_size
) {
3454 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3465 d
->size
= total_len
;
3466 if (total_len
> size
) total_len
= size
;
3467 memcpy(buf
, d
->buf
, total_len
);
3476 free(memswlimit_str
);
3477 free(memswusage_str
);
3483 * Read the cpuset.cpus for cg
3484 * Return the answer in a newly allocated string which must be freed
3486 static char *get_cpuset(const char *cg
)
3490 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3495 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3497 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3501 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3503 return cpu_in_cpuset(cpu
, cpuset
);
3507 * check whether this is a '^processor" line in /proc/cpuinfo
3509 static bool is_processor_line(const char *line
)
3513 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3518 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3519 struct fuse_file_info
*fi
)
3521 struct fuse_context
*fc
= fuse_get_context();
3522 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3524 char *cpuset
= NULL
;
3526 size_t linelen
= 0, total_len
= 0, rv
= 0;
3527 bool am_printing
= false, firstline
= true, is_s390x
= false;
3528 int curcpu
= -1, cpu
;
3529 char *cache
= d
->buf
;
3530 size_t cache_size
= d
->buflen
;
3534 if (offset
> d
->size
)
3538 int left
= d
->size
- offset
;
3539 total_len
= left
> size
? size
: left
;
3540 memcpy(buf
, cache
+ offset
, total_len
);
3544 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3547 cg
= get_pid_cgroup(initpid
, "cpuset");
3549 return read_file("proc/cpuinfo", buf
, size
, d
);
3550 prune_init_slice(cg
);
3552 cpuset
= get_cpuset(cg
);
3556 f
= fopen("/proc/cpuinfo", "r");
3560 while (getline(&line
, &linelen
, f
) != -1) {
3564 if (strstr(line
, "IBM/S390") != NULL
) {
3570 if (strncmp(line
, "# processors:", 12) == 0)
3572 if (is_processor_line(line
)) {
3573 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3576 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3578 perror("Error writing to cache");
3582 if (l
>= cache_size
) {
3583 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3592 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3594 if (!cpu_in_cpuset(cpu
, cpuset
))
3597 p
= strchr(line
, ':');
3601 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3603 perror("Error writing to cache");
3607 if (l
>= cache_size
) {
3608 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3619 l
= snprintf(cache
, cache_size
, "%s", line
);
3621 perror("Error writing to cache");
3625 if (l
>= cache_size
) {
3626 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3637 char *origcache
= d
->buf
;
3640 d
->buf
= malloc(d
->buflen
);
3643 cache_size
= d
->buflen
;
3645 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3646 if (l
< 0 || l
>= cache_size
) {
3653 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3654 if (l
< 0 || l
>= cache_size
) {
3661 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3663 if (l
< 0 || l
>= cache_size
)
3669 d
->size
= total_len
;
3670 if (total_len
> size
) total_len
= size
;
3672 /* read from off 0 */
3673 memcpy(buf
, d
->buf
, total_len
);
3684 static uint64_t get_reaper_start_time(pid_t pid
)
3689 /* strlen("/proc/") = 6
3693 * strlen("/stat") = 5
3697 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3698 char path
[__PROC_PID_STAT_LEN
];
3701 qpid
= lookup_initpid_in_store(pid
);
3703 /* Caller can check for EINVAL on 0. */
3708 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3709 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3710 /* Caller can check for EINVAL on 0. */
3715 f
= fopen(path
, "r");
3717 /* Caller can check for EINVAL on 0. */
3722 /* Note that the *scanf() argument supression requires that length
3723 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3724 * at us. It's like telling someone you're not married and then asking
3725 * if you can bring your wife to the party.
3727 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3728 "%*s " /* (2) comm %s */
3729 "%*c " /* (3) state %c */
3730 "%*d " /* (4) ppid %d */
3731 "%*d " /* (5) pgrp %d */
3732 "%*d " /* (6) session %d */
3733 "%*d " /* (7) tty_nr %d */
3734 "%*d " /* (8) tpgid %d */
3735 "%*u " /* (9) flags %u */
3736 "%*u " /* (10) minflt %lu */
3737 "%*u " /* (11) cminflt %lu */
3738 "%*u " /* (12) majflt %lu */
3739 "%*u " /* (13) cmajflt %lu */
3740 "%*u " /* (14) utime %lu */
3741 "%*u " /* (15) stime %lu */
3742 "%*d " /* (16) cutime %ld */
3743 "%*d " /* (17) cstime %ld */
3744 "%*d " /* (18) priority %ld */
3745 "%*d " /* (19) nice %ld */
3746 "%*d " /* (20) num_threads %ld */
3747 "%*d " /* (21) itrealvalue %ld */
3748 "%" PRIu64
, /* (22) starttime %llu */
3752 /* Caller can check for EINVAL on 0. */
3763 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3765 uint64_t clockticks
;
3766 int64_t ticks_per_sec
;
3768 clockticks
= get_reaper_start_time(pid
);
3769 if (clockticks
== 0 && errno
== EINVAL
) {
3770 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3774 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3775 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3778 "failed to determine number of clock ticks in a second");
3782 return (clockticks
/= ticks_per_sec
);
3785 static uint64_t get_reaper_age(pid_t pid
)
3787 uint64_t procstart
, uptime
, procage
;
3789 /* We need to substract the time the process has started since system
3790 * boot minus the time when the system has started to get the actual
3793 procstart
= get_reaper_start_time_in_sec(pid
);
3794 procage
= procstart
;
3795 if (procstart
> 0) {
3797 struct timespec spec
;
3799 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3802 /* We could make this more precise here by using the tv_nsec
3803 * field in the timespec struct and convert it to milliseconds
3804 * and then create a double for the seconds and milliseconds but
3805 * that seems more work than it is worth.
3807 uptime
= spec
.tv_sec
;
3808 procage
= uptime
- procstart
;
3815 * Returns 0 on success.
3816 * It is the caller's responsibility to free `return_usage`, unless this
3817 * function returns an error.
3819 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
)
3821 int cpucount
= get_nprocs();
3822 struct cpuacct_usage
*cpu_usage
;
3823 int rv
= 0, i
, j
, ret
, read_pos
= 0, read_cnt
;
3825 uint64_t cg_user
, cg_system
;
3826 int64_t ticks_per_sec
;
3827 char *usage_str
= NULL
;
3829 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3831 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3834 "read_cpuacct_usage_all failed to determine number of clock ticks "
3839 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
3843 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
3848 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
3849 lxcfs_error("read_cpuacct_usage_all reading first line from "
3850 "%s/cpuacct.usage_all failed.\n", cg
);
3855 read_pos
+= read_cnt
;
3857 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
3858 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
3859 &cg_system
, &read_cnt
);
3865 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
3871 read_pos
+= read_cnt
;
3873 if (!cpu_in_cpuset(i
, cpuset
))
3876 /* Convert the time from nanoseconds to USER_HZ */
3877 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3878 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3883 *return_usage
= cpu_usage
;
3891 *return_usage
= NULL
;
3897 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
3898 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3899 struct fuse_file_info
*fi
)
3901 struct fuse_context
*fc
= fuse_get_context();
3902 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3904 char *cpuset
= NULL
;
3906 size_t linelen
= 0, total_len
= 0, rv
= 0;
3907 int curcpu
= -1; /* cpu numbering starts at 0 */
3908 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
3909 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3910 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
3911 char cpuall
[CPUALL_MAX_SIZE
];
3912 /* reserve for cpu all */
3913 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3914 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3916 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
3919 if (offset
> d
->size
)
3923 int left
= d
->size
- offset
;
3924 total_len
= left
> size
? size
: left
;
3925 memcpy(buf
, d
->buf
+ offset
, total_len
);
3929 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3932 cg
= get_pid_cgroup(initpid
, "cpuset");
3934 return read_file("/proc/stat", buf
, size
, d
);
3935 prune_init_slice(cg
);
3937 cpuset
= get_cpuset(cg
);
3942 * Read cpuacct.usage_all for all CPUs.
3943 * If the cpuacct cgroup is present, it is used to calculate the container's
3944 * CPU usage. If not, values from the host's /proc/stat are used.
3946 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
) != 0) {
3947 lxcfs_debug("%s\n", "proc_stat_read failed to read from cpuacct, "
3948 "falling back to the host's /proc/stat");
3951 f
= fopen("/proc/stat", "r");
3956 if (getline(&line
, &linelen
, f
) < 0) {
3957 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3961 while (getline(&line
, &linelen
, f
) != -1) {
3964 char cpu_char
[10]; /* That's a lot of cores */
3966 uint64_t all_used
, cg_used
, new_idle
;
3969 if (strlen(line
) == 0)
3971 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3972 /* not a ^cpuN line containing a number N, just print it */
3973 l
= snprintf(cache
, cache_size
, "%s", line
);
3975 perror("Error writing to cache");
3979 if (l
>= cache_size
) {
3980 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3990 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3992 if (!cpu_in_cpuset(cpu
, cpuset
))
3996 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4008 if (ret
!= 10 || !cg_cpu_usage
) {
4009 c
= strchr(line
, ' ');
4012 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4014 perror("Error writing to cache");
4019 if (l
>= cache_size
) {
4020 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4034 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4035 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4037 if (all_used
>= cg_used
) {
4038 new_idle
= idle
+ (all_used
- cg_used
);
4041 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4042 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4043 curcpu
, cg
, all_used
, cg_used
);
4047 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4048 curcpu
, cg_cpu_usage
[curcpu
].user
, cg_cpu_usage
[curcpu
].system
,
4052 perror("Error writing to cache");
4057 if (l
>= cache_size
) {
4058 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4067 user_sum
+= cg_cpu_usage
[curcpu
].user
;
4068 system_sum
+= cg_cpu_usage
[curcpu
].system
;
4069 idle_sum
+= new_idle
;
4074 system_sum
+= system
;
4076 iowait_sum
+= iowait
;
4078 softirq_sum
+= softirq
;
4081 guest_nice_sum
+= guest_nice
;
4087 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4098 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4099 memcpy(cache
, cpuall
, cpuall_len
);
4100 cache
+= cpuall_len
;
4102 /* shouldn't happen */
4103 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4107 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4108 total_len
+= cpuall_len
;
4110 d
->size
= total_len
;
4111 if (total_len
> size
)
4114 memcpy(buf
, d
->buf
, total_len
);
4128 /* This function retrieves the busy time of a group of tasks by looking at
4129 * cpuacct.usage. Unfortunately, this only makes sense when the container has
4130 * been given it's own cpuacct cgroup. If not, this function will take the busy
4131 * time of all other taks that do not actually belong to the container into
4132 * account as well. If someone has a clever solution for this please send a
4135 static unsigned long get_reaper_busy(pid_t task
)
4137 pid_t initpid
= lookup_initpid_in_store(task
);
4138 char *cgroup
= NULL
, *usage_str
= NULL
;
4139 unsigned long usage
= 0;
4144 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
4147 prune_init_slice(cgroup
);
4148 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
4150 usage
= strtoul(usage_str
, NULL
, 10);
4151 usage
/= 1000000000;
4164 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4171 * We read /proc/uptime and reuse its second field.
4172 * For the first field, we use the mtime for the reaper for
4173 * the calling pid as returned by getreaperage
4175 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4176 struct fuse_file_info
*fi
)
4178 struct fuse_context
*fc
= fuse_get_context();
4179 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4180 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
4181 char *cache
= d
->buf
;
4182 ssize_t total_len
= 0;
4183 uint64_t idletime
, reaperage
;
4192 if (offset
> d
->size
)
4194 int left
= d
->size
- offset
;
4195 total_len
= left
> size
? size
: left
;
4196 memcpy(buf
, cache
+ offset
, total_len
);
4200 reaperage
= get_reaper_age(fc
->pid
);
4201 /* To understand why this is done, please read the comment to the
4202 * get_reaper_busy() function.
4204 idletime
= reaperage
;
4205 if (reaperage
>= busytime
)
4206 idletime
= reaperage
- busytime
;
4208 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
4209 if (total_len
< 0 || total_len
>= d
->buflen
){
4210 lxcfs_error("%s\n", "failed to write to cache");
4214 d
->size
= (int)total_len
;
4217 if (total_len
> size
) total_len
= size
;
4219 memcpy(buf
, d
->buf
, total_len
);
4223 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
4224 struct fuse_file_info
*fi
)
4227 struct fuse_context
*fc
= fuse_get_context();
4228 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4230 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
4231 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
4232 unsigned long read
= 0, write
= 0;
4233 unsigned long read_merged
= 0, write_merged
= 0;
4234 unsigned long read_sectors
= 0, write_sectors
= 0;
4235 unsigned long read_ticks
= 0, write_ticks
= 0;
4236 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
4237 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
4238 char *cache
= d
->buf
;
4239 size_t cache_size
= d
->buflen
;
4241 size_t linelen
= 0, total_len
= 0, rv
= 0;
4242 unsigned int major
= 0, minor
= 0;
4247 if (offset
> d
->size
)
4251 int left
= d
->size
- offset
;
4252 total_len
= left
> size
? size
: left
;
4253 memcpy(buf
, cache
+ offset
, total_len
);
4257 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4260 cg
= get_pid_cgroup(initpid
, "blkio");
4262 return read_file("/proc/diskstats", buf
, size
, d
);
4263 prune_init_slice(cg
);
4265 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
4267 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
4269 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
4271 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
4273 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
4277 f
= fopen("/proc/diskstats", "r");
4281 while (getline(&line
, &linelen
, f
) != -1) {
4285 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
4289 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
4290 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
4291 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
4292 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
4293 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
4294 read_sectors
= read_sectors
/512;
4295 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
4296 write_sectors
= write_sectors
/512;
4298 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
4299 rd_svctm
= rd_svctm
/1000000;
4300 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
4301 rd_wait
= rd_wait
/1000000;
4302 read_ticks
= rd_svctm
+ rd_wait
;
4304 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
4305 wr_svctm
= wr_svctm
/1000000;
4306 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
4307 wr_wait
= wr_wait
/1000000;
4308 write_ticks
= wr_svctm
+ wr_wait
;
4310 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
4311 tot_ticks
= tot_ticks
/1000000;
4313 memset(lbuf
, 0, 256);
4314 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
4315 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4316 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
4317 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
4321 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
4323 perror("Error writing to fuse buf");
4327 if (l
>= cache_size
) {
4328 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4338 d
->size
= total_len
;
4339 if (total_len
> size
) total_len
= size
;
4340 memcpy(buf
, d
->buf
, total_len
);
4348 free(io_serviced_str
);
4349 free(io_merged_str
);
4350 free(io_service_bytes_str
);
4351 free(io_wait_time_str
);
4352 free(io_service_time_str
);
4356 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
4357 struct fuse_file_info
*fi
)
4359 struct fuse_context
*fc
= fuse_get_context();
4360 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4362 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
4363 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
4364 ssize_t total_len
= 0, rv
= 0;
4366 char *cache
= d
->buf
;
4369 if (offset
> d
->size
)
4373 int left
= d
->size
- offset
;
4374 total_len
= left
> size
? size
: left
;
4375 memcpy(buf
, cache
+ offset
, total_len
);
4379 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4382 cg
= get_pid_cgroup(initpid
, "memory");
4384 return read_file("/proc/swaps", buf
, size
, d
);
4385 prune_init_slice(cg
);
4387 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
4389 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
4392 memusage
= strtoul(memusage_str
, NULL
, 10);
4394 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
4395 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
4397 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
4398 memswusage
= strtoul(memswusage_str
, NULL
, 10);
4400 swap_total
= (memswlimit
- memlimit
) / 1024;
4401 swap_free
= (memswusage
- memusage
) / 1024;
4404 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
4406 /* When no mem + swap limit is specified or swapaccount=0*/
4410 FILE *f
= fopen("/proc/meminfo", "r");
4415 while (getline(&line
, &linelen
, f
) != -1) {
4416 if (startswith(line
, "SwapTotal:")) {
4417 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
4418 } else if (startswith(line
, "SwapFree:")) {
4419 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
4427 if (swap_total
> 0) {
4428 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
4429 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
4430 swap_total
, swap_free
);
4434 if (total_len
< 0 || l
< 0) {
4435 perror("Error writing to cache");
4441 d
->size
= (int)total_len
;
4443 if (total_len
> size
) total_len
= size
;
4444 memcpy(buf
, d
->buf
, total_len
);
4449 free(memswlimit_str
);
4452 free(memswusage_str
);
4456 * Find the process pid from cgroup path.
4457 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
4458 * @pid_buf : put pid to pid_buf.
4459 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
4460 * @depth : the depth of cgroup in container.
4461 * @sum : return the number of pid.
4462 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
4464 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
4468 struct dirent
*file
;
4473 char *path_dir
, *path
;
4476 /* path = dpath + "/cgroup.procs" + /0 */
4478 path
= malloc(strlen(dpath
) + 20);
4481 strcpy(path
, dpath
);
4482 fd
= openat(cfd
, path
, O_RDONLY
);
4486 dir
= fdopendir(fd
);
4492 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
4493 if (strncmp(file
->d_name
, ".", 1) == 0)
4495 if (strncmp(file
->d_name
, "..", 1) == 0)
4497 if (file
->d_type
== DT_DIR
) {
4498 /* path + '/' + d_name +/0 */
4500 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
4501 } while (!path_dir
);
4502 strcpy(path_dir
, path
);
4503 strcat(path_dir
, "/");
4504 strcat(path_dir
, file
->d_name
);
4506 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
4512 strcat(path
, "/cgroup.procs");
4513 fd
= openat(cfd
, path
, O_RDONLY
);
4517 f
= fdopen(fd
, "r");
4523 while (getline(&line
, &linelen
, f
) != -1) {
4525 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
4529 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
4530 } while (*(*pid_buf
+ sum
) == NULL
);
4531 strcpy(*(*pid_buf
+ sum
), line
);
4542 * calc_load calculates the load according to the following formula:
4543 * load1 = load0 * exp + active * (1 - exp)
4545 * @load1: the new loadavg.
4546 * @load0: the former loadavg.
4547 * @active: the total number of running pid at this moment.
4548 * @exp: the fixed-point defined in the beginning.
4550 static unsigned long
4551 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
4553 unsigned long newload
;
4555 active
= active
> 0 ? active
* FIXED_1
: 0;
4556 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
4558 newload
+= FIXED_1
- 1;
4560 return newload
/ FIXED_1
;
4564 * Return 0 means that container p->cg is closed.
4565 * Return -1 means that error occurred in refresh.
4566 * Positive num equals the total number of pid.
4568 static int refresh_load(struct load_node
*p
, char *path
)
4572 char proc_path
[256];
4573 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
4578 struct dirent
*file
;
4581 idbuf
= malloc(sizeof(char *));
4583 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
4588 for (i
= 0; i
< sum
; i
++) {
4590 length
= strlen(idbuf
[i
])-1;
4591 idbuf
[i
][length
] = '\0';
4592 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
4593 if (ret
< 0 || ret
> 255) {
4594 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4600 dp
= opendir(proc_path
);
4602 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
4605 while ((file
= readdir(dp
)) != NULL
) {
4606 if (strncmp(file
->d_name
, ".", 1) == 0)
4608 if (strncmp(file
->d_name
, "..", 1) == 0)
4611 /* We make the biggest pid become last_pid.*/
4612 ret
= atof(file
->d_name
);
4613 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
4615 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
4616 if (ret
< 0 || ret
> 255) {
4617 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4623 f
= fopen(proc_path
, "r");
4625 while (getline(&line
, &linelen
, f
) != -1) {
4627 if ((line
[0] == 'S') && (line
[1] == 't'))
4630 if ((line
[7] == 'R') || (line
[7] == 'D'))
4637 /*Calculate the loadavg.*/
4638 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
4639 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
4640 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
4641 p
->run_pid
= run_pid
;
4642 p
->total_pid
= total_pid
;
4643 p
->last_pid
= last_pid
;
4654 * Traverse the hash table and update it.
4656 void *load_begin(void *arg
)
4660 int i
, sum
, length
, ret
;
4661 struct load_node
*f
;
4663 clock_t time1
, time2
;
4666 if (loadavg_stop
== 1)
4670 for (i
= 0; i
< LOAD_SIZE
; i
++) {
4671 pthread_mutex_lock(&load_hash
[i
].lock
);
4672 if (load_hash
[i
].next
== NULL
) {
4673 pthread_mutex_unlock(&load_hash
[i
].lock
);
4676 f
= load_hash
[i
].next
;
4679 length
= strlen(f
->cg
) + 2;
4681 /* strlen(f->cg) + '.' or '' + \0 */
4682 path
= malloc(length
);
4685 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
4686 if (ret
< 0 || ret
> length
- 1) {
4687 /* snprintf failed, ignore the node.*/
4688 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
4691 sum
= refresh_load(f
, path
);
4698 /* load_hash[i].lock locks only on the first node.*/
4699 if (first_node
== 1) {
4701 pthread_mutex_unlock(&load_hash
[i
].lock
);
4706 if (loadavg_stop
== 1)
4710 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
4714 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
4715 struct fuse_file_info
*fi
)
4717 struct fuse_context
*fc
= fuse_get_context();
4718 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4721 size_t total_len
= 0;
4722 char *cache
= d
->buf
;
4723 struct load_node
*n
;
4726 unsigned long a
, b
, c
;
4729 if (offset
> d
->size
)
4733 int left
= d
->size
- offset
;
4734 total_len
= left
> size
? size
: left
;
4735 memcpy(buf
, cache
+ offset
, total_len
);
4739 return read_file("/proc/loadavg", buf
, size
, d
);
4741 initpid
= lookup_initpid_in_store(fc
->pid
);
4744 cg
= get_pid_cgroup(initpid
, "cpu");
4746 return read_file("/proc/loadavg", buf
, size
, d
);
4748 prune_init_slice(cg
);
4749 hash
= calc_hash(cg
);
4750 n
= locate_node(cg
, hash
);
4754 if (!find_mounted_controller("cpu", &cfd
)) {
4756 * In locate_node() above, pthread_rwlock_unlock() isn't used
4757 * because delete is not allowed before read has ended.
4759 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4764 n
= malloc(sizeof(struct load_node
));
4768 n
->cg
= malloc(strlen(cg
)+1);
4776 n
->last_pid
= initpid
;
4778 insert_node(&n
, hash
);
4780 a
= n
->avenrun
[0] + (FIXED_1
/200);
4781 b
= n
->avenrun
[1] + (FIXED_1
/200);
4782 c
= n
->avenrun
[2] + (FIXED_1
/200);
4783 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
4784 LOAD_INT(a
), LOAD_FRAC(a
),
4785 LOAD_INT(b
), LOAD_FRAC(b
),
4786 LOAD_INT(c
), LOAD_FRAC(c
),
4787 n
->run_pid
, n
->total_pid
, n
->last_pid
);
4788 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4789 if (total_len
< 0 || total_len
>= d
->buflen
) {
4790 lxcfs_error("%s\n", "Failed to write to cache");
4794 d
->size
= (int)total_len
;
4797 if (total_len
> size
)
4799 memcpy(buf
, d
->buf
, total_len
);
4806 /* Return a positive number on success, return 0 on failure.*/
4807 pthread_t
load_daemon(int load_use
)
4814 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
4817 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
4819 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
4823 /* use loadavg, here loadavg = 1*/
4828 /* Returns 0 on success. */
4829 int stop_load_daemon(pthread_t pid
)
4833 /* Signal the thread to gracefully stop */
4836 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
4838 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
4848 static off_t
get_procfile_size(const char *which
)
4850 FILE *f
= fopen(which
, "r");
4853 ssize_t sz
, answer
= 0;
4857 while ((sz
= getline(&line
, &len
, f
)) != -1)
4865 int proc_getattr(const char *path
, struct stat
*sb
)
4867 struct timespec now
;
4869 memset(sb
, 0, sizeof(struct stat
));
4870 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
4872 sb
->st_uid
= sb
->st_gid
= 0;
4873 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4874 if (strcmp(path
, "/proc") == 0) {
4875 sb
->st_mode
= S_IFDIR
| 00555;
4879 if (strcmp(path
, "/proc/meminfo") == 0 ||
4880 strcmp(path
, "/proc/cpuinfo") == 0 ||
4881 strcmp(path
, "/proc/uptime") == 0 ||
4882 strcmp(path
, "/proc/stat") == 0 ||
4883 strcmp(path
, "/proc/diskstats") == 0 ||
4884 strcmp(path
, "/proc/swaps") == 0 ||
4885 strcmp(path
, "/proc/loadavg") == 0) {
4887 sb
->st_mode
= S_IFREG
| 00444;
4895 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4896 struct fuse_file_info
*fi
)
4898 if (filler(buf
, ".", NULL
, 0) != 0 ||
4899 filler(buf
, "..", NULL
, 0) != 0 ||
4900 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4901 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4902 filler(buf
, "stat", NULL
, 0) != 0 ||
4903 filler(buf
, "uptime", NULL
, 0) != 0 ||
4904 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4905 filler(buf
, "swaps", NULL
, 0) != 0 ||
4906 filler(buf
, "loadavg", NULL
, 0) != 0)
4911 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4914 struct file_info
*info
;
4916 if (strcmp(path
, "/proc/meminfo") == 0)
4917 type
= LXC_TYPE_PROC_MEMINFO
;
4918 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4919 type
= LXC_TYPE_PROC_CPUINFO
;
4920 else if (strcmp(path
, "/proc/uptime") == 0)
4921 type
= LXC_TYPE_PROC_UPTIME
;
4922 else if (strcmp(path
, "/proc/stat") == 0)
4923 type
= LXC_TYPE_PROC_STAT
;
4924 else if (strcmp(path
, "/proc/diskstats") == 0)
4925 type
= LXC_TYPE_PROC_DISKSTATS
;
4926 else if (strcmp(path
, "/proc/swaps") == 0)
4927 type
= LXC_TYPE_PROC_SWAPS
;
4928 else if (strcmp(path
, "/proc/loadavg") == 0)
4929 type
= LXC_TYPE_PROC_LOADAVG
;
4933 info
= malloc(sizeof(*info
));
4937 memset(info
, 0, sizeof(*info
));
4940 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4942 info
->buf
= malloc(info
->buflen
);
4943 } while (!info
->buf
);
4944 memset(info
->buf
, 0, info
->buflen
);
4945 /* set actual size to buffer size */
4946 info
->size
= info
->buflen
;
4948 fi
->fh
= (unsigned long)info
;
4952 int proc_access(const char *path
, int mask
)
4954 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4957 /* these are all read-only */
4958 if ((mask
& ~R_OK
) != 0)
4963 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4965 do_release_file_info(fi
);
4969 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4970 struct fuse_file_info
*fi
)
4972 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4975 case LXC_TYPE_PROC_MEMINFO
:
4976 return proc_meminfo_read(buf
, size
, offset
, fi
);
4977 case LXC_TYPE_PROC_CPUINFO
:
4978 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4979 case LXC_TYPE_PROC_UPTIME
:
4980 return proc_uptime_read(buf
, size
, offset
, fi
);
4981 case LXC_TYPE_PROC_STAT
:
4982 return proc_stat_read(buf
, size
, offset
, fi
);
4983 case LXC_TYPE_PROC_DISKSTATS
:
4984 return proc_diskstats_read(buf
, size
, offset
, fi
);
4985 case LXC_TYPE_PROC_SWAPS
:
4986 return proc_swaps_read(buf
, size
, offset
, fi
);
4987 case LXC_TYPE_PROC_LOADAVG
:
4988 return proc_loadavg_read(buf
, size
, offset
, fi
);
4995 * Functions needed to setup cgroups in the __constructor__.
4998 static bool mkdir_p(const char *dir
, mode_t mode
)
5000 const char *tmp
= dir
;
5001 const char *orig
= dir
;
5005 dir
= tmp
+ strspn(tmp
, "/");
5006 tmp
= dir
+ strcspn(dir
, "/");
5007 makeme
= strndup(orig
, dir
- orig
);
5010 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
5011 lxcfs_error("Failed to create directory '%s': %s.\n",
5012 makeme
, strerror(errno
));
5017 } while(tmp
!= dir
);
5022 static bool umount_if_mounted(void)
5024 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5025 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5031 /* __typeof__ should be safe to use with all compilers. */
5032 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5033 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5035 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5039 * looking at fs/proc_namespace.c, it appears we can
5040 * actually expect the rootfs entry to very specifically contain
5041 * " - rootfs rootfs "
5042 * IIUC, so long as we've chrooted so that rootfs is not our root,
5043 * the rootfs entry should always be skipped in mountinfo contents.
5045 static bool is_on_ramfs(void)
5053 f
= fopen("/proc/self/mountinfo", "r");
5057 while (getline(&line
, &len
, f
) != -1) {
5058 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5059 p
= strchr(p
+ 1, ' ');
5062 p2
= strchr(p
+ 1, ' ');
5066 if (strcmp(p
+ 1, "/") == 0) {
5067 // this is '/'. is it the ramfs?
5068 p
= strchr(p2
+ 1, '-');
5069 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5081 static int pivot_enter()
5083 int ret
= -1, oldroot
= -1, newroot
= -1;
5085 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5087 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5091 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5093 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5097 /* change into new root fs */
5098 if (fchdir(newroot
) < 0) {
5099 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5103 /* pivot_root into our new root fs */
5104 if (pivot_root(".", ".") < 0) {
5105 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5110 * At this point the old-root is mounted on top of our new-root.
5111 * To unmounted it we must not be chdir'd into it, so escape back
5114 if (fchdir(oldroot
) < 0) {
5115 lxcfs_error("%s\n", "Failed to enter old root.");
5119 if (umount2(".", MNT_DETACH
) < 0) {
5120 lxcfs_error("%s\n", "Failed to detach old root.");
5124 if (fchdir(newroot
) < 0) {
5125 lxcfs_error("%s\n", "Failed to re-enter new root.");
5140 static int chroot_enter()
5142 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
5143 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
5147 if (chroot(".") < 0) {
5148 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
5152 if (chdir("/") < 0) {
5153 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
5160 static int permute_and_enter(void)
5164 if (statfs("/", &sb
) < 0) {
5165 lxcfs_error("%s\n", "Could not stat / mountpoint.");
5169 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
5170 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
5171 * /proc/1/mountinfo. */
5172 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
5173 return chroot_enter();
5175 if (pivot_enter() < 0) {
5176 lxcfs_error("%s\n", "Could not perform pivot root.");
5183 /* Prepare our new clean root. */
5184 static int permute_prepare(void)
5186 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
5187 lxcfs_error("%s\n", "Failed to create directory for new root.");
5191 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
5192 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
5196 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
5197 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
5201 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
5202 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
5209 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
5210 static bool permute_root(void)
5212 /* Prepare new root. */
5213 if (permute_prepare() < 0)
5216 /* Pivot into new root. */
5217 if (permute_and_enter() < 0)
5223 static int preserve_mnt_ns(int pid
)
5226 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
5229 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
5230 if (ret
< 0 || (size_t)ret
>= len
)
5233 return open(path
, O_RDONLY
| O_CLOEXEC
);
5236 static bool cgfs_prepare_mounts(void)
5238 if (!mkdir_p(BASEDIR
, 0700)) {
5239 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
5243 if (!umount_if_mounted()) {
5244 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
5248 if (unshare(CLONE_NEWNS
) < 0) {
5249 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
5253 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
5254 if (cgroup_mount_ns_fd
< 0) {
5255 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
5259 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
5260 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
5264 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
5265 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
5272 static bool cgfs_mount_hierarchies(void)
5278 for (i
= 0; i
< num_hierarchies
; i
++) {
5279 char *controller
= hierarchies
[i
];
5281 clen
= strlen(controller
);
5282 len
= strlen(BASEDIR
) + clen
+ 2;
5283 target
= malloc(len
);
5287 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
5288 if (ret
< 0 || ret
>= len
) {
5292 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
5296 if (!strcmp(controller
, "unified"))
5297 ret
= mount("none", target
, "cgroup2", 0, NULL
);
5299 ret
= mount(controller
, target
, "cgroup", 0, controller
);
5301 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
5306 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
5307 if (fd_hierarchies
[i
] < 0) {
5316 static bool cgfs_setup_controllers(void)
5318 if (!cgfs_prepare_mounts())
5321 if (!cgfs_mount_hierarchies()) {
5322 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
5326 if (!permute_root())
5332 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
5335 char *cret
, *line
= NULL
;
5336 char cwd
[MAXPATHLEN
];
5338 int i
, init_ns
= -1;
5339 bool found_unified
= false;
5341 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
5342 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
5346 while (getline(&line
, &len
, f
) != -1) {
5349 p
= strchr(line
, ':');
5355 p2
= strrchr(p
, ':');
5360 /* With cgroupv2 /proc/self/cgroup can contain entries of the
5361 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
5362 * because it parses out the empty string "" and later on passes
5363 * it to mount(). Let's skip such entries.
5365 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
5366 found_unified
= true;
5370 if (!store_hierarchy(line
, p
))
5374 /* Preserve initial namespace. */
5375 init_ns
= preserve_mnt_ns(getpid());
5377 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
5381 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
5382 if (!fd_hierarchies
) {
5383 lxcfs_error("%s\n", strerror(errno
));
5387 for (i
= 0; i
< num_hierarchies
; i
++)
5388 fd_hierarchies
[i
] = -1;
5390 cret
= getcwd(cwd
, MAXPATHLEN
);
5392 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
5394 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
5395 * to privately mount lxcfs cgroups. */
5396 if (!cgfs_setup_controllers()) {
5397 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
5401 if (setns(init_ns
, 0) < 0) {
5402 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
5406 if (!cret
|| chdir(cwd
) < 0)
5407 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
5418 static void __attribute__((destructor
)) free_subsystems(void)
5422 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
5424 for (i
= 0; i
< num_hierarchies
; i
++) {
5426 free(hierarchies
[i
]);
5427 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
5428 close(fd_hierarchies
[i
]);
5431 free(fd_hierarchies
);
5433 if (cgroup_mount_ns_fd
>= 0)
5434 close(cgroup_mount_ns_fd
);