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
)
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;
3189 eol
= strchr(memstat
, '\n');
3196 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3202 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3204 size_t len
= strlen(key
);
3208 if (startswith(str
, key
)) {
3209 sscanf(str
+ len
, "%lu", v
);
3212 eol
= strchr(str
, '\n');
3219 static int read_file(const char *path
, char *buf
, size_t size
,
3220 struct file_info
*d
)
3222 size_t linelen
= 0, total_len
= 0, rv
= 0;
3224 char *cache
= d
->buf
;
3225 size_t cache_size
= d
->buflen
;
3226 FILE *f
= fopen(path
, "r");
3230 while (getline(&line
, &linelen
, f
) != -1) {
3231 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3233 perror("Error writing to cache");
3237 if (l
>= cache_size
) {
3238 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3247 d
->size
= total_len
;
3248 if (total_len
> size
)
3251 /* read from off 0 */
3252 memcpy(buf
, d
->buf
, total_len
);
3261 * FUSE ops for /proc
3264 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3266 char *memlimit_str
= NULL
;
3267 unsigned long memlimit
= -1;
3269 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3270 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3277 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3279 char *copy
= strdupa(cgroup
);
3280 unsigned long memlimit
= 0, retlimit
;
3282 retlimit
= get_memlimit(copy
, file
);
3284 while (strcmp(copy
, "/") != 0) {
3285 copy
= dirname(copy
);
3286 memlimit
= get_memlimit(copy
, file
);
3287 if (memlimit
!= -1 && memlimit
< retlimit
)
3288 retlimit
= memlimit
;
3294 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3295 struct fuse_file_info
*fi
)
3297 struct fuse_context
*fc
= fuse_get_context();
3298 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3300 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3301 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3302 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3303 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3304 active_file
= 0, inactive_file
= 0, unevictable
= 0,
3307 size_t linelen
= 0, total_len
= 0, rv
= 0;
3308 char *cache
= d
->buf
;
3309 size_t cache_size
= d
->buflen
;
3313 if (offset
> d
->size
)
3317 int left
= d
->size
- offset
;
3318 total_len
= left
> size
? size
: left
;
3319 memcpy(buf
, cache
+ offset
, total_len
);
3323 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3326 cg
= get_pid_cgroup(initpid
, "memory");
3328 return read_file("/proc/meminfo", buf
, size
, d
);
3329 prune_init_slice(cg
);
3331 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3332 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3334 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3337 // Following values are allowed to fail, because swapaccount might be turned
3338 // off for current kernel
3339 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3340 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3342 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3343 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3345 memswlimit
= memswlimit
/ 1024;
3346 memswusage
= memswusage
/ 1024;
3349 memusage
= strtoul(memusage_str
, NULL
, 10);
3353 parse_memstat(memstat_str
, &cached
, &active_anon
,
3354 &inactive_anon
, &active_file
, &inactive_file
,
3357 f
= fopen("/proc/meminfo", "r");
3361 while (getline(&line
, &linelen
, f
) != -1) {
3363 char *printme
, lbuf
[100];
3365 memset(lbuf
, 0, 100);
3366 if (startswith(line
, "MemTotal:")) {
3367 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3368 if (hosttotal
< memlimit
)
3369 memlimit
= hosttotal
;
3370 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3372 } else if (startswith(line
, "MemFree:")) {
3373 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3375 } else if (startswith(line
, "MemAvailable:")) {
3376 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3378 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3379 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3380 if (hostswtotal
< memswlimit
)
3381 memswlimit
= hostswtotal
;
3382 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3384 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3385 unsigned long swaptotal
= memswlimit
,
3386 swapusage
= memswusage
- memusage
,
3387 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3388 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3390 } else if (startswith(line
, "Slab:")) {
3391 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3393 } else if (startswith(line
, "Buffers:")) {
3394 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3396 } else if (startswith(line
, "Cached:")) {
3397 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3399 } else if (startswith(line
, "SwapCached:")) {
3400 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3402 } else if (startswith(line
, "Active:")) {
3403 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3404 active_anon
+ active_file
);
3406 } else if (startswith(line
, "Inactive:")) {
3407 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3408 inactive_anon
+ inactive_file
);
3410 } else if (startswith(line
, "Active(anon)")) {
3411 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3413 } else if (startswith(line
, "Inactive(anon)")) {
3414 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3416 } else if (startswith(line
, "Active(file)")) {
3417 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3419 } else if (startswith(line
, "Inactive(file)")) {
3420 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3422 } else if (startswith(line
, "Unevictable")) {
3423 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3425 } else if (startswith(line
, "SReclaimable")) {
3426 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3428 } else if (startswith(line
, "SUnreclaim")) {
3429 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3434 l
= snprintf(cache
, cache_size
, "%s", printme
);
3436 perror("Error writing to cache");
3441 if (l
>= cache_size
) {
3442 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3453 d
->size
= total_len
;
3454 if (total_len
> size
) total_len
= size
;
3455 memcpy(buf
, d
->buf
, total_len
);
3464 free(memswlimit_str
);
3465 free(memswusage_str
);
3471 * Read the cpuset.cpus for cg
3472 * Return the answer in a newly allocated string which must be freed
3474 static char *get_cpuset(const char *cg
)
3478 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3483 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3485 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3489 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3491 return cpu_in_cpuset(cpu
, cpuset
);
3495 * check whether this is a '^processor" line in /proc/cpuinfo
3497 static bool is_processor_line(const char *line
)
3501 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3506 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3507 struct fuse_file_info
*fi
)
3509 struct fuse_context
*fc
= fuse_get_context();
3510 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3512 char *cpuset
= NULL
;
3514 size_t linelen
= 0, total_len
= 0, rv
= 0;
3515 bool am_printing
= false, firstline
= true, is_s390x
= false;
3516 int curcpu
= -1, cpu
;
3517 char *cache
= d
->buf
;
3518 size_t cache_size
= d
->buflen
;
3522 if (offset
> d
->size
)
3526 int left
= d
->size
- offset
;
3527 total_len
= left
> size
? size
: left
;
3528 memcpy(buf
, cache
+ offset
, total_len
);
3532 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3535 cg
= get_pid_cgroup(initpid
, "cpuset");
3537 return read_file("proc/cpuinfo", buf
, size
, d
);
3538 prune_init_slice(cg
);
3540 cpuset
= get_cpuset(cg
);
3544 f
= fopen("/proc/cpuinfo", "r");
3548 while (getline(&line
, &linelen
, f
) != -1) {
3552 if (strstr(line
, "IBM/S390") != NULL
) {
3558 if (strncmp(line
, "# processors:", 12) == 0)
3560 if (is_processor_line(line
)) {
3561 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3564 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3566 perror("Error writing to cache");
3570 if (l
>= cache_size
) {
3571 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3580 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3582 if (!cpu_in_cpuset(cpu
, cpuset
))
3585 p
= strchr(line
, ':');
3589 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3591 perror("Error writing to cache");
3595 if (l
>= cache_size
) {
3596 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3607 l
= snprintf(cache
, cache_size
, "%s", line
);
3609 perror("Error writing to cache");
3613 if (l
>= cache_size
) {
3614 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3625 char *origcache
= d
->buf
;
3628 d
->buf
= malloc(d
->buflen
);
3631 cache_size
= d
->buflen
;
3633 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3634 if (l
< 0 || l
>= cache_size
) {
3641 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3642 if (l
< 0 || l
>= cache_size
) {
3649 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3651 if (l
< 0 || l
>= cache_size
)
3657 d
->size
= total_len
;
3658 if (total_len
> size
) total_len
= size
;
3660 /* read from off 0 */
3661 memcpy(buf
, d
->buf
, total_len
);
3672 static uint64_t get_reaper_start_time(pid_t pid
)
3677 /* strlen("/proc/") = 6
3681 * strlen("/stat") = 5
3685 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3686 char path
[__PROC_PID_STAT_LEN
];
3689 qpid
= lookup_initpid_in_store(pid
);
3691 /* Caller can check for EINVAL on 0. */
3696 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3697 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3698 /* Caller can check for EINVAL on 0. */
3703 f
= fopen(path
, "r");
3705 /* Caller can check for EINVAL on 0. */
3710 /* Note that the *scanf() argument supression requires that length
3711 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3712 * at us. It's like telling someone you're not married and then asking
3713 * if you can bring your wife to the party.
3715 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3716 "%*s " /* (2) comm %s */
3717 "%*c " /* (3) state %c */
3718 "%*d " /* (4) ppid %d */
3719 "%*d " /* (5) pgrp %d */
3720 "%*d " /* (6) session %d */
3721 "%*d " /* (7) tty_nr %d */
3722 "%*d " /* (8) tpgid %d */
3723 "%*u " /* (9) flags %u */
3724 "%*u " /* (10) minflt %lu */
3725 "%*u " /* (11) cminflt %lu */
3726 "%*u " /* (12) majflt %lu */
3727 "%*u " /* (13) cmajflt %lu */
3728 "%*u " /* (14) utime %lu */
3729 "%*u " /* (15) stime %lu */
3730 "%*d " /* (16) cutime %ld */
3731 "%*d " /* (17) cstime %ld */
3732 "%*d " /* (18) priority %ld */
3733 "%*d " /* (19) nice %ld */
3734 "%*d " /* (20) num_threads %ld */
3735 "%*d " /* (21) itrealvalue %ld */
3736 "%" PRIu64
, /* (22) starttime %llu */
3740 /* Caller can check for EINVAL on 0. */
3751 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3753 uint64_t clockticks
;
3754 int64_t ticks_per_sec
;
3756 clockticks
= get_reaper_start_time(pid
);
3757 if (clockticks
== 0 && errno
== EINVAL
) {
3758 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3762 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3763 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3766 "failed to determine number of clock ticks in a second");
3770 return (clockticks
/= ticks_per_sec
);
3773 static uint64_t get_reaper_age(pid_t pid
)
3775 uint64_t procstart
, uptime
, procage
;
3777 /* We need to substract the time the process has started since system
3778 * boot minus the time when the system has started to get the actual
3781 procstart
= get_reaper_start_time_in_sec(pid
);
3782 procage
= procstart
;
3783 if (procstart
> 0) {
3785 struct timespec spec
;
3787 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3790 /* We could make this more precise here by using the tv_nsec
3791 * field in the timespec struct and convert it to milliseconds
3792 * and then create a double for the seconds and milliseconds but
3793 * that seems more work than it is worth.
3795 uptime
= spec
.tv_sec
;
3796 procage
= uptime
- procstart
;
3803 * Returns 0 on success.
3804 * It is the caller's responsibility to free `return_usage`, unless this
3805 * function returns an error.
3807 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
)
3809 int cpucount
= get_nprocs();
3810 struct cpuacct_usage
*cpu_usage
;
3811 int rv
= 0, i
, j
, ret
, read_pos
= 0, read_cnt
;
3813 uint64_t cg_user
, cg_system
;
3814 int64_t ticks_per_sec
;
3815 char *usage_str
= NULL
;
3817 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3819 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3822 "read_cpuacct_usage_all failed to determine number of clock ticks "
3827 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
3831 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
3836 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
3837 lxcfs_error("read_cpuacct_usage_all reading first line from "
3838 "%s/cpuacct.usage_all failed.\n", cg
);
3843 read_pos
+= read_cnt
;
3845 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
3846 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
3847 &cg_system
, &read_cnt
);
3853 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
3859 read_pos
+= read_cnt
;
3861 if (!cpu_in_cpuset(i
, cpuset
))
3864 /* Convert the time from nanoseconds to USER_HZ */
3865 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3866 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3871 *return_usage
= cpu_usage
;
3879 *return_usage
= NULL
;
3885 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
3886 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3887 struct fuse_file_info
*fi
)
3889 struct fuse_context
*fc
= fuse_get_context();
3890 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3892 char *cpuset
= NULL
;
3894 size_t linelen
= 0, total_len
= 0, rv
= 0;
3895 int curcpu
= -1; /* cpu numbering starts at 0 */
3896 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
3897 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3898 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
3899 char cpuall
[CPUALL_MAX_SIZE
];
3900 /* reserve for cpu all */
3901 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3902 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3904 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
3907 if (offset
> d
->size
)
3911 int left
= d
->size
- offset
;
3912 total_len
= left
> size
? size
: left
;
3913 memcpy(buf
, d
->buf
+ offset
, total_len
);
3917 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3920 cg
= get_pid_cgroup(initpid
, "cpuset");
3922 return read_file("/proc/stat", buf
, size
, d
);
3923 prune_init_slice(cg
);
3925 cpuset
= get_cpuset(cg
);
3930 * Read cpuacct.usage_all for all CPUs.
3931 * If the cpuacct cgroup is present, it is used to calculate the container's
3932 * CPU usage. If not, values from the host's /proc/stat are used.
3934 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
) != 0) {
3935 lxcfs_debug("%s\n", "proc_stat_read failed to read from cpuacct, "
3936 "falling back to the host's /proc/stat");
3939 f
= fopen("/proc/stat", "r");
3944 if (getline(&line
, &linelen
, f
) < 0) {
3945 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3949 while (getline(&line
, &linelen
, f
) != -1) {
3952 char cpu_char
[10]; /* That's a lot of cores */
3954 uint64_t all_used
, cg_used
, new_idle
;
3957 if (strlen(line
) == 0)
3959 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3960 /* not a ^cpuN line containing a number N, just print it */
3961 l
= snprintf(cache
, cache_size
, "%s", line
);
3963 perror("Error writing to cache");
3967 if (l
>= cache_size
) {
3968 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3978 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3980 if (!cpu_in_cpuset(cpu
, cpuset
))
3984 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
3996 if (ret
!= 10 || !cg_cpu_usage
) {
3997 c
= strchr(line
, ' ');
4000 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4002 perror("Error writing to cache");
4007 if (l
>= cache_size
) {
4008 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4022 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4023 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4025 if (all_used
>= cg_used
) {
4026 new_idle
= idle
+ (all_used
- cg_used
);
4029 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4030 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4031 curcpu
, cg
, all_used
, cg_used
);
4035 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4036 curcpu
, cg_cpu_usage
[curcpu
].user
, cg_cpu_usage
[curcpu
].system
,
4040 perror("Error writing to cache");
4045 if (l
>= cache_size
) {
4046 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4055 user_sum
+= cg_cpu_usage
[curcpu
].user
;
4056 system_sum
+= cg_cpu_usage
[curcpu
].system
;
4057 idle_sum
+= new_idle
;
4062 system_sum
+= system
;
4064 iowait_sum
+= iowait
;
4066 softirq_sum
+= softirq
;
4069 guest_nice_sum
+= guest_nice
;
4075 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4086 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4087 memcpy(cache
, cpuall
, cpuall_len
);
4088 cache
+= cpuall_len
;
4090 /* shouldn't happen */
4091 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4095 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4096 total_len
+= cpuall_len
;
4098 d
->size
= total_len
;
4099 if (total_len
> size
)
4102 memcpy(buf
, d
->buf
, total_len
);
4116 /* This function retrieves the busy time of a group of tasks by looking at
4117 * cpuacct.usage. Unfortunately, this only makes sense when the container has
4118 * been given it's own cpuacct cgroup. If not, this function will take the busy
4119 * time of all other taks that do not actually belong to the container into
4120 * account as well. If someone has a clever solution for this please send a
4123 static unsigned long get_reaper_busy(pid_t task
)
4125 pid_t initpid
= lookup_initpid_in_store(task
);
4126 char *cgroup
= NULL
, *usage_str
= NULL
;
4127 unsigned long usage
= 0;
4132 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
4135 prune_init_slice(cgroup
);
4136 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
4138 usage
= strtoul(usage_str
, NULL
, 10);
4139 usage
/= 1000000000;
4152 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4159 * We read /proc/uptime and reuse its second field.
4160 * For the first field, we use the mtime for the reaper for
4161 * the calling pid as returned by getreaperage
4163 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4164 struct fuse_file_info
*fi
)
4166 struct fuse_context
*fc
= fuse_get_context();
4167 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4168 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
4169 char *cache
= d
->buf
;
4170 ssize_t total_len
= 0;
4171 uint64_t idletime
, reaperage
;
4180 if (offset
> d
->size
)
4182 int left
= d
->size
- offset
;
4183 total_len
= left
> size
? size
: left
;
4184 memcpy(buf
, cache
+ offset
, total_len
);
4188 reaperage
= get_reaper_age(fc
->pid
);
4189 /* To understand why this is done, please read the comment to the
4190 * get_reaper_busy() function.
4192 idletime
= reaperage
;
4193 if (reaperage
>= busytime
)
4194 idletime
= reaperage
- busytime
;
4196 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
4197 if (total_len
< 0 || total_len
>= d
->buflen
){
4198 lxcfs_error("%s\n", "failed to write to cache");
4202 d
->size
= (int)total_len
;
4205 if (total_len
> size
) total_len
= size
;
4207 memcpy(buf
, d
->buf
, total_len
);
4211 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
4212 struct fuse_file_info
*fi
)
4215 struct fuse_context
*fc
= fuse_get_context();
4216 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4218 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
4219 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
4220 unsigned long read
= 0, write
= 0;
4221 unsigned long read_merged
= 0, write_merged
= 0;
4222 unsigned long read_sectors
= 0, write_sectors
= 0;
4223 unsigned long read_ticks
= 0, write_ticks
= 0;
4224 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
4225 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
4226 char *cache
= d
->buf
;
4227 size_t cache_size
= d
->buflen
;
4229 size_t linelen
= 0, total_len
= 0, rv
= 0;
4230 unsigned int major
= 0, minor
= 0;
4235 if (offset
> d
->size
)
4239 int left
= d
->size
- offset
;
4240 total_len
= left
> size
? size
: left
;
4241 memcpy(buf
, cache
+ offset
, total_len
);
4245 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4248 cg
= get_pid_cgroup(initpid
, "blkio");
4250 return read_file("/proc/diskstats", buf
, size
, d
);
4251 prune_init_slice(cg
);
4253 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
4255 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
4257 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
4259 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
4261 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
4265 f
= fopen("/proc/diskstats", "r");
4269 while (getline(&line
, &linelen
, f
) != -1) {
4273 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
4277 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
4278 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
4279 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
4280 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
4281 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
4282 read_sectors
= read_sectors
/512;
4283 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
4284 write_sectors
= write_sectors
/512;
4286 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
4287 rd_svctm
= rd_svctm
/1000000;
4288 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
4289 rd_wait
= rd_wait
/1000000;
4290 read_ticks
= rd_svctm
+ rd_wait
;
4292 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
4293 wr_svctm
= wr_svctm
/1000000;
4294 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
4295 wr_wait
= wr_wait
/1000000;
4296 write_ticks
= wr_svctm
+ wr_wait
;
4298 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
4299 tot_ticks
= tot_ticks
/1000000;
4301 memset(lbuf
, 0, 256);
4302 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
4303 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4304 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
4305 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
4309 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
4311 perror("Error writing to fuse buf");
4315 if (l
>= cache_size
) {
4316 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4326 d
->size
= total_len
;
4327 if (total_len
> size
) total_len
= size
;
4328 memcpy(buf
, d
->buf
, total_len
);
4336 free(io_serviced_str
);
4337 free(io_merged_str
);
4338 free(io_service_bytes_str
);
4339 free(io_wait_time_str
);
4340 free(io_service_time_str
);
4344 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
4345 struct fuse_file_info
*fi
)
4347 struct fuse_context
*fc
= fuse_get_context();
4348 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4350 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
4351 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
4352 ssize_t total_len
= 0, rv
= 0;
4354 char *cache
= d
->buf
;
4357 if (offset
> d
->size
)
4361 int left
= d
->size
- offset
;
4362 total_len
= left
> size
? size
: left
;
4363 memcpy(buf
, cache
+ offset
, total_len
);
4367 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4370 cg
= get_pid_cgroup(initpid
, "memory");
4372 return read_file("/proc/swaps", buf
, size
, d
);
4373 prune_init_slice(cg
);
4375 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
4377 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
4380 memusage
= strtoul(memusage_str
, NULL
, 10);
4382 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
4383 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
4385 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
4386 memswusage
= strtoul(memswusage_str
, NULL
, 10);
4388 swap_total
= (memswlimit
- memlimit
) / 1024;
4389 swap_free
= (memswusage
- memusage
) / 1024;
4392 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
4394 /* When no mem + swap limit is specified or swapaccount=0*/
4398 FILE *f
= fopen("/proc/meminfo", "r");
4403 while (getline(&line
, &linelen
, f
) != -1) {
4404 if (startswith(line
, "SwapTotal:")) {
4405 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
4406 } else if (startswith(line
, "SwapFree:")) {
4407 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
4415 if (swap_total
> 0) {
4416 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
4417 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
4418 swap_total
, swap_free
);
4422 if (total_len
< 0 || l
< 0) {
4423 perror("Error writing to cache");
4429 d
->size
= (int)total_len
;
4431 if (total_len
> size
) total_len
= size
;
4432 memcpy(buf
, d
->buf
, total_len
);
4437 free(memswlimit_str
);
4440 free(memswusage_str
);
4444 * Find the process pid from cgroup path.
4445 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
4446 * @pid_buf : put pid to pid_buf.
4447 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
4448 * @depth : the depth of cgroup in container.
4449 * @sum : return the number of pid.
4450 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
4452 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
4456 struct dirent
*file
;
4461 char *path_dir
, *path
;
4464 /* path = dpath + "/cgroup.procs" + /0 */
4466 path
= malloc(strlen(dpath
) + 20);
4469 strcpy(path
, dpath
);
4470 fd
= openat(cfd
, path
, O_RDONLY
);
4474 dir
= fdopendir(fd
);
4480 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
4481 if (strncmp(file
->d_name
, ".", 1) == 0)
4483 if (strncmp(file
->d_name
, "..", 1) == 0)
4485 if (file
->d_type
== DT_DIR
) {
4486 /* path + '/' + d_name +/0 */
4488 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
4489 } while (!path_dir
);
4490 strcpy(path_dir
, path
);
4491 strcat(path_dir
, "/");
4492 strcat(path_dir
, file
->d_name
);
4494 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
4500 strcat(path
, "/cgroup.procs");
4501 fd
= openat(cfd
, path
, O_RDONLY
);
4505 f
= fdopen(fd
, "r");
4511 while (getline(&line
, &linelen
, f
) != -1) {
4513 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
4517 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
4518 } while (*(*pid_buf
+ sum
) == NULL
);
4519 strcpy(*(*pid_buf
+ sum
), line
);
4528 * calc_load calculates the load according to the following formula:
4529 * load1 = load0 * exp + active * (1 - exp)
4531 * @load1: the new loadavg.
4532 * @load0: the former loadavg.
4533 * @active: the total number of running pid at this moment.
4534 * @exp: the fixed-point defined in the beginning.
4536 static unsigned long
4537 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
4539 unsigned long newload
;
4541 active
= active
> 0 ? active
* FIXED_1
: 0;
4542 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
4544 newload
+= FIXED_1
- 1;
4546 return newload
/ FIXED_1
;
4550 * Return 0 means that container p->cg is closed.
4551 * Return -1 means that error occurred in refresh.
4552 * Positive num equals the total number of pid.
4554 static int refresh_load(struct load_node
*p
, char *path
)
4558 char proc_path
[256];
4559 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
4564 struct dirent
*file
;
4567 idbuf
= malloc(sizeof(char *));
4569 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
4574 for (i
= 0; i
< sum
; i
++) {
4576 length
= strlen(idbuf
[i
])-1;
4577 idbuf
[i
][length
] = '\0';
4578 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
4579 if (ret
< 0 || ret
> 255) {
4580 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4586 dp
= opendir(proc_path
);
4588 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
4591 while ((file
= readdir(dp
)) != NULL
) {
4592 if (strncmp(file
->d_name
, ".", 1) == 0)
4594 if (strncmp(file
->d_name
, "..", 1) == 0)
4597 /* We make the biggest pid become last_pid.*/
4598 ret
= atof(file
->d_name
);
4599 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
4601 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
4602 if (ret
< 0 || ret
> 255) {
4603 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4609 f
= fopen(proc_path
, "r");
4611 while (getline(&line
, &linelen
, f
) != -1) {
4613 if ((line
[0] == 'S') && (line
[1] == 't'))
4616 if ((line
[7] == 'R') || (line
[7] == 'D'))
4623 /*Calculate the loadavg.*/
4624 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
4625 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
4626 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
4627 p
->run_pid
= run_pid
;
4628 p
->total_pid
= total_pid
;
4629 p
->last_pid
= last_pid
;
4640 * Traverse the hash table and update it.
4642 void *load_begin(void *arg
)
4646 int i
, sum
, length
, ret
;
4647 struct load_node
*f
;
4649 clock_t time1
, time2
;
4652 if (loadavg_stop
== 1)
4656 for (i
= 0; i
< LOAD_SIZE
; i
++) {
4657 pthread_mutex_lock(&load_hash
[i
].lock
);
4658 if (load_hash
[i
].next
== NULL
) {
4659 pthread_mutex_unlock(&load_hash
[i
].lock
);
4662 f
= load_hash
[i
].next
;
4665 length
= strlen(f
->cg
) + 2;
4667 /* strlen(f->cg) + '.' or '' + \0 */
4668 path
= malloc(length
);
4671 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
4672 if (ret
< 0 || ret
> length
- 1) {
4673 /* snprintf failed, ignore the node.*/
4674 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
4677 sum
= refresh_load(f
, path
);
4684 /* load_hash[i].lock locks only on the first node.*/
4685 if (first_node
== 1) {
4687 pthread_mutex_unlock(&load_hash
[i
].lock
);
4692 if (loadavg_stop
== 1)
4696 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
4700 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
4701 struct fuse_file_info
*fi
)
4703 struct fuse_context
*fc
= fuse_get_context();
4704 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4707 size_t total_len
= 0;
4708 char *cache
= d
->buf
;
4709 struct load_node
*n
;
4712 unsigned long a
, b
, c
;
4715 if (offset
> d
->size
)
4719 int left
= d
->size
- offset
;
4720 total_len
= left
> size
? size
: left
;
4721 memcpy(buf
, cache
+ offset
, total_len
);
4725 return read_file("/proc/loadavg", buf
, size
, d
);
4727 initpid
= lookup_initpid_in_store(fc
->pid
);
4730 cg
= get_pid_cgroup(initpid
, "cpu");
4732 return read_file("/proc/loadavg", buf
, size
, d
);
4734 prune_init_slice(cg
);
4735 hash
= calc_hash(cg
);
4736 n
= locate_node(cg
, hash
);
4740 if (!find_mounted_controller("cpu", &cfd
)) {
4742 * In locate_node() above, pthread_rwlock_unlock() isn't used
4743 * because delete is not allowed before read has ended.
4745 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4750 n
= malloc(sizeof(struct load_node
));
4754 n
->cg
= malloc(strlen(cg
)+1);
4762 n
->last_pid
= initpid
;
4764 insert_node(&n
, hash
);
4766 a
= n
->avenrun
[0] + (FIXED_1
/200);
4767 b
= n
->avenrun
[1] + (FIXED_1
/200);
4768 c
= n
->avenrun
[2] + (FIXED_1
/200);
4769 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
4770 LOAD_INT(a
), LOAD_FRAC(a
),
4771 LOAD_INT(b
), LOAD_FRAC(b
),
4772 LOAD_INT(c
), LOAD_FRAC(c
),
4773 n
->run_pid
, n
->total_pid
, n
->last_pid
);
4774 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4775 if (total_len
< 0 || total_len
>= d
->buflen
) {
4776 lxcfs_error("%s\n", "Failed to write to cache");
4780 d
->size
= (int)total_len
;
4783 if (total_len
> size
)
4785 memcpy(buf
, d
->buf
, total_len
);
4792 /* Return a positive number on success, return 0 on failure.*/
4793 pthread_t
load_daemon(int load_use
)
4800 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
4803 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
4805 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
4809 /* use loadavg, here loadavg = 1*/
4814 /* Returns 0 on success. */
4815 int stop_load_daemon(pthread_t pid
)
4819 /* Signal the thread to gracefully stop */
4822 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
4824 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
4834 static off_t
get_procfile_size(const char *which
)
4836 FILE *f
= fopen(which
, "r");
4839 ssize_t sz
, answer
= 0;
4843 while ((sz
= getline(&line
, &len
, f
)) != -1)
4851 int proc_getattr(const char *path
, struct stat
*sb
)
4853 struct timespec now
;
4855 memset(sb
, 0, sizeof(struct stat
));
4856 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
4858 sb
->st_uid
= sb
->st_gid
= 0;
4859 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4860 if (strcmp(path
, "/proc") == 0) {
4861 sb
->st_mode
= S_IFDIR
| 00555;
4865 if (strcmp(path
, "/proc/meminfo") == 0 ||
4866 strcmp(path
, "/proc/cpuinfo") == 0 ||
4867 strcmp(path
, "/proc/uptime") == 0 ||
4868 strcmp(path
, "/proc/stat") == 0 ||
4869 strcmp(path
, "/proc/diskstats") == 0 ||
4870 strcmp(path
, "/proc/swaps") == 0 ||
4871 strcmp(path
, "/proc/loadavg") == 0) {
4873 sb
->st_mode
= S_IFREG
| 00444;
4881 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4882 struct fuse_file_info
*fi
)
4884 if (filler(buf
, ".", NULL
, 0) != 0 ||
4885 filler(buf
, "..", NULL
, 0) != 0 ||
4886 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4887 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4888 filler(buf
, "stat", NULL
, 0) != 0 ||
4889 filler(buf
, "uptime", NULL
, 0) != 0 ||
4890 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4891 filler(buf
, "swaps", NULL
, 0) != 0 ||
4892 filler(buf
, "loadavg", NULL
, 0) != 0)
4897 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4900 struct file_info
*info
;
4902 if (strcmp(path
, "/proc/meminfo") == 0)
4903 type
= LXC_TYPE_PROC_MEMINFO
;
4904 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4905 type
= LXC_TYPE_PROC_CPUINFO
;
4906 else if (strcmp(path
, "/proc/uptime") == 0)
4907 type
= LXC_TYPE_PROC_UPTIME
;
4908 else if (strcmp(path
, "/proc/stat") == 0)
4909 type
= LXC_TYPE_PROC_STAT
;
4910 else if (strcmp(path
, "/proc/diskstats") == 0)
4911 type
= LXC_TYPE_PROC_DISKSTATS
;
4912 else if (strcmp(path
, "/proc/swaps") == 0)
4913 type
= LXC_TYPE_PROC_SWAPS
;
4914 else if (strcmp(path
, "/proc/loadavg") == 0)
4915 type
= LXC_TYPE_PROC_LOADAVG
;
4919 info
= malloc(sizeof(*info
));
4923 memset(info
, 0, sizeof(*info
));
4926 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4928 info
->buf
= malloc(info
->buflen
);
4929 } while (!info
->buf
);
4930 memset(info
->buf
, 0, info
->buflen
);
4931 /* set actual size to buffer size */
4932 info
->size
= info
->buflen
;
4934 fi
->fh
= (unsigned long)info
;
4938 int proc_access(const char *path
, int mask
)
4940 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4943 /* these are all read-only */
4944 if ((mask
& ~R_OK
) != 0)
4949 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4951 do_release_file_info(fi
);
4955 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4956 struct fuse_file_info
*fi
)
4958 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4961 case LXC_TYPE_PROC_MEMINFO
:
4962 return proc_meminfo_read(buf
, size
, offset
, fi
);
4963 case LXC_TYPE_PROC_CPUINFO
:
4964 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4965 case LXC_TYPE_PROC_UPTIME
:
4966 return proc_uptime_read(buf
, size
, offset
, fi
);
4967 case LXC_TYPE_PROC_STAT
:
4968 return proc_stat_read(buf
, size
, offset
, fi
);
4969 case LXC_TYPE_PROC_DISKSTATS
:
4970 return proc_diskstats_read(buf
, size
, offset
, fi
);
4971 case LXC_TYPE_PROC_SWAPS
:
4972 return proc_swaps_read(buf
, size
, offset
, fi
);
4973 case LXC_TYPE_PROC_LOADAVG
:
4974 return proc_loadavg_read(buf
, size
, offset
, fi
);
4981 * Functions needed to setup cgroups in the __constructor__.
4984 static bool mkdir_p(const char *dir
, mode_t mode
)
4986 const char *tmp
= dir
;
4987 const char *orig
= dir
;
4991 dir
= tmp
+ strspn(tmp
, "/");
4992 tmp
= dir
+ strcspn(dir
, "/");
4993 makeme
= strndup(orig
, dir
- orig
);
4996 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4997 lxcfs_error("Failed to create directory '%s': %s.\n",
4998 makeme
, strerror(errno
));
5003 } while(tmp
!= dir
);
5008 static bool umount_if_mounted(void)
5010 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5011 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5017 /* __typeof__ should be safe to use with all compilers. */
5018 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5019 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5021 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5025 * looking at fs/proc_namespace.c, it appears we can
5026 * actually expect the rootfs entry to very specifically contain
5027 * " - rootfs rootfs "
5028 * IIUC, so long as we've chrooted so that rootfs is not our root,
5029 * the rootfs entry should always be skipped in mountinfo contents.
5031 static bool is_on_ramfs(void)
5039 f
= fopen("/proc/self/mountinfo", "r");
5043 while (getline(&line
, &len
, f
) != -1) {
5044 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5045 p
= strchr(p
+ 1, ' ');
5048 p2
= strchr(p
+ 1, ' ');
5052 if (strcmp(p
+ 1, "/") == 0) {
5053 // this is '/'. is it the ramfs?
5054 p
= strchr(p2
+ 1, '-');
5055 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5067 static int pivot_enter()
5069 int ret
= -1, oldroot
= -1, newroot
= -1;
5071 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5073 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5077 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5079 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5083 /* change into new root fs */
5084 if (fchdir(newroot
) < 0) {
5085 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5089 /* pivot_root into our new root fs */
5090 if (pivot_root(".", ".") < 0) {
5091 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5096 * At this point the old-root is mounted on top of our new-root.
5097 * To unmounted it we must not be chdir'd into it, so escape back
5100 if (fchdir(oldroot
) < 0) {
5101 lxcfs_error("%s\n", "Failed to enter old root.");
5105 if (umount2(".", MNT_DETACH
) < 0) {
5106 lxcfs_error("%s\n", "Failed to detach old root.");
5110 if (fchdir(newroot
) < 0) {
5111 lxcfs_error("%s\n", "Failed to re-enter new root.");
5126 static int chroot_enter()
5128 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
5129 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
5133 if (chroot(".") < 0) {
5134 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
5138 if (chdir("/") < 0) {
5139 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
5146 static int permute_and_enter(void)
5150 if (statfs("/", &sb
) < 0) {
5151 lxcfs_error("%s\n", "Could not stat / mountpoint.");
5155 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
5156 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
5157 * /proc/1/mountinfo. */
5158 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
5159 return chroot_enter();
5161 if (pivot_enter() < 0) {
5162 lxcfs_error("%s\n", "Could not perform pivot root.");
5169 /* Prepare our new clean root. */
5170 static int permute_prepare(void)
5172 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
5173 lxcfs_error("%s\n", "Failed to create directory for new root.");
5177 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
5178 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
5182 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
5183 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
5187 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
5188 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
5195 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
5196 static bool permute_root(void)
5198 /* Prepare new root. */
5199 if (permute_prepare() < 0)
5202 /* Pivot into new root. */
5203 if (permute_and_enter() < 0)
5209 static int preserve_mnt_ns(int pid
)
5212 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
5215 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
5216 if (ret
< 0 || (size_t)ret
>= len
)
5219 return open(path
, O_RDONLY
| O_CLOEXEC
);
5222 static bool cgfs_prepare_mounts(void)
5224 if (!mkdir_p(BASEDIR
, 0700)) {
5225 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
5229 if (!umount_if_mounted()) {
5230 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
5234 if (unshare(CLONE_NEWNS
) < 0) {
5235 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
5239 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
5240 if (cgroup_mount_ns_fd
< 0) {
5241 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
5245 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
5246 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
5250 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
5251 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
5258 static bool cgfs_mount_hierarchies(void)
5264 for (i
= 0; i
< num_hierarchies
; i
++) {
5265 char *controller
= hierarchies
[i
];
5267 clen
= strlen(controller
);
5268 len
= strlen(BASEDIR
) + clen
+ 2;
5269 target
= malloc(len
);
5273 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
5274 if (ret
< 0 || ret
>= len
) {
5278 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
5282 if (!strcmp(controller
, "unified"))
5283 ret
= mount("none", target
, "cgroup2", 0, NULL
);
5285 ret
= mount(controller
, target
, "cgroup", 0, controller
);
5287 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
5292 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
5293 if (fd_hierarchies
[i
] < 0) {
5302 static bool cgfs_setup_controllers(void)
5304 if (!cgfs_prepare_mounts())
5307 if (!cgfs_mount_hierarchies()) {
5308 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
5312 if (!permute_root())
5318 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
5321 char *cret
, *line
= NULL
;
5322 char cwd
[MAXPATHLEN
];
5324 int i
, init_ns
= -1;
5325 bool found_unified
= false;
5327 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
5328 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
5332 while (getline(&line
, &len
, f
) != -1) {
5335 p
= strchr(line
, ':');
5341 p2
= strrchr(p
, ':');
5346 /* With cgroupv2 /proc/self/cgroup can contain entries of the
5347 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
5348 * because it parses out the empty string "" and later on passes
5349 * it to mount(). Let's skip such entries.
5351 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
5352 found_unified
= true;
5356 if (!store_hierarchy(line
, p
))
5360 /* Preserve initial namespace. */
5361 init_ns
= preserve_mnt_ns(getpid());
5363 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
5367 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
5368 if (!fd_hierarchies
) {
5369 lxcfs_error("%s\n", strerror(errno
));
5373 for (i
= 0; i
< num_hierarchies
; i
++)
5374 fd_hierarchies
[i
] = -1;
5376 cret
= getcwd(cwd
, MAXPATHLEN
);
5378 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
5380 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
5381 * to privately mount lxcfs cgroups. */
5382 if (!cgfs_setup_controllers()) {
5383 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
5387 if (setns(init_ns
, 0) < 0) {
5388 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
5392 if (!cret
|| chdir(cwd
) < 0)
5393 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
5404 static void __attribute__((destructor
)) free_subsystems(void)
5408 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
5410 for (i
= 0; i
< num_hierarchies
; i
++) {
5412 free(hierarchies
[i
]);
5413 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
5414 close(fd_hierarchies
[i
]);
5417 free(fd_hierarchies
);
5419 if (cgroup_mount_ns_fd
>= 0)
5420 close(cgroup_mount_ns_fd
);