3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
11 #define __STDC_FORMAT_MACROS
28 #include <linux/magic.h>
29 #include <linux/sched.h>
30 #include <sys/epoll.h>
32 #include <sys/mount.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/sysinfo.h>
40 #include "config.h" // for VERSION
42 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
43 #define LXCFS_NUMSTRLEN64 21
45 /* Define pivot_root() if missing from the C library */
46 #ifndef HAVE_PIVOT_ROOT
47 static int pivot_root(const char * new_root
, const char * put_old
)
49 #ifdef __NR_pivot_root
50 return syscall(__NR_pivot_root
, new_root
, put_old
);
57 extern int pivot_root(const char * new_root
, const char * put_old
);
63 LXC_TYPE_PROC_MEMINFO
,
64 LXC_TYPE_PROC_CPUINFO
,
67 LXC_TYPE_PROC_DISKSTATS
,
69 LXC_TYPE_PROC_LOADAVG
,
77 char *buf
; // unused as of yet
79 int size
; //actual data size
83 struct cpuacct_usage
{
90 /* The function of hash table.*/
91 #define LOAD_SIZE 100 /*the size of hash_table */
92 #define FLUSH_TIME 5 /*the flush rate */
93 #define DEPTH_DIR 3 /*the depth of per cgroup */
94 /* The function of calculate loadavg .*/
95 #define FSHIFT 11 /* nr of bits of precision */
96 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
97 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
98 #define EXP_5 2014 /* 1/exp(5sec/5min) */
99 #define EXP_15 2037 /* 1/exp(5sec/15min) */
100 #define LOAD_INT(x) ((x) >> FSHIFT)
101 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
103 * This parameter is used for proc_loadavg_read().
104 * 1 means use loadavg, 0 means not use.
106 static int loadavg
= 0;
107 static volatile sig_atomic_t loadavg_stop
= 0;
108 static int calc_hash(const char *name
)
110 unsigned int hash
= 0;
112 /* ELFHash algorithm. */
114 hash
= (hash
<< 4) + *name
++;
115 x
= hash
& 0xf0000000;
120 return (hash
& 0x7fffffff);
125 unsigned long avenrun
[3]; /* Load averages */
126 unsigned int run_pid
;
127 unsigned int total_pid
;
128 unsigned int last_pid
;
129 int cfd
; /* The file descriptor of the mounted cgroup */
130 struct load_node
*next
;
131 struct load_node
**pre
;
136 * The lock is about insert load_node and refresh load_node.To the first
137 * load_node of each hash bucket, insert and refresh in this hash bucket is
138 * mutually exclusive.
140 pthread_mutex_t lock
;
142 * The rdlock is about read loadavg and delete load_node.To each hash
143 * bucket, read and delete is mutually exclusive. But at the same time, we
144 * allow paratactic read operation. This rdlock is at list level.
146 pthread_rwlock_t rdlock
;
148 * The rilock is about read loadavg and insert load_node.To the first
149 * load_node of each hash bucket, read and insert is mutually exclusive.
150 * But at the same time, we allow paratactic read operation.
152 pthread_rwlock_t rilock
;
153 struct load_node
*next
;
156 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
158 * init_load initialize the hash table.
159 * Return 0 on success, return -1 on failure.
161 static int init_load(void)
166 for (i
= 0; i
< LOAD_SIZE
; i
++) {
167 load_hash
[i
].next
= NULL
;
168 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
170 lxcfs_error("%s\n", "Failed to initialize lock");
173 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
175 lxcfs_error("%s\n", "Failed to initialize rdlock");
178 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
180 lxcfs_error("%s\n", "Failed to initialize rilock");
186 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
188 pthread_mutex_destroy(&load_hash
[i
].lock
);
192 pthread_mutex_destroy(&load_hash
[i
].lock
);
193 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
194 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
199 static void insert_node(struct load_node
**n
, int locate
)
203 pthread_mutex_lock(&load_hash
[locate
].lock
);
204 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
205 f
= load_hash
[locate
].next
;
206 load_hash
[locate
].next
= *n
;
208 (*n
)->pre
= &(load_hash
[locate
].next
);
210 f
->pre
= &((*n
)->next
);
212 pthread_mutex_unlock(&load_hash
[locate
].lock
);
213 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
216 * locate_node() finds special node. Not return NULL means success.
217 * It should be noted that rdlock isn't unlocked at the end of code
218 * because this function is used to read special node. Delete is not
219 * allowed before read has ended.
220 * unlock rdlock only in proc_loadavg_read().
222 static struct load_node
*locate_node(char *cg
, int locate
)
224 struct load_node
*f
= NULL
;
227 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
228 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
229 if (load_hash
[locate
].next
== NULL
) {
230 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
233 f
= load_hash
[locate
].next
;
234 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
235 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
239 /* Delete the load_node n and return the next node of it. */
240 static struct load_node
*del_node(struct load_node
*n
, int locate
)
244 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
245 if (n
->next
== NULL
) {
249 n
->next
->pre
= n
->pre
;
254 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
258 static void load_free(void)
261 struct load_node
*f
, *p
;
263 for (i
= 0; i
< LOAD_SIZE
; i
++) {
264 pthread_mutex_lock(&load_hash
[i
].lock
);
265 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
266 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
267 if (load_hash
[i
].next
== NULL
) {
268 pthread_mutex_unlock(&load_hash
[i
].lock
);
269 pthread_mutex_destroy(&load_hash
[i
].lock
);
270 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
271 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
272 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
273 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
276 for (f
= load_hash
[i
].next
; f
; ) {
282 pthread_mutex_unlock(&load_hash
[i
].lock
);
283 pthread_mutex_destroy(&load_hash
[i
].lock
);
284 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
285 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
286 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
287 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
291 /* Data for CPU view */
292 struct cg_proc_stat
{
294 struct cpuacct_usage
*usage
; // Real usage as read from the host's /proc/stat
295 struct cpuacct_usage
*view
; // Usage stats reported to the container
297 pthread_mutex_t lock
; // For node manipulation
298 struct cg_proc_stat
*next
;
301 struct cg_proc_stat_head
{
302 struct cg_proc_stat
*next
;
306 * For access to the list. Reading can be parallel, pruning is exclusive.
308 pthread_rwlock_t lock
;
311 #define CPUVIEW_HASH_SIZE 100
312 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
314 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
316 *head
= malloc(sizeof(struct cg_proc_stat_head
));
318 lxcfs_error("%s\n", strerror(errno
));
322 (*head
)->lastcheck
= time(NULL
);
323 (*head
)->next
= NULL
;
325 if (pthread_rwlock_init(&(*head
)->lock
, NULL
) != 0) {
326 lxcfs_error("%s\n", "Failed to initialize list lock");
334 static bool init_cpuview()
338 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
339 proc_stat_history
[i
] = NULL
;
341 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
342 if (!cpuview_init_head(&proc_stat_history
[i
]))
349 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
350 if (proc_stat_history
[i
]) {
351 free(proc_stat_history
[i
]);
352 proc_stat_history
[i
] = NULL
;
359 static void free_proc_stat_node(struct cg_proc_stat
*node
)
361 pthread_mutex_destroy(&node
->lock
);
368 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
370 struct cg_proc_stat
*node
, *tmp
;
378 free_proc_stat_node(tmp
);
385 pthread_rwlock_destroy(&head
->lock
);
389 static void free_cpuview()
393 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
394 if (proc_stat_history
[i
])
395 cpuview_free_head(proc_stat_history
[i
]);
399 /* Reserve buffer size to account for file size changes. */
400 #define BUF_RESERVE_SIZE 512
403 * A table caching which pid is init for a pid namespace.
404 * When looking up which pid is init for $qpid, we first
405 * 1. Stat /proc/$qpid/ns/pid.
406 * 2. Check whether the ino_t is in our store.
407 * a. if not, fork a child in qpid's ns to send us
408 * ucred.pid = 1, and read the initpid. Cache
409 * initpid and creation time for /proc/initpid
410 * in a new store entry.
411 * b. if so, verify that /proc/initpid still matches
412 * what we have saved. If not, clear the store
413 * entry and go back to a. If so, return the
416 struct pidns_init_store
{
417 ino_t ino
; // inode number for /proc/$pid/ns/pid
418 pid_t initpid
; // the pid of nit in that ns
419 long int ctime
; // the time at which /proc/$initpid was created
420 struct pidns_init_store
*next
;
424 /* lol - look at how they are allocated in the kernel */
425 #define PIDNS_HASH_SIZE 4096
426 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
428 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
429 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
430 static void lock_mutex(pthread_mutex_t
*l
)
434 if ((ret
= pthread_mutex_lock(l
)) != 0) {
435 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
440 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
441 * Number of hierarchies mounted. */
442 static int num_hierarchies
;
444 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
445 * Hierachies mounted {cpuset, blkio, ...}:
446 * Initialized via __constructor__ collect_and_mount_subsystems(). */
447 static char **hierarchies
;
449 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
450 * Open file descriptors:
451 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
452 * private mount namespace.
453 * Initialized via __constructor__ collect_and_mount_subsystems().
454 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
455 * mounts and respective files in the private namespace even when located in
456 * another namespace using the *at() family of functions
457 * {openat(), fchownat(), ...}. */
458 static int *fd_hierarchies
;
459 static int cgroup_mount_ns_fd
= -1;
461 static void unlock_mutex(pthread_mutex_t
*l
)
465 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
466 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
471 static void store_lock(void)
473 lock_mutex(&pidns_store_mutex
);
476 static void store_unlock(void)
478 unlock_mutex(&pidns_store_mutex
);
481 /* Must be called under store_lock */
482 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
487 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
488 if (stat(fnam
, &initsb
) < 0)
491 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
492 initsb
.st_ctime
, e
->initpid
);
494 if (e
->ctime
!= initsb
.st_ctime
)
499 /* Must be called under store_lock */
500 static void remove_initpid(struct pidns_init_store
*e
)
502 struct pidns_init_store
*tmp
;
505 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
508 if (pidns_hash_table
[h
] == e
) {
509 pidns_hash_table
[h
] = e
->next
;
514 tmp
= pidns_hash_table
[h
];
516 if (tmp
->next
== e
) {
526 /* Must be called under store_lock */
527 static void prune_initpid_store(void)
529 static long int last_prune
= 0;
530 struct pidns_init_store
*e
, *prev
, *delme
;
531 long int now
, threshold
;
535 last_prune
= time(NULL
);
539 if (now
< last_prune
+ PURGE_SECS
)
542 lxcfs_debug("%s\n", "Pruning.");
545 threshold
= now
- 2 * PURGE_SECS
;
547 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
548 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
549 if (e
->lastcheck
< threshold
) {
551 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
555 prev
->next
= e
->next
;
557 pidns_hash_table
[i
] = e
->next
;
568 /* Must be called under store_lock */
569 static void save_initpid(struct stat
*sb
, pid_t pid
)
571 struct pidns_init_store
*e
;
576 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
578 snprintf(fpath
, 100, "/proc/%d", pid
);
579 if (stat(fpath
, &procsb
) < 0)
582 e
= malloc(sizeof(*e
));
586 e
->ctime
= procsb
.st_ctime
;
588 e
->next
= pidns_hash_table
[h
];
589 e
->lastcheck
= time(NULL
);
590 pidns_hash_table
[h
] = e
;
594 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
595 * entry for the inode number and creation time. Verify that the init pid
596 * is still valid. If not, remove it. Return the entry if valid, NULL
598 * Must be called under store_lock
600 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
602 int h
= HASH(sb
->st_ino
);
603 struct pidns_init_store
*e
= pidns_hash_table
[h
];
606 if (e
->ino
== sb
->st_ino
) {
607 if (initpid_still_valid(e
, sb
)) {
608 e
->lastcheck
= time(NULL
);
620 static int is_dir(const char *path
, int fd
)
623 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
624 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
629 static char *must_copy_string(const char *str
)
641 static inline void drop_trailing_newlines(char *s
)
645 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
649 #define BATCH_SIZE 50
650 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
652 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
653 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
655 if (!*mem
|| newbatches
> oldbatches
) {
658 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
663 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
665 size_t newlen
= *len
+ linelen
;
666 dorealloc(contents
, *len
, newlen
+ 1);
667 memcpy(*contents
+ *len
, line
, linelen
+1);
671 static char *slurp_file(const char *from
, int fd
)
674 char *contents
= NULL
;
675 FILE *f
= fdopen(fd
, "r");
676 size_t len
= 0, fulllen
= 0;
682 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
683 append_line(&contents
, &fulllen
, line
, linelen
);
688 drop_trailing_newlines(contents
);
693 static bool write_string(const char *fnam
, const char *string
, int fd
)
702 len
= strlen(string
);
703 ret
= fwrite(string
, 1, len
, f
);
705 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
706 strerror(errno
), string
, fnam
);
712 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
726 static bool store_hierarchy(char *stridx
, char *h
)
728 if (num_hierarchies
% ALLOC_NUM
== 0) {
729 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
731 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
733 lxcfs_error("%s\n", strerror(errno
));
739 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
743 static void print_subsystems(void)
747 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
748 fprintf(stderr
, "hierarchies:\n");
749 for (i
= 0; i
< num_hierarchies
; i
++) {
751 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
752 fd_hierarchies
[i
], hierarchies
[i
]);
756 static bool in_comma_list(const char *needle
, const char *haystack
)
758 const char *s
= haystack
, *e
;
759 size_t nlen
= strlen(needle
);
761 while (*s
&& (e
= strchr(s
, ','))) {
766 if (strncmp(needle
, s
, nlen
) == 0)
770 if (strcmp(needle
, s
) == 0)
775 /* do we need to do any massaging here? I'm not sure... */
776 /* Return the mounted controller and store the corresponding open file descriptor
777 * referring to the controller mountpoint in the private lxcfs namespace in
780 static char *find_mounted_controller(const char *controller
, int *cfd
)
784 for (i
= 0; i
< num_hierarchies
; i
++) {
787 if (strcmp(hierarchies
[i
], controller
) == 0) {
788 *cfd
= fd_hierarchies
[i
];
789 return hierarchies
[i
];
791 if (in_comma_list(controller
, hierarchies
[i
])) {
792 *cfd
= fd_hierarchies
[i
];
793 return hierarchies
[i
];
800 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
807 tmpc
= find_mounted_controller(controller
, &cfd
);
811 /* Make sure we pass a relative path to *at() family of functions.
812 * . + /cgroup + / + file + \0
814 len
= strlen(cgroup
) + strlen(file
) + 3;
816 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
817 if (ret
< 0 || (size_t)ret
>= len
)
820 fd
= openat(cfd
, fnam
, O_WRONLY
);
824 return write_string(fnam
, value
, fd
);
827 // Chown all the files in the cgroup directory. We do this when we create
828 // a cgroup on behalf of a user.
829 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
831 struct dirent
*direntp
;
832 char path
[MAXPATHLEN
];
837 len
= strlen(dirname
);
838 if (len
>= MAXPATHLEN
) {
839 lxcfs_error("Pathname too long: %s\n", dirname
);
843 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
849 lxcfs_error("Failed to open %s\n", dirname
);
853 while ((direntp
= readdir(d
))) {
854 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
856 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
857 if (ret
< 0 || ret
>= MAXPATHLEN
) {
858 lxcfs_error("Pathname too long under %s\n", dirname
);
861 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
862 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
867 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
873 tmpc
= find_mounted_controller(controller
, &cfd
);
877 /* Make sure we pass a relative path to *at() family of functions.
880 len
= strlen(cg
) + 2;
881 dirnam
= alloca(len
);
882 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
884 if (mkdirat(cfd
, dirnam
, 0755) < 0)
887 if (uid
== 0 && gid
== 0)
890 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
893 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
898 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
900 struct dirent
*direntp
;
903 char pathname
[MAXPATHLEN
];
906 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
910 dir
= fdopendir(dupfd
);
912 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
917 while ((direntp
= readdir(dir
))) {
921 if (!strcmp(direntp
->d_name
, ".") ||
922 !strcmp(direntp
->d_name
, ".."))
925 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
926 if (rc
< 0 || rc
>= MAXPATHLEN
) {
927 lxcfs_error("%s\n", "Pathname too long.");
931 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
933 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
936 if (S_ISDIR(mystat
.st_mode
))
937 if (!recursive_rmdir(pathname
, fd
, cfd
))
938 lxcfs_debug("Error removing %s.\n", pathname
);
942 if (closedir(dir
) < 0) {
943 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
947 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
948 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
957 bool cgfs_remove(const char *controller
, const char *cg
)
964 tmpc
= find_mounted_controller(controller
, &cfd
);
968 /* Make sure we pass a relative path to *at() family of functions.
971 len
= strlen(cg
) + 2;
972 dirnam
= alloca(len
);
973 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
975 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
979 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
984 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
988 char *pathname
, *tmpc
;
990 tmpc
= find_mounted_controller(controller
, &cfd
);
994 /* Make sure we pass a relative path to *at() family of functions.
997 len
= strlen(file
) + 2;
998 pathname
= alloca(len
);
999 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1000 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
1005 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
1010 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
1011 fname
= alloca(len
);
1012 snprintf(fname
, len
, "%s/tasks", dirname
);
1013 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1015 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
1016 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1021 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
1025 char *pathname
, *tmpc
;
1027 tmpc
= find_mounted_controller(controller
, &cfd
);
1031 /* Make sure we pass a relative path to *at() family of functions.
1034 len
= strlen(file
) + 2;
1035 pathname
= alloca(len
);
1036 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1037 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
1040 if (is_dir(pathname
, cfd
))
1041 // like cgmanager did, we want to chown the tasks file as well
1042 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
1047 FILE *open_pids_file(const char *controller
, const char *cgroup
)
1051 char *pathname
, *tmpc
;
1053 tmpc
= find_mounted_controller(controller
, &cfd
);
1057 /* Make sure we pass a relative path to *at() family of functions.
1058 * . + /cgroup + / "cgroup.procs" + \0
1060 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
1061 pathname
= alloca(len
);
1062 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
1064 fd
= openat(cfd
, pathname
, O_WRONLY
);
1068 return fdopen(fd
, "w");
1071 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
1072 void ***list
, size_t typesize
,
1073 void* (*iterator
)(const char*, const char*, const char*))
1078 char pathname
[MAXPATHLEN
];
1079 size_t sz
= 0, asz
= 0;
1080 struct dirent
*dirent
;
1083 tmpc
= find_mounted_controller(controller
, &cfd
);
1088 /* Make sure we pass a relative path to *at() family of functions. */
1089 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
1091 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
1092 if (ret
< 0 || (size_t)ret
>= len
) {
1093 lxcfs_error("Pathname too long under %s\n", cgroup
);
1097 fd
= openat(cfd
, cg
, O_DIRECTORY
);
1101 dir
= fdopendir(fd
);
1105 while ((dirent
= readdir(dir
))) {
1108 if (!strcmp(dirent
->d_name
, ".") ||
1109 !strcmp(dirent
->d_name
, ".."))
1112 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1113 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1114 lxcfs_error("Pathname too long under %s\n", cg
);
1118 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1120 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1123 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1124 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1131 tmp
= realloc(*list
, asz
* typesize
);
1135 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1136 (*list
)[sz
+1] = NULL
;
1139 if (closedir(dir
) < 0) {
1140 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1146 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1150 dup
= strdup(dir_entry
);
1155 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1157 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1160 void free_key(struct cgfs_files
*k
)
1168 void free_keys(struct cgfs_files
**keys
)
1174 for (i
= 0; keys
[i
]; i
++) {
1180 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1186 tmpc
= find_mounted_controller(controller
, &cfd
);
1190 /* Make sure we pass a relative path to *at() family of functions.
1191 * . + /cgroup + / + file + \0
1193 len
= strlen(cgroup
) + strlen(file
) + 3;
1195 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1196 if (ret
< 0 || (size_t)ret
>= len
)
1199 fd
= openat(cfd
, fnam
, O_RDONLY
);
1203 *value
= slurp_file(fnam
, fd
);
1204 return *value
!= NULL
;
1207 bool cgfs_param_exist(const char *controller
, const char *cgroup
, const char *file
)
1213 tmpc
= find_mounted_controller(controller
, &cfd
);
1217 /* Make sure we pass a relative path to *at() family of functions.
1218 * . + /cgroup + / + file + \0
1220 len
= strlen(cgroup
) + strlen(file
) + 3;
1222 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1223 if (ret
< 0 || (size_t)ret
>= len
)
1226 return (faccessat(cfd
, fnam
, F_OK
, 0) == 0);
1229 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1235 struct cgfs_files
*newkey
;
1237 tmpc
= find_mounted_controller(controller
, &cfd
);
1241 if (file
&& *file
== '/')
1244 if (file
&& strchr(file
, '/'))
1247 /* Make sure we pass a relative path to *at() family of functions.
1248 * . + /cgroup + / + file + \0
1250 len
= strlen(cgroup
) + 3;
1252 len
+= strlen(file
) + 1;
1254 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1255 file
? "/" : "", file
? file
: "");
1257 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1262 newkey
= malloc(sizeof(struct cgfs_files
));
1265 newkey
->name
= must_copy_string(file
);
1266 else if (strrchr(cgroup
, '/'))
1267 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1269 newkey
->name
= must_copy_string(cgroup
);
1270 newkey
->uid
= sb
.st_uid
;
1271 newkey
->gid
= sb
.st_gid
;
1272 newkey
->mode
= sb
.st_mode
;
1277 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1279 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1281 lxcfs_error("Error getting files under %s:%s\n", controller
,
1287 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1289 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1292 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1300 tmpc
= find_mounted_controller(controller
, &cfd
);
1304 /* Make sure we pass a relative path to *at() family of functions.
1305 * . + /cgroup + / + f + \0
1307 len
= strlen(cgroup
) + strlen(f
) + 3;
1309 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1310 if (ret
< 0 || (size_t)ret
>= len
)
1313 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1314 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1320 #define SEND_CREDS_OK 0
1321 #define SEND_CREDS_NOTSK 1
1322 #define SEND_CREDS_FAIL 2
1323 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1324 static int wait_for_pid(pid_t pid
);
1325 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1326 static int send_creds_clone_wrapper(void *arg
);
1329 * clone a task which switches to @task's namespace and writes '1'.
1330 * over a unix sock so we can read the task's reaper's pid in our
1333 * Note: glibc's fork() does not respect pidns, which can lead to failed
1334 * assertions inside glibc (and thus failed forks) if the child's pid in
1335 * the pidns and the parent pid outside are identical. Using clone prevents
1338 static void write_task_init_pid_exit(int sock
, pid_t target
)
1343 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1344 void *stack
= alloca(stack_size
);
1346 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1347 if (ret
< 0 || ret
>= sizeof(fnam
))
1350 fd
= open(fnam
, O_RDONLY
);
1352 perror("write_task_init_pid_exit open of ns/pid");
1356 perror("write_task_init_pid_exit setns 1");
1360 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1364 if (!wait_for_pid(pid
))
1370 static int send_creds_clone_wrapper(void *arg
) {
1373 int sock
= *(int *)arg
;
1375 /* we are the child */
1380 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1385 static pid_t
get_init_pid_for_task(pid_t task
)
1393 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1394 perror("socketpair");
1403 write_task_init_pid_exit(sock
[0], task
);
1407 if (!recv_creds(sock
[1], &cred
, &v
))
1419 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1423 struct pidns_init_store
*e
;
1426 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1428 if (stat(fnam
, &sb
) < 0)
1430 e
= lookup_verify_initpid(&sb
);
1432 answer
= e
->initpid
;
1435 answer
= get_init_pid_for_task(qpid
);
1437 save_initpid(&sb
, answer
);
1440 /* we prune at end in case we are returning
1441 * the value we were about to return */
1442 prune_initpid_store();
1447 static int wait_for_pid(pid_t pid
)
1455 ret
= waitpid(pid
, &status
, 0);
1463 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1470 * append pid to *src.
1471 * src: a pointer to a char* in which ot append the pid.
1472 * sz: the number of characters printed so far, minus trailing \0.
1473 * asz: the allocated size so far
1474 * pid: the pid to append
1476 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1480 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1482 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1485 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1488 *asz
+= BUF_RESERVE_SIZE
;
1490 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1495 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1496 * valid in the caller's namespace, return the id mapped into
1498 * Returns the mapped id, or -1 on error.
1501 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1503 unsigned int nsuid
, // base id for a range in the idfile's namespace
1504 hostuid
, // base id for a range in the caller's namespace
1505 count
; // number of ids in this range
1509 fseek(idfile
, 0L, SEEK_SET
);
1510 while (fgets(line
, 400, idfile
)) {
1511 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1514 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1516 * uids wrapped around - unexpected as this is a procfile,
1519 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1520 nsuid
, hostuid
, count
, line
);
1523 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1525 * now since hostuid <= in_id < hostuid+count, and
1526 * hostuid+count and nsuid+count do not wrap around,
1527 * we know that nsuid+(in_id-hostuid) which must be
1528 * less that nsuid+(count) must not wrap around
1530 return (in_id
- hostuid
) + nsuid
;
1539 * for is_privileged_over,
1540 * specify whether we require the calling uid to be root in his
1543 #define NS_ROOT_REQD true
1544 #define NS_ROOT_OPT false
1548 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1550 char fpath
[PROCLEN
];
1552 bool answer
= false;
1555 if (victim
== -1 || uid
== -1)
1559 * If the request is one not requiring root in the namespace,
1560 * then having the same uid suffices. (i.e. uid 1000 has write
1561 * access to files owned by uid 1000
1563 if (!req_ns_root
&& uid
== victim
)
1566 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1567 if (ret
< 0 || ret
>= PROCLEN
)
1569 FILE *f
= fopen(fpath
, "r");
1573 /* if caller's not root in his namespace, reject */
1574 nsuid
= convert_id_to_ns(f
, uid
);
1579 * If victim is not mapped into caller's ns, reject.
1580 * XXX I'm not sure this check is needed given that fuse
1581 * will be sending requests where the vfs has converted
1583 nsuid
= convert_id_to_ns(f
, victim
);
1594 static bool perms_include(int fmode
, mode_t req_mode
)
1598 switch (req_mode
& O_ACCMODE
) {
1606 r
= S_IROTH
| S_IWOTH
;
1611 return ((fmode
& r
) == r
);
1617 * querycg is /a/b/c/d/e
1620 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1624 if (strlen(taskcg
) <= strlen(querycg
)) {
1625 lxcfs_error("%s\n", "I was fed bad input.");
1629 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1630 start
= strdup(taskcg
+ 1);
1632 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1635 end
= strchr(start
, '/');
1641 static void stripnewline(char *x
)
1643 size_t l
= strlen(x
);
1644 if (l
&& x
[l
-1] == '\n')
1648 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1653 char *answer
= NULL
;
1657 const char *h
= find_mounted_controller(contrl
, &cfd
);
1661 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1662 if (ret
< 0 || ret
>= PROCLEN
)
1664 if (!(f
= fopen(fnam
, "r")))
1667 while (getline(&line
, &len
, f
) != -1) {
1671 c1
= strchr(line
, ':');
1675 c2
= strchr(c1
, ':');
1679 if (strcmp(c1
, h
) != 0)
1684 answer
= strdup(c2
);
1696 * check whether a fuse context may access a cgroup dir or file
1698 * If file is not null, it is a cgroup file to check under cg.
1699 * If file is null, then we are checking perms on cg itself.
1701 * For files we can check the mode of the list_keys result.
1702 * For cgroups, we must make assumptions based on the files under the
1703 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1706 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1708 struct cgfs_files
*k
= NULL
;
1711 k
= cgfs_get_key(contrl
, cg
, file
);
1715 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1716 if (perms_include(k
->mode
>> 6, mode
)) {
1721 if (fc
->gid
== k
->gid
) {
1722 if (perms_include(k
->mode
>> 3, mode
)) {
1727 ret
= perms_include(k
->mode
, mode
);
1734 #define INITSCOPE "/init.scope"
1735 static void prune_init_slice(char *cg
)
1738 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1740 if (cg_len
< initscope_len
)
1743 point
= cg
+ cg_len
- initscope_len
;
1744 if (strcmp(point
, INITSCOPE
) == 0) {
1753 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1754 * If pid is in /a, he may act on /a/b, but not on /b.
1755 * if the answer is false and nextcg is not NULL, then *nextcg will point
1756 * to a string containing the next cgroup directory under cg, which must be
1757 * freed by the caller.
1759 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1761 bool answer
= false;
1762 char *c2
= get_pid_cgroup(pid
, contrl
);
1767 prune_init_slice(c2
);
1770 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1771 * they pass in a cgroup without leading '/'
1773 * The original line here was:
1774 * linecmp = *cg == '/' ? c2 : c2+1;
1775 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1776 * Serge, do you know?
1778 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1782 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1784 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1796 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1798 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1800 bool answer
= false;
1802 size_t target_len
, task_len
;
1804 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1807 c2
= get_pid_cgroup(pid
, contrl
);
1810 prune_init_slice(c2
);
1813 target_len
= strlen(cg
);
1814 task_len
= strlen(task_cg
);
1815 if (task_len
== 0) {
1816 /* Task is in the root cg, it can see everything. This case is
1817 * not handled by the strmcps below, since they test for the
1818 * last /, but that is the first / that we've chopped off
1824 if (strcmp(cg
, task_cg
) == 0) {
1828 if (target_len
< task_len
) {
1829 /* looking up a parent dir */
1830 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1834 if (target_len
> task_len
) {
1835 /* looking up a child dir */
1836 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1847 * given /cgroup/freezer/a/b, return "freezer".
1848 * the returned char* should NOT be freed.
1850 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1853 char *contr
, *slash
;
1855 if (strlen(path
) < 9) {
1859 if (*(path
+ 7) != '/') {
1864 contr
= strdupa(p1
);
1869 slash
= strstr(contr
, "/");
1874 for (i
= 0; i
< num_hierarchies
; i
++) {
1875 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1876 return hierarchies
[i
];
1883 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1884 * Note that the returned value may include files (keynames) etc
1886 static const char *find_cgroup_in_path(const char *path
)
1890 if (strlen(path
) < 9) {
1894 p1
= strstr(path
+ 8, "/");
1904 * split the last path element from the path in @cg.
1905 * @dir is newly allocated and should be freed, @last not
1907 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1914 *last
= strrchr(cg
, '/');
1919 p
= strrchr(*dir
, '/');
1924 * FUSE ops for /cgroup
1927 int cg_getattr(const char *path
, struct stat
*sb
)
1929 struct timespec now
;
1930 struct fuse_context
*fc
= fuse_get_context();
1931 char * cgdir
= NULL
;
1932 char *last
= NULL
, *path1
, *path2
;
1933 struct cgfs_files
*k
= NULL
;
1935 const char *controller
= NULL
;
1942 memset(sb
, 0, sizeof(struct stat
));
1944 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1947 sb
->st_uid
= sb
->st_gid
= 0;
1948 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1951 if (strcmp(path
, "/cgroup") == 0) {
1952 sb
->st_mode
= S_IFDIR
| 00755;
1957 controller
= pick_controller_from_path(fc
, path
);
1960 cgroup
= find_cgroup_in_path(path
);
1962 /* this is just /cgroup/controller, return it as a dir */
1963 sb
->st_mode
= S_IFDIR
| 00755;
1968 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1978 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1981 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1982 * Then check that caller's cgroup is under path if last is a child
1983 * cgroup, or cgdir if last is a file */
1985 if (is_child_cgroup(controller
, path1
, path2
)) {
1986 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1990 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1991 /* this is just /cgroup/controller, return it as a dir */
1992 sb
->st_mode
= S_IFDIR
| 00555;
1997 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
2002 // get uid, gid, from '/tasks' file and make up a mode
2003 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2004 sb
->st_mode
= S_IFDIR
| 00755;
2005 k
= cgfs_get_key(controller
, cgroup
, NULL
);
2007 sb
->st_uid
= sb
->st_gid
= 0;
2009 sb
->st_uid
= k
->uid
;
2010 sb
->st_gid
= k
->gid
;
2018 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
2019 sb
->st_mode
= S_IFREG
| k
->mode
;
2021 sb
->st_uid
= k
->uid
;
2022 sb
->st_gid
= k
->gid
;
2025 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2037 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
2039 struct fuse_context
*fc
= fuse_get_context();
2041 struct file_info
*dir_info
;
2042 char *controller
= NULL
;
2047 if (strcmp(path
, "/cgroup") == 0) {
2051 // return list of keys for the controller, and list of child cgroups
2052 controller
= pick_controller_from_path(fc
, path
);
2056 cgroup
= find_cgroup_in_path(path
);
2058 /* this is just /cgroup/controller, return its contents */
2063 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2067 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
2069 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
2073 /* we'll free this at cg_releasedir */
2074 dir_info
= malloc(sizeof(*dir_info
));
2077 dir_info
->controller
= must_copy_string(controller
);
2078 dir_info
->cgroup
= must_copy_string(cgroup
);
2079 dir_info
->type
= LXC_TYPE_CGDIR
;
2080 dir_info
->buf
= NULL
;
2081 dir_info
->file
= NULL
;
2082 dir_info
->buflen
= 0;
2084 fi
->fh
= (unsigned long)dir_info
;
2088 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2089 struct fuse_file_info
*fi
)
2091 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2092 struct cgfs_files
**list
= NULL
;
2094 char *nextcg
= NULL
;
2095 struct fuse_context
*fc
= fuse_get_context();
2096 char **clist
= NULL
;
2098 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
2101 if (d
->type
!= LXC_TYPE_CGDIR
) {
2102 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
2105 if (!d
->cgroup
&& !d
->controller
) {
2106 // ls /var/lib/lxcfs/cgroup - just show list of controllers
2109 for (i
= 0; i
< num_hierarchies
; i
++) {
2110 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
2117 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
2118 // not a valid cgroup
2123 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2126 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
2128 ret
= filler(buf
, nextcg
, NULL
, 0);
2139 for (i
= 0; list
&& list
[i
]; i
++) {
2140 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2146 // now get the list of child cgroups
2148 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2153 for (i
= 0; clist
[i
]; i
++) {
2154 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2165 for (i
= 0; clist
[i
]; i
++)
2172 static pthread_mutex_t do_release_file_info_lock
= PTHREAD_MUTEX_INITIALIZER
;
2174 static void do_release_file_info(struct fuse_file_info
*fi
)
2176 lock_mutex(&do_release_file_info_lock
);
2178 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2181 unlock_mutex(&do_release_file_info_lock
);
2186 free(f
->controller
);
2187 f
->controller
= NULL
;
2197 unlock_mutex(&do_release_file_info_lock
);
2200 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2202 do_release_file_info(fi
);
2206 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2209 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2210 struct cgfs_files
*k
= NULL
;
2211 struct file_info
*file_info
;
2212 struct fuse_context
*fc
= fuse_get_context();
2218 controller
= pick_controller_from_path(fc
, path
);
2221 cgroup
= find_cgroup_in_path(path
);
2225 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2234 k
= cgfs_get_key(controller
, path1
, path2
);
2241 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2244 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2248 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2253 /* we'll free this at cg_release */
2254 file_info
= malloc(sizeof(*file_info
));
2259 file_info
->controller
= must_copy_string(controller
);
2260 file_info
->cgroup
= must_copy_string(path1
);
2261 file_info
->file
= must_copy_string(path2
);
2262 file_info
->type
= LXC_TYPE_CGFILE
;
2263 file_info
->buf
= NULL
;
2264 file_info
->buflen
= 0;
2266 fi
->fh
= (unsigned long)file_info
;
2274 int cg_access(const char *path
, int mode
)
2278 char *path1
, *path2
, *controller
;
2279 char *last
= NULL
, *cgdir
= NULL
;
2280 struct cgfs_files
*k
= NULL
;
2281 struct fuse_context
*fc
= fuse_get_context();
2283 if (strcmp(path
, "/cgroup") == 0)
2289 controller
= pick_controller_from_path(fc
, path
);
2292 cgroup
= find_cgroup_in_path(path
);
2294 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2295 if ((mode
& W_OK
) == 0)
2300 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2309 k
= cgfs_get_key(controller
, path1
, path2
);
2311 if ((mode
& W_OK
) == 0)
2319 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2322 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2326 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2338 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2340 do_release_file_info(fi
);
2344 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2346 static bool wait_for_sock(int sock
, int timeout
)
2348 struct epoll_event ev
;
2349 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2351 if ((starttime
= time(NULL
)) < 0)
2354 if ((epfd
= epoll_create(1)) < 0) {
2355 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2359 ev
.events
= POLLIN_SET
;
2361 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2362 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2368 if ((now
= time(NULL
)) < 0) {
2373 deltatime
= (starttime
+ timeout
) - now
;
2374 if (deltatime
< 0) { // timeout
2379 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2380 if (ret
< 0 && errno
== EINTR
)
2382 saved_errno
= errno
;
2386 errno
= saved_errno
;
2392 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2394 if (!wait_for_sock(sockfd
, 2))
2396 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2399 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2401 struct msghdr msg
= { 0 };
2403 struct cmsghdr
*cmsg
;
2404 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2409 if (msgrecv(sock
, buf
, 1) != 1) {
2410 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2411 return SEND_CREDS_FAIL
;
2415 msg
.msg_control
= cmsgbuf
;
2416 msg
.msg_controllen
= sizeof(cmsgbuf
);
2418 cmsg
= CMSG_FIRSTHDR(&msg
);
2419 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2420 cmsg
->cmsg_level
= SOL_SOCKET
;
2421 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2422 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2424 msg
.msg_name
= NULL
;
2425 msg
.msg_namelen
= 0;
2429 iov
.iov_len
= sizeof(buf
);
2433 if (sendmsg(sock
, &msg
, 0) < 0) {
2434 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2436 return SEND_CREDS_NOTSK
;
2437 return SEND_CREDS_FAIL
;
2440 return SEND_CREDS_OK
;
2443 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2445 struct msghdr msg
= { 0 };
2447 struct cmsghdr
*cmsg
;
2448 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2459 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2460 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2464 if (write(sock
, buf
, 1) != 1) {
2465 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2469 msg
.msg_name
= NULL
;
2470 msg
.msg_namelen
= 0;
2471 msg
.msg_control
= cmsgbuf
;
2472 msg
.msg_controllen
= sizeof(cmsgbuf
);
2475 iov
.iov_len
= sizeof(buf
);
2479 if (!wait_for_sock(sock
, 2)) {
2480 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2483 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2485 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2489 cmsg
= CMSG_FIRSTHDR(&msg
);
2491 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2492 cmsg
->cmsg_level
== SOL_SOCKET
&&
2493 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2494 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2501 struct pid_ns_clone_args
{
2505 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2509 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2510 * with clone(). This simply writes '1' as ACK back to the parent
2511 * before calling the actual wrapped function.
2513 static int pid_ns_clone_wrapper(void *arg
) {
2514 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2517 close(args
->cpipe
[0]);
2518 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2519 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2520 close(args
->cpipe
[1]);
2521 return args
->wrapped(args
->sock
, args
->tpid
);
2525 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2526 * int value back over the socket. This shifts the pid from the
2527 * sender's pidns into tpid's pidns.
2529 static int pid_to_ns(int sock
, pid_t tpid
)
2534 while (recv_creds(sock
, &cred
, &v
)) {
2537 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2545 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2546 * in your old pidns. Only children which you clone will be in the target
2547 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2548 * actually convert pids.
2550 * Note: glibc's fork() does not respect pidns, which can lead to failed
2551 * assertions inside glibc (and thus failed forks) if the child's pid in
2552 * the pidns and the parent pid outside are identical. Using clone prevents
2555 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2557 int newnsfd
= -1, ret
, cpipe
[2];
2562 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2563 if (ret
< 0 || ret
>= sizeof(fnam
))
2565 newnsfd
= open(fnam
, O_RDONLY
);
2568 if (setns(newnsfd
, 0) < 0)
2572 if (pipe(cpipe
) < 0)
2575 struct pid_ns_clone_args args
= {
2579 .wrapped
= &pid_to_ns
2581 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2582 void *stack
= alloca(stack_size
);
2584 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2588 // give the child 1 second to be done forking and
2590 if (!wait_for_sock(cpipe
[0], 1))
2592 ret
= read(cpipe
[0], &v
, 1);
2593 if (ret
!= sizeof(char) || v
!= '1')
2596 if (!wait_for_pid(cpid
))
2602 * To read cgroup files with a particular pid, we will setns into the child
2603 * pidns, open a pipe, fork a child - which will be the first to really be in
2604 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2606 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2608 int sock
[2] = {-1, -1};
2609 char *tmpdata
= NULL
;
2611 pid_t qpid
, cpid
= -1;
2612 bool answer
= false;
2615 size_t sz
= 0, asz
= 0;
2617 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2621 * Now we read the pids from returned data one by one, pass
2622 * them into a child in the target namespace, read back the
2623 * translated pids, and put them into our to-return data
2626 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2627 perror("socketpair");
2636 if (!cpid
) // child - exits when done
2637 pid_to_ns_wrapper(sock
[1], tpid
);
2639 char *ptr
= tmpdata
;
2642 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2644 ret
= send_creds(sock
[0], &cred
, v
, true);
2646 if (ret
== SEND_CREDS_NOTSK
)
2648 if (ret
== SEND_CREDS_FAIL
)
2651 // read converted results
2652 if (!wait_for_sock(sock
[0], 2)) {
2653 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2656 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2657 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2660 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2662 ptr
= strchr(ptr
, '\n');
2668 cred
.pid
= getpid();
2670 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2671 // failed to ask child to exit
2672 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2682 if (sock
[0] != -1) {
2689 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2690 struct fuse_file_info
*fi
)
2692 struct fuse_context
*fc
= fuse_get_context();
2693 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2694 struct cgfs_files
*k
= NULL
;
2699 if (f
->type
!= LXC_TYPE_CGFILE
) {
2700 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2713 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2719 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2724 if (strcmp(f
->file
, "tasks") == 0 ||
2725 strcmp(f
->file
, "/tasks") == 0 ||
2726 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2727 strcmp(f
->file
, "cgroup.procs") == 0)
2728 // special case - we have to translate the pids
2729 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2731 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2745 memcpy(buf
, data
, s
);
2746 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2756 static int pid_from_ns(int sock
, pid_t tpid
)
2766 if (!wait_for_sock(sock
, 2)) {
2767 lxcfs_error("%s\n", "Timeout reading from parent.");
2770 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2771 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2774 if (vpid
== -1) // done
2778 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2780 cred
.pid
= getpid();
2781 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2788 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2790 int newnsfd
= -1, ret
, cpipe
[2];
2795 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2796 if (ret
< 0 || ret
>= sizeof(fnam
))
2798 newnsfd
= open(fnam
, O_RDONLY
);
2801 if (setns(newnsfd
, 0) < 0)
2805 if (pipe(cpipe
) < 0)
2808 struct pid_ns_clone_args args
= {
2812 .wrapped
= &pid_from_ns
2814 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2815 void *stack
= alloca(stack_size
);
2817 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2821 // give the child 1 second to be done forking and
2823 if (!wait_for_sock(cpipe
[0], 1))
2825 ret
= read(cpipe
[0], &v
, 1);
2826 if (ret
!= sizeof(char) || v
!= '1')
2829 if (!wait_for_pid(cpid
))
2835 * Given host @uid, return the uid to which it maps in
2836 * @pid's user namespace, or -1 if none.
2838 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2843 sprintf(line
, "/proc/%d/uid_map", pid
);
2844 if ((f
= fopen(line
, "r")) == NULL
) {
2848 *answer
= convert_id_to_ns(f
, uid
);
2857 * get_pid_creds: get the real uid and gid of @pid from
2859 * (XXX should we use euid here?)
2861 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2870 sprintf(line
, "/proc/%d/status", pid
);
2871 if ((f
= fopen(line
, "r")) == NULL
) {
2872 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2875 while (fgets(line
, 400, f
)) {
2876 if (strncmp(line
, "Uid:", 4) == 0) {
2877 if (sscanf(line
+4, "%u", &u
) != 1) {
2878 lxcfs_error("bad uid line for pid %u\n", pid
);
2883 } else if (strncmp(line
, "Gid:", 4) == 0) {
2884 if (sscanf(line
+4, "%u", &g
) != 1) {
2885 lxcfs_error("bad gid line for pid %u\n", pid
);
2896 * May the requestor @r move victim @v to a new cgroup?
2897 * This is allowed if
2898 * . they are the same task
2899 * . they are ownedy by the same uid
2900 * . @r is root on the host, or
2901 * . @v's uid is mapped into @r's where @r is root.
2903 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2905 uid_t v_uid
, tmpuid
;
2912 get_pid_creds(v
, &v_uid
, &v_gid
);
2915 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2916 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2921 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2922 const char *file
, const char *buf
)
2924 int sock
[2] = {-1, -1};
2925 pid_t qpid
, cpid
= -1;
2926 FILE *pids_file
= NULL
;
2927 bool answer
= false, fail
= false;
2929 pids_file
= open_pids_file(contrl
, cg
);
2934 * write the pids to a socket, have helper in writer's pidns
2935 * call movepid for us
2937 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2938 perror("socketpair");
2946 if (!cpid
) { // child
2948 pid_from_ns_wrapper(sock
[1], tpid
);
2951 const char *ptr
= buf
;
2952 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2956 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2957 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2961 if (recv_creds(sock
[0], &cred
, &v
)) {
2963 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2967 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2972 ptr
= strchr(ptr
, '\n');
2978 /* All good, write the value */
2980 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2981 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2989 if (sock
[0] != -1) {
2994 if (fclose(pids_file
) != 0)
3000 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
3001 struct fuse_file_info
*fi
)
3003 struct fuse_context
*fc
= fuse_get_context();
3004 char *localbuf
= NULL
;
3005 struct cgfs_files
*k
= NULL
;
3006 struct file_info
*f
= (struct file_info
*)fi
->fh
;
3009 if (f
->type
!= LXC_TYPE_CGFILE
) {
3010 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
3020 localbuf
= alloca(size
+1);
3021 localbuf
[size
] = '\0';
3022 memcpy(localbuf
, buf
, size
);
3024 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
3029 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
3034 if (strcmp(f
->file
, "tasks") == 0 ||
3035 strcmp(f
->file
, "/tasks") == 0 ||
3036 strcmp(f
->file
, "/cgroup.procs") == 0 ||
3037 strcmp(f
->file
, "cgroup.procs") == 0)
3038 // special case - we have to translate the pids
3039 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3041 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3051 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
3053 struct fuse_context
*fc
= fuse_get_context();
3054 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3055 struct cgfs_files
*k
= NULL
;
3062 if (strcmp(path
, "/cgroup") == 0)
3065 controller
= pick_controller_from_path(fc
, path
);
3067 return errno
== ENOENT
? -EPERM
: -errno
;
3069 cgroup
= find_cgroup_in_path(path
);
3071 /* this is just /cgroup/controller */
3074 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3084 if (is_child_cgroup(controller
, path1
, path2
)) {
3085 // get uid, gid, from '/tasks' file and make up a mode
3086 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3087 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3090 k
= cgfs_get_key(controller
, path1
, path2
);
3098 * This being a fuse request, the uid and gid must be valid
3099 * in the caller's namespace. So we can just check to make
3100 * sure that the caller is root in his uid, and privileged
3101 * over the file's current owner.
3103 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
3108 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
3117 int cg_chmod(const char *path
, mode_t mode
)
3119 struct fuse_context
*fc
= fuse_get_context();
3120 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3121 struct cgfs_files
*k
= NULL
;
3128 if (strcmp(path
, "/cgroup") == 0)
3131 controller
= pick_controller_from_path(fc
, path
);
3133 return errno
== ENOENT
? -EPERM
: -errno
;
3135 cgroup
= find_cgroup_in_path(path
);
3137 /* this is just /cgroup/controller */
3140 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3150 if (is_child_cgroup(controller
, path1
, path2
)) {
3151 // get uid, gid, from '/tasks' file and make up a mode
3152 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3153 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3156 k
= cgfs_get_key(controller
, path1
, path2
);
3164 * This being a fuse request, the uid and gid must be valid
3165 * in the caller's namespace. So we can just check to make
3166 * sure that the caller is root in his uid, and privileged
3167 * over the file's current owner.
3169 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3174 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3186 int cg_mkdir(const char *path
, mode_t mode
)
3188 struct fuse_context
*fc
= fuse_get_context();
3189 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3196 controller
= pick_controller_from_path(fc
, path
);
3198 return errno
== ENOENT
? -EPERM
: -errno
;
3200 cgroup
= find_cgroup_in_path(path
);
3204 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3210 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3213 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3216 else if (last
&& strcmp(next
, last
) == 0)
3223 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3227 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3232 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3240 int cg_rmdir(const char *path
)
3242 struct fuse_context
*fc
= fuse_get_context();
3243 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3250 controller
= pick_controller_from_path(fc
, path
);
3251 if (!controller
) /* Someone's trying to delete "/cgroup". */
3254 cgroup
= find_cgroup_in_path(path
);
3255 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3258 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3260 /* Someone's trying to delete a cgroup on the same level as the
3261 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3262 * rmdir "/cgroup/blkio/init.slice".
3268 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3271 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3272 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3279 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3283 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3288 if (!cgfs_remove(controller
, cgroup
)) {
3301 static bool startswith(const char *line
, const char *pref
)
3303 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3308 static void parse_memstat(char *memstat
, unsigned long *cached
,
3309 unsigned long *active_anon
, unsigned long *inactive_anon
,
3310 unsigned long *active_file
, unsigned long *inactive_file
,
3311 unsigned long *unevictable
, unsigned long *shmem
)
3316 if (startswith(memstat
, "total_cache")) {
3317 sscanf(memstat
+ 11, "%lu", cached
);
3319 } else if (startswith(memstat
, "total_active_anon")) {
3320 sscanf(memstat
+ 17, "%lu", active_anon
);
3321 *active_anon
/= 1024;
3322 } else if (startswith(memstat
, "total_inactive_anon")) {
3323 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3324 *inactive_anon
/= 1024;
3325 } else if (startswith(memstat
, "total_active_file")) {
3326 sscanf(memstat
+ 17, "%lu", active_file
);
3327 *active_file
/= 1024;
3328 } else if (startswith(memstat
, "total_inactive_file")) {
3329 sscanf(memstat
+ 19, "%lu", inactive_file
);
3330 *inactive_file
/= 1024;
3331 } else if (startswith(memstat
, "total_unevictable")) {
3332 sscanf(memstat
+ 17, "%lu", unevictable
);
3333 *unevictable
/= 1024;
3334 } else if (startswith(memstat
, "total_shmem")) {
3335 sscanf(memstat
+ 11, "%lu", shmem
);
3338 eol
= strchr(memstat
, '\n');
3345 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3351 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3353 size_t len
= strlen(key
);
3357 if (startswith(str
, key
)) {
3358 sscanf(str
+ len
, "%lu", v
);
3361 eol
= strchr(str
, '\n');
3368 static int read_file(const char *path
, char *buf
, size_t size
,
3369 struct file_info
*d
)
3371 size_t linelen
= 0, total_len
= 0, rv
= 0;
3373 char *cache
= d
->buf
;
3374 size_t cache_size
= d
->buflen
;
3375 FILE *f
= fopen(path
, "r");
3379 while (getline(&line
, &linelen
, f
) != -1) {
3380 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3382 perror("Error writing to cache");
3386 if (l
>= cache_size
) {
3387 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3396 d
->size
= total_len
;
3397 if (total_len
> size
)
3400 /* read from off 0 */
3401 memcpy(buf
, d
->buf
, total_len
);
3410 * FUSE ops for /proc
3413 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3415 char *memlimit_str
= NULL
;
3416 unsigned long memlimit
= -1;
3418 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3419 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3426 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3428 char *copy
= strdupa(cgroup
);
3429 unsigned long memlimit
= 0, retlimit
;
3431 retlimit
= get_memlimit(copy
, file
);
3433 while (strcmp(copy
, "/") != 0) {
3434 copy
= dirname(copy
);
3435 memlimit
= get_memlimit(copy
, file
);
3436 if (memlimit
!= -1 && memlimit
< retlimit
)
3437 retlimit
= memlimit
;
3443 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3444 struct fuse_file_info
*fi
)
3446 struct fuse_context
*fc
= fuse_get_context();
3447 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3449 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3450 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3451 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3452 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3453 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3456 size_t linelen
= 0, total_len
= 0, rv
= 0;
3457 char *cache
= d
->buf
;
3458 size_t cache_size
= d
->buflen
;
3462 if (offset
> d
->size
)
3466 int left
= d
->size
- offset
;
3467 total_len
= left
> size
? size
: left
;
3468 memcpy(buf
, cache
+ offset
, total_len
);
3472 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3475 cg
= get_pid_cgroup(initpid
, "memory");
3477 return read_file("/proc/meminfo", buf
, size
, d
);
3478 prune_init_slice(cg
);
3480 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3481 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3483 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3486 // Following values are allowed to fail, because swapaccount might be turned
3487 // off for current kernel
3488 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3489 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3491 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3492 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3494 memswlimit
= memswlimit
/ 1024;
3495 memswusage
= memswusage
/ 1024;
3498 memusage
= strtoul(memusage_str
, NULL
, 10);
3502 parse_memstat(memstat_str
, &cached
, &active_anon
,
3503 &inactive_anon
, &active_file
, &inactive_file
,
3504 &unevictable
, &shmem
);
3506 f
= fopen("/proc/meminfo", "r");
3510 while (getline(&line
, &linelen
, f
) != -1) {
3512 char *printme
, lbuf
[100];
3514 memset(lbuf
, 0, 100);
3515 if (startswith(line
, "MemTotal:")) {
3516 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3517 if (hosttotal
< memlimit
)
3518 memlimit
= hosttotal
;
3519 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3521 } else if (startswith(line
, "MemFree:")) {
3522 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3524 } else if (startswith(line
, "MemAvailable:")) {
3525 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3527 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3528 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3529 if (hostswtotal
< memswlimit
)
3530 memswlimit
= hostswtotal
;
3531 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3533 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3534 unsigned long swaptotal
= memswlimit
,
3535 swapusage
= memswusage
- memusage
,
3536 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3537 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3539 } else if (startswith(line
, "Slab:")) {
3540 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3542 } else if (startswith(line
, "Buffers:")) {
3543 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3545 } else if (startswith(line
, "Cached:")) {
3546 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3548 } else if (startswith(line
, "SwapCached:")) {
3549 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3551 } else if (startswith(line
, "Active:")) {
3552 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3553 active_anon
+ active_file
);
3555 } else if (startswith(line
, "Inactive:")) {
3556 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3557 inactive_anon
+ inactive_file
);
3559 } else if (startswith(line
, "Active(anon)")) {
3560 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3562 } else if (startswith(line
, "Inactive(anon)")) {
3563 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3565 } else if (startswith(line
, "Active(file)")) {
3566 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3568 } else if (startswith(line
, "Inactive(file)")) {
3569 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3571 } else if (startswith(line
, "Unevictable")) {
3572 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3574 } else if (startswith(line
, "SReclaimable")) {
3575 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3577 } else if (startswith(line
, "SUnreclaim")) {
3578 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3580 } else if (startswith(line
, "Shmem:")) {
3581 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3583 } else if (startswith(line
, "ShmemHugePages")) {
3584 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3586 } else if (startswith(line
, "ShmemPmdMapped")) {
3587 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3592 l
= snprintf(cache
, cache_size
, "%s", printme
);
3594 perror("Error writing to cache");
3599 if (l
>= cache_size
) {
3600 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3611 d
->size
= total_len
;
3612 if (total_len
> size
) total_len
= size
;
3613 memcpy(buf
, d
->buf
, total_len
);
3622 free(memswlimit_str
);
3623 free(memswusage_str
);
3629 * Read the cpuset.cpus for cg
3630 * Return the answer in a newly allocated string which must be freed
3632 static char *get_cpuset(const char *cg
)
3636 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3641 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3643 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3647 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3649 return cpu_in_cpuset(cpu
, cpuset
);
3653 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3654 * depending on `param`. Parameter value is returned throuh `value`.
3656 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3659 char file
[11 + 6 + 1]; // cpu.cfs__us + quota/period + \0
3662 sprintf(file
, "cpu.cfs_%s_us", param
);
3664 if (!cgfs_get_value("cpu", cg
, file
, &str
))
3667 if (sscanf(str
, "%ld", value
) != 1)
3679 * Return the maximum number of visible CPUs based on CPU quotas.
3680 * If there is no quota set, zero is returned.
3682 int max_cpu_count(const char *cg
)
3685 int64_t cfs_quota
, cfs_period
;
3687 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3690 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3693 if (cfs_quota
<= 0 || cfs_period
<= 0)
3696 rv
= cfs_quota
/ cfs_period
;
3698 /* In case quota/period does not yield a whole number, add one CPU for
3701 if ((cfs_quota
% cfs_period
) > 0)
3704 nprocs
= get_nprocs();
3713 * Determine whether CPU views should be used or not.
3715 bool use_cpuview(const char *cg
)
3720 tmpc
= find_mounted_controller("cpu", &cfd
);
3724 tmpc
= find_mounted_controller("cpuacct", &cfd
);
3732 * check whether this is a '^processor" line in /proc/cpuinfo
3734 static bool is_processor_line(const char *line
)
3738 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3743 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3744 struct fuse_file_info
*fi
)
3746 struct fuse_context
*fc
= fuse_get_context();
3747 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3749 char *cpuset
= NULL
;
3751 size_t linelen
= 0, total_len
= 0, rv
= 0;
3752 bool am_printing
= false, firstline
= true, is_s390x
= false;
3753 int curcpu
= -1, cpu
, max_cpus
= 0;
3755 char *cache
= d
->buf
;
3756 size_t cache_size
= d
->buflen
;
3760 if (offset
> d
->size
)
3764 int left
= d
->size
- offset
;
3765 total_len
= left
> size
? size
: left
;
3766 memcpy(buf
, cache
+ offset
, total_len
);
3770 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3773 cg
= get_pid_cgroup(initpid
, "cpuset");
3775 return read_file("proc/cpuinfo", buf
, size
, d
);
3776 prune_init_slice(cg
);
3778 cpuset
= get_cpuset(cg
);
3782 use_view
= use_cpuview(cg
);
3785 max_cpus
= max_cpu_count(cg
);
3787 f
= fopen("/proc/cpuinfo", "r");
3791 while (getline(&line
, &linelen
, f
) != -1) {
3795 if (strstr(line
, "IBM/S390") != NULL
) {
3801 if (strncmp(line
, "# processors:", 12) == 0)
3803 if (is_processor_line(line
)) {
3804 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3806 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3809 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3811 perror("Error writing to cache");
3815 if (l
>= cache_size
) {
3816 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3825 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3827 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3829 if (!cpu_in_cpuset(cpu
, cpuset
))
3832 p
= strchr(line
, ':');
3836 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3838 perror("Error writing to cache");
3842 if (l
>= cache_size
) {
3843 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3854 l
= snprintf(cache
, cache_size
, "%s", line
);
3856 perror("Error writing to cache");
3860 if (l
>= cache_size
) {
3861 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3872 char *origcache
= d
->buf
;
3875 d
->buf
= malloc(d
->buflen
);
3878 cache_size
= d
->buflen
;
3880 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3881 if (l
< 0 || l
>= cache_size
) {
3888 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3889 if (l
< 0 || l
>= cache_size
) {
3896 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3898 if (l
< 0 || l
>= cache_size
)
3904 d
->size
= total_len
;
3905 if (total_len
> size
) total_len
= size
;
3907 /* read from off 0 */
3908 memcpy(buf
, d
->buf
, total_len
);
3919 static uint64_t get_reaper_start_time(pid_t pid
)
3924 /* strlen("/proc/") = 6
3928 * strlen("/stat") = 5
3932 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3933 char path
[__PROC_PID_STAT_LEN
];
3936 qpid
= lookup_initpid_in_store(pid
);
3938 /* Caller can check for EINVAL on 0. */
3943 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3944 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3945 /* Caller can check for EINVAL on 0. */
3950 f
= fopen(path
, "r");
3952 /* Caller can check for EINVAL on 0. */
3957 /* Note that the *scanf() argument supression requires that length
3958 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3959 * at us. It's like telling someone you're not married and then asking
3960 * if you can bring your wife to the party.
3962 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3963 "%*s " /* (2) comm %s */
3964 "%*c " /* (3) state %c */
3965 "%*d " /* (4) ppid %d */
3966 "%*d " /* (5) pgrp %d */
3967 "%*d " /* (6) session %d */
3968 "%*d " /* (7) tty_nr %d */
3969 "%*d " /* (8) tpgid %d */
3970 "%*u " /* (9) flags %u */
3971 "%*u " /* (10) minflt %lu */
3972 "%*u " /* (11) cminflt %lu */
3973 "%*u " /* (12) majflt %lu */
3974 "%*u " /* (13) cmajflt %lu */
3975 "%*u " /* (14) utime %lu */
3976 "%*u " /* (15) stime %lu */
3977 "%*d " /* (16) cutime %ld */
3978 "%*d " /* (17) cstime %ld */
3979 "%*d " /* (18) priority %ld */
3980 "%*d " /* (19) nice %ld */
3981 "%*d " /* (20) num_threads %ld */
3982 "%*d " /* (21) itrealvalue %ld */
3983 "%" PRIu64
, /* (22) starttime %llu */
3987 /* Caller can check for EINVAL on 0. */
3998 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
4000 uint64_t clockticks
;
4001 int64_t ticks_per_sec
;
4003 clockticks
= get_reaper_start_time(pid
);
4004 if (clockticks
== 0 && errno
== EINVAL
) {
4005 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
4009 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4010 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4013 "failed to determine number of clock ticks in a second");
4017 return (clockticks
/= ticks_per_sec
);
4020 static uint64_t get_reaper_age(pid_t pid
)
4022 uint64_t procstart
, uptime
, procage
;
4024 /* We need to substract the time the process has started since system
4025 * boot minus the time when the system has started to get the actual
4028 procstart
= get_reaper_start_time_in_sec(pid
);
4029 procage
= procstart
;
4030 if (procstart
> 0) {
4032 struct timespec spec
;
4034 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
4037 /* We could make this more precise here by using the tv_nsec
4038 * field in the timespec struct and convert it to milliseconds
4039 * and then create a double for the seconds and milliseconds but
4040 * that seems more work than it is worth.
4042 uptime
= spec
.tv_sec
;
4043 procage
= uptime
- procstart
;
4050 * Returns 0 on success.
4051 * It is the caller's responsibility to free `return_usage`, unless this
4052 * function returns an error.
4054 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
, int *size
)
4056 int cpucount
= get_nprocs_conf();
4057 struct cpuacct_usage
*cpu_usage
;
4058 int rv
= 0, i
, j
, ret
, read_pos
= 0, read_cnt
;
4060 uint64_t cg_user
, cg_system
;
4061 int64_t ticks_per_sec
;
4062 char *usage_str
= NULL
;
4064 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4066 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4069 "read_cpuacct_usage_all failed to determine number of clock ticks "
4074 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
4078 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
4083 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
4084 lxcfs_error("read_cpuacct_usage_all reading first line from "
4085 "%s/cpuacct.usage_all failed.\n", cg
);
4090 read_pos
+= read_cnt
;
4092 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
4093 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
4094 &cg_system
, &read_cnt
);
4100 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
4106 read_pos
+= read_cnt
;
4108 /* Convert the time from nanoseconds to USER_HZ */
4109 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4110 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4115 *return_usage
= cpu_usage
;
4124 *return_usage
= NULL
;
4130 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
4133 unsigned long sum
= 0;
4135 for (i
= 0; i
< cpu_count
; i
++) {
4136 if (!newer
[i
].online
)
4139 /* When cpuset is changed on the fly, the CPUs might get reordered.
4140 * We could either reset all counters, or check that the substractions
4141 * below will return expected results.
4143 if (newer
[i
].user
> older
[i
].user
)
4144 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
4148 if (newer
[i
].system
> older
[i
].system
)
4149 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
4153 if (newer
[i
].idle
> older
[i
].idle
)
4154 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
4158 sum
+= diff
[i
].user
;
4159 sum
+= diff
[i
].system
;
4160 sum
+= diff
[i
].idle
;
4166 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
4168 unsigned long free_space
, to_add
;
4170 free_space
= threshold
- usage
->user
- usage
->system
;
4172 if (free_space
> usage
->idle
)
4173 free_space
= usage
->idle
;
4175 to_add
= free_space
> *surplus
? *surplus
: free_space
;
4178 usage
->idle
-= to_add
;
4182 static struct cg_proc_stat
*prune_proc_stat_list(struct cg_proc_stat
*node
)
4184 struct cg_proc_stat
*first
= NULL
, *prev
, *tmp
;
4186 for (prev
= NULL
; node
; ) {
4187 if (!cgfs_param_exist("cpu", node
->cg
, "cpu.shares")) {
4189 lxcfs_debug("Removing stat node for %s\n", node
->cg
);
4192 prev
->next
= node
->next
;
4197 free_proc_stat_node(tmp
);
4209 #define PROC_STAT_PRUNE_INTERVAL 10
4210 static void prune_proc_stat_history(void)
4213 time_t now
= time(NULL
);
4215 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
4216 pthread_rwlock_wrlock(&proc_stat_history
[i
]->lock
);
4218 if ((proc_stat_history
[i
]->lastcheck
+ PROC_STAT_PRUNE_INTERVAL
) > now
) {
4219 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4223 if (proc_stat_history
[i
]->next
) {
4224 proc_stat_history
[i
]->next
= prune_proc_stat_list(proc_stat_history
[i
]->next
);
4225 proc_stat_history
[i
]->lastcheck
= now
;
4228 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4232 static struct cg_proc_stat
*find_proc_stat_node(struct cg_proc_stat_head
*head
, const char *cg
)
4234 struct cg_proc_stat
*node
;
4236 pthread_rwlock_rdlock(&head
->lock
);
4239 pthread_rwlock_unlock(&head
->lock
);
4246 if (strcmp(cg
, node
->cg
) == 0)
4248 } while ((node
= node
->next
));
4253 pthread_rwlock_unlock(&head
->lock
);
4254 prune_proc_stat_history();
4258 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4260 struct cg_proc_stat
*node
;
4263 node
= malloc(sizeof(struct cg_proc_stat
));
4271 node
->cg
= malloc(strlen(cg
) + 1);
4275 strcpy(node
->cg
, cg
);
4277 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4281 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4283 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4287 node
->cpu_count
= cpu_count
;
4290 if (pthread_mutex_init(&node
->lock
, NULL
) != 0) {
4291 lxcfs_error("%s\n", "Failed to initialize node lock");
4295 for (i
= 0; i
< cpu_count
; i
++) {
4296 node
->view
[i
].user
= 0;
4297 node
->view
[i
].system
= 0;
4298 node
->view
[i
].idle
= 0;
4304 if (node
&& node
->cg
)
4306 if (node
&& node
->usage
)
4308 if (node
&& node
->view
)
4316 static struct cg_proc_stat
*add_proc_stat_node(struct cg_proc_stat
*new_node
)
4318 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4319 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4320 struct cg_proc_stat
*node
, *rv
= new_node
;
4322 pthread_rwlock_wrlock(&head
->lock
);
4325 head
->next
= new_node
;
4332 if (strcmp(node
->cg
, new_node
->cg
) == 0) {
4333 /* The node is already present, return it */
4334 free_proc_stat_node(new_node
);
4344 node
->next
= new_node
;
4349 pthread_rwlock_unlock(&head
->lock
);
4353 static bool expand_proc_stat_node(struct cg_proc_stat
*node
, int cpu_count
)
4355 struct cpuacct_usage
*new_usage
, *new_view
;
4358 /* Allocate new memory */
4359 new_usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4363 new_view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4369 /* Copy existing data & initialize new elements */
4370 for (i
= 0; i
< cpu_count
; i
++) {
4371 if (i
< node
->cpu_count
) {
4372 new_usage
[i
].user
= node
->usage
[i
].user
;
4373 new_usage
[i
].system
= node
->usage
[i
].system
;
4374 new_usage
[i
].idle
= node
->usage
[i
].idle
;
4376 new_view
[i
].user
= node
->view
[i
].user
;
4377 new_view
[i
].system
= node
->view
[i
].system
;
4378 new_view
[i
].idle
= node
->view
[i
].idle
;
4380 new_usage
[i
].user
= 0;
4381 new_usage
[i
].system
= 0;
4382 new_usage
[i
].idle
= 0;
4384 new_view
[i
].user
= 0;
4385 new_view
[i
].system
= 0;
4386 new_view
[i
].idle
= 0;
4393 node
->usage
= new_usage
;
4394 node
->view
= new_view
;
4395 node
->cpu_count
= cpu_count
;
4400 static struct cg_proc_stat
*find_or_create_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4402 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4403 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4404 struct cg_proc_stat
*node
;
4406 node
= find_proc_stat_node(head
, cg
);
4409 node
= new_proc_stat_node(usage
, cpu_count
, cg
);
4413 node
= add_proc_stat_node(node
);
4414 lxcfs_debug("New stat node (%d) for %s\n", cpu_count
, cg
);
4417 pthread_mutex_lock(&node
->lock
);
4419 /* If additional CPUs on the host have been enabled, CPU usage counter
4420 * arrays have to be expanded */
4421 if (node
->cpu_count
< cpu_count
) {
4422 lxcfs_debug("Expanding stat node %d->%d for %s\n",
4423 node
->cpu_count
, cpu_count
, cg
);
4425 if (!expand_proc_stat_node(node
, cpu_count
)) {
4426 pthread_mutex_unlock(&node
->lock
);
4427 lxcfs_debug("Unable to expand stat node %d->%d for %s\n",
4428 node
->cpu_count
, cpu_count
, cg
);
4436 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4440 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4441 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4443 for (i
= 0; i
< cpu_count
; i
++) {
4444 node
->view
[i
].user
= 0;
4445 node
->view
[i
].system
= 0;
4446 node
->view
[i
].idle
= 0;
4449 node
->cpu_count
= cpu_count
;
4452 static int cpuview_proc_stat(const char *cg
, const char *cpuset
, struct cpuacct_usage
*cg_cpu_usage
, int cg_cpu_usage_size
, FILE *f
, char *buf
, size_t buf_size
)
4455 size_t linelen
= 0, total_len
= 0, rv
= 0, l
;
4456 int curcpu
= -1; /* cpu numbering starts at 0 */
4458 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4459 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4460 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4461 unsigned long user_surplus
= 0, system_surplus
= 0;
4462 unsigned long total_sum
, threshold
;
4463 struct cg_proc_stat
*stat_node
;
4464 struct cpuacct_usage
*diff
= NULL
;
4465 int nprocs
= get_nprocs_conf();
4467 if (cg_cpu_usage_size
< nprocs
)
4468 nprocs
= cg_cpu_usage_size
;
4470 /* Read all CPU stats and stop when we've encountered other lines */
4471 while (getline(&line
, &linelen
, f
) != -1) {
4473 char cpu_char
[10]; /* That's a lot of cores */
4474 uint64_t all_used
, cg_used
;
4476 if (strlen(line
) == 0)
4478 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4479 /* not a ^cpuN line containing a number N */
4483 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4486 if (physcpu
>= cg_cpu_usage_size
)
4492 if (!cpu_in_cpuset(physcpu
, cpuset
)) {
4493 for (i
= curcpu
; i
<= physcpu
; i
++) {
4494 cg_cpu_usage
[i
].online
= false;
4499 if (curcpu
< physcpu
) {
4500 /* Some CPUs may be disabled */
4501 for (i
= curcpu
; i
< physcpu
; i
++)
4502 cg_cpu_usage
[i
].online
= false;
4507 cg_cpu_usage
[curcpu
].online
= true;
4509 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4524 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4525 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4527 if (all_used
>= cg_used
) {
4528 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4531 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4532 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4533 curcpu
, cg
, all_used
, cg_used
);
4534 cg_cpu_usage
[curcpu
].idle
= idle
;
4538 /* Cannot use more CPUs than is available due to cpuset */
4539 if (max_cpus
> cpu_cnt
)
4542 stat_node
= find_or_create_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4545 lxcfs_error("unable to find/create stat node for %s\n", cg
);
4550 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4557 * If the new values are LOWER than values stored in memory, it means
4558 * the cgroup has been reset/recreated and we should reset too.
4560 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4561 if (!cg_cpu_usage
[curcpu
].online
)
4564 if (cg_cpu_usage
[curcpu
].user
< stat_node
->usage
[curcpu
].user
)
4565 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4570 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, nprocs
);
4572 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4573 stat_node
->usage
[curcpu
].online
= cg_cpu_usage
[curcpu
].online
;
4575 if (!stat_node
->usage
[curcpu
].online
)
4580 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4581 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4582 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4584 if (max_cpus
> 0 && i
>= max_cpus
) {
4585 user_surplus
+= diff
[curcpu
].user
;
4586 system_surplus
+= diff
[curcpu
].system
;
4590 /* Calculate usage counters of visible CPUs */
4592 /* threshold = maximum usage per cpu, including idle */
4593 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4595 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4599 if (!stat_node
->usage
[curcpu
].online
)
4604 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4614 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4617 /* If there is still room, add system */
4621 &diff
[curcpu
].system
,
4625 if (user_surplus
> 0)
4626 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4627 if (system_surplus
> 0)
4628 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4630 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4634 if (!stat_node
->usage
[curcpu
].online
)
4639 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4640 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4641 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4643 user_sum
+= stat_node
->view
[curcpu
].user
;
4644 system_sum
+= stat_node
->view
[curcpu
].system
;
4645 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4649 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4650 if (!stat_node
->usage
[curcpu
].online
)
4653 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4654 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4655 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4657 user_sum
+= stat_node
->view
[curcpu
].user
;
4658 system_sum
+= stat_node
->view
[curcpu
].system
;
4659 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4663 /* Render the file */
4665 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4671 perror("Error writing to cache");
4676 if (l
>= buf_size
) {
4677 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4686 /* Render visible CPUs */
4687 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4688 if (!stat_node
->usage
[curcpu
].online
)
4693 if (max_cpus
> 0 && i
== max_cpus
)
4696 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4698 stat_node
->view
[curcpu
].user
,
4699 stat_node
->view
[curcpu
].system
,
4700 stat_node
->view
[curcpu
].idle
);
4703 perror("Error writing to cache");
4708 if (l
>= buf_size
) {
4709 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4719 /* Pass the rest of /proc/stat, start with the last line read */
4720 l
= snprintf(buf
, buf_size
, "%s", line
);
4723 perror("Error writing to cache");
4728 if (l
>= buf_size
) {
4729 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4738 /* Pass the rest of the host's /proc/stat */
4739 while (getline(&line
, &linelen
, f
) != -1) {
4740 l
= snprintf(buf
, buf_size
, "%s", line
);
4742 perror("Error writing to cache");
4746 if (l
>= buf_size
) {
4747 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4760 pthread_mutex_unlock(&stat_node
->lock
);
4768 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4769 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4770 struct fuse_file_info
*fi
)
4772 struct fuse_context
*fc
= fuse_get_context();
4773 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4775 char *cpuset
= NULL
;
4777 size_t linelen
= 0, total_len
= 0, rv
= 0;
4778 int curcpu
= -1; /* cpu numbering starts at 0 */
4780 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4781 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
4782 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4783 char cpuall
[CPUALL_MAX_SIZE
];
4784 /* reserve for cpu all */
4785 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4786 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4788 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4789 int cg_cpu_usage_size
= 0;
4792 if (offset
> d
->size
)
4796 int left
= d
->size
- offset
;
4797 total_len
= left
> size
? size
: left
;
4798 memcpy(buf
, d
->buf
+ offset
, total_len
);
4802 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4805 cg
= get_pid_cgroup(initpid
, "cpuset");
4807 return read_file("/proc/stat", buf
, size
, d
);
4808 prune_init_slice(cg
);
4810 cpuset
= get_cpuset(cg
);
4815 * Read cpuacct.usage_all for all CPUs.
4816 * If the cpuacct cgroup is present, it is used to calculate the container's
4817 * CPU usage. If not, values from the host's /proc/stat are used.
4819 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
, &cg_cpu_usage_size
) != 0) {
4820 lxcfs_debug("%s\n", "proc_stat_read failed to read from cpuacct, "
4821 "falling back to the host's /proc/stat");
4824 f
= fopen("/proc/stat", "r");
4829 if (getline(&line
, &linelen
, f
) < 0) {
4830 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
4834 if (use_cpuview(cg
) && cg_cpu_usage
) {
4835 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, cg_cpu_usage_size
,
4836 f
, d
->buf
, d
->buflen
);
4840 while (getline(&line
, &linelen
, f
) != -1) {
4842 char cpu_char
[10]; /* That's a lot of cores */
4844 uint64_t all_used
, cg_used
, new_idle
;
4847 if (strlen(line
) == 0)
4849 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4850 /* not a ^cpuN line containing a number N, just print it */
4851 l
= snprintf(cache
, cache_size
, "%s", line
);
4853 perror("Error writing to cache");
4857 if (l
>= cache_size
) {
4858 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4868 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4870 if (!cpu_in_cpuset(physcpu
, cpuset
))
4874 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4886 if (ret
!= 10 || !cg_cpu_usage
) {
4887 c
= strchr(line
, ' ');
4890 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4892 perror("Error writing to cache");
4897 if (l
>= cache_size
) {
4898 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4912 if (physcpu
>= cg_cpu_usage_size
)
4915 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4916 cg_used
= cg_cpu_usage
[physcpu
].user
+ cg_cpu_usage
[physcpu
].system
;
4918 if (all_used
>= cg_used
) {
4919 new_idle
= idle
+ (all_used
- cg_used
);
4922 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4923 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4924 curcpu
, cg
, all_used
, cg_used
);
4928 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4929 curcpu
, cg_cpu_usage
[physcpu
].user
, cg_cpu_usage
[physcpu
].system
,
4933 perror("Error writing to cache");
4938 if (l
>= cache_size
) {
4939 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4948 user_sum
+= cg_cpu_usage
[physcpu
].user
;
4949 system_sum
+= cg_cpu_usage
[physcpu
].system
;
4950 idle_sum
+= new_idle
;
4955 system_sum
+= system
;
4957 iowait_sum
+= iowait
;
4959 softirq_sum
+= softirq
;
4962 guest_nice_sum
+= guest_nice
;
4968 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4979 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4980 memcpy(cache
, cpuall
, cpuall_len
);
4981 cache
+= cpuall_len
;
4983 /* shouldn't happen */
4984 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4988 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4989 total_len
+= cpuall_len
;
4993 d
->size
= total_len
;
4994 if (total_len
> size
)
4997 memcpy(buf
, d
->buf
, total_len
);
5011 /* This function retrieves the busy time of a group of tasks by looking at
5012 * cpuacct.usage. Unfortunately, this only makes sense when the container has
5013 * been given it's own cpuacct cgroup. If not, this function will take the busy
5014 * time of all other taks that do not actually belong to the container into
5015 * account as well. If someone has a clever solution for this please send a
5018 static unsigned long get_reaper_busy(pid_t task
)
5020 pid_t initpid
= lookup_initpid_in_store(task
);
5021 char *cgroup
= NULL
, *usage_str
= NULL
;
5022 unsigned long usage
= 0;
5027 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
5030 prune_init_slice(cgroup
);
5031 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
5033 usage
= strtoul(usage_str
, NULL
, 10);
5034 usage
/= 1000000000;
5047 fd
= creat("/tmp/lxcfs-iwashere", 0644);
5054 * We read /proc/uptime and reuse its second field.
5055 * For the first field, we use the mtime for the reaper for
5056 * the calling pid as returned by getreaperage
5058 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
5059 struct fuse_file_info
*fi
)
5061 struct fuse_context
*fc
= fuse_get_context();
5062 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5063 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
5064 char *cache
= d
->buf
;
5065 ssize_t total_len
= 0;
5066 uint64_t idletime
, reaperage
;
5075 if (offset
> d
->size
)
5077 int left
= d
->size
- offset
;
5078 total_len
= left
> size
? size
: left
;
5079 memcpy(buf
, cache
+ offset
, total_len
);
5083 reaperage
= get_reaper_age(fc
->pid
);
5084 /* To understand why this is done, please read the comment to the
5085 * get_reaper_busy() function.
5087 idletime
= reaperage
;
5088 if (reaperage
>= busytime
)
5089 idletime
= reaperage
- busytime
;
5091 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
5092 if (total_len
< 0 || total_len
>= d
->buflen
){
5093 lxcfs_error("%s\n", "failed to write to cache");
5097 d
->size
= (int)total_len
;
5100 if (total_len
> size
) total_len
= size
;
5102 memcpy(buf
, d
->buf
, total_len
);
5106 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
5107 struct fuse_file_info
*fi
)
5110 struct fuse_context
*fc
= fuse_get_context();
5111 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5113 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
5114 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
5115 unsigned long read
= 0, write
= 0;
5116 unsigned long read_merged
= 0, write_merged
= 0;
5117 unsigned long read_sectors
= 0, write_sectors
= 0;
5118 unsigned long read_ticks
= 0, write_ticks
= 0;
5119 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
5120 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
5121 char *cache
= d
->buf
;
5122 size_t cache_size
= d
->buflen
;
5124 size_t linelen
= 0, total_len
= 0, rv
= 0;
5125 unsigned int major
= 0, minor
= 0;
5130 if (offset
> d
->size
)
5134 int left
= d
->size
- offset
;
5135 total_len
= left
> size
? size
: left
;
5136 memcpy(buf
, cache
+ offset
, total_len
);
5140 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5143 cg
= get_pid_cgroup(initpid
, "blkio");
5145 return read_file("/proc/diskstats", buf
, size
, d
);
5146 prune_init_slice(cg
);
5148 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
5150 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
5152 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
5154 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
5156 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
5160 f
= fopen("/proc/diskstats", "r");
5164 while (getline(&line
, &linelen
, f
) != -1) {
5168 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
5172 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
5173 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
5174 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
5175 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
5176 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
5177 read_sectors
= read_sectors
/512;
5178 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
5179 write_sectors
= write_sectors
/512;
5181 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
5182 rd_svctm
= rd_svctm
/1000000;
5183 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
5184 rd_wait
= rd_wait
/1000000;
5185 read_ticks
= rd_svctm
+ rd_wait
;
5187 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
5188 wr_svctm
= wr_svctm
/1000000;
5189 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
5190 wr_wait
= wr_wait
/1000000;
5191 write_ticks
= wr_svctm
+ wr_wait
;
5193 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
5194 tot_ticks
= tot_ticks
/1000000;
5196 memset(lbuf
, 0, 256);
5197 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
5198 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5199 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
5200 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
5204 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
5206 perror("Error writing to fuse buf");
5210 if (l
>= cache_size
) {
5211 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5221 d
->size
= total_len
;
5222 if (total_len
> size
) total_len
= size
;
5223 memcpy(buf
, d
->buf
, total_len
);
5231 free(io_serviced_str
);
5232 free(io_merged_str
);
5233 free(io_service_bytes_str
);
5234 free(io_wait_time_str
);
5235 free(io_service_time_str
);
5239 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
5240 struct fuse_file_info
*fi
)
5242 struct fuse_context
*fc
= fuse_get_context();
5243 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5245 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
5246 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
5247 ssize_t total_len
= 0, rv
= 0;
5249 char *cache
= d
->buf
;
5252 if (offset
> d
->size
)
5256 int left
= d
->size
- offset
;
5257 total_len
= left
> size
? size
: left
;
5258 memcpy(buf
, cache
+ offset
, total_len
);
5262 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5265 cg
= get_pid_cgroup(initpid
, "memory");
5267 return read_file("/proc/swaps", buf
, size
, d
);
5268 prune_init_slice(cg
);
5270 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
5272 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
5275 memusage
= strtoul(memusage_str
, NULL
, 10);
5277 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
5278 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
5280 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
5281 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5283 swap_total
= (memswlimit
- memlimit
) / 1024;
5284 swap_free
= (memswusage
- memusage
) / 1024;
5287 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5289 /* When no mem + swap limit is specified or swapaccount=0*/
5293 FILE *f
= fopen("/proc/meminfo", "r");
5298 while (getline(&line
, &linelen
, f
) != -1) {
5299 if (startswith(line
, "SwapTotal:")) {
5300 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5301 } else if (startswith(line
, "SwapFree:")) {
5302 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5310 if (swap_total
> 0) {
5311 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5312 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5313 swap_total
, swap_free
);
5317 if (total_len
< 0 || l
< 0) {
5318 perror("Error writing to cache");
5324 d
->size
= (int)total_len
;
5326 if (total_len
> size
) total_len
= size
;
5327 memcpy(buf
, d
->buf
, total_len
);
5332 free(memswlimit_str
);
5335 free(memswusage_str
);
5339 * Find the process pid from cgroup path.
5340 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5341 * @pid_buf : put pid to pid_buf.
5342 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5343 * @depth : the depth of cgroup in container.
5344 * @sum : return the number of pid.
5345 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5347 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5351 struct dirent
*file
;
5356 char *path_dir
, *path
;
5359 /* path = dpath + "/cgroup.procs" + /0 */
5361 path
= malloc(strlen(dpath
) + 20);
5364 strcpy(path
, dpath
);
5365 fd
= openat(cfd
, path
, O_RDONLY
);
5369 dir
= fdopendir(fd
);
5375 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5376 if (strncmp(file
->d_name
, ".", 1) == 0)
5378 if (strncmp(file
->d_name
, "..", 1) == 0)
5380 if (file
->d_type
== DT_DIR
) {
5381 /* path + '/' + d_name +/0 */
5383 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5384 } while (!path_dir
);
5385 strcpy(path_dir
, path
);
5386 strcat(path_dir
, "/");
5387 strcat(path_dir
, file
->d_name
);
5389 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5395 strcat(path
, "/cgroup.procs");
5396 fd
= openat(cfd
, path
, O_RDONLY
);
5400 f
= fdopen(fd
, "r");
5406 while (getline(&line
, &linelen
, f
) != -1) {
5408 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5412 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5413 } while (*(*pid_buf
+ sum
) == NULL
);
5414 strcpy(*(*pid_buf
+ sum
), line
);
5425 * calc_load calculates the load according to the following formula:
5426 * load1 = load0 * exp + active * (1 - exp)
5428 * @load1: the new loadavg.
5429 * @load0: the former loadavg.
5430 * @active: the total number of running pid at this moment.
5431 * @exp: the fixed-point defined in the beginning.
5433 static unsigned long
5434 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5436 unsigned long newload
;
5438 active
= active
> 0 ? active
* FIXED_1
: 0;
5439 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5441 newload
+= FIXED_1
- 1;
5443 return newload
/ FIXED_1
;
5447 * Return 0 means that container p->cg is closed.
5448 * Return -1 means that error occurred in refresh.
5449 * Positive num equals the total number of pid.
5451 static int refresh_load(struct load_node
*p
, char *path
)
5455 char proc_path
[256];
5456 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5461 struct dirent
*file
;
5464 idbuf
= malloc(sizeof(char *));
5466 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5471 for (i
= 0; i
< sum
; i
++) {
5473 length
= strlen(idbuf
[i
])-1;
5474 idbuf
[i
][length
] = '\0';
5475 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5476 if (ret
< 0 || ret
> 255) {
5477 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5483 dp
= opendir(proc_path
);
5485 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5488 while ((file
= readdir(dp
)) != NULL
) {
5489 if (strncmp(file
->d_name
, ".", 1) == 0)
5491 if (strncmp(file
->d_name
, "..", 1) == 0)
5494 /* We make the biggest pid become last_pid.*/
5495 ret
= atof(file
->d_name
);
5496 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5498 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5499 if (ret
< 0 || ret
> 255) {
5500 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5506 f
= fopen(proc_path
, "r");
5508 while (getline(&line
, &linelen
, f
) != -1) {
5510 if ((line
[0] == 'S') && (line
[1] == 't'))
5513 if ((line
[7] == 'R') || (line
[7] == 'D'))
5520 /*Calculate the loadavg.*/
5521 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5522 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5523 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5524 p
->run_pid
= run_pid
;
5525 p
->total_pid
= total_pid
;
5526 p
->last_pid
= last_pid
;
5537 * Traverse the hash table and update it.
5539 void *load_begin(void *arg
)
5543 int i
, sum
, length
, ret
;
5544 struct load_node
*f
;
5546 clock_t time1
, time2
;
5549 if (loadavg_stop
== 1)
5553 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5554 pthread_mutex_lock(&load_hash
[i
].lock
);
5555 if (load_hash
[i
].next
== NULL
) {
5556 pthread_mutex_unlock(&load_hash
[i
].lock
);
5559 f
= load_hash
[i
].next
;
5562 length
= strlen(f
->cg
) + 2;
5564 /* strlen(f->cg) + '.' or '' + \0 */
5565 path
= malloc(length
);
5568 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
5569 if (ret
< 0 || ret
> length
- 1) {
5570 /* snprintf failed, ignore the node.*/
5571 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5574 sum
= refresh_load(f
, path
);
5581 /* load_hash[i].lock locks only on the first node.*/
5582 if (first_node
== 1) {
5584 pthread_mutex_unlock(&load_hash
[i
].lock
);
5589 if (loadavg_stop
== 1)
5593 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5597 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5598 struct fuse_file_info
*fi
)
5600 struct fuse_context
*fc
= fuse_get_context();
5601 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5604 size_t total_len
= 0;
5605 char *cache
= d
->buf
;
5606 struct load_node
*n
;
5609 unsigned long a
, b
, c
;
5612 if (offset
> d
->size
)
5616 int left
= d
->size
- offset
;
5617 total_len
= left
> size
? size
: left
;
5618 memcpy(buf
, cache
+ offset
, total_len
);
5622 return read_file("/proc/loadavg", buf
, size
, d
);
5624 initpid
= lookup_initpid_in_store(fc
->pid
);
5627 cg
= get_pid_cgroup(initpid
, "cpu");
5629 return read_file("/proc/loadavg", buf
, size
, d
);
5631 prune_init_slice(cg
);
5632 hash
= calc_hash(cg
) % LOAD_SIZE
;
5633 n
= locate_node(cg
, hash
);
5637 if (!find_mounted_controller("cpu", &cfd
)) {
5639 * In locate_node() above, pthread_rwlock_unlock() isn't used
5640 * because delete is not allowed before read has ended.
5642 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5647 n
= malloc(sizeof(struct load_node
));
5651 n
->cg
= malloc(strlen(cg
)+1);
5659 n
->last_pid
= initpid
;
5661 insert_node(&n
, hash
);
5663 a
= n
->avenrun
[0] + (FIXED_1
/200);
5664 b
= n
->avenrun
[1] + (FIXED_1
/200);
5665 c
= n
->avenrun
[2] + (FIXED_1
/200);
5666 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5667 LOAD_INT(a
), LOAD_FRAC(a
),
5668 LOAD_INT(b
), LOAD_FRAC(b
),
5669 LOAD_INT(c
), LOAD_FRAC(c
),
5670 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5671 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5672 if (total_len
< 0 || total_len
>= d
->buflen
) {
5673 lxcfs_error("%s\n", "Failed to write to cache");
5677 d
->size
= (int)total_len
;
5680 if (total_len
> size
)
5682 memcpy(buf
, d
->buf
, total_len
);
5689 /* Return a positive number on success, return 0 on failure.*/
5690 pthread_t
load_daemon(int load_use
)
5697 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5700 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5702 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5706 /* use loadavg, here loadavg = 1*/
5711 /* Returns 0 on success. */
5712 int stop_load_daemon(pthread_t pid
)
5716 /* Signal the thread to gracefully stop */
5719 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5721 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5731 static off_t
get_procfile_size(const char *which
)
5733 FILE *f
= fopen(which
, "r");
5736 ssize_t sz
, answer
= 0;
5740 while ((sz
= getline(&line
, &len
, f
)) != -1)
5748 int proc_getattr(const char *path
, struct stat
*sb
)
5750 struct timespec now
;
5752 memset(sb
, 0, sizeof(struct stat
));
5753 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5755 sb
->st_uid
= sb
->st_gid
= 0;
5756 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5757 if (strcmp(path
, "/proc") == 0) {
5758 sb
->st_mode
= S_IFDIR
| 00555;
5762 if (strcmp(path
, "/proc/meminfo") == 0 ||
5763 strcmp(path
, "/proc/cpuinfo") == 0 ||
5764 strcmp(path
, "/proc/uptime") == 0 ||
5765 strcmp(path
, "/proc/stat") == 0 ||
5766 strcmp(path
, "/proc/diskstats") == 0 ||
5767 strcmp(path
, "/proc/swaps") == 0 ||
5768 strcmp(path
, "/proc/loadavg") == 0) {
5770 sb
->st_mode
= S_IFREG
| 00444;
5778 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5779 struct fuse_file_info
*fi
)
5781 if (filler(buf
, ".", NULL
, 0) != 0 ||
5782 filler(buf
, "..", NULL
, 0) != 0 ||
5783 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5784 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5785 filler(buf
, "stat", NULL
, 0) != 0 ||
5786 filler(buf
, "uptime", NULL
, 0) != 0 ||
5787 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5788 filler(buf
, "swaps", NULL
, 0) != 0 ||
5789 filler(buf
, "loadavg", NULL
, 0) != 0)
5794 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5797 struct file_info
*info
;
5799 if (strcmp(path
, "/proc/meminfo") == 0)
5800 type
= LXC_TYPE_PROC_MEMINFO
;
5801 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5802 type
= LXC_TYPE_PROC_CPUINFO
;
5803 else if (strcmp(path
, "/proc/uptime") == 0)
5804 type
= LXC_TYPE_PROC_UPTIME
;
5805 else if (strcmp(path
, "/proc/stat") == 0)
5806 type
= LXC_TYPE_PROC_STAT
;
5807 else if (strcmp(path
, "/proc/diskstats") == 0)
5808 type
= LXC_TYPE_PROC_DISKSTATS
;
5809 else if (strcmp(path
, "/proc/swaps") == 0)
5810 type
= LXC_TYPE_PROC_SWAPS
;
5811 else if (strcmp(path
, "/proc/loadavg") == 0)
5812 type
= LXC_TYPE_PROC_LOADAVG
;
5816 info
= malloc(sizeof(*info
));
5820 memset(info
, 0, sizeof(*info
));
5823 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
5825 info
->buf
= malloc(info
->buflen
);
5826 } while (!info
->buf
);
5827 memset(info
->buf
, 0, info
->buflen
);
5828 /* set actual size to buffer size */
5829 info
->size
= info
->buflen
;
5831 fi
->fh
= (unsigned long)info
;
5835 int proc_access(const char *path
, int mask
)
5837 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
5840 /* these are all read-only */
5841 if ((mask
& ~R_OK
) != 0)
5846 int proc_release(const char *path
, struct fuse_file_info
*fi
)
5848 do_release_file_info(fi
);
5852 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
5853 struct fuse_file_info
*fi
)
5855 struct file_info
*f
= (struct file_info
*) fi
->fh
;
5858 case LXC_TYPE_PROC_MEMINFO
:
5859 return proc_meminfo_read(buf
, size
, offset
, fi
);
5860 case LXC_TYPE_PROC_CPUINFO
:
5861 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
5862 case LXC_TYPE_PROC_UPTIME
:
5863 return proc_uptime_read(buf
, size
, offset
, fi
);
5864 case LXC_TYPE_PROC_STAT
:
5865 return proc_stat_read(buf
, size
, offset
, fi
);
5866 case LXC_TYPE_PROC_DISKSTATS
:
5867 return proc_diskstats_read(buf
, size
, offset
, fi
);
5868 case LXC_TYPE_PROC_SWAPS
:
5869 return proc_swaps_read(buf
, size
, offset
, fi
);
5870 case LXC_TYPE_PROC_LOADAVG
:
5871 return proc_loadavg_read(buf
, size
, offset
, fi
);
5878 * Functions needed to setup cgroups in the __constructor__.
5881 static bool mkdir_p(const char *dir
, mode_t mode
)
5883 const char *tmp
= dir
;
5884 const char *orig
= dir
;
5888 dir
= tmp
+ strspn(tmp
, "/");
5889 tmp
= dir
+ strcspn(dir
, "/");
5890 makeme
= strndup(orig
, dir
- orig
);
5893 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
5894 lxcfs_error("Failed to create directory '%s': %s.\n",
5895 makeme
, strerror(errno
));
5900 } while(tmp
!= dir
);
5905 static bool umount_if_mounted(void)
5907 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5908 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5914 /* __typeof__ should be safe to use with all compilers. */
5915 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5916 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5918 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5922 * looking at fs/proc_namespace.c, it appears we can
5923 * actually expect the rootfs entry to very specifically contain
5924 * " - rootfs rootfs "
5925 * IIUC, so long as we've chrooted so that rootfs is not our root,
5926 * the rootfs entry should always be skipped in mountinfo contents.
5928 static bool is_on_ramfs(void)
5936 f
= fopen("/proc/self/mountinfo", "r");
5940 while (getline(&line
, &len
, f
) != -1) {
5941 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5942 p
= strchr(p
+ 1, ' ');
5945 p2
= strchr(p
+ 1, ' ');
5949 if (strcmp(p
+ 1, "/") == 0) {
5950 // this is '/'. is it the ramfs?
5951 p
= strchr(p2
+ 1, '-');
5952 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5964 static int pivot_enter()
5966 int ret
= -1, oldroot
= -1, newroot
= -1;
5968 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5970 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5974 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5976 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5980 /* change into new root fs */
5981 if (fchdir(newroot
) < 0) {
5982 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5986 /* pivot_root into our new root fs */
5987 if (pivot_root(".", ".") < 0) {
5988 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5993 * At this point the old-root is mounted on top of our new-root.
5994 * To unmounted it we must not be chdir'd into it, so escape back
5997 if (fchdir(oldroot
) < 0) {
5998 lxcfs_error("%s\n", "Failed to enter old root.");
6002 if (umount2(".", MNT_DETACH
) < 0) {
6003 lxcfs_error("%s\n", "Failed to detach old root.");
6007 if (fchdir(newroot
) < 0) {
6008 lxcfs_error("%s\n", "Failed to re-enter new root.");
6023 static int chroot_enter()
6025 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
6026 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
6030 if (chroot(".") < 0) {
6031 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
6035 if (chdir("/") < 0) {
6036 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
6043 static int permute_and_enter(void)
6047 if (statfs("/", &sb
) < 0) {
6048 lxcfs_error("%s\n", "Could not stat / mountpoint.");
6052 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
6053 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
6054 * /proc/1/mountinfo. */
6055 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
6056 return chroot_enter();
6058 if (pivot_enter() < 0) {
6059 lxcfs_error("%s\n", "Could not perform pivot root.");
6066 /* Prepare our new clean root. */
6067 static int permute_prepare(void)
6069 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
6070 lxcfs_error("%s\n", "Failed to create directory for new root.");
6074 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
6075 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
6079 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
6080 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
6084 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
6085 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
6092 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
6093 static bool permute_root(void)
6095 /* Prepare new root. */
6096 if (permute_prepare() < 0)
6099 /* Pivot into new root. */
6100 if (permute_and_enter() < 0)
6106 static int preserve_mnt_ns(int pid
)
6109 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
6112 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
6113 if (ret
< 0 || (size_t)ret
>= len
)
6116 return open(path
, O_RDONLY
| O_CLOEXEC
);
6119 static bool cgfs_prepare_mounts(void)
6121 if (!mkdir_p(BASEDIR
, 0700)) {
6122 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
6126 if (!umount_if_mounted()) {
6127 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
6131 if (unshare(CLONE_NEWNS
) < 0) {
6132 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
6136 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
6137 if (cgroup_mount_ns_fd
< 0) {
6138 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
6142 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
6143 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
6147 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
6148 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
6155 static bool cgfs_mount_hierarchies(void)
6161 for (i
= 0; i
< num_hierarchies
; i
++) {
6162 char *controller
= hierarchies
[i
];
6164 clen
= strlen(controller
);
6165 len
= strlen(BASEDIR
) + clen
+ 2;
6166 target
= malloc(len
);
6170 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
6171 if (ret
< 0 || ret
>= len
) {
6175 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
6179 if (!strcmp(controller
, "unified"))
6180 ret
= mount("none", target
, "cgroup2", 0, NULL
);
6182 ret
= mount(controller
, target
, "cgroup", 0, controller
);
6184 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
6189 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
6190 if (fd_hierarchies
[i
] < 0) {
6199 static bool cgfs_setup_controllers(void)
6201 if (!cgfs_prepare_mounts())
6204 if (!cgfs_mount_hierarchies()) {
6205 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
6209 if (!permute_root())
6215 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
6218 char *cret
, *line
= NULL
;
6219 char cwd
[MAXPATHLEN
];
6221 int i
, init_ns
= -1;
6222 bool found_unified
= false;
6224 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
6225 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
6229 while (getline(&line
, &len
, f
) != -1) {
6232 p
= strchr(line
, ':');
6238 p2
= strrchr(p
, ':');
6243 /* With cgroupv2 /proc/self/cgroup can contain entries of the
6244 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
6245 * because it parses out the empty string "" and later on passes
6246 * it to mount(). Let's skip such entries.
6248 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
6249 found_unified
= true;
6253 if (!store_hierarchy(line
, p
))
6257 /* Preserve initial namespace. */
6258 init_ns
= preserve_mnt_ns(getpid());
6260 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
6264 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
6265 if (!fd_hierarchies
) {
6266 lxcfs_error("%s\n", strerror(errno
));
6270 for (i
= 0; i
< num_hierarchies
; i
++)
6271 fd_hierarchies
[i
] = -1;
6273 cret
= getcwd(cwd
, MAXPATHLEN
);
6275 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
6277 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
6278 * to privately mount lxcfs cgroups. */
6279 if (!cgfs_setup_controllers()) {
6280 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
6284 if (setns(init_ns
, 0) < 0) {
6285 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
6289 if (!cret
|| chdir(cwd
) < 0)
6290 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
6292 if (!init_cpuview()) {
6293 lxcfs_error("%s\n", "failed to init CPU view");
6306 static void __attribute__((destructor
)) free_subsystems(void)
6310 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
6312 for (i
= 0; i
< num_hierarchies
; i
++) {
6314 free(hierarchies
[i
]);
6315 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
6316 close(fd_hierarchies
[i
]);
6319 free(fd_hierarchies
);
6322 if (cgroup_mount_ns_fd
>= 0)
6323 close(cgroup_mount_ns_fd
);