3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
11 #define __STDC_FORMAT_MACROS
28 #include <linux/magic.h>
29 #include <linux/sched.h>
30 #include <sys/epoll.h>
32 #include <sys/mount.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/sysinfo.h>
40 #include "config.h" // for VERSION
42 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
43 #define LXCFS_NUMSTRLEN64 21
45 /* Define pivot_root() if missing from the C library */
46 #ifndef HAVE_PIVOT_ROOT
47 static int pivot_root(const char * new_root
, const char * put_old
)
49 #ifdef __NR_pivot_root
50 return syscall(__NR_pivot_root
, new_root
, put_old
);
57 extern int pivot_root(const char * new_root
, const char * put_old
);
63 LXC_TYPE_PROC_MEMINFO
,
64 LXC_TYPE_PROC_CPUINFO
,
67 LXC_TYPE_PROC_DISKSTATS
,
69 LXC_TYPE_PROC_LOADAVG
,
77 char *buf
; // unused as of yet
79 int size
; //actual data size
83 /* The function of hash table.*/
84 #define LOAD_SIZE 100 /*the size of hash_table */
85 #define FLUSH_TIME 5 /*the flush rate */
86 #define DEPTH_DIR 3 /*the depth of per cgroup */
87 /* The function of calculate loadavg .*/
88 #define FSHIFT 11 /* nr of bits of precision */
89 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
90 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
91 #define EXP_5 2014 /* 1/exp(5sec/5min) */
92 #define EXP_15 2037 /* 1/exp(5sec/15min) */
93 #define LOAD_INT(x) ((x) >> FSHIFT)
94 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
96 * This parameter is used for proc_loadavg_read().
97 * 1 means use loadavg, 0 means not use.
99 static int loadavg
= 0;
100 static int calc_hash(char *name
)
102 unsigned int hash
= 0;
104 /* ELFHash algorithm. */
106 hash
= (hash
<< 4) + *name
++;
107 x
= hash
& 0xf0000000;
112 return ((hash
& 0x7fffffff) % LOAD_SIZE
);
117 unsigned long avenrun
[3]; /* Load averages */
118 unsigned int run_pid
;
119 unsigned int total_pid
;
120 unsigned int last_pid
;
121 int cfd
; /* The file descriptor of the mounted cgroup */
122 struct load_node
*next
;
123 struct load_node
**pre
;
128 * The lock is about insert load_node and refresh load_node.To the first
129 * load_node of each hash bucket, insert and refresh in this hash bucket is
130 * mutually exclusive.
132 pthread_mutex_t lock
;
134 * The rdlock is about read loadavg and delete load_node.To each hash
135 * bucket, read and delete is mutually exclusive. But at the same time, we
136 * allow paratactic read operation. This rdlock is at list level.
138 pthread_rwlock_t rdlock
;
140 * The rilock is about read loadavg and insert load_node.To the first
141 * load_node of each hash bucket, read and insert is mutually exclusive.
142 * But at the same time, we allow paratactic read operation.
144 pthread_rwlock_t rilock
;
145 struct load_node
*next
;
148 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
150 * init_load initialize the hash table.
151 * Return 0 on success, return -1 on failure.
153 static int init_load(void)
158 for (i
= 0; i
< LOAD_SIZE
; i
++) {
159 load_hash
[i
].next
= NULL
;
160 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
162 lxcfs_error("%s\n", "Failed to initialize lock");
165 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
167 lxcfs_error("%s\n", "Failed to initialize rdlock");
170 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
172 lxcfs_error("%s\n", "Failed to initialize rilock");
178 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
180 pthread_mutex_destroy(&load_hash
[i
].lock
);
184 pthread_mutex_destroy(&load_hash
[i
].lock
);
185 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
186 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
191 static void insert_node(struct load_node
**n
, int locate
)
195 pthread_mutex_lock(&load_hash
[locate
].lock
);
196 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
197 f
= load_hash
[locate
].next
;
198 load_hash
[locate
].next
= *n
;
200 (*n
)->pre
= &(load_hash
[locate
].next
);
202 f
->pre
= &((*n
)->next
);
204 pthread_mutex_unlock(&load_hash
[locate
].lock
);
205 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
208 * locate_node() finds special node. Not return NULL means success.
209 * It should be noted that rdlock isn't unlocked at the end of code
210 * because this function is used to read special node. Delete is not
211 * allowed before read has ended.
212 * unlock rdlock only in proc_loadavg_read().
214 static struct load_node
*locate_node(char *cg
, int locate
)
216 struct load_node
*f
= NULL
;
219 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
220 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
221 if (load_hash
[locate
].next
== NULL
) {
222 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
225 f
= load_hash
[locate
].next
;
226 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
227 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
231 /* Delete the load_node n and return the next node of it. */
232 static struct load_node
*del_node(struct load_node
*n
, int locate
)
236 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
237 if (n
->next
== NULL
) {
241 n
->next
->pre
= n
->pre
;
246 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
253 struct load_node
*f
, *p
;
255 for (i
= 0; i
< LOAD_SIZE
; i
++) {
256 pthread_mutex_lock(&load_hash
[i
].lock
);
257 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
258 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
259 if (load_hash
[i
].next
== NULL
) {
260 pthread_mutex_unlock(&load_hash
[i
].lock
);
261 pthread_mutex_destroy(&load_hash
[i
].lock
);
262 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
263 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
264 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
265 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
268 for (f
= load_hash
[i
].next
; f
; ) {
274 pthread_mutex_unlock(&load_hash
[i
].lock
);
275 pthread_mutex_destroy(&load_hash
[i
].lock
);
276 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
277 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
278 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
279 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
282 /* Reserve buffer size to account for file size changes. */
283 #define BUF_RESERVE_SIZE 512
286 * A table caching which pid is init for a pid namespace.
287 * When looking up which pid is init for $qpid, we first
288 * 1. Stat /proc/$qpid/ns/pid.
289 * 2. Check whether the ino_t is in our store.
290 * a. if not, fork a child in qpid's ns to send us
291 * ucred.pid = 1, and read the initpid. Cache
292 * initpid and creation time for /proc/initpid
293 * in a new store entry.
294 * b. if so, verify that /proc/initpid still matches
295 * what we have saved. If not, clear the store
296 * entry and go back to a. If so, return the
299 struct pidns_init_store
{
300 ino_t ino
; // inode number for /proc/$pid/ns/pid
301 pid_t initpid
; // the pid of nit in that ns
302 long int ctime
; // the time at which /proc/$initpid was created
303 struct pidns_init_store
*next
;
307 /* lol - look at how they are allocated in the kernel */
308 #define PIDNS_HASH_SIZE 4096
309 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
311 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
312 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
313 static void lock_mutex(pthread_mutex_t
*l
)
317 if ((ret
= pthread_mutex_lock(l
)) != 0) {
318 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
323 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
324 * Number of hierarchies mounted. */
325 static int num_hierarchies
;
327 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
328 * Hierachies mounted {cpuset, blkio, ...}:
329 * Initialized via __constructor__ collect_and_mount_subsystems(). */
330 static char **hierarchies
;
332 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
333 * Open file descriptors:
334 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
335 * private mount namespace.
336 * Initialized via __constructor__ collect_and_mount_subsystems().
337 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
338 * mounts and respective files in the private namespace even when located in
339 * another namespace using the *at() family of functions
340 * {openat(), fchownat(), ...}. */
341 static int *fd_hierarchies
;
342 static int cgroup_mount_ns_fd
= -1;
344 static void unlock_mutex(pthread_mutex_t
*l
)
348 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
349 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
354 static void store_lock(void)
356 lock_mutex(&pidns_store_mutex
);
359 static void store_unlock(void)
361 unlock_mutex(&pidns_store_mutex
);
364 /* Must be called under store_lock */
365 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
370 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
371 if (stat(fnam
, &initsb
) < 0)
374 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
375 initsb
.st_ctime
, e
->initpid
);
377 if (e
->ctime
!= initsb
.st_ctime
)
382 /* Must be called under store_lock */
383 static void remove_initpid(struct pidns_init_store
*e
)
385 struct pidns_init_store
*tmp
;
388 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
391 if (pidns_hash_table
[h
] == e
) {
392 pidns_hash_table
[h
] = e
->next
;
397 tmp
= pidns_hash_table
[h
];
399 if (tmp
->next
== e
) {
409 /* Must be called under store_lock */
410 static void prune_initpid_store(void)
412 static long int last_prune
= 0;
413 struct pidns_init_store
*e
, *prev
, *delme
;
414 long int now
, threshold
;
418 last_prune
= time(NULL
);
422 if (now
< last_prune
+ PURGE_SECS
)
425 lxcfs_debug("%s\n", "Pruning.");
428 threshold
= now
- 2 * PURGE_SECS
;
430 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
431 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
432 if (e
->lastcheck
< threshold
) {
434 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
438 prev
->next
= e
->next
;
440 pidns_hash_table
[i
] = e
->next
;
451 /* Must be called under store_lock */
452 static void save_initpid(struct stat
*sb
, pid_t pid
)
454 struct pidns_init_store
*e
;
459 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
461 snprintf(fpath
, 100, "/proc/%d", pid
);
462 if (stat(fpath
, &procsb
) < 0)
465 e
= malloc(sizeof(*e
));
469 e
->ctime
= procsb
.st_ctime
;
471 e
->next
= pidns_hash_table
[h
];
472 e
->lastcheck
= time(NULL
);
473 pidns_hash_table
[h
] = e
;
477 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
478 * entry for the inode number and creation time. Verify that the init pid
479 * is still valid. If not, remove it. Return the entry if valid, NULL
481 * Must be called under store_lock
483 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
485 int h
= HASH(sb
->st_ino
);
486 struct pidns_init_store
*e
= pidns_hash_table
[h
];
489 if (e
->ino
== sb
->st_ino
) {
490 if (initpid_still_valid(e
, sb
)) {
491 e
->lastcheck
= time(NULL
);
503 static int is_dir(const char *path
, int fd
)
506 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
507 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
512 static char *must_copy_string(const char *str
)
524 static inline void drop_trailing_newlines(char *s
)
528 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
532 #define BATCH_SIZE 50
533 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
535 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
536 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
538 if (!*mem
|| newbatches
> oldbatches
) {
541 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
546 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
548 size_t newlen
= *len
+ linelen
;
549 dorealloc(contents
, *len
, newlen
+ 1);
550 memcpy(*contents
+ *len
, line
, linelen
+1);
554 static char *slurp_file(const char *from
, int fd
)
557 char *contents
= NULL
;
558 FILE *f
= fdopen(fd
, "r");
559 size_t len
= 0, fulllen
= 0;
565 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
566 append_line(&contents
, &fulllen
, line
, linelen
);
571 drop_trailing_newlines(contents
);
576 static bool write_string(const char *fnam
, const char *string
, int fd
)
581 if (!(f
= fdopen(fd
, "w")))
583 len
= strlen(string
);
584 ret
= fwrite(string
, 1, len
, f
);
586 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
591 lxcfs_error("Error writing to file: %s\n", strerror(errno
));
604 static bool store_hierarchy(char *stridx
, char *h
)
606 if (num_hierarchies
% ALLOC_NUM
== 0) {
607 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
609 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
611 lxcfs_error("%s\n", strerror(errno
));
617 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
621 static void print_subsystems(void)
625 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
626 fprintf(stderr
, "hierarchies:\n");
627 for (i
= 0; i
< num_hierarchies
; i
++) {
629 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
630 fd_hierarchies
[i
], hierarchies
[i
]);
634 static bool in_comma_list(const char *needle
, const char *haystack
)
636 const char *s
= haystack
, *e
;
637 size_t nlen
= strlen(needle
);
639 while (*s
&& (e
= strchr(s
, ','))) {
644 if (strncmp(needle
, s
, nlen
) == 0)
648 if (strcmp(needle
, s
) == 0)
653 /* do we need to do any massaging here? I'm not sure... */
654 /* Return the mounted controller and store the corresponding open file descriptor
655 * referring to the controller mountpoint in the private lxcfs namespace in
658 static char *find_mounted_controller(const char *controller
, int *cfd
)
662 for (i
= 0; i
< num_hierarchies
; i
++) {
665 if (strcmp(hierarchies
[i
], controller
) == 0) {
666 *cfd
= fd_hierarchies
[i
];
667 return hierarchies
[i
];
669 if (in_comma_list(controller
, hierarchies
[i
])) {
670 *cfd
= fd_hierarchies
[i
];
671 return hierarchies
[i
];
678 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
685 tmpc
= find_mounted_controller(controller
, &cfd
);
689 /* Make sure we pass a relative path to *at() family of functions.
690 * . + /cgroup + / + file + \0
692 len
= strlen(cgroup
) + strlen(file
) + 3;
694 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
695 if (ret
< 0 || (size_t)ret
>= len
)
698 fd
= openat(cfd
, fnam
, O_WRONLY
);
702 return write_string(fnam
, value
, fd
);
705 // Chown all the files in the cgroup directory. We do this when we create
706 // a cgroup on behalf of a user.
707 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
709 struct dirent
*direntp
;
710 char path
[MAXPATHLEN
];
715 len
= strlen(dirname
);
716 if (len
>= MAXPATHLEN
) {
717 lxcfs_error("Pathname too long: %s\n", dirname
);
721 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
727 lxcfs_error("Failed to open %s\n", dirname
);
731 while ((direntp
= readdir(d
))) {
732 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
734 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
735 if (ret
< 0 || ret
>= MAXPATHLEN
) {
736 lxcfs_error("Pathname too long under %s\n", dirname
);
739 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
740 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
745 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
751 tmpc
= find_mounted_controller(controller
, &cfd
);
755 /* Make sure we pass a relative path to *at() family of functions.
758 len
= strlen(cg
) + 2;
759 dirnam
= alloca(len
);
760 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
762 if (mkdirat(cfd
, dirnam
, 0755) < 0)
765 if (uid
== 0 && gid
== 0)
768 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
771 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
776 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
778 struct dirent
*direntp
;
781 char pathname
[MAXPATHLEN
];
784 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
788 dir
= fdopendir(dupfd
);
790 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
795 while ((direntp
= readdir(dir
))) {
799 if (!strcmp(direntp
->d_name
, ".") ||
800 !strcmp(direntp
->d_name
, ".."))
803 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
804 if (rc
< 0 || rc
>= MAXPATHLEN
) {
805 lxcfs_error("%s\n", "Pathname too long.");
809 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
811 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
814 if (S_ISDIR(mystat
.st_mode
))
815 if (!recursive_rmdir(pathname
, fd
, cfd
))
816 lxcfs_debug("Error removing %s.\n", pathname
);
820 if (closedir(dir
) < 0) {
821 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
825 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
826 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
835 bool cgfs_remove(const char *controller
, const char *cg
)
842 tmpc
= find_mounted_controller(controller
, &cfd
);
846 /* Make sure we pass a relative path to *at() family of functions.
849 len
= strlen(cg
) + 2;
850 dirnam
= alloca(len
);
851 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
853 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
857 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
862 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
866 char *pathname
, *tmpc
;
868 tmpc
= find_mounted_controller(controller
, &cfd
);
872 /* Make sure we pass a relative path to *at() family of functions.
875 len
= strlen(file
) + 2;
876 pathname
= alloca(len
);
877 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
878 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
883 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
888 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
890 snprintf(fname
, len
, "%s/tasks", dirname
);
891 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
893 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
894 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
899 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
903 char *pathname
, *tmpc
;
905 tmpc
= find_mounted_controller(controller
, &cfd
);
909 /* Make sure we pass a relative path to *at() family of functions.
912 len
= strlen(file
) + 2;
913 pathname
= alloca(len
);
914 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
915 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
918 if (is_dir(pathname
, cfd
))
919 // like cgmanager did, we want to chown the tasks file as well
920 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
925 FILE *open_pids_file(const char *controller
, const char *cgroup
)
929 char *pathname
, *tmpc
;
931 tmpc
= find_mounted_controller(controller
, &cfd
);
935 /* Make sure we pass a relative path to *at() family of functions.
936 * . + /cgroup + / "cgroup.procs" + \0
938 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
939 pathname
= alloca(len
);
940 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
942 fd
= openat(cfd
, pathname
, O_WRONLY
);
946 return fdopen(fd
, "w");
949 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
950 void ***list
, size_t typesize
,
951 void* (*iterator
)(const char*, const char*, const char*))
956 char pathname
[MAXPATHLEN
];
957 size_t sz
= 0, asz
= 0;
958 struct dirent
*dirent
;
961 tmpc
= find_mounted_controller(controller
, &cfd
);
966 /* Make sure we pass a relative path to *at() family of functions. */
967 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
969 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
970 if (ret
< 0 || (size_t)ret
>= len
) {
971 lxcfs_error("Pathname too long under %s\n", cgroup
);
975 fd
= openat(cfd
, cg
, O_DIRECTORY
);
983 while ((dirent
= readdir(dir
))) {
986 if (!strcmp(dirent
->d_name
, ".") ||
987 !strcmp(dirent
->d_name
, ".."))
990 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
991 if (ret
< 0 || ret
>= MAXPATHLEN
) {
992 lxcfs_error("Pathname too long under %s\n", cg
);
996 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
998 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1001 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1002 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1009 tmp
= realloc(*list
, asz
* typesize
);
1013 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1014 (*list
)[sz
+1] = NULL
;
1017 if (closedir(dir
) < 0) {
1018 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1024 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1028 dup
= strdup(dir_entry
);
1033 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1035 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1038 void free_key(struct cgfs_files
*k
)
1046 void free_keys(struct cgfs_files
**keys
)
1052 for (i
= 0; keys
[i
]; i
++) {
1058 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1064 tmpc
= find_mounted_controller(controller
, &cfd
);
1068 /* Make sure we pass a relative path to *at() family of functions.
1069 * . + /cgroup + / + file + \0
1071 len
= strlen(cgroup
) + strlen(file
) + 3;
1073 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1074 if (ret
< 0 || (size_t)ret
>= len
)
1077 fd
= openat(cfd
, fnam
, O_RDONLY
);
1081 *value
= slurp_file(fnam
, fd
);
1082 return *value
!= NULL
;
1085 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1091 struct cgfs_files
*newkey
;
1093 tmpc
= find_mounted_controller(controller
, &cfd
);
1097 if (file
&& *file
== '/')
1100 if (file
&& strchr(file
, '/'))
1103 /* Make sure we pass a relative path to *at() family of functions.
1104 * . + /cgroup + / + file + \0
1106 len
= strlen(cgroup
) + 3;
1108 len
+= strlen(file
) + 1;
1110 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1111 file
? "/" : "", file
? file
: "");
1113 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1118 newkey
= malloc(sizeof(struct cgfs_files
));
1121 newkey
->name
= must_copy_string(file
);
1122 else if (strrchr(cgroup
, '/'))
1123 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1125 newkey
->name
= must_copy_string(cgroup
);
1126 newkey
->uid
= sb
.st_uid
;
1127 newkey
->gid
= sb
.st_gid
;
1128 newkey
->mode
= sb
.st_mode
;
1133 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1135 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1137 lxcfs_error("Error getting files under %s:%s\n", controller
,
1143 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1145 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1148 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1156 tmpc
= find_mounted_controller(controller
, &cfd
);
1160 /* Make sure we pass a relative path to *at() family of functions.
1161 * . + /cgroup + / + f + \0
1163 len
= strlen(cgroup
) + strlen(f
) + 3;
1165 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1166 if (ret
< 0 || (size_t)ret
>= len
)
1169 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1170 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1176 #define SEND_CREDS_OK 0
1177 #define SEND_CREDS_NOTSK 1
1178 #define SEND_CREDS_FAIL 2
1179 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1180 static int wait_for_pid(pid_t pid
);
1181 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1182 static int send_creds_clone_wrapper(void *arg
);
1185 * clone a task which switches to @task's namespace and writes '1'.
1186 * over a unix sock so we can read the task's reaper's pid in our
1189 * Note: glibc's fork() does not respect pidns, which can lead to failed
1190 * assertions inside glibc (and thus failed forks) if the child's pid in
1191 * the pidns and the parent pid outside are identical. Using clone prevents
1194 static void write_task_init_pid_exit(int sock
, pid_t target
)
1199 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1200 void *stack
= alloca(stack_size
);
1202 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1203 if (ret
< 0 || ret
>= sizeof(fnam
))
1206 fd
= open(fnam
, O_RDONLY
);
1208 perror("write_task_init_pid_exit open of ns/pid");
1212 perror("write_task_init_pid_exit setns 1");
1216 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1220 if (!wait_for_pid(pid
))
1226 static int send_creds_clone_wrapper(void *arg
) {
1229 int sock
= *(int *)arg
;
1231 /* we are the child */
1236 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1241 static pid_t
get_init_pid_for_task(pid_t task
)
1249 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1250 perror("socketpair");
1259 write_task_init_pid_exit(sock
[0], task
);
1263 if (!recv_creds(sock
[1], &cred
, &v
))
1275 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1279 struct pidns_init_store
*e
;
1282 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1284 if (stat(fnam
, &sb
) < 0)
1286 e
= lookup_verify_initpid(&sb
);
1288 answer
= e
->initpid
;
1291 answer
= get_init_pid_for_task(qpid
);
1293 save_initpid(&sb
, answer
);
1296 /* we prune at end in case we are returning
1297 * the value we were about to return */
1298 prune_initpid_store();
1303 static int wait_for_pid(pid_t pid
)
1311 ret
= waitpid(pid
, &status
, 0);
1319 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1326 * append pid to *src.
1327 * src: a pointer to a char* in which ot append the pid.
1328 * sz: the number of characters printed so far, minus trailing \0.
1329 * asz: the allocated size so far
1330 * pid: the pid to append
1332 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1336 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1338 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1341 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1344 *asz
+= BUF_RESERVE_SIZE
;
1346 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1351 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1352 * valid in the caller's namespace, return the id mapped into
1354 * Returns the mapped id, or -1 on error.
1357 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1359 unsigned int nsuid
, // base id for a range in the idfile's namespace
1360 hostuid
, // base id for a range in the caller's namespace
1361 count
; // number of ids in this range
1365 fseek(idfile
, 0L, SEEK_SET
);
1366 while (fgets(line
, 400, idfile
)) {
1367 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1370 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1372 * uids wrapped around - unexpected as this is a procfile,
1375 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1376 nsuid
, hostuid
, count
, line
);
1379 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1381 * now since hostuid <= in_id < hostuid+count, and
1382 * hostuid+count and nsuid+count do not wrap around,
1383 * we know that nsuid+(in_id-hostuid) which must be
1384 * less that nsuid+(count) must not wrap around
1386 return (in_id
- hostuid
) + nsuid
;
1395 * for is_privileged_over,
1396 * specify whether we require the calling uid to be root in his
1399 #define NS_ROOT_REQD true
1400 #define NS_ROOT_OPT false
1404 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1406 char fpath
[PROCLEN
];
1408 bool answer
= false;
1411 if (victim
== -1 || uid
== -1)
1415 * If the request is one not requiring root in the namespace,
1416 * then having the same uid suffices. (i.e. uid 1000 has write
1417 * access to files owned by uid 1000
1419 if (!req_ns_root
&& uid
== victim
)
1422 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1423 if (ret
< 0 || ret
>= PROCLEN
)
1425 FILE *f
= fopen(fpath
, "r");
1429 /* if caller's not root in his namespace, reject */
1430 nsuid
= convert_id_to_ns(f
, uid
);
1435 * If victim is not mapped into caller's ns, reject.
1436 * XXX I'm not sure this check is needed given that fuse
1437 * will be sending requests where the vfs has converted
1439 nsuid
= convert_id_to_ns(f
, victim
);
1450 static bool perms_include(int fmode
, mode_t req_mode
)
1454 switch (req_mode
& O_ACCMODE
) {
1462 r
= S_IROTH
| S_IWOTH
;
1467 return ((fmode
& r
) == r
);
1473 * querycg is /a/b/c/d/e
1476 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1480 if (strlen(taskcg
) <= strlen(querycg
)) {
1481 lxcfs_error("%s\n", "I was fed bad input.");
1485 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1486 start
= strdup(taskcg
+ 1);
1488 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1491 end
= strchr(start
, '/');
1497 static void stripnewline(char *x
)
1499 size_t l
= strlen(x
);
1500 if (l
&& x
[l
-1] == '\n')
1504 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1509 char *answer
= NULL
;
1513 const char *h
= find_mounted_controller(contrl
, &cfd
);
1517 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1518 if (ret
< 0 || ret
>= PROCLEN
)
1520 if (!(f
= fopen(fnam
, "r")))
1523 while (getline(&line
, &len
, f
) != -1) {
1527 c1
= strchr(line
, ':');
1531 c2
= strchr(c1
, ':');
1535 if (strcmp(c1
, h
) != 0)
1540 answer
= strdup(c2
);
1552 * check whether a fuse context may access a cgroup dir or file
1554 * If file is not null, it is a cgroup file to check under cg.
1555 * If file is null, then we are checking perms on cg itself.
1557 * For files we can check the mode of the list_keys result.
1558 * For cgroups, we must make assumptions based on the files under the
1559 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1562 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1564 struct cgfs_files
*k
= NULL
;
1567 k
= cgfs_get_key(contrl
, cg
, file
);
1571 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1572 if (perms_include(k
->mode
>> 6, mode
)) {
1577 if (fc
->gid
== k
->gid
) {
1578 if (perms_include(k
->mode
>> 3, mode
)) {
1583 ret
= perms_include(k
->mode
, mode
);
1590 #define INITSCOPE "/init.scope"
1591 static void prune_init_slice(char *cg
)
1594 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1596 if (cg_len
< initscope_len
)
1599 point
= cg
+ cg_len
- initscope_len
;
1600 if (strcmp(point
, INITSCOPE
) == 0) {
1609 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1610 * If pid is in /a, he may act on /a/b, but not on /b.
1611 * if the answer is false and nextcg is not NULL, then *nextcg will point
1612 * to a string containing the next cgroup directory under cg, which must be
1613 * freed by the caller.
1615 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1617 bool answer
= false;
1618 char *c2
= get_pid_cgroup(pid
, contrl
);
1623 prune_init_slice(c2
);
1626 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1627 * they pass in a cgroup without leading '/'
1629 * The original line here was:
1630 * linecmp = *cg == '/' ? c2 : c2+1;
1631 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1632 * Serge, do you know?
1634 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1638 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1640 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1652 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1654 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1656 bool answer
= false;
1658 size_t target_len
, task_len
;
1660 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1663 c2
= get_pid_cgroup(pid
, contrl
);
1666 prune_init_slice(c2
);
1669 target_len
= strlen(cg
);
1670 task_len
= strlen(task_cg
);
1671 if (task_len
== 0) {
1672 /* Task is in the root cg, it can see everything. This case is
1673 * not handled by the strmcps below, since they test for the
1674 * last /, but that is the first / that we've chopped off
1680 if (strcmp(cg
, task_cg
) == 0) {
1684 if (target_len
< task_len
) {
1685 /* looking up a parent dir */
1686 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1690 if (target_len
> task_len
) {
1691 /* looking up a child dir */
1692 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1703 * given /cgroup/freezer/a/b, return "freezer".
1704 * the returned char* should NOT be freed.
1706 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1709 char *contr
, *slash
;
1711 if (strlen(path
) < 9) {
1715 if (*(path
+ 7) != '/') {
1720 contr
= strdupa(p1
);
1725 slash
= strstr(contr
, "/");
1730 for (i
= 0; i
< num_hierarchies
; i
++) {
1731 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1732 return hierarchies
[i
];
1739 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1740 * Note that the returned value may include files (keynames) etc
1742 static const char *find_cgroup_in_path(const char *path
)
1746 if (strlen(path
) < 9) {
1750 p1
= strstr(path
+ 8, "/");
1760 * split the last path element from the path in @cg.
1761 * @dir is newly allocated and should be freed, @last not
1763 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1770 *last
= strrchr(cg
, '/');
1775 p
= strrchr(*dir
, '/');
1780 * FUSE ops for /cgroup
1783 int cg_getattr(const char *path
, struct stat
*sb
)
1785 struct timespec now
;
1786 struct fuse_context
*fc
= fuse_get_context();
1787 char * cgdir
= NULL
;
1788 char *last
= NULL
, *path1
, *path2
;
1789 struct cgfs_files
*k
= NULL
;
1791 const char *controller
= NULL
;
1798 memset(sb
, 0, sizeof(struct stat
));
1800 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1803 sb
->st_uid
= sb
->st_gid
= 0;
1804 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1807 if (strcmp(path
, "/cgroup") == 0) {
1808 sb
->st_mode
= S_IFDIR
| 00755;
1813 controller
= pick_controller_from_path(fc
, path
);
1816 cgroup
= find_cgroup_in_path(path
);
1818 /* this is just /cgroup/controller, return it as a dir */
1819 sb
->st_mode
= S_IFDIR
| 00755;
1824 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1834 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1837 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1838 * Then check that caller's cgroup is under path if last is a child
1839 * cgroup, or cgdir if last is a file */
1841 if (is_child_cgroup(controller
, path1
, path2
)) {
1842 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1846 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1847 /* this is just /cgroup/controller, return it as a dir */
1848 sb
->st_mode
= S_IFDIR
| 00555;
1853 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1858 // get uid, gid, from '/tasks' file and make up a mode
1859 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1860 sb
->st_mode
= S_IFDIR
| 00755;
1861 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1863 sb
->st_uid
= sb
->st_gid
= 0;
1865 sb
->st_uid
= k
->uid
;
1866 sb
->st_gid
= k
->gid
;
1874 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1875 sb
->st_mode
= S_IFREG
| k
->mode
;
1877 sb
->st_uid
= k
->uid
;
1878 sb
->st_gid
= k
->gid
;
1881 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1893 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1895 struct fuse_context
*fc
= fuse_get_context();
1897 struct file_info
*dir_info
;
1898 char *controller
= NULL
;
1903 if (strcmp(path
, "/cgroup") == 0) {
1907 // return list of keys for the controller, and list of child cgroups
1908 controller
= pick_controller_from_path(fc
, path
);
1912 cgroup
= find_cgroup_in_path(path
);
1914 /* this is just /cgroup/controller, return its contents */
1919 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1923 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1925 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1929 /* we'll free this at cg_releasedir */
1930 dir_info
= malloc(sizeof(*dir_info
));
1933 dir_info
->controller
= must_copy_string(controller
);
1934 dir_info
->cgroup
= must_copy_string(cgroup
);
1935 dir_info
->type
= LXC_TYPE_CGDIR
;
1936 dir_info
->buf
= NULL
;
1937 dir_info
->file
= NULL
;
1938 dir_info
->buflen
= 0;
1940 fi
->fh
= (unsigned long)dir_info
;
1944 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1945 struct fuse_file_info
*fi
)
1947 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1948 struct cgfs_files
**list
= NULL
;
1950 char *nextcg
= NULL
;
1951 struct fuse_context
*fc
= fuse_get_context();
1952 char **clist
= NULL
;
1954 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1957 if (d
->type
!= LXC_TYPE_CGDIR
) {
1958 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1961 if (!d
->cgroup
&& !d
->controller
) {
1962 // ls /var/lib/lxcfs/cgroup - just show list of controllers
1965 for (i
= 0; i
< num_hierarchies
; i
++) {
1966 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
1973 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1974 // not a valid cgroup
1979 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1982 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1984 ret
= filler(buf
, nextcg
, NULL
, 0);
1995 for (i
= 0; list
[i
]; i
++) {
1996 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2002 // now get the list of child cgroups
2004 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2009 for (i
= 0; clist
[i
]; i
++) {
2010 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2021 for (i
= 0; clist
[i
]; i
++)
2028 static void do_release_file_info(struct fuse_file_info
*fi
)
2030 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2037 free(f
->controller
);
2038 f
->controller
= NULL
;
2048 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2050 do_release_file_info(fi
);
2054 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2057 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2058 struct cgfs_files
*k
= NULL
;
2059 struct file_info
*file_info
;
2060 struct fuse_context
*fc
= fuse_get_context();
2066 controller
= pick_controller_from_path(fc
, path
);
2069 cgroup
= find_cgroup_in_path(path
);
2073 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2082 k
= cgfs_get_key(controller
, path1
, path2
);
2089 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2092 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2096 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2101 /* we'll free this at cg_release */
2102 file_info
= malloc(sizeof(*file_info
));
2107 file_info
->controller
= must_copy_string(controller
);
2108 file_info
->cgroup
= must_copy_string(path1
);
2109 file_info
->file
= must_copy_string(path2
);
2110 file_info
->type
= LXC_TYPE_CGFILE
;
2111 file_info
->buf
= NULL
;
2112 file_info
->buflen
= 0;
2114 fi
->fh
= (unsigned long)file_info
;
2122 int cg_access(const char *path
, int mode
)
2126 char *path1
, *path2
, *controller
;
2127 char *last
= NULL
, *cgdir
= NULL
;
2128 struct cgfs_files
*k
= NULL
;
2129 struct fuse_context
*fc
= fuse_get_context();
2131 if (strcmp(path
, "/cgroup") == 0)
2137 controller
= pick_controller_from_path(fc
, path
);
2140 cgroup
= find_cgroup_in_path(path
);
2142 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2143 if ((mode
& W_OK
) == 0)
2148 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2157 k
= cgfs_get_key(controller
, path1
, path2
);
2159 if ((mode
& W_OK
) == 0)
2167 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2170 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2174 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2186 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2188 do_release_file_info(fi
);
2192 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2194 static bool wait_for_sock(int sock
, int timeout
)
2196 struct epoll_event ev
;
2197 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2199 if ((starttime
= time(NULL
)) < 0)
2202 if ((epfd
= epoll_create(1)) < 0) {
2203 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2207 ev
.events
= POLLIN_SET
;
2209 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2210 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2216 if ((now
= time(NULL
)) < 0) {
2221 deltatime
= (starttime
+ timeout
) - now
;
2222 if (deltatime
< 0) { // timeout
2227 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2228 if (ret
< 0 && errno
== EINTR
)
2230 saved_errno
= errno
;
2234 errno
= saved_errno
;
2240 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2242 if (!wait_for_sock(sockfd
, 2))
2244 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2247 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2249 struct msghdr msg
= { 0 };
2251 struct cmsghdr
*cmsg
;
2252 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2257 if (msgrecv(sock
, buf
, 1) != 1) {
2258 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2259 return SEND_CREDS_FAIL
;
2263 msg
.msg_control
= cmsgbuf
;
2264 msg
.msg_controllen
= sizeof(cmsgbuf
);
2266 cmsg
= CMSG_FIRSTHDR(&msg
);
2267 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2268 cmsg
->cmsg_level
= SOL_SOCKET
;
2269 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2270 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2272 msg
.msg_name
= NULL
;
2273 msg
.msg_namelen
= 0;
2277 iov
.iov_len
= sizeof(buf
);
2281 if (sendmsg(sock
, &msg
, 0) < 0) {
2282 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2284 return SEND_CREDS_NOTSK
;
2285 return SEND_CREDS_FAIL
;
2288 return SEND_CREDS_OK
;
2291 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2293 struct msghdr msg
= { 0 };
2295 struct cmsghdr
*cmsg
;
2296 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2307 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2308 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2312 if (write(sock
, buf
, 1) != 1) {
2313 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2317 msg
.msg_name
= NULL
;
2318 msg
.msg_namelen
= 0;
2319 msg
.msg_control
= cmsgbuf
;
2320 msg
.msg_controllen
= sizeof(cmsgbuf
);
2323 iov
.iov_len
= sizeof(buf
);
2327 if (!wait_for_sock(sock
, 2)) {
2328 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2331 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2333 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2337 cmsg
= CMSG_FIRSTHDR(&msg
);
2339 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2340 cmsg
->cmsg_level
== SOL_SOCKET
&&
2341 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2342 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2349 struct pid_ns_clone_args
{
2353 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2357 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2358 * with clone(). This simply writes '1' as ACK back to the parent
2359 * before calling the actual wrapped function.
2361 static int pid_ns_clone_wrapper(void *arg
) {
2362 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2365 close(args
->cpipe
[0]);
2366 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2367 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2368 close(args
->cpipe
[1]);
2369 return args
->wrapped(args
->sock
, args
->tpid
);
2373 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2374 * int value back over the socket. This shifts the pid from the
2375 * sender's pidns into tpid's pidns.
2377 static int pid_to_ns(int sock
, pid_t tpid
)
2382 while (recv_creds(sock
, &cred
, &v
)) {
2385 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2393 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2394 * in your old pidns. Only children which you clone will be in the target
2395 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2396 * actually convert pids.
2398 * Note: glibc's fork() does not respect pidns, which can lead to failed
2399 * assertions inside glibc (and thus failed forks) if the child's pid in
2400 * the pidns and the parent pid outside are identical. Using clone prevents
2403 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2405 int newnsfd
= -1, ret
, cpipe
[2];
2410 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2411 if (ret
< 0 || ret
>= sizeof(fnam
))
2413 newnsfd
= open(fnam
, O_RDONLY
);
2416 if (setns(newnsfd
, 0) < 0)
2420 if (pipe(cpipe
) < 0)
2423 struct pid_ns_clone_args args
= {
2427 .wrapped
= &pid_to_ns
2429 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2430 void *stack
= alloca(stack_size
);
2432 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2436 // give the child 1 second to be done forking and
2438 if (!wait_for_sock(cpipe
[0], 1))
2440 ret
= read(cpipe
[0], &v
, 1);
2441 if (ret
!= sizeof(char) || v
!= '1')
2444 if (!wait_for_pid(cpid
))
2450 * To read cgroup files with a particular pid, we will setns into the child
2451 * pidns, open a pipe, fork a child - which will be the first to really be in
2452 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2454 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2456 int sock
[2] = {-1, -1};
2457 char *tmpdata
= NULL
;
2459 pid_t qpid
, cpid
= -1;
2460 bool answer
= false;
2463 size_t sz
= 0, asz
= 0;
2465 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2469 * Now we read the pids from returned data one by one, pass
2470 * them into a child in the target namespace, read back the
2471 * translated pids, and put them into our to-return data
2474 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2475 perror("socketpair");
2484 if (!cpid
) // child - exits when done
2485 pid_to_ns_wrapper(sock
[1], tpid
);
2487 char *ptr
= tmpdata
;
2490 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2492 ret
= send_creds(sock
[0], &cred
, v
, true);
2494 if (ret
== SEND_CREDS_NOTSK
)
2496 if (ret
== SEND_CREDS_FAIL
)
2499 // read converted results
2500 if (!wait_for_sock(sock
[0], 2)) {
2501 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2504 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2505 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2508 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2510 ptr
= strchr(ptr
, '\n');
2516 cred
.pid
= getpid();
2518 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2519 // failed to ask child to exit
2520 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2530 if (sock
[0] != -1) {
2537 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2538 struct fuse_file_info
*fi
)
2540 struct fuse_context
*fc
= fuse_get_context();
2541 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2542 struct cgfs_files
*k
= NULL
;
2547 if (f
->type
!= LXC_TYPE_CGFILE
) {
2548 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2561 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2567 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2572 if (strcmp(f
->file
, "tasks") == 0 ||
2573 strcmp(f
->file
, "/tasks") == 0 ||
2574 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2575 strcmp(f
->file
, "cgroup.procs") == 0)
2576 // special case - we have to translate the pids
2577 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2579 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2593 memcpy(buf
, data
, s
);
2594 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2604 static int pid_from_ns(int sock
, pid_t tpid
)
2614 if (!wait_for_sock(sock
, 2)) {
2615 lxcfs_error("%s\n", "Timeout reading from parent.");
2618 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2619 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2622 if (vpid
== -1) // done
2626 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2628 cred
.pid
= getpid();
2629 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2636 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2638 int newnsfd
= -1, ret
, cpipe
[2];
2643 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2644 if (ret
< 0 || ret
>= sizeof(fnam
))
2646 newnsfd
= open(fnam
, O_RDONLY
);
2649 if (setns(newnsfd
, 0) < 0)
2653 if (pipe(cpipe
) < 0)
2656 struct pid_ns_clone_args args
= {
2660 .wrapped
= &pid_from_ns
2662 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2663 void *stack
= alloca(stack_size
);
2665 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2669 // give the child 1 second to be done forking and
2671 if (!wait_for_sock(cpipe
[0], 1))
2673 ret
= read(cpipe
[0], &v
, 1);
2674 if (ret
!= sizeof(char) || v
!= '1')
2677 if (!wait_for_pid(cpid
))
2683 * Given host @uid, return the uid to which it maps in
2684 * @pid's user namespace, or -1 if none.
2686 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2691 sprintf(line
, "/proc/%d/uid_map", pid
);
2692 if ((f
= fopen(line
, "r")) == NULL
) {
2696 *answer
= convert_id_to_ns(f
, uid
);
2705 * get_pid_creds: get the real uid and gid of @pid from
2707 * (XXX should we use euid here?)
2709 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2718 sprintf(line
, "/proc/%d/status", pid
);
2719 if ((f
= fopen(line
, "r")) == NULL
) {
2720 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2723 while (fgets(line
, 400, f
)) {
2724 if (strncmp(line
, "Uid:", 4) == 0) {
2725 if (sscanf(line
+4, "%u", &u
) != 1) {
2726 lxcfs_error("bad uid line for pid %u\n", pid
);
2731 } else if (strncmp(line
, "Gid:", 4) == 0) {
2732 if (sscanf(line
+4, "%u", &g
) != 1) {
2733 lxcfs_error("bad gid line for pid %u\n", pid
);
2744 * May the requestor @r move victim @v to a new cgroup?
2745 * This is allowed if
2746 * . they are the same task
2747 * . they are ownedy by the same uid
2748 * . @r is root on the host, or
2749 * . @v's uid is mapped into @r's where @r is root.
2751 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2753 uid_t v_uid
, tmpuid
;
2760 get_pid_creds(v
, &v_uid
, &v_gid
);
2763 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2764 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2769 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2770 const char *file
, const char *buf
)
2772 int sock
[2] = {-1, -1};
2773 pid_t qpid
, cpid
= -1;
2774 FILE *pids_file
= NULL
;
2775 bool answer
= false, fail
= false;
2777 pids_file
= open_pids_file(contrl
, cg
);
2782 * write the pids to a socket, have helper in writer's pidns
2783 * call movepid for us
2785 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2786 perror("socketpair");
2794 if (!cpid
) { // child
2796 pid_from_ns_wrapper(sock
[1], tpid
);
2799 const char *ptr
= buf
;
2800 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2804 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2805 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2809 if (recv_creds(sock
[0], &cred
, &v
)) {
2811 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2815 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2820 ptr
= strchr(ptr
, '\n');
2826 /* All good, write the value */
2828 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2829 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2837 if (sock
[0] != -1) {
2842 if (fclose(pids_file
) != 0)
2848 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2849 struct fuse_file_info
*fi
)
2851 struct fuse_context
*fc
= fuse_get_context();
2852 char *localbuf
= NULL
;
2853 struct cgfs_files
*k
= NULL
;
2854 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2857 if (f
->type
!= LXC_TYPE_CGFILE
) {
2858 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2868 localbuf
= alloca(size
+1);
2869 localbuf
[size
] = '\0';
2870 memcpy(localbuf
, buf
, size
);
2872 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2877 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2882 if (strcmp(f
->file
, "tasks") == 0 ||
2883 strcmp(f
->file
, "/tasks") == 0 ||
2884 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2885 strcmp(f
->file
, "cgroup.procs") == 0)
2886 // special case - we have to translate the pids
2887 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2889 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2899 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2901 struct fuse_context
*fc
= fuse_get_context();
2902 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2903 struct cgfs_files
*k
= NULL
;
2910 if (strcmp(path
, "/cgroup") == 0)
2913 controller
= pick_controller_from_path(fc
, path
);
2915 return errno
== ENOENT
? -EPERM
: -errno
;
2917 cgroup
= find_cgroup_in_path(path
);
2919 /* this is just /cgroup/controller */
2922 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2932 if (is_child_cgroup(controller
, path1
, path2
)) {
2933 // get uid, gid, from '/tasks' file and make up a mode
2934 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2935 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2938 k
= cgfs_get_key(controller
, path1
, path2
);
2946 * This being a fuse request, the uid and gid must be valid
2947 * in the caller's namespace. So we can just check to make
2948 * sure that the caller is root in his uid, and privileged
2949 * over the file's current owner.
2951 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2956 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2965 int cg_chmod(const char *path
, mode_t mode
)
2967 struct fuse_context
*fc
= fuse_get_context();
2968 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2969 struct cgfs_files
*k
= NULL
;
2976 if (strcmp(path
, "/cgroup") == 0)
2979 controller
= pick_controller_from_path(fc
, path
);
2981 return errno
== ENOENT
? -EPERM
: -errno
;
2983 cgroup
= find_cgroup_in_path(path
);
2985 /* this is just /cgroup/controller */
2988 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2998 if (is_child_cgroup(controller
, path1
, path2
)) {
2999 // get uid, gid, from '/tasks' file and make up a mode
3000 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3001 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3004 k
= cgfs_get_key(controller
, path1
, path2
);
3012 * This being a fuse request, the uid and gid must be valid
3013 * in the caller's namespace. So we can just check to make
3014 * sure that the caller is root in his uid, and privileged
3015 * over the file's current owner.
3017 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3022 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3034 int cg_mkdir(const char *path
, mode_t mode
)
3036 struct fuse_context
*fc
= fuse_get_context();
3037 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3044 controller
= pick_controller_from_path(fc
, path
);
3046 return errno
== ENOENT
? -EPERM
: -errno
;
3048 cgroup
= find_cgroup_in_path(path
);
3052 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3058 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3061 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3064 else if (last
&& strcmp(next
, last
) == 0)
3071 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3075 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3080 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3088 int cg_rmdir(const char *path
)
3090 struct fuse_context
*fc
= fuse_get_context();
3091 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3098 controller
= pick_controller_from_path(fc
, path
);
3099 if (!controller
) /* Someone's trying to delete "/cgroup". */
3102 cgroup
= find_cgroup_in_path(path
);
3103 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3106 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3108 /* Someone's trying to delete a cgroup on the same level as the
3109 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3110 * rmdir "/cgroup/blkio/init.slice".
3116 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3119 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3120 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3127 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3131 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3136 if (!cgfs_remove(controller
, cgroup
)) {
3149 static bool startswith(const char *line
, const char *pref
)
3151 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3156 static void parse_memstat(char *memstat
, unsigned long *cached
,
3157 unsigned long *active_anon
, unsigned long *inactive_anon
,
3158 unsigned long *active_file
, unsigned long *inactive_file
,
3159 unsigned long *unevictable
)
3164 if (startswith(memstat
, "total_cache")) {
3165 sscanf(memstat
+ 11, "%lu", cached
);
3167 } else if (startswith(memstat
, "total_active_anon")) {
3168 sscanf(memstat
+ 17, "%lu", active_anon
);
3169 *active_anon
/= 1024;
3170 } else if (startswith(memstat
, "total_inactive_anon")) {
3171 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3172 *inactive_anon
/= 1024;
3173 } else if (startswith(memstat
, "total_active_file")) {
3174 sscanf(memstat
+ 17, "%lu", active_file
);
3175 *active_file
/= 1024;
3176 } else if (startswith(memstat
, "total_inactive_file")) {
3177 sscanf(memstat
+ 19, "%lu", inactive_file
);
3178 *inactive_file
/= 1024;
3179 } else if (startswith(memstat
, "total_unevictable")) {
3180 sscanf(memstat
+ 17, "%lu", unevictable
);
3181 *unevictable
/= 1024;
3183 eol
= strchr(memstat
, '\n');
3190 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3196 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3198 size_t len
= strlen(key
);
3202 if (startswith(str
, key
)) {
3203 sscanf(str
+ len
, "%lu", v
);
3206 eol
= strchr(str
, '\n');
3213 static int read_file(const char *path
, char *buf
, size_t size
,
3214 struct file_info
*d
)
3216 size_t linelen
= 0, total_len
= 0, rv
= 0;
3218 char *cache
= d
->buf
;
3219 size_t cache_size
= d
->buflen
;
3220 FILE *f
= fopen(path
, "r");
3224 while (getline(&line
, &linelen
, f
) != -1) {
3225 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3227 perror("Error writing to cache");
3231 if (l
>= cache_size
) {
3232 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3241 d
->size
= total_len
;
3242 if (total_len
> size
)
3245 /* read from off 0 */
3246 memcpy(buf
, d
->buf
, total_len
);
3255 * FUSE ops for /proc
3258 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3260 char *memlimit_str
= NULL
;
3261 unsigned long memlimit
= -1;
3263 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3264 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3271 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3273 char *copy
= strdupa(cgroup
);
3274 unsigned long memlimit
= 0, retlimit
;
3276 retlimit
= get_memlimit(copy
, file
);
3278 while (strcmp(copy
, "/") != 0) {
3279 copy
= dirname(copy
);
3280 memlimit
= get_memlimit(copy
, file
);
3281 if (memlimit
!= -1 && memlimit
< retlimit
)
3282 retlimit
= memlimit
;
3288 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3289 struct fuse_file_info
*fi
)
3291 struct fuse_context
*fc
= fuse_get_context();
3292 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3294 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3295 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3296 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3297 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3298 active_file
= 0, inactive_file
= 0, unevictable
= 0,
3301 size_t linelen
= 0, total_len
= 0, rv
= 0;
3302 char *cache
= d
->buf
;
3303 size_t cache_size
= d
->buflen
;
3307 if (offset
> d
->size
)
3311 int left
= d
->size
- offset
;
3312 total_len
= left
> size
? size
: left
;
3313 memcpy(buf
, cache
+ offset
, total_len
);
3317 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3320 cg
= get_pid_cgroup(initpid
, "memory");
3322 return read_file("/proc/meminfo", buf
, size
, d
);
3323 prune_init_slice(cg
);
3325 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3326 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3328 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3331 // Following values are allowed to fail, because swapaccount might be turned
3332 // off for current kernel
3333 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3334 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3336 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3337 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3339 memswlimit
= memswlimit
/ 1024;
3340 memswusage
= memswusage
/ 1024;
3343 memusage
= strtoul(memusage_str
, NULL
, 10);
3347 parse_memstat(memstat_str
, &cached
, &active_anon
,
3348 &inactive_anon
, &active_file
, &inactive_file
,
3351 f
= fopen("/proc/meminfo", "r");
3355 while (getline(&line
, &linelen
, f
) != -1) {
3357 char *printme
, lbuf
[100];
3359 memset(lbuf
, 0, 100);
3360 if (startswith(line
, "MemTotal:")) {
3361 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3362 if (hosttotal
< memlimit
)
3363 memlimit
= hosttotal
;
3364 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3366 } else if (startswith(line
, "MemFree:")) {
3367 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3369 } else if (startswith(line
, "MemAvailable:")) {
3370 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3372 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3373 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3374 if (hostswtotal
< memswlimit
)
3375 memswlimit
= hostswtotal
;
3376 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3378 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3379 unsigned long swaptotal
= memswlimit
,
3380 swapusage
= memswusage
- memusage
,
3381 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3382 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3384 } else if (startswith(line
, "Slab:")) {
3385 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3387 } else if (startswith(line
, "Buffers:")) {
3388 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3390 } else if (startswith(line
, "Cached:")) {
3391 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3393 } else if (startswith(line
, "SwapCached:")) {
3394 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3396 } else if (startswith(line
, "Active:")) {
3397 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3398 active_anon
+ active_file
);
3400 } else if (startswith(line
, "Inactive:")) {
3401 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3402 inactive_anon
+ inactive_file
);
3404 } else if (startswith(line
, "Active(anon)")) {
3405 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3407 } else if (startswith(line
, "Inactive(anon)")) {
3408 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3410 } else if (startswith(line
, "Active(file)")) {
3411 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3413 } else if (startswith(line
, "Inactive(file)")) {
3414 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3416 } else if (startswith(line
, "Unevictable")) {
3417 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3419 } else if (startswith(line
, "SReclaimable")) {
3420 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3422 } else if (startswith(line
, "SUnreclaim")) {
3423 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3428 l
= snprintf(cache
, cache_size
, "%s", printme
);
3430 perror("Error writing to cache");
3435 if (l
>= cache_size
) {
3436 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3447 d
->size
= total_len
;
3448 if (total_len
> size
) total_len
= size
;
3449 memcpy(buf
, d
->buf
, total_len
);
3458 free(memswlimit_str
);
3459 free(memswusage_str
);
3465 * Read the cpuset.cpus for cg
3466 * Return the answer in a newly allocated string which must be freed
3468 static char *get_cpuset(const char *cg
)
3472 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3477 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3479 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3483 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3485 return cpu_in_cpuset(cpu
, cpuset
);
3489 * check whether this is a '^processor" line in /proc/cpuinfo
3491 static bool is_processor_line(const char *line
)
3495 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3500 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3501 struct fuse_file_info
*fi
)
3503 struct fuse_context
*fc
= fuse_get_context();
3504 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3506 char *cpuset
= NULL
;
3508 size_t linelen
= 0, total_len
= 0, rv
= 0;
3509 bool am_printing
= false, firstline
= true, is_s390x
= false;
3510 int curcpu
= -1, cpu
;
3511 char *cache
= d
->buf
;
3512 size_t cache_size
= d
->buflen
;
3516 if (offset
> d
->size
)
3520 int left
= d
->size
- offset
;
3521 total_len
= left
> size
? size
: left
;
3522 memcpy(buf
, cache
+ offset
, total_len
);
3526 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3529 cg
= get_pid_cgroup(initpid
, "cpuset");
3531 return read_file("proc/cpuinfo", buf
, size
, d
);
3532 prune_init_slice(cg
);
3534 cpuset
= get_cpuset(cg
);
3538 f
= fopen("/proc/cpuinfo", "r");
3542 while (getline(&line
, &linelen
, f
) != -1) {
3546 if (strstr(line
, "IBM/S390") != NULL
) {
3552 if (strncmp(line
, "# processors:", 12) == 0)
3554 if (is_processor_line(line
)) {
3555 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3558 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3560 perror("Error writing to cache");
3564 if (l
>= cache_size
) {
3565 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3574 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3576 if (!cpu_in_cpuset(cpu
, cpuset
))
3579 p
= strchr(line
, ':');
3583 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3585 perror("Error writing to cache");
3589 if (l
>= cache_size
) {
3590 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3601 l
= snprintf(cache
, cache_size
, "%s", line
);
3603 perror("Error writing to cache");
3607 if (l
>= cache_size
) {
3608 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3619 char *origcache
= d
->buf
;
3622 d
->buf
= malloc(d
->buflen
);
3625 cache_size
= d
->buflen
;
3627 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3628 if (l
< 0 || l
>= cache_size
) {
3635 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3636 if (l
< 0 || l
>= cache_size
) {
3643 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3645 if (l
< 0 || l
>= cache_size
)
3651 d
->size
= total_len
;
3652 if (total_len
> size
) total_len
= size
;
3654 /* read from off 0 */
3655 memcpy(buf
, d
->buf
, total_len
);
3666 static uint64_t get_reaper_start_time(pid_t pid
)
3671 /* strlen("/proc/") = 6
3675 * strlen("/stat") = 5
3679 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3680 char path
[__PROC_PID_STAT_LEN
];
3683 qpid
= lookup_initpid_in_store(pid
);
3685 /* Caller can check for EINVAL on 0. */
3690 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3691 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3692 /* Caller can check for EINVAL on 0. */
3697 f
= fopen(path
, "r");
3699 /* Caller can check for EINVAL on 0. */
3704 /* Note that the *scanf() argument supression requires that length
3705 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3706 * at us. It's like telling someone you're not married and then asking
3707 * if you can bring your wife to the party.
3709 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3710 "%*s " /* (2) comm %s */
3711 "%*c " /* (3) state %c */
3712 "%*d " /* (4) ppid %d */
3713 "%*d " /* (5) pgrp %d */
3714 "%*d " /* (6) session %d */
3715 "%*d " /* (7) tty_nr %d */
3716 "%*d " /* (8) tpgid %d */
3717 "%*u " /* (9) flags %u */
3718 "%*u " /* (10) minflt %lu */
3719 "%*u " /* (11) cminflt %lu */
3720 "%*u " /* (12) majflt %lu */
3721 "%*u " /* (13) cmajflt %lu */
3722 "%*u " /* (14) utime %lu */
3723 "%*u " /* (15) stime %lu */
3724 "%*d " /* (16) cutime %ld */
3725 "%*d " /* (17) cstime %ld */
3726 "%*d " /* (18) priority %ld */
3727 "%*d " /* (19) nice %ld */
3728 "%*d " /* (20) num_threads %ld */
3729 "%*d " /* (21) itrealvalue %ld */
3730 "%" PRIu64
, /* (22) starttime %llu */
3734 /* Caller can check for EINVAL on 0. */
3745 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3747 uint64_t clockticks
;
3748 int64_t ticks_per_sec
;
3750 clockticks
= get_reaper_start_time(pid
);
3751 if (clockticks
== 0 && errno
== EINVAL
) {
3752 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3756 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3757 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3760 "failed to determine number of clock ticks in a second");
3764 return (clockticks
/= ticks_per_sec
);
3767 static uint64_t get_reaper_age(pid_t pid
)
3769 uint64_t procstart
, uptime
, procage
;
3771 /* We need to substract the time the process has started since system
3772 * boot minus the time when the system has started to get the actual
3775 procstart
= get_reaper_start_time_in_sec(pid
);
3776 procage
= procstart
;
3777 if (procstart
> 0) {
3779 struct timespec spec
;
3781 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3784 /* We could make this more precise here by using the tv_nsec
3785 * field in the timespec struct and convert it to milliseconds
3786 * and then create a double for the seconds and milliseconds but
3787 * that seems more work than it is worth.
3789 uptime
= spec
.tv_sec
;
3790 procage
= uptime
- procstart
;
3796 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
3797 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
3798 struct fuse_file_info
*fi
)
3800 struct fuse_context
*fc
= fuse_get_context();
3801 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3803 char *cpuset
= NULL
;
3805 size_t linelen
= 0, total_len
= 0, rv
= 0;
3806 int curcpu
= -1; /* cpu numbering starts at 0 */
3807 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
3808 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
3809 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
3810 char cpuall
[CPUALL_MAX_SIZE
];
3811 /* reserve for cpu all */
3812 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
3813 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
3817 if (offset
> d
->size
)
3821 int left
= d
->size
- offset
;
3822 total_len
= left
> size
? size
: left
;
3823 memcpy(buf
, d
->buf
+ offset
, total_len
);
3827 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3830 cg
= get_pid_cgroup(initpid
, "cpuset");
3832 return read_file("/proc/stat", buf
, size
, d
);
3833 prune_init_slice(cg
);
3835 cpuset
= get_cpuset(cg
);
3839 f
= fopen("/proc/stat", "r");
3844 if (getline(&line
, &linelen
, f
) < 0) {
3845 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
3849 while (getline(&line
, &linelen
, f
) != -1) {
3852 char cpu_char
[10]; /* That's a lot of cores */
3855 if (strlen(line
) == 0)
3857 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
3858 /* not a ^cpuN line containing a number N, just print it */
3859 l
= snprintf(cache
, cache_size
, "%s", line
);
3861 perror("Error writing to cache");
3865 if (l
>= cache_size
) {
3866 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3876 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
3878 if (!cpu_in_cpuset(cpu
, cpuset
))
3882 c
= strchr(line
, ' ');
3885 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
3887 perror("Error writing to cache");
3892 if (l
>= cache_size
) {
3893 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3902 if (sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
3916 system_sum
+= system
;
3918 iowait_sum
+= iowait
;
3920 softirq_sum
+= softirq
;
3923 guest_nice_sum
+= guest_nice
;
3928 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
3939 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
3940 memcpy(cache
, cpuall
, cpuall_len
);
3941 cache
+= cpuall_len
;
3943 /* shouldn't happen */
3944 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
3948 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
3949 total_len
+= cpuall_len
;
3951 d
->size
= total_len
;
3952 if (total_len
> size
)
3955 memcpy(buf
, d
->buf
, total_len
);
3967 /* This function retrieves the busy time of a group of tasks by looking at
3968 * cpuacct.usage. Unfortunately, this only makes sense when the container has
3969 * been given it's own cpuacct cgroup. If not, this function will take the busy
3970 * time of all other taks that do not actually belong to the container into
3971 * account as well. If someone has a clever solution for this please send a
3974 static unsigned long get_reaper_busy(pid_t task
)
3976 pid_t initpid
= lookup_initpid_in_store(task
);
3977 char *cgroup
= NULL
, *usage_str
= NULL
;
3978 unsigned long usage
= 0;
3983 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
3986 prune_init_slice(cgroup
);
3987 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
3989 usage
= strtoul(usage_str
, NULL
, 10);
3990 usage
/= 1000000000;
4003 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4010 * We read /proc/uptime and reuse its second field.
4011 * For the first field, we use the mtime for the reaper for
4012 * the calling pid as returned by getreaperage
4014 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4015 struct fuse_file_info
*fi
)
4017 struct fuse_context
*fc
= fuse_get_context();
4018 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4019 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
4020 char *cache
= d
->buf
;
4021 ssize_t total_len
= 0;
4022 uint64_t idletime
, reaperage
;
4031 if (offset
> d
->size
)
4033 int left
= d
->size
- offset
;
4034 total_len
= left
> size
? size
: left
;
4035 memcpy(buf
, cache
+ offset
, total_len
);
4039 reaperage
= get_reaper_age(fc
->pid
);
4040 /* To understand why this is done, please read the comment to the
4041 * get_reaper_busy() function.
4043 idletime
= reaperage
;
4044 if (reaperage
>= busytime
)
4045 idletime
= reaperage
- busytime
;
4047 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
4048 if (total_len
< 0 || total_len
>= d
->buflen
){
4049 lxcfs_error("%s\n", "failed to write to cache");
4053 d
->size
= (int)total_len
;
4056 if (total_len
> size
) total_len
= size
;
4058 memcpy(buf
, d
->buf
, total_len
);
4062 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
4063 struct fuse_file_info
*fi
)
4066 struct fuse_context
*fc
= fuse_get_context();
4067 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4069 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
4070 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
4071 unsigned long read
= 0, write
= 0;
4072 unsigned long read_merged
= 0, write_merged
= 0;
4073 unsigned long read_sectors
= 0, write_sectors
= 0;
4074 unsigned long read_ticks
= 0, write_ticks
= 0;
4075 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
4076 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
4077 char *cache
= d
->buf
;
4078 size_t cache_size
= d
->buflen
;
4080 size_t linelen
= 0, total_len
= 0, rv
= 0;
4081 unsigned int major
= 0, minor
= 0;
4086 if (offset
> d
->size
)
4090 int left
= d
->size
- offset
;
4091 total_len
= left
> size
? size
: left
;
4092 memcpy(buf
, cache
+ offset
, total_len
);
4096 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4099 cg
= get_pid_cgroup(initpid
, "blkio");
4101 return read_file("/proc/diskstats", buf
, size
, d
);
4102 prune_init_slice(cg
);
4104 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
4106 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
4108 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
4110 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
4112 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
4116 f
= fopen("/proc/diskstats", "r");
4120 while (getline(&line
, &linelen
, f
) != -1) {
4124 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
4128 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
4129 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
4130 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
4131 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
4132 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
4133 read_sectors
= read_sectors
/512;
4134 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
4135 write_sectors
= write_sectors
/512;
4137 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
4138 rd_svctm
= rd_svctm
/1000000;
4139 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
4140 rd_wait
= rd_wait
/1000000;
4141 read_ticks
= rd_svctm
+ rd_wait
;
4143 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
4144 wr_svctm
= wr_svctm
/1000000;
4145 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
4146 wr_wait
= wr_wait
/1000000;
4147 write_ticks
= wr_svctm
+ wr_wait
;
4149 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
4150 tot_ticks
= tot_ticks
/1000000;
4152 memset(lbuf
, 0, 256);
4153 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
4154 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4155 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
4156 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
4160 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
4162 perror("Error writing to fuse buf");
4166 if (l
>= cache_size
) {
4167 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4177 d
->size
= total_len
;
4178 if (total_len
> size
) total_len
= size
;
4179 memcpy(buf
, d
->buf
, total_len
);
4187 free(io_serviced_str
);
4188 free(io_merged_str
);
4189 free(io_service_bytes_str
);
4190 free(io_wait_time_str
);
4191 free(io_service_time_str
);
4195 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
4196 struct fuse_file_info
*fi
)
4198 struct fuse_context
*fc
= fuse_get_context();
4199 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4201 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
4202 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
4203 ssize_t total_len
= 0, rv
= 0;
4205 char *cache
= d
->buf
;
4208 if (offset
> d
->size
)
4212 int left
= d
->size
- offset
;
4213 total_len
= left
> size
? size
: left
;
4214 memcpy(buf
, cache
+ offset
, total_len
);
4218 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4221 cg
= get_pid_cgroup(initpid
, "memory");
4223 return read_file("/proc/swaps", buf
, size
, d
);
4224 prune_init_slice(cg
);
4226 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
4228 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
4231 memusage
= strtoul(memusage_str
, NULL
, 10);
4233 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
4234 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
4236 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
4237 memswusage
= strtoul(memswusage_str
, NULL
, 10);
4239 swap_total
= (memswlimit
- memlimit
) / 1024;
4240 swap_free
= (memswusage
- memusage
) / 1024;
4243 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
4245 /* When no mem + swap limit is specified or swapaccount=0*/
4249 FILE *f
= fopen("/proc/meminfo", "r");
4254 while (getline(&line
, &linelen
, f
) != -1) {
4255 if (startswith(line
, "SwapTotal:")) {
4256 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
4257 } else if (startswith(line
, "SwapFree:")) {
4258 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
4266 if (swap_total
> 0) {
4267 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
4268 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
4269 swap_total
, swap_free
);
4273 if (total_len
< 0 || l
< 0) {
4274 perror("Error writing to cache");
4280 d
->size
= (int)total_len
;
4282 if (total_len
> size
) total_len
= size
;
4283 memcpy(buf
, d
->buf
, total_len
);
4288 free(memswlimit_str
);
4291 free(memswusage_str
);
4295 * Find the process pid from cgroup path.
4296 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
4297 * @pid_buf : put pid to pid_buf.
4298 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
4299 * @depth : the depth of cgroup in container.
4300 * @sum : return the number of pid.
4301 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
4303 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
4307 struct dirent
*file
;
4312 char *path_dir
, *path
;
4315 /* path = dpath + "/cgroup.procs" + /0 */
4317 path
= malloc(strlen(dpath
) + 20);
4320 strcpy(path
, dpath
);
4321 fd
= openat(cfd
, path
, O_RDONLY
);
4325 dir
= fdopendir(fd
);
4331 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
4332 if (strncmp(file
->d_name
, ".", 1) == 0)
4334 if (strncmp(file
->d_name
, "..", 1) == 0)
4336 if (file
->d_type
== DT_DIR
) {
4337 /* path + '/' + d_name +/0 */
4339 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
4340 } while (!path_dir
);
4341 strcpy(path_dir
, path
);
4342 strcat(path_dir
, "/");
4343 strcat(path_dir
, file
->d_name
);
4345 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
4351 strcat(path
, "/cgroup.procs");
4352 fd
= openat(cfd
, path
, O_RDONLY
);
4356 f
= fdopen(fd
, "r");
4362 while (getline(&line
, &linelen
, f
) != -1) {
4364 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
4368 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
4369 } while (*(*pid_buf
+ sum
) == NULL
);
4370 strcpy(*(*pid_buf
+ sum
), line
);
4379 * calc_load calculates the load according to the following formula:
4380 * load1 = load0 * exp + active * (1 - exp)
4382 * @load1: the new loadavg.
4383 * @load0: the former loadavg.
4384 * @active: the total number of running pid at this moment.
4385 * @exp: the fixed-point defined in the beginning.
4387 static unsigned long
4388 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
4390 unsigned long newload
;
4392 active
= active
> 0 ? active
* FIXED_1
: 0;
4393 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
4395 newload
+= FIXED_1
- 1;
4397 return newload
/ FIXED_1
;
4401 * Return 0 means that container p->cg is closed.
4402 * Return -1 means that error occurred in refresh.
4403 * Positive num equals the total number of pid.
4405 static int refresh_load(struct load_node
*p
, char *path
)
4409 char proc_path
[256];
4410 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
4415 struct dirent
*file
;
4418 idbuf
= malloc(sizeof(char *));
4420 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
4425 for (i
= 0; i
< sum
; i
++) {
4427 length
= strlen(idbuf
[i
])-1;
4428 idbuf
[i
][length
] = '\0';
4429 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
4430 if (ret
< 0 || ret
> 255) {
4431 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4437 dp
= opendir(proc_path
);
4439 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
4442 while ((file
= readdir(dp
)) != NULL
) {
4443 if (strncmp(file
->d_name
, ".", 1) == 0)
4445 if (strncmp(file
->d_name
, "..", 1) == 0)
4448 /* We make the biggest pid become last_pid.*/
4449 ret
= atof(file
->d_name
);
4450 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
4452 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
4453 if (ret
< 0 || ret
> 255) {
4454 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
4460 f
= fopen(proc_path
, "r");
4462 while (getline(&line
, &linelen
, f
) != -1) {
4464 if ((line
[0] == 'S') && (line
[1] == 't'))
4467 if ((line
[7] == 'R') || (line
[7] == 'D'))
4474 /*Calculate the loadavg.*/
4475 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
4476 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
4477 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
4478 p
->run_pid
= run_pid
;
4479 p
->total_pid
= total_pid
;
4480 p
->last_pid
= last_pid
;
4491 * Traverse the hash table and update it.
4493 void *load_begin(void *arg
)
4497 int i
, sum
, length
, ret
;
4498 struct load_node
*f
;
4500 clock_t time1
, time2
;
4504 for (i
= 0; i
< LOAD_SIZE
; i
++) {
4505 pthread_mutex_lock(&load_hash
[i
].lock
);
4506 if (load_hash
[i
].next
== NULL
) {
4507 pthread_mutex_unlock(&load_hash
[i
].lock
);
4510 f
= load_hash
[i
].next
;
4513 length
= strlen(f
->cg
) + 2;
4515 /* strlen(f->cg) + '.' or '' + \0 */
4516 path
= malloc(length
);
4519 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
4520 if (ret
< 0 || ret
> length
- 1) {
4521 /* snprintf failed, ignore the node.*/
4522 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
4525 sum
= refresh_load(f
, path
);
4532 /* load_hash[i].lock locks only on the first node.*/
4533 if (first_node
== 1) {
4535 pthread_mutex_unlock(&load_hash
[i
].lock
);
4540 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
4544 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
4545 struct fuse_file_info
*fi
)
4547 struct fuse_context
*fc
= fuse_get_context();
4548 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4551 size_t total_len
= 0;
4552 char *cache
= d
->buf
;
4553 struct load_node
*n
;
4556 unsigned long a
, b
, c
;
4559 if (offset
> d
->size
)
4563 int left
= d
->size
- offset
;
4564 total_len
= left
> size
? size
: left
;
4565 memcpy(buf
, cache
+ offset
, total_len
);
4569 return read_file("/proc/loadavg", buf
, size
, d
);
4571 initpid
= lookup_initpid_in_store(fc
->pid
);
4574 cg
= get_pid_cgroup(initpid
, "cpu");
4576 return read_file("/proc/loadavg", buf
, size
, d
);
4578 prune_init_slice(cg
);
4579 hash
= calc_hash(cg
);
4580 n
= locate_node(cg
, hash
);
4584 if (!find_mounted_controller("cpu", &cfd
)) {
4586 * In locate_node() above, pthread_rwlock_unlock() isn't used
4587 * because delete is not allowed before read has ended.
4589 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4593 n
= malloc(sizeof(struct load_node
));
4597 n
->cg
= malloc(strlen(cg
)+1);
4605 n
->last_pid
= initpid
;
4607 insert_node(&n
, hash
);
4609 a
= n
->avenrun
[0] + (FIXED_1
/200);
4610 b
= n
->avenrun
[1] + (FIXED_1
/200);
4611 c
= n
->avenrun
[2] + (FIXED_1
/200);
4612 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
4613 LOAD_INT(a
), LOAD_FRAC(a
),
4614 LOAD_INT(b
), LOAD_FRAC(b
),
4615 LOAD_INT(c
), LOAD_FRAC(c
),
4616 n
->run_pid
, n
->total_pid
, n
->last_pid
);
4617 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
4618 if (total_len
< 0 || total_len
>= d
->buflen
) {
4619 lxcfs_error("%s\n", "Failed to write to cache");
4622 d
->size
= (int)total_len
;
4625 if (total_len
> size
)
4627 memcpy(buf
, d
->buf
, total_len
);
4630 /* Return a positive number on success, return 0 on failure.*/
4631 pthread_t
load_daemon(int load_use
)
4638 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
4641 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
4643 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
4647 /* use loadavg, here loadavg = 1*/
4652 static off_t
get_procfile_size(const char *which
)
4654 FILE *f
= fopen(which
, "r");
4657 ssize_t sz
, answer
= 0;
4661 while ((sz
= getline(&line
, &len
, f
)) != -1)
4669 int proc_getattr(const char *path
, struct stat
*sb
)
4671 struct timespec now
;
4673 memset(sb
, 0, sizeof(struct stat
));
4674 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
4676 sb
->st_uid
= sb
->st_gid
= 0;
4677 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
4678 if (strcmp(path
, "/proc") == 0) {
4679 sb
->st_mode
= S_IFDIR
| 00555;
4683 if (strcmp(path
, "/proc/meminfo") == 0 ||
4684 strcmp(path
, "/proc/cpuinfo") == 0 ||
4685 strcmp(path
, "/proc/uptime") == 0 ||
4686 strcmp(path
, "/proc/stat") == 0 ||
4687 strcmp(path
, "/proc/diskstats") == 0 ||
4688 strcmp(path
, "/proc/swaps") == 0 ||
4689 strcmp(path
, "/proc/loadavg") == 0) {
4691 sb
->st_mode
= S_IFREG
| 00444;
4699 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
4700 struct fuse_file_info
*fi
)
4702 if (filler(buf
, ".", NULL
, 0) != 0 ||
4703 filler(buf
, "..", NULL
, 0) != 0 ||
4704 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
4705 filler(buf
, "meminfo", NULL
, 0) != 0 ||
4706 filler(buf
, "stat", NULL
, 0) != 0 ||
4707 filler(buf
, "uptime", NULL
, 0) != 0 ||
4708 filler(buf
, "diskstats", NULL
, 0) != 0 ||
4709 filler(buf
, "swaps", NULL
, 0) != 0 ||
4710 filler(buf
, "loadavg", NULL
, 0) != 0)
4715 int proc_open(const char *path
, struct fuse_file_info
*fi
)
4718 struct file_info
*info
;
4720 if (strcmp(path
, "/proc/meminfo") == 0)
4721 type
= LXC_TYPE_PROC_MEMINFO
;
4722 else if (strcmp(path
, "/proc/cpuinfo") == 0)
4723 type
= LXC_TYPE_PROC_CPUINFO
;
4724 else if (strcmp(path
, "/proc/uptime") == 0)
4725 type
= LXC_TYPE_PROC_UPTIME
;
4726 else if (strcmp(path
, "/proc/stat") == 0)
4727 type
= LXC_TYPE_PROC_STAT
;
4728 else if (strcmp(path
, "/proc/diskstats") == 0)
4729 type
= LXC_TYPE_PROC_DISKSTATS
;
4730 else if (strcmp(path
, "/proc/swaps") == 0)
4731 type
= LXC_TYPE_PROC_SWAPS
;
4732 else if (strcmp(path
, "/proc/loadavg") == 0)
4733 type
= LXC_TYPE_PROC_LOADAVG
;
4737 info
= malloc(sizeof(*info
));
4741 memset(info
, 0, sizeof(*info
));
4744 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
4746 info
->buf
= malloc(info
->buflen
);
4747 } while (!info
->buf
);
4748 memset(info
->buf
, 0, info
->buflen
);
4749 /* set actual size to buffer size */
4750 info
->size
= info
->buflen
;
4752 fi
->fh
= (unsigned long)info
;
4756 int proc_access(const char *path
, int mask
)
4758 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
4761 /* these are all read-only */
4762 if ((mask
& ~R_OK
) != 0)
4767 int proc_release(const char *path
, struct fuse_file_info
*fi
)
4769 do_release_file_info(fi
);
4773 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
4774 struct fuse_file_info
*fi
)
4776 struct file_info
*f
= (struct file_info
*) fi
->fh
;
4779 case LXC_TYPE_PROC_MEMINFO
:
4780 return proc_meminfo_read(buf
, size
, offset
, fi
);
4781 case LXC_TYPE_PROC_CPUINFO
:
4782 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
4783 case LXC_TYPE_PROC_UPTIME
:
4784 return proc_uptime_read(buf
, size
, offset
, fi
);
4785 case LXC_TYPE_PROC_STAT
:
4786 return proc_stat_read(buf
, size
, offset
, fi
);
4787 case LXC_TYPE_PROC_DISKSTATS
:
4788 return proc_diskstats_read(buf
, size
, offset
, fi
);
4789 case LXC_TYPE_PROC_SWAPS
:
4790 return proc_swaps_read(buf
, size
, offset
, fi
);
4791 case LXC_TYPE_PROC_LOADAVG
:
4792 return proc_loadavg_read(buf
, size
, offset
, fi
);
4799 * Functions needed to setup cgroups in the __constructor__.
4802 static bool mkdir_p(const char *dir
, mode_t mode
)
4804 const char *tmp
= dir
;
4805 const char *orig
= dir
;
4809 dir
= tmp
+ strspn(tmp
, "/");
4810 tmp
= dir
+ strcspn(dir
, "/");
4811 makeme
= strndup(orig
, dir
- orig
);
4814 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
4815 lxcfs_error("Failed to create directory '%s': %s.\n",
4816 makeme
, strerror(errno
));
4821 } while(tmp
!= dir
);
4826 static bool umount_if_mounted(void)
4828 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
4829 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
4835 /* __typeof__ should be safe to use with all compilers. */
4836 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
4837 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
4839 return (fs
->f_type
== (fs_type_magic
)magic_val
);
4843 * looking at fs/proc_namespace.c, it appears we can
4844 * actually expect the rootfs entry to very specifically contain
4845 * " - rootfs rootfs "
4846 * IIUC, so long as we've chrooted so that rootfs is not our root,
4847 * the rootfs entry should always be skipped in mountinfo contents.
4849 static bool is_on_ramfs(void)
4857 f
= fopen("/proc/self/mountinfo", "r");
4861 while (getline(&line
, &len
, f
) != -1) {
4862 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
4863 p
= strchr(p
+ 1, ' ');
4866 p2
= strchr(p
+ 1, ' ');
4870 if (strcmp(p
+ 1, "/") == 0) {
4871 // this is '/'. is it the ramfs?
4872 p
= strchr(p2
+ 1, '-');
4873 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
4885 static int pivot_enter()
4887 int ret
= -1, oldroot
= -1, newroot
= -1;
4889 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
4891 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
4895 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
4897 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
4901 /* change into new root fs */
4902 if (fchdir(newroot
) < 0) {
4903 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
4907 /* pivot_root into our new root fs */
4908 if (pivot_root(".", ".") < 0) {
4909 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
4914 * At this point the old-root is mounted on top of our new-root.
4915 * To unmounted it we must not be chdir'd into it, so escape back
4918 if (fchdir(oldroot
) < 0) {
4919 lxcfs_error("%s\n", "Failed to enter old root.");
4923 if (umount2(".", MNT_DETACH
) < 0) {
4924 lxcfs_error("%s\n", "Failed to detach old root.");
4928 if (fchdir(newroot
) < 0) {
4929 lxcfs_error("%s\n", "Failed to re-enter new root.");
4944 static int chroot_enter()
4946 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
4947 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
4951 if (chroot(".") < 0) {
4952 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
4956 if (chdir("/") < 0) {
4957 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
4964 static int permute_and_enter(void)
4968 if (statfs("/", &sb
) < 0) {
4969 lxcfs_error("%s\n", "Could not stat / mountpoint.");
4973 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
4974 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
4975 * /proc/1/mountinfo. */
4976 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
4977 return chroot_enter();
4979 if (pivot_enter() < 0) {
4980 lxcfs_error("%s\n", "Could not perform pivot root.");
4987 /* Prepare our new clean root. */
4988 static int permute_prepare(void)
4990 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
4991 lxcfs_error("%s\n", "Failed to create directory for new root.");
4995 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
4996 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
5000 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
5001 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
5005 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
5006 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
5013 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
5014 static bool permute_root(void)
5016 /* Prepare new root. */
5017 if (permute_prepare() < 0)
5020 /* Pivot into new root. */
5021 if (permute_and_enter() < 0)
5027 static int preserve_mnt_ns(int pid
)
5030 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
5033 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
5034 if (ret
< 0 || (size_t)ret
>= len
)
5037 return open(path
, O_RDONLY
| O_CLOEXEC
);
5040 static bool cgfs_prepare_mounts(void)
5042 if (!mkdir_p(BASEDIR
, 0700)) {
5043 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
5047 if (!umount_if_mounted()) {
5048 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
5052 if (unshare(CLONE_NEWNS
) < 0) {
5053 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
5057 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
5058 if (cgroup_mount_ns_fd
< 0) {
5059 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
5063 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
5064 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
5068 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
5069 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
5076 static bool cgfs_mount_hierarchies(void)
5082 for (i
= 0; i
< num_hierarchies
; i
++) {
5083 char *controller
= hierarchies
[i
];
5085 clen
= strlen(controller
);
5086 len
= strlen(BASEDIR
) + clen
+ 2;
5087 target
= malloc(len
);
5091 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
5092 if (ret
< 0 || ret
>= len
) {
5096 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
5100 if (!strcmp(controller
, "unified"))
5101 ret
= mount("none", target
, "cgroup2", 0, NULL
);
5103 ret
= mount(controller
, target
, "cgroup", 0, controller
);
5105 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
5110 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
5111 if (fd_hierarchies
[i
] < 0) {
5120 static bool cgfs_setup_controllers(void)
5122 if (!cgfs_prepare_mounts())
5125 if (!cgfs_mount_hierarchies()) {
5126 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
5130 if (!permute_root())
5136 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
5139 char *cret
, *line
= NULL
;
5140 char cwd
[MAXPATHLEN
];
5142 int i
, init_ns
= -1;
5143 bool found_unified
= false;
5145 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
5146 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
5150 while (getline(&line
, &len
, f
) != -1) {
5153 p
= strchr(line
, ':');
5159 p2
= strrchr(p
, ':');
5164 /* With cgroupv2 /proc/self/cgroup can contain entries of the
5165 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
5166 * because it parses out the empty string "" and later on passes
5167 * it to mount(). Let's skip such entries.
5169 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
5170 found_unified
= true;
5174 if (!store_hierarchy(line
, p
))
5178 /* Preserve initial namespace. */
5179 init_ns
= preserve_mnt_ns(getpid());
5181 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
5185 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
5186 if (!fd_hierarchies
) {
5187 lxcfs_error("%s\n", strerror(errno
));
5191 for (i
= 0; i
< num_hierarchies
; i
++)
5192 fd_hierarchies
[i
] = -1;
5194 cret
= getcwd(cwd
, MAXPATHLEN
);
5196 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
5198 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
5199 * to privately mount lxcfs cgroups. */
5200 if (!cgfs_setup_controllers()) {
5201 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
5205 if (setns(init_ns
, 0) < 0) {
5206 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
5210 if (!cret
|| chdir(cwd
) < 0)
5211 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
5222 static void __attribute__((destructor
)) free_subsystems(void)
5226 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
5228 for (i
= 0; i
< num_hierarchies
; i
++) {
5230 free(hierarchies
[i
]);
5231 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
5232 close(fd_hierarchies
[i
]);
5235 free(fd_hierarchies
);
5237 if (cgroup_mount_ns_fd
>= 0)
5238 close(cgroup_mount_ns_fd
);