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
29 #include <linux/magic.h>
30 #include <linux/sched.h>
31 #include <sys/epoll.h>
33 #include <sys/mount.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <sys/syscall.h>
37 #include <sys/sysinfo.h>
41 #include "memory_utils.h"
44 /* Define pivot_root() if missing from the C library */
45 #ifndef HAVE_PIVOT_ROOT
46 static int pivot_root(const char * new_root
, const char * put_old
)
48 #ifdef __NR_pivot_root
49 return syscall(__NR_pivot_root
, new_root
, put_old
);
56 extern int pivot_root(const char * new_root
, const char * put_old
);
59 struct cpuacct_usage
{
66 /* The function of hash table.*/
67 #define LOAD_SIZE 100 /*the size of hash_table */
68 #define FLUSH_TIME 5 /*the flush rate */
69 #define DEPTH_DIR 3 /*the depth of per cgroup */
70 /* The function of calculate loadavg .*/
71 #define FSHIFT 11 /* nr of bits of precision */
72 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
73 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
74 #define EXP_5 2014 /* 1/exp(5sec/5min) */
75 #define EXP_15 2037 /* 1/exp(5sec/15min) */
76 #define LOAD_INT(x) ((x) >> FSHIFT)
77 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
79 * This parameter is used for proc_loadavg_read().
80 * 1 means use loadavg, 0 means not use.
82 static int loadavg
= 0;
83 static volatile sig_atomic_t loadavg_stop
= 0;
84 static int calc_hash(const char *name
)
86 unsigned int hash
= 0;
88 /* ELFHash algorithm. */
90 hash
= (hash
<< 4) + *name
++;
91 x
= hash
& 0xf0000000;
96 return (hash
& 0x7fffffff);
101 unsigned long avenrun
[3]; /* Load averages */
102 unsigned int run_pid
;
103 unsigned int total_pid
;
104 unsigned int last_pid
;
105 int cfd
; /* The file descriptor of the mounted cgroup */
106 struct load_node
*next
;
107 struct load_node
**pre
;
112 * The lock is about insert load_node and refresh load_node.To the first
113 * load_node of each hash bucket, insert and refresh in this hash bucket is
114 * mutually exclusive.
116 pthread_mutex_t lock
;
118 * The rdlock is about read loadavg and delete load_node.To each hash
119 * bucket, read and delete is mutually exclusive. But at the same time, we
120 * allow paratactic read operation. This rdlock is at list level.
122 pthread_rwlock_t rdlock
;
124 * The rilock is about read loadavg and insert load_node.To the first
125 * load_node of each hash bucket, read and insert is mutually exclusive.
126 * But at the same time, we allow paratactic read operation.
128 pthread_rwlock_t rilock
;
129 struct load_node
*next
;
132 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
134 * init_load initialize the hash table.
135 * Return 0 on success, return -1 on failure.
137 static int init_load(void)
142 for (i
= 0; i
< LOAD_SIZE
; i
++) {
143 load_hash
[i
].next
= NULL
;
144 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
146 lxcfs_error("%s\n", "Failed to initialize lock");
149 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
151 lxcfs_error("%s\n", "Failed to initialize rdlock");
154 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
156 lxcfs_error("%s\n", "Failed to initialize rilock");
162 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
164 pthread_mutex_destroy(&load_hash
[i
].lock
);
168 pthread_mutex_destroy(&load_hash
[i
].lock
);
169 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
170 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
175 static void insert_node(struct load_node
**n
, int locate
)
179 pthread_mutex_lock(&load_hash
[locate
].lock
);
180 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
181 f
= load_hash
[locate
].next
;
182 load_hash
[locate
].next
= *n
;
184 (*n
)->pre
= &(load_hash
[locate
].next
);
186 f
->pre
= &((*n
)->next
);
188 pthread_mutex_unlock(&load_hash
[locate
].lock
);
189 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
192 * locate_node() finds special node. Not return NULL means success.
193 * It should be noted that rdlock isn't unlocked at the end of code
194 * because this function is used to read special node. Delete is not
195 * allowed before read has ended.
196 * unlock rdlock only in proc_loadavg_read().
198 static struct load_node
*locate_node(char *cg
, int locate
)
200 struct load_node
*f
= NULL
;
203 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
204 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
205 if (load_hash
[locate
].next
== NULL
) {
206 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
209 f
= load_hash
[locate
].next
;
210 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
211 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
215 /* Delete the load_node n and return the next node of it. */
216 static struct load_node
*del_node(struct load_node
*n
, int locate
)
220 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
221 if (n
->next
== NULL
) {
225 n
->next
->pre
= n
->pre
;
230 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
234 static void load_free(void)
237 struct load_node
*f
, *p
;
239 for (i
= 0; i
< LOAD_SIZE
; i
++) {
240 pthread_mutex_lock(&load_hash
[i
].lock
);
241 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
242 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
243 if (load_hash
[i
].next
== NULL
) {
244 pthread_mutex_unlock(&load_hash
[i
].lock
);
245 pthread_mutex_destroy(&load_hash
[i
].lock
);
246 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
247 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
248 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
249 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
252 for (f
= load_hash
[i
].next
; f
; ) {
258 pthread_mutex_unlock(&load_hash
[i
].lock
);
259 pthread_mutex_destroy(&load_hash
[i
].lock
);
260 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
261 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
262 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
263 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
267 /* Data for CPU view */
268 struct cg_proc_stat
{
270 struct cpuacct_usage
*usage
; // Real usage as read from the host's /proc/stat
271 struct cpuacct_usage
*view
; // Usage stats reported to the container
273 pthread_mutex_t lock
; // For node manipulation
274 struct cg_proc_stat
*next
;
277 struct cg_proc_stat_head
{
278 struct cg_proc_stat
*next
;
282 * For access to the list. Reading can be parallel, pruning is exclusive.
284 pthread_rwlock_t lock
;
287 #define CPUVIEW_HASH_SIZE 100
288 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
290 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
292 *head
= malloc(sizeof(struct cg_proc_stat_head
));
294 lxcfs_error("%s\n", strerror(errno
));
298 (*head
)->lastcheck
= time(NULL
);
299 (*head
)->next
= NULL
;
301 if (pthread_rwlock_init(&(*head
)->lock
, NULL
) != 0) {
302 lxcfs_error("%s\n", "Failed to initialize list lock");
310 static bool init_cpuview()
314 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
315 proc_stat_history
[i
] = NULL
;
317 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
318 if (!cpuview_init_head(&proc_stat_history
[i
]))
325 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
326 if (proc_stat_history
[i
]) {
327 free(proc_stat_history
[i
]);
328 proc_stat_history
[i
] = NULL
;
335 static void free_proc_stat_node(struct cg_proc_stat
*node
)
337 pthread_mutex_destroy(&node
->lock
);
344 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
346 struct cg_proc_stat
*node
, *tmp
;
354 free_proc_stat_node(tmp
);
361 pthread_rwlock_destroy(&head
->lock
);
365 static void free_cpuview()
369 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
370 if (proc_stat_history
[i
])
371 cpuview_free_head(proc_stat_history
[i
]);
376 * A table caching which pid is init for a pid namespace.
377 * When looking up which pid is init for $qpid, we first
378 * 1. Stat /proc/$qpid/ns/pid.
379 * 2. Check whether the ino_t is in our store.
380 * a. if not, fork a child in qpid's ns to send us
381 * ucred.pid = 1, and read the initpid. Cache
382 * initpid and creation time for /proc/initpid
383 * in a new store entry.
384 * b. if so, verify that /proc/initpid still matches
385 * what we have saved. If not, clear the store
386 * entry and go back to a. If so, return the
389 struct pidns_init_store
{
390 ino_t ino
; // inode number for /proc/$pid/ns/pid
391 pid_t initpid
; // the pid of nit in that ns
392 long int ctime
; // the time at which /proc/$initpid was created
393 struct pidns_init_store
*next
;
397 /* lol - look at how they are allocated in the kernel */
398 #define PIDNS_HASH_SIZE 4096
399 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
401 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
402 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
403 static void lock_mutex(pthread_mutex_t
*l
)
407 if ((ret
= pthread_mutex_lock(l
)) != 0) {
408 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
413 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
414 * Number of hierarchies mounted. */
415 static int num_hierarchies
;
417 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
418 * Hierachies mounted {cpuset, blkio, ...}:
419 * Initialized via __constructor__ collect_and_mount_subsystems(). */
420 static char **hierarchies
;
422 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
423 * Open file descriptors:
424 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
425 * private mount namespace.
426 * Initialized via __constructor__ collect_and_mount_subsystems().
427 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
428 * mounts and respective files in the private namespace even when located in
429 * another namespace using the *at() family of functions
430 * {openat(), fchownat(), ...}. */
431 static int *fd_hierarchies
;
432 static int cgroup_mount_ns_fd
= -1;
434 static void unlock_mutex(pthread_mutex_t
*l
)
438 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
439 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
444 static void store_lock(void)
446 lock_mutex(&pidns_store_mutex
);
449 static void store_unlock(void)
451 unlock_mutex(&pidns_store_mutex
);
454 /* Must be called under store_lock */
455 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
460 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
461 if (stat(fnam
, &initsb
) < 0)
464 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
465 initsb
.st_ctime
, e
->initpid
);
467 if (e
->ctime
!= initsb
.st_ctime
)
472 /* Must be called under store_lock */
473 static void remove_initpid(struct pidns_init_store
*e
)
475 struct pidns_init_store
*tmp
;
478 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
481 if (pidns_hash_table
[h
] == e
) {
482 pidns_hash_table
[h
] = e
->next
;
487 tmp
= pidns_hash_table
[h
];
489 if (tmp
->next
== e
) {
499 /* Must be called under store_lock */
500 static void prune_initpid_store(void)
502 static long int last_prune
= 0;
503 struct pidns_init_store
*e
, *prev
, *delme
;
504 long int now
, threshold
;
508 last_prune
= time(NULL
);
512 if (now
< last_prune
+ PURGE_SECS
)
515 lxcfs_debug("%s\n", "Pruning.");
518 threshold
= now
- 2 * PURGE_SECS
;
520 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
521 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
522 if (e
->lastcheck
< threshold
) {
524 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
528 prev
->next
= e
->next
;
530 pidns_hash_table
[i
] = e
->next
;
541 /* Must be called under store_lock */
542 static void save_initpid(struct stat
*sb
, pid_t pid
)
544 struct pidns_init_store
*e
;
549 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
551 snprintf(fpath
, 100, "/proc/%d", pid
);
552 if (stat(fpath
, &procsb
) < 0)
555 e
= malloc(sizeof(*e
));
559 e
->ctime
= procsb
.st_ctime
;
561 e
->next
= pidns_hash_table
[h
];
562 e
->lastcheck
= time(NULL
);
563 pidns_hash_table
[h
] = e
;
567 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
568 * entry for the inode number and creation time. Verify that the init pid
569 * is still valid. If not, remove it. Return the entry if valid, NULL
571 * Must be called under store_lock
573 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
575 int h
= HASH(sb
->st_ino
);
576 struct pidns_init_store
*e
= pidns_hash_table
[h
];
579 if (e
->ino
== sb
->st_ino
) {
580 if (initpid_still_valid(e
, sb
)) {
581 e
->lastcheck
= time(NULL
);
593 static int is_dir(const char *path
, int fd
)
596 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
597 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
602 static char *must_copy_string(const char *str
)
614 static inline void drop_trailing_newlines(char *s
)
618 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
622 #define BATCH_SIZE 50
623 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
625 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
626 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
628 if (!*mem
|| newbatches
> oldbatches
) {
631 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
636 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
638 size_t newlen
= *len
+ linelen
;
639 dorealloc(contents
, *len
, newlen
+ 1);
640 memcpy(*contents
+ *len
, line
, linelen
+1);
644 static char *slurp_file(const char *from
, int fd
)
647 char *contents
= NULL
;
648 FILE *f
= fdopen(fd
, "r");
649 size_t len
= 0, fulllen
= 0;
655 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
656 append_line(&contents
, &fulllen
, line
, linelen
);
661 drop_trailing_newlines(contents
);
666 static int preserve_ns(const int pid
, const char *ns
)
669 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
670 #define __NS_PATH_LEN 50
671 char path
[__NS_PATH_LEN
];
673 /* This way we can use this function to also check whether namespaces
674 * are supported by the kernel by passing in the NULL or the empty
677 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
678 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
679 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
680 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
) {
685 return open(path
, O_RDONLY
| O_CLOEXEC
);
689 * in_same_namespace - Check whether two processes are in the same namespace.
690 * @pid1 - PID of the first process.
691 * @pid2 - PID of the second process.
692 * @ns - Name of the namespace to check. Must correspond to one of the names
693 * for the namespaces as shown in /proc/<pid/ns/
695 * If the two processes are not in the same namespace returns an fd to the
696 * namespace of the second process identified by @pid2. If the two processes are
697 * in the same namespace returns -EINVAL, -1 if an error occurred.
699 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
701 __do_close_prot_errno
int ns_fd1
= -1, ns_fd2
= -1;
703 struct stat ns_st1
, ns_st2
;
705 ns_fd1
= preserve_ns(pid1
, ns
);
707 /* The kernel does not support this namespace. This is not an
716 ns_fd2
= preserve_ns(pid2
, ns
);
720 ret
= fstat(ns_fd1
, &ns_st1
);
724 ret
= fstat(ns_fd2
, &ns_st2
);
728 /* processes are in the same namespace */
729 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
732 /* processes are in different namespaces */
733 return move_fd(ns_fd2
);
736 static bool is_shared_pidns(pid_t pid
)
741 if (in_same_namespace(pid
, getpid(), "pid") == -EINVAL
)
747 static bool write_string(const char *fnam
, const char *string
, int fd
)
756 len
= strlen(string
);
757 ret
= fwrite(string
, 1, len
, f
);
759 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
760 strerror(errno
), string
, fnam
);
766 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
780 static bool store_hierarchy(char *stridx
, char *h
)
782 if (num_hierarchies
% ALLOC_NUM
== 0) {
783 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
785 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
787 lxcfs_error("%s\n", strerror(errno
));
793 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
797 static void print_subsystems(void)
801 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
802 fprintf(stderr
, "hierarchies:\n");
803 for (i
= 0; i
< num_hierarchies
; i
++) {
805 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
806 fd_hierarchies
[i
], hierarchies
[i
]);
810 static bool in_comma_list(const char *needle
, const char *haystack
)
812 const char *s
= haystack
, *e
;
813 size_t nlen
= strlen(needle
);
815 while (*s
&& (e
= strchr(s
, ','))) {
820 if (strncmp(needle
, s
, nlen
) == 0)
824 if (strcmp(needle
, s
) == 0)
829 /* do we need to do any massaging here? I'm not sure... */
830 /* Return the mounted controller and store the corresponding open file descriptor
831 * referring to the controller mountpoint in the private lxcfs namespace in
834 static char *find_mounted_controller(const char *controller
, int *cfd
)
838 for (i
= 0; i
< num_hierarchies
; i
++) {
841 if (strcmp(hierarchies
[i
], controller
) == 0) {
842 *cfd
= fd_hierarchies
[i
];
843 return hierarchies
[i
];
845 if (in_comma_list(controller
, hierarchies
[i
])) {
846 *cfd
= fd_hierarchies
[i
];
847 return hierarchies
[i
];
854 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
861 tmpc
= find_mounted_controller(controller
, &cfd
);
865 /* Make sure we pass a relative path to *at() family of functions.
866 * . + /cgroup + / + file + \0
868 len
= strlen(cgroup
) + strlen(file
) + 3;
870 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
871 if (ret
< 0 || (size_t)ret
>= len
)
874 fd
= openat(cfd
, fnam
, O_WRONLY
);
878 return write_string(fnam
, value
, fd
);
881 // Chown all the files in the cgroup directory. We do this when we create
882 // a cgroup on behalf of a user.
883 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
885 struct dirent
*direntp
;
886 char path
[MAXPATHLEN
];
891 len
= strlen(dirname
);
892 if (len
>= MAXPATHLEN
) {
893 lxcfs_error("Pathname too long: %s\n", dirname
);
897 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
903 lxcfs_error("Failed to open %s\n", dirname
);
907 while ((direntp
= readdir(d
))) {
908 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
910 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
911 if (ret
< 0 || ret
>= MAXPATHLEN
) {
912 lxcfs_error("Pathname too long under %s\n", dirname
);
915 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
916 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
921 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
927 tmpc
= find_mounted_controller(controller
, &cfd
);
931 /* Make sure we pass a relative path to *at() family of functions.
934 len
= strlen(cg
) + 2;
935 dirnam
= alloca(len
);
936 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
938 if (mkdirat(cfd
, dirnam
, 0755) < 0)
941 if (uid
== 0 && gid
== 0)
944 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
947 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
952 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
954 struct dirent
*direntp
;
957 char pathname
[MAXPATHLEN
];
960 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
964 dir
= fdopendir(dupfd
);
966 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
971 while ((direntp
= readdir(dir
))) {
975 if (!strcmp(direntp
->d_name
, ".") ||
976 !strcmp(direntp
->d_name
, ".."))
979 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
980 if (rc
< 0 || rc
>= MAXPATHLEN
) {
981 lxcfs_error("%s\n", "Pathname too long.");
985 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
987 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
990 if (S_ISDIR(mystat
.st_mode
))
991 if (!recursive_rmdir(pathname
, fd
, cfd
))
992 lxcfs_debug("Error removing %s.\n", pathname
);
996 if (closedir(dir
) < 0) {
997 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
1001 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
1002 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
1011 bool cgfs_remove(const char *controller
, const char *cg
)
1015 char *dirnam
, *tmpc
;
1018 tmpc
= find_mounted_controller(controller
, &cfd
);
1022 /* Make sure we pass a relative path to *at() family of functions.
1025 len
= strlen(cg
) + 2;
1026 dirnam
= alloca(len
);
1027 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
1029 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
1033 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
1038 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
1042 char *pathname
, *tmpc
;
1044 tmpc
= find_mounted_controller(controller
, &cfd
);
1048 /* Make sure we pass a relative path to *at() family of functions.
1051 len
= strlen(file
) + 2;
1052 pathname
= alloca(len
);
1053 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1054 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
1059 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
1064 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
1065 fname
= alloca(len
);
1066 snprintf(fname
, len
, "%s/tasks", dirname
);
1067 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1069 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
1070 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1075 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
1079 char *pathname
, *tmpc
;
1081 tmpc
= find_mounted_controller(controller
, &cfd
);
1085 /* Make sure we pass a relative path to *at() family of functions.
1088 len
= strlen(file
) + 2;
1089 pathname
= alloca(len
);
1090 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1091 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
1094 if (is_dir(pathname
, cfd
))
1095 // like cgmanager did, we want to chown the tasks file as well
1096 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
1101 FILE *open_pids_file(const char *controller
, const char *cgroup
)
1105 char *pathname
, *tmpc
;
1107 tmpc
= find_mounted_controller(controller
, &cfd
);
1111 /* Make sure we pass a relative path to *at() family of functions.
1112 * . + /cgroup + / "cgroup.procs" + \0
1114 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
1115 pathname
= alloca(len
);
1116 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
1118 fd
= openat(cfd
, pathname
, O_WRONLY
);
1122 return fdopen(fd
, "w");
1125 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
1126 void ***list
, size_t typesize
,
1127 void* (*iterator
)(const char*, const char*, const char*))
1132 char pathname
[MAXPATHLEN
];
1133 size_t sz
= 0, asz
= 0;
1134 struct dirent
*dirent
;
1137 tmpc
= find_mounted_controller(controller
, &cfd
);
1142 /* Make sure we pass a relative path to *at() family of functions. */
1143 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
1145 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
1146 if (ret
< 0 || (size_t)ret
>= len
) {
1147 lxcfs_error("Pathname too long under %s\n", cgroup
);
1151 fd
= openat(cfd
, cg
, O_DIRECTORY
);
1155 dir
= fdopendir(fd
);
1159 while ((dirent
= readdir(dir
))) {
1162 if (!strcmp(dirent
->d_name
, ".") ||
1163 !strcmp(dirent
->d_name
, ".."))
1166 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1167 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1168 lxcfs_error("Pathname too long under %s\n", cg
);
1172 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1174 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1177 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1178 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1185 tmp
= realloc(*list
, asz
* typesize
);
1189 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1190 (*list
)[sz
+1] = NULL
;
1193 if (closedir(dir
) < 0) {
1194 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1200 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1204 dup
= strdup(dir_entry
);
1209 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1211 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1214 void free_key(struct cgfs_files
*k
)
1222 void free_keys(struct cgfs_files
**keys
)
1228 for (i
= 0; keys
[i
]; i
++) {
1234 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1240 tmpc
= find_mounted_controller(controller
, &cfd
);
1244 /* Make sure we pass a relative path to *at() family of functions.
1245 * . + /cgroup + / + file + \0
1247 len
= strlen(cgroup
) + strlen(file
) + 3;
1249 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1250 if (ret
< 0 || (size_t)ret
>= len
)
1253 fd
= openat(cfd
, fnam
, O_RDONLY
);
1257 *value
= slurp_file(fnam
, fd
);
1258 return *value
!= NULL
;
1261 bool cgfs_param_exist(const char *controller
, const char *cgroup
, const char *file
)
1267 tmpc
= find_mounted_controller(controller
, &cfd
);
1271 /* Make sure we pass a relative path to *at() family of functions.
1272 * . + /cgroup + / + file + \0
1274 len
= strlen(cgroup
) + strlen(file
) + 3;
1276 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1277 if (ret
< 0 || (size_t)ret
>= len
)
1280 return (faccessat(cfd
, fnam
, F_OK
, 0) == 0);
1283 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1289 struct cgfs_files
*newkey
;
1291 tmpc
= find_mounted_controller(controller
, &cfd
);
1295 if (file
&& *file
== '/')
1298 if (file
&& strchr(file
, '/'))
1301 /* Make sure we pass a relative path to *at() family of functions.
1302 * . + /cgroup + / + file + \0
1304 len
= strlen(cgroup
) + 3;
1306 len
+= strlen(file
) + 1;
1308 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1309 file
? "/" : "", file
? file
: "");
1311 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1316 newkey
= malloc(sizeof(struct cgfs_files
));
1319 newkey
->name
= must_copy_string(file
);
1320 else if (strrchr(cgroup
, '/'))
1321 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1323 newkey
->name
= must_copy_string(cgroup
);
1324 newkey
->uid
= sb
.st_uid
;
1325 newkey
->gid
= sb
.st_gid
;
1326 newkey
->mode
= sb
.st_mode
;
1331 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1333 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1335 lxcfs_error("Error getting files under %s:%s\n", controller
,
1341 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1343 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1346 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1354 tmpc
= find_mounted_controller(controller
, &cfd
);
1358 /* Make sure we pass a relative path to *at() family of functions.
1359 * . + /cgroup + / + f + \0
1361 len
= strlen(cgroup
) + strlen(f
) + 3;
1363 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1364 if (ret
< 0 || (size_t)ret
>= len
)
1367 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1368 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1374 #define SEND_CREDS_OK 0
1375 #define SEND_CREDS_NOTSK 1
1376 #define SEND_CREDS_FAIL 2
1377 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1378 static int wait_for_pid(pid_t pid
);
1379 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1380 static int send_creds_clone_wrapper(void *arg
);
1383 * clone a task which switches to @task's namespace and writes '1'.
1384 * over a unix sock so we can read the task's reaper's pid in our
1387 * Note: glibc's fork() does not respect pidns, which can lead to failed
1388 * assertions inside glibc (and thus failed forks) if the child's pid in
1389 * the pidns and the parent pid outside are identical. Using clone prevents
1392 static void write_task_init_pid_exit(int sock
, pid_t target
)
1397 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1398 void *stack
= alloca(stack_size
);
1400 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1401 if (ret
< 0 || ret
>= sizeof(fnam
))
1404 fd
= open(fnam
, O_RDONLY
);
1406 perror("write_task_init_pid_exit open of ns/pid");
1410 perror("write_task_init_pid_exit setns 1");
1414 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1418 if (!wait_for_pid(pid
))
1424 static int send_creds_clone_wrapper(void *arg
) {
1427 int sock
= *(int *)arg
;
1429 /* we are the child */
1434 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1439 static pid_t
get_init_pid_for_task(pid_t task
)
1447 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1448 perror("socketpair");
1457 write_task_init_pid_exit(sock
[0], task
);
1461 if (!recv_creds(sock
[1], &cred
, &v
))
1473 pid_t
lookup_initpid_in_store(pid_t qpid
)
1477 struct pidns_init_store
*e
;
1480 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1482 if (stat(fnam
, &sb
) < 0)
1484 e
= lookup_verify_initpid(&sb
);
1486 answer
= e
->initpid
;
1489 answer
= get_init_pid_for_task(qpid
);
1491 save_initpid(&sb
, answer
);
1494 /* we prune at end in case we are returning
1495 * the value we were about to return */
1496 prune_initpid_store();
1501 static int wait_for_pid(pid_t pid
)
1509 ret
= waitpid(pid
, &status
, 0);
1517 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1523 * append the given formatted string to *src.
1524 * src: a pointer to a char* in which to append the formatted string.
1525 * sz: the number of characters printed so far, minus trailing \0.
1526 * asz: the allocated size so far
1527 * format: string format. See printf for details.
1528 * ...: varargs. See printf for details.
1530 static void must_strcat(char **src
, size_t *sz
, size_t *asz
, const char *format
, ...)
1532 char tmp
[BUF_RESERVE_SIZE
];
1535 va_start (args
, format
);
1536 int tmplen
= vsnprintf(tmp
, BUF_RESERVE_SIZE
, format
, args
);
1539 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1542 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1545 *asz
+= BUF_RESERVE_SIZE
;
1547 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1552 * append pid to *src.
1553 * src: a pointer to a char* in which ot append the pid.
1554 * sz: the number of characters printed so far, minus trailing \0.
1555 * asz: the allocated size so far
1556 * pid: the pid to append
1558 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1560 must_strcat(src
, sz
, asz
, "%d\n", (int)pid
);
1564 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1565 * valid in the caller's namespace, return the id mapped into
1567 * Returns the mapped id, or -1 on error.
1570 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1572 unsigned int nsuid
, // base id for a range in the idfile's namespace
1573 hostuid
, // base id for a range in the caller's namespace
1574 count
; // number of ids in this range
1578 fseek(idfile
, 0L, SEEK_SET
);
1579 while (fgets(line
, 400, idfile
)) {
1580 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1583 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1585 * uids wrapped around - unexpected as this is a procfile,
1588 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1589 nsuid
, hostuid
, count
, line
);
1592 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1594 * now since hostuid <= in_id < hostuid+count, and
1595 * hostuid+count and nsuid+count do not wrap around,
1596 * we know that nsuid+(in_id-hostuid) which must be
1597 * less that nsuid+(count) must not wrap around
1599 return (in_id
- hostuid
) + nsuid
;
1608 * for is_privileged_over,
1609 * specify whether we require the calling uid to be root in his
1612 #define NS_ROOT_REQD true
1613 #define NS_ROOT_OPT false
1617 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1619 char fpath
[PROCLEN
];
1621 bool answer
= false;
1624 if (victim
== -1 || uid
== -1)
1628 * If the request is one not requiring root in the namespace,
1629 * then having the same uid suffices. (i.e. uid 1000 has write
1630 * access to files owned by uid 1000
1632 if (!req_ns_root
&& uid
== victim
)
1635 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1636 if (ret
< 0 || ret
>= PROCLEN
)
1638 FILE *f
= fopen(fpath
, "r");
1642 /* if caller's not root in his namespace, reject */
1643 nsuid
= convert_id_to_ns(f
, uid
);
1648 * If victim is not mapped into caller's ns, reject.
1649 * XXX I'm not sure this check is needed given that fuse
1650 * will be sending requests where the vfs has converted
1652 nsuid
= convert_id_to_ns(f
, victim
);
1663 static bool perms_include(int fmode
, mode_t req_mode
)
1667 switch (req_mode
& O_ACCMODE
) {
1675 r
= S_IROTH
| S_IWOTH
;
1680 return ((fmode
& r
) == r
);
1686 * querycg is /a/b/c/d/e
1689 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1693 if (strlen(taskcg
) <= strlen(querycg
)) {
1694 lxcfs_error("%s\n", "I was fed bad input.");
1698 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1699 start
= strdup(taskcg
+ 1);
1701 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1704 end
= strchr(start
, '/');
1710 static void stripnewline(char *x
)
1712 size_t l
= strlen(x
);
1713 if (l
&& x
[l
-1] == '\n')
1717 char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1722 char *answer
= NULL
;
1726 const char *h
= find_mounted_controller(contrl
, &cfd
);
1730 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1731 if (ret
< 0 || ret
>= PROCLEN
)
1733 if (!(f
= fopen(fnam
, "r")))
1736 while (getline(&line
, &len
, f
) != -1) {
1740 c1
= strchr(line
, ':');
1744 c2
= strchr(c1
, ':');
1748 if (strcmp(c1
, h
) != 0)
1753 answer
= strdup(c2
);
1765 * check whether a fuse context may access a cgroup dir or file
1767 * If file is not null, it is a cgroup file to check under cg.
1768 * If file is null, then we are checking perms on cg itself.
1770 * For files we can check the mode of the list_keys result.
1771 * For cgroups, we must make assumptions based on the files under the
1772 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1775 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1777 struct cgfs_files
*k
= NULL
;
1780 k
= cgfs_get_key(contrl
, cg
, file
);
1784 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1785 if (perms_include(k
->mode
>> 6, mode
)) {
1790 if (fc
->gid
== k
->gid
) {
1791 if (perms_include(k
->mode
>> 3, mode
)) {
1796 ret
= perms_include(k
->mode
, mode
);
1803 #define INITSCOPE "/init.scope"
1804 void prune_init_slice(char *cg
)
1807 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1809 if (cg_len
< initscope_len
)
1812 point
= cg
+ cg_len
- initscope_len
;
1813 if (strcmp(point
, INITSCOPE
) == 0) {
1822 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1823 * If pid is in /a, he may act on /a/b, but not on /b.
1824 * if the answer is false and nextcg is not NULL, then *nextcg will point
1825 * to a string containing the next cgroup directory under cg, which must be
1826 * freed by the caller.
1828 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1830 bool answer
= false;
1831 char *c2
= get_pid_cgroup(pid
, contrl
);
1836 prune_init_slice(c2
);
1839 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1840 * they pass in a cgroup without leading '/'
1842 * The original line here was:
1843 * linecmp = *cg == '/' ? c2 : c2+1;
1844 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1845 * Serge, do you know?
1847 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1851 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1853 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1865 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1867 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1869 bool answer
= false;
1871 size_t target_len
, task_len
;
1873 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1876 c2
= get_pid_cgroup(pid
, contrl
);
1879 prune_init_slice(c2
);
1882 target_len
= strlen(cg
);
1883 task_len
= strlen(task_cg
);
1884 if (task_len
== 0) {
1885 /* Task is in the root cg, it can see everything. This case is
1886 * not handled by the strmcps below, since they test for the
1887 * last /, but that is the first / that we've chopped off
1893 if (strcmp(cg
, task_cg
) == 0) {
1897 if (target_len
< task_len
) {
1898 /* looking up a parent dir */
1899 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1903 if (target_len
> task_len
) {
1904 /* looking up a child dir */
1905 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1916 * given /cgroup/freezer/a/b, return "freezer".
1917 * the returned char* should NOT be freed.
1919 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1922 char *contr
, *slash
;
1924 if (strlen(path
) < 9) {
1928 if (*(path
+ 7) != '/') {
1933 contr
= strdupa(p1
);
1938 slash
= strstr(contr
, "/");
1943 for (i
= 0; i
< num_hierarchies
; i
++) {
1944 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1945 return hierarchies
[i
];
1952 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1953 * Note that the returned value may include files (keynames) etc
1955 static const char *find_cgroup_in_path(const char *path
)
1959 if (strlen(path
) < 9) {
1963 p1
= strstr(path
+ 8, "/");
1973 * split the last path element from the path in @cg.
1974 * @dir is newly allocated and should be freed, @last not
1976 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1983 *last
= strrchr(cg
, '/');
1988 p
= strrchr(*dir
, '/');
1993 * FUSE ops for /cgroup
1996 int cg_getattr(const char *path
, struct stat
*sb
)
1998 struct timespec now
;
1999 struct fuse_context
*fc
= fuse_get_context();
2000 char * cgdir
= NULL
;
2001 char *last
= NULL
, *path1
, *path2
;
2002 struct cgfs_files
*k
= NULL
;
2004 const char *controller
= NULL
;
2011 memset(sb
, 0, sizeof(struct stat
));
2013 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
2016 sb
->st_uid
= sb
->st_gid
= 0;
2017 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
2020 if (strcmp(path
, "/cgroup") == 0) {
2021 sb
->st_mode
= S_IFDIR
| 00755;
2026 controller
= pick_controller_from_path(fc
, path
);
2029 cgroup
= find_cgroup_in_path(path
);
2031 /* this is just /cgroup/controller, return it as a dir */
2032 sb
->st_mode
= S_IFDIR
| 00755;
2037 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2047 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2048 if (initpid
<= 1 || is_shared_pidns(initpid
))
2050 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
2051 * Then check that caller's cgroup is under path if last is a child
2052 * cgroup, or cgdir if last is a file */
2054 if (is_child_cgroup(controller
, path1
, path2
)) {
2055 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
2059 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
2060 /* this is just /cgroup/controller, return it as a dir */
2061 sb
->st_mode
= S_IFDIR
| 00555;
2066 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
2071 // get uid, gid, from '/tasks' file and make up a mode
2072 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2073 sb
->st_mode
= S_IFDIR
| 00755;
2074 k
= cgfs_get_key(controller
, cgroup
, NULL
);
2076 sb
->st_uid
= sb
->st_gid
= 0;
2078 sb
->st_uid
= k
->uid
;
2079 sb
->st_gid
= k
->gid
;
2087 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
2088 sb
->st_mode
= S_IFREG
| k
->mode
;
2090 sb
->st_uid
= k
->uid
;
2091 sb
->st_gid
= k
->gid
;
2094 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2106 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
2108 struct fuse_context
*fc
= fuse_get_context();
2110 struct file_info
*dir_info
;
2111 char *controller
= NULL
;
2116 if (strcmp(path
, "/cgroup") == 0) {
2120 // return list of keys for the controller, and list of child cgroups
2121 controller
= pick_controller_from_path(fc
, path
);
2125 cgroup
= find_cgroup_in_path(path
);
2127 /* this is just /cgroup/controller, return its contents */
2132 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2133 if (initpid
<= 1 || is_shared_pidns(initpid
))
2136 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
2138 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
2142 /* we'll free this at cg_releasedir */
2143 dir_info
= malloc(sizeof(*dir_info
));
2146 dir_info
->controller
= must_copy_string(controller
);
2147 dir_info
->cgroup
= must_copy_string(cgroup
);
2148 dir_info
->type
= LXC_TYPE_CGDIR
;
2149 dir_info
->buf
= NULL
;
2150 dir_info
->file
= NULL
;
2151 dir_info
->buflen
= 0;
2153 fi
->fh
= (unsigned long)dir_info
;
2157 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2158 struct fuse_file_info
*fi
)
2160 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2161 struct cgfs_files
**list
= NULL
;
2163 char *nextcg
= NULL
;
2164 struct fuse_context
*fc
= fuse_get_context();
2165 char **clist
= NULL
;
2167 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
2170 if (d
->type
!= LXC_TYPE_CGDIR
) {
2171 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
2174 if (!d
->cgroup
&& !d
->controller
) {
2175 // ls /var/lib/lxcfs/cgroup - just show list of controllers
2178 for (i
= 0; i
< num_hierarchies
; i
++) {
2179 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
2186 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
2187 // not a valid cgroup
2192 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2193 if (initpid
<= 1 || is_shared_pidns(initpid
))
2195 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
2197 ret
= filler(buf
, nextcg
, NULL
, 0);
2208 for (i
= 0; list
&& list
[i
]; i
++) {
2209 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2215 // now get the list of child cgroups
2217 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2222 for (i
= 0; clist
[i
]; i
++) {
2223 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2234 for (i
= 0; clist
[i
]; i
++)
2241 void do_release_file_info(struct fuse_file_info
*fi
)
2243 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2250 free(f
->controller
);
2251 f
->controller
= NULL
;
2262 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2264 do_release_file_info(fi
);
2268 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2271 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2272 struct cgfs_files
*k
= NULL
;
2273 struct file_info
*file_info
;
2274 struct fuse_context
*fc
= fuse_get_context();
2280 controller
= pick_controller_from_path(fc
, path
);
2283 cgroup
= find_cgroup_in_path(path
);
2287 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2296 k
= cgfs_get_key(controller
, path1
, path2
);
2303 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2304 if (initpid
<= 1 || is_shared_pidns(initpid
))
2306 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2310 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2315 /* we'll free this at cg_release */
2316 file_info
= malloc(sizeof(*file_info
));
2321 file_info
->controller
= must_copy_string(controller
);
2322 file_info
->cgroup
= must_copy_string(path1
);
2323 file_info
->file
= must_copy_string(path2
);
2324 file_info
->type
= LXC_TYPE_CGFILE
;
2325 file_info
->buf
= NULL
;
2326 file_info
->buflen
= 0;
2328 fi
->fh
= (unsigned long)file_info
;
2336 int cg_access(const char *path
, int mode
)
2340 char *path1
, *path2
, *controller
;
2341 char *last
= NULL
, *cgdir
= NULL
;
2342 struct cgfs_files
*k
= NULL
;
2343 struct fuse_context
*fc
= fuse_get_context();
2345 if (strcmp(path
, "/cgroup") == 0)
2351 controller
= pick_controller_from_path(fc
, path
);
2354 cgroup
= find_cgroup_in_path(path
);
2356 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2357 if ((mode
& W_OK
) == 0)
2362 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2371 k
= cgfs_get_key(controller
, path1
, path2
);
2373 if ((mode
& W_OK
) == 0)
2381 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2382 if (initpid
<= 1 || is_shared_pidns(initpid
))
2384 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2388 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2400 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2402 do_release_file_info(fi
);
2406 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2408 static bool wait_for_sock(int sock
, int timeout
)
2410 struct epoll_event ev
;
2411 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2413 if ((starttime
= time(NULL
)) < 0)
2416 if ((epfd
= epoll_create(1)) < 0) {
2417 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2421 ev
.events
= POLLIN_SET
;
2423 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2424 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2430 if ((now
= time(NULL
)) < 0) {
2435 deltatime
= (starttime
+ timeout
) - now
;
2436 if (deltatime
< 0) { // timeout
2441 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2442 if (ret
< 0 && errno
== EINTR
)
2444 saved_errno
= errno
;
2448 errno
= saved_errno
;
2454 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2456 if (!wait_for_sock(sockfd
, 2))
2458 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2461 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2463 struct msghdr msg
= { 0 };
2465 struct cmsghdr
*cmsg
;
2466 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2471 if (msgrecv(sock
, buf
, 1) != 1) {
2472 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2473 return SEND_CREDS_FAIL
;
2477 msg
.msg_control
= cmsgbuf
;
2478 msg
.msg_controllen
= sizeof(cmsgbuf
);
2480 cmsg
= CMSG_FIRSTHDR(&msg
);
2481 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2482 cmsg
->cmsg_level
= SOL_SOCKET
;
2483 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2484 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2486 msg
.msg_name
= NULL
;
2487 msg
.msg_namelen
= 0;
2491 iov
.iov_len
= sizeof(buf
);
2495 if (sendmsg(sock
, &msg
, 0) < 0) {
2496 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2498 return SEND_CREDS_NOTSK
;
2499 return SEND_CREDS_FAIL
;
2502 return SEND_CREDS_OK
;
2505 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2507 struct msghdr msg
= { 0 };
2509 struct cmsghdr
*cmsg
;
2510 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2521 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2522 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2526 if (write(sock
, buf
, 1) != 1) {
2527 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2531 msg
.msg_name
= NULL
;
2532 msg
.msg_namelen
= 0;
2533 msg
.msg_control
= cmsgbuf
;
2534 msg
.msg_controllen
= sizeof(cmsgbuf
);
2537 iov
.iov_len
= sizeof(buf
);
2541 if (!wait_for_sock(sock
, 2)) {
2542 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2545 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2547 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2551 cmsg
= CMSG_FIRSTHDR(&msg
);
2553 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2554 cmsg
->cmsg_level
== SOL_SOCKET
&&
2555 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2556 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2563 struct pid_ns_clone_args
{
2567 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2571 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2572 * with clone(). This simply writes '1' as ACK back to the parent
2573 * before calling the actual wrapped function.
2575 static int pid_ns_clone_wrapper(void *arg
) {
2576 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2579 close(args
->cpipe
[0]);
2580 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2581 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2582 close(args
->cpipe
[1]);
2583 return args
->wrapped(args
->sock
, args
->tpid
);
2587 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2588 * int value back over the socket. This shifts the pid from the
2589 * sender's pidns into tpid's pidns.
2591 static int pid_to_ns(int sock
, pid_t tpid
)
2596 while (recv_creds(sock
, &cred
, &v
)) {
2599 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2607 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2608 * in your old pidns. Only children which you clone will be in the target
2609 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2610 * actually convert pids.
2612 * Note: glibc's fork() does not respect pidns, which can lead to failed
2613 * assertions inside glibc (and thus failed forks) if the child's pid in
2614 * the pidns and the parent pid outside are identical. Using clone prevents
2617 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2619 int newnsfd
= -1, ret
, cpipe
[2];
2624 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2625 if (ret
< 0 || ret
>= sizeof(fnam
))
2627 newnsfd
= open(fnam
, O_RDONLY
);
2630 if (setns(newnsfd
, 0) < 0)
2634 if (pipe(cpipe
) < 0)
2637 struct pid_ns_clone_args args
= {
2641 .wrapped
= &pid_to_ns
2643 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2644 void *stack
= alloca(stack_size
);
2646 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2650 // give the child 1 second to be done forking and
2652 if (!wait_for_sock(cpipe
[0], 1))
2654 ret
= read(cpipe
[0], &v
, 1);
2655 if (ret
!= sizeof(char) || v
!= '1')
2658 if (!wait_for_pid(cpid
))
2664 * To read cgroup files with a particular pid, we will setns into the child
2665 * pidns, open a pipe, fork a child - which will be the first to really be in
2666 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2668 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2670 int sock
[2] = {-1, -1};
2671 char *tmpdata
= NULL
;
2673 pid_t qpid
, cpid
= -1;
2674 bool answer
= false;
2677 size_t sz
= 0, asz
= 0;
2679 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2683 * Now we read the pids from returned data one by one, pass
2684 * them into a child in the target namespace, read back the
2685 * translated pids, and put them into our to-return data
2688 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2689 perror("socketpair");
2698 if (!cpid
) // child - exits when done
2699 pid_to_ns_wrapper(sock
[1], tpid
);
2701 char *ptr
= tmpdata
;
2704 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2706 ret
= send_creds(sock
[0], &cred
, v
, true);
2708 if (ret
== SEND_CREDS_NOTSK
)
2710 if (ret
== SEND_CREDS_FAIL
)
2713 // read converted results
2714 if (!wait_for_sock(sock
[0], 2)) {
2715 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2718 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2719 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2722 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2724 ptr
= strchr(ptr
, '\n');
2730 cred
.pid
= getpid();
2732 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2733 // failed to ask child to exit
2734 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2744 if (sock
[0] != -1) {
2751 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2752 struct fuse_file_info
*fi
)
2754 struct fuse_context
*fc
= fuse_get_context();
2755 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2756 struct cgfs_files
*k
= NULL
;
2761 if (f
->type
!= LXC_TYPE_CGFILE
) {
2762 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2775 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2781 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2786 if (strcmp(f
->file
, "tasks") == 0 ||
2787 strcmp(f
->file
, "/tasks") == 0 ||
2788 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2789 strcmp(f
->file
, "cgroup.procs") == 0)
2790 // special case - we have to translate the pids
2791 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2793 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2807 memcpy(buf
, data
, s
);
2808 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2818 static int pid_from_ns(int sock
, pid_t tpid
)
2828 if (!wait_for_sock(sock
, 2)) {
2829 lxcfs_error("%s\n", "Timeout reading from parent.");
2832 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2833 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2836 if (vpid
== -1) // done
2840 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2842 cred
.pid
= getpid();
2843 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2850 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2852 int newnsfd
= -1, ret
, cpipe
[2];
2857 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2858 if (ret
< 0 || ret
>= sizeof(fnam
))
2860 newnsfd
= open(fnam
, O_RDONLY
);
2863 if (setns(newnsfd
, 0) < 0)
2867 if (pipe(cpipe
) < 0)
2870 struct pid_ns_clone_args args
= {
2874 .wrapped
= &pid_from_ns
2876 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2877 void *stack
= alloca(stack_size
);
2879 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2883 // give the child 1 second to be done forking and
2885 if (!wait_for_sock(cpipe
[0], 1))
2887 ret
= read(cpipe
[0], &v
, 1);
2888 if (ret
!= sizeof(char) || v
!= '1')
2891 if (!wait_for_pid(cpid
))
2897 * Given host @uid, return the uid to which it maps in
2898 * @pid's user namespace, or -1 if none.
2900 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2905 sprintf(line
, "/proc/%d/uid_map", pid
);
2906 if ((f
= fopen(line
, "r")) == NULL
) {
2910 *answer
= convert_id_to_ns(f
, uid
);
2919 * get_pid_creds: get the real uid and gid of @pid from
2921 * (XXX should we use euid here?)
2923 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2932 sprintf(line
, "/proc/%d/status", pid
);
2933 if ((f
= fopen(line
, "r")) == NULL
) {
2934 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2937 while (fgets(line
, 400, f
)) {
2938 if (strncmp(line
, "Uid:", 4) == 0) {
2939 if (sscanf(line
+4, "%u", &u
) != 1) {
2940 lxcfs_error("bad uid line for pid %u\n", pid
);
2945 } else if (strncmp(line
, "Gid:", 4) == 0) {
2946 if (sscanf(line
+4, "%u", &g
) != 1) {
2947 lxcfs_error("bad gid line for pid %u\n", pid
);
2958 * May the requestor @r move victim @v to a new cgroup?
2959 * This is allowed if
2960 * . they are the same task
2961 * . they are ownedy by the same uid
2962 * . @r is root on the host, or
2963 * . @v's uid is mapped into @r's where @r is root.
2965 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2967 uid_t v_uid
, tmpuid
;
2974 get_pid_creds(v
, &v_uid
, &v_gid
);
2977 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2978 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2983 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2984 const char *file
, const char *buf
)
2986 int sock
[2] = {-1, -1};
2987 pid_t qpid
, cpid
= -1;
2988 FILE *pids_file
= NULL
;
2989 bool answer
= false, fail
= false;
2991 pids_file
= open_pids_file(contrl
, cg
);
2996 * write the pids to a socket, have helper in writer's pidns
2997 * call movepid for us
2999 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
3000 perror("socketpair");
3008 if (!cpid
) { // child
3010 pid_from_ns_wrapper(sock
[1], tpid
);
3013 const char *ptr
= buf
;
3014 while (sscanf(ptr
, "%d", &qpid
) == 1) {
3018 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
3019 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
3023 if (recv_creds(sock
[0], &cred
, &v
)) {
3025 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
3029 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
3034 ptr
= strchr(ptr
, '\n');
3040 /* All good, write the value */
3042 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
3043 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
3051 if (sock
[0] != -1) {
3056 if (fclose(pids_file
) != 0)
3062 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
3063 struct fuse_file_info
*fi
)
3065 struct fuse_context
*fc
= fuse_get_context();
3066 char *localbuf
= NULL
;
3067 struct cgfs_files
*k
= NULL
;
3068 struct file_info
*f
= (struct file_info
*)fi
->fh
;
3071 if (f
->type
!= LXC_TYPE_CGFILE
) {
3072 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
3082 localbuf
= alloca(size
+1);
3083 localbuf
[size
] = '\0';
3084 memcpy(localbuf
, buf
, size
);
3086 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
3091 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
3096 if (strcmp(f
->file
, "tasks") == 0 ||
3097 strcmp(f
->file
, "/tasks") == 0 ||
3098 strcmp(f
->file
, "/cgroup.procs") == 0 ||
3099 strcmp(f
->file
, "cgroup.procs") == 0)
3100 // special case - we have to translate the pids
3101 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3103 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3113 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
3115 struct fuse_context
*fc
= fuse_get_context();
3116 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3117 struct cgfs_files
*k
= NULL
;
3124 if (strcmp(path
, "/cgroup") == 0)
3127 controller
= pick_controller_from_path(fc
, path
);
3129 return errno
== ENOENT
? -EPERM
: -errno
;
3131 cgroup
= find_cgroup_in_path(path
);
3133 /* this is just /cgroup/controller */
3136 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3146 if (is_child_cgroup(controller
, path1
, path2
)) {
3147 // get uid, gid, from '/tasks' file and make up a mode
3148 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3149 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3152 k
= cgfs_get_key(controller
, path1
, path2
);
3160 * This being a fuse request, the uid and gid must be valid
3161 * in the caller's namespace. So we can just check to make
3162 * sure that the caller is root in his uid, and privileged
3163 * over the file's current owner.
3165 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
3170 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
3179 int cg_chmod(const char *path
, mode_t mode
)
3181 struct fuse_context
*fc
= fuse_get_context();
3182 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3183 struct cgfs_files
*k
= NULL
;
3190 if (strcmp(path
, "/cgroup") == 0)
3193 controller
= pick_controller_from_path(fc
, path
);
3195 return errno
== ENOENT
? -EPERM
: -errno
;
3197 cgroup
= find_cgroup_in_path(path
);
3199 /* this is just /cgroup/controller */
3202 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3212 if (is_child_cgroup(controller
, path1
, path2
)) {
3213 // get uid, gid, from '/tasks' file and make up a mode
3214 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3215 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3218 k
= cgfs_get_key(controller
, path1
, path2
);
3226 * This being a fuse request, the uid and gid must be valid
3227 * in the caller's namespace. So we can just check to make
3228 * sure that the caller is root in his uid, and privileged
3229 * over the file's current owner.
3231 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3236 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3248 int cg_mkdir(const char *path
, mode_t mode
)
3250 struct fuse_context
*fc
= fuse_get_context();
3251 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3258 controller
= pick_controller_from_path(fc
, path
);
3260 return errno
== ENOENT
? -EPERM
: -errno
;
3262 cgroup
= find_cgroup_in_path(path
);
3266 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3272 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3273 if (initpid
<= 1 || is_shared_pidns(initpid
))
3275 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3278 else if (last
&& strcmp(next
, last
) == 0)
3285 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3289 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3294 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3302 int cg_rmdir(const char *path
)
3304 struct fuse_context
*fc
= fuse_get_context();
3305 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3312 controller
= pick_controller_from_path(fc
, path
);
3313 if (!controller
) /* Someone's trying to delete "/cgroup". */
3316 cgroup
= find_cgroup_in_path(path
);
3317 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3320 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3322 /* Someone's trying to delete a cgroup on the same level as the
3323 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3324 * rmdir "/cgroup/blkio/init.slice".
3330 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3331 if (initpid
<= 1 || is_shared_pidns(initpid
))
3333 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3334 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3341 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3345 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3350 if (!cgfs_remove(controller
, cgroup
)) {
3363 static bool startswith(const char *line
, const char *pref
)
3365 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3370 static void parse_memstat(char *memstat
, unsigned long *cached
,
3371 unsigned long *active_anon
, unsigned long *inactive_anon
,
3372 unsigned long *active_file
, unsigned long *inactive_file
,
3373 unsigned long *unevictable
, unsigned long *shmem
)
3378 if (startswith(memstat
, "total_cache")) {
3379 sscanf(memstat
+ 11, "%lu", cached
);
3381 } else if (startswith(memstat
, "total_active_anon")) {
3382 sscanf(memstat
+ 17, "%lu", active_anon
);
3383 *active_anon
/= 1024;
3384 } else if (startswith(memstat
, "total_inactive_anon")) {
3385 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3386 *inactive_anon
/= 1024;
3387 } else if (startswith(memstat
, "total_active_file")) {
3388 sscanf(memstat
+ 17, "%lu", active_file
);
3389 *active_file
/= 1024;
3390 } else if (startswith(memstat
, "total_inactive_file")) {
3391 sscanf(memstat
+ 19, "%lu", inactive_file
);
3392 *inactive_file
/= 1024;
3393 } else if (startswith(memstat
, "total_unevictable")) {
3394 sscanf(memstat
+ 17, "%lu", unevictable
);
3395 *unevictable
/= 1024;
3396 } else if (startswith(memstat
, "total_shmem")) {
3397 sscanf(memstat
+ 11, "%lu", shmem
);
3400 eol
= strchr(memstat
, '\n');
3407 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3413 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3415 size_t len
= strlen(key
);
3419 if (startswith(str
, key
)) {
3420 sscanf(str
+ len
, "%lu", v
);
3423 eol
= strchr(str
, '\n');
3430 int read_file(const char *path
, char *buf
, size_t size
, struct file_info
*d
)
3432 size_t linelen
= 0, total_len
= 0, rv
= 0;
3434 char *cache
= d
->buf
;
3435 size_t cache_size
= d
->buflen
;
3436 FILE *f
= fopen(path
, "r");
3440 while (getline(&line
, &linelen
, f
) != -1) {
3441 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3443 perror("Error writing to cache");
3447 if (l
>= cache_size
) {
3448 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3457 d
->size
= total_len
;
3458 if (total_len
> size
)
3461 /* read from off 0 */
3462 memcpy(buf
, d
->buf
, total_len
);
3471 * FUSE ops for /proc
3474 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3476 char *memlimit_str
= NULL
;
3477 unsigned long memlimit
= -1;
3479 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3480 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3487 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3489 char *copy
= strdupa(cgroup
);
3490 unsigned long memlimit
= 0, retlimit
;
3492 retlimit
= get_memlimit(copy
, file
);
3494 while (strcmp(copy
, "/") != 0) {
3495 copy
= dirname(copy
);
3496 memlimit
= get_memlimit(copy
, file
);
3497 if (memlimit
!= -1 && memlimit
< retlimit
)
3498 retlimit
= memlimit
;
3504 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3505 struct fuse_file_info
*fi
)
3507 struct fuse_context
*fc
= fuse_get_context();
3508 struct lxcfs_opts
*opts
= (struct lxcfs_opts
*) fuse_get_context()->private_data
;
3509 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3511 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3512 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3513 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3514 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3515 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3518 size_t linelen
= 0, total_len
= 0, rv
= 0;
3519 char *cache
= d
->buf
;
3520 size_t cache_size
= d
->buflen
;
3524 if (offset
> d
->size
)
3528 int left
= d
->size
- offset
;
3529 total_len
= left
> size
? size
: left
;
3530 memcpy(buf
, cache
+ offset
, total_len
);
3534 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3535 if (initpid
<= 1 || is_shared_pidns(initpid
))
3537 cg
= get_pid_cgroup(initpid
, "memory");
3539 return read_file("/proc/meminfo", buf
, size
, d
);
3540 prune_init_slice(cg
);
3542 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3543 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3545 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3548 // Following values are allowed to fail, because swapaccount might be turned
3549 // off for current kernel
3550 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3551 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3553 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3554 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3556 memswlimit
= memswlimit
/ 1024;
3557 memswusage
= memswusage
/ 1024;
3560 memusage
= strtoul(memusage_str
, NULL
, 10);
3564 parse_memstat(memstat_str
, &cached
, &active_anon
,
3565 &inactive_anon
, &active_file
, &inactive_file
,
3566 &unevictable
, &shmem
);
3568 f
= fopen("/proc/meminfo", "r");
3572 while (getline(&line
, &linelen
, f
) != -1) {
3574 char *printme
, lbuf
[100];
3576 memset(lbuf
, 0, 100);
3577 if (startswith(line
, "MemTotal:")) {
3578 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3579 if (hosttotal
< memlimit
)
3580 memlimit
= hosttotal
;
3581 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3583 } else if (startswith(line
, "MemFree:")) {
3584 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3586 } else if (startswith(line
, "MemAvailable:")) {
3587 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3589 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0 && opts
&& opts
->swap_off
== false) {
3590 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3591 if (hostswtotal
< memswlimit
)
3592 memswlimit
= hostswtotal
;
3593 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3595 } else if (startswith(line
, "SwapTotal:") && opts
&& opts
->swap_off
== true) {
3596 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", 0UL);
3598 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0 && opts
&& opts
->swap_off
== false) {
3599 unsigned long swaptotal
= memswlimit
,
3600 swapusage
= memswusage
- memusage
,
3601 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3602 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3604 } else if (startswith(line
, "SwapFree:") && opts
&& opts
->swap_off
== true) {
3605 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", 0UL);
3607 } else if (startswith(line
, "Slab:")) {
3608 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3610 } else if (startswith(line
, "Buffers:")) {
3611 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3613 } else if (startswith(line
, "Cached:")) {
3614 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3616 } else if (startswith(line
, "SwapCached:")) {
3617 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3619 } else if (startswith(line
, "Active:")) {
3620 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3621 active_anon
+ active_file
);
3623 } else if (startswith(line
, "Inactive:")) {
3624 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3625 inactive_anon
+ inactive_file
);
3627 } else if (startswith(line
, "Active(anon)")) {
3628 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3630 } else if (startswith(line
, "Inactive(anon)")) {
3631 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3633 } else if (startswith(line
, "Active(file)")) {
3634 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3636 } else if (startswith(line
, "Inactive(file)")) {
3637 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3639 } else if (startswith(line
, "Unevictable")) {
3640 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3642 } else if (startswith(line
, "SReclaimable")) {
3643 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3645 } else if (startswith(line
, "SUnreclaim")) {
3646 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3648 } else if (startswith(line
, "Shmem:")) {
3649 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3651 } else if (startswith(line
, "ShmemHugePages")) {
3652 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3654 } else if (startswith(line
, "ShmemPmdMapped")) {
3655 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3660 l
= snprintf(cache
, cache_size
, "%s", printme
);
3662 perror("Error writing to cache");
3667 if (l
>= cache_size
) {
3668 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3679 d
->size
= total_len
;
3680 if (total_len
> size
) total_len
= size
;
3681 memcpy(buf
, d
->buf
, total_len
);
3690 free(memswlimit_str
);
3691 free(memswusage_str
);
3697 * Read the cpuset.cpus for cg
3698 * Return the answer in a newly allocated string which must be freed
3700 char *get_cpuset(const char *cg
)
3704 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3709 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3711 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3715 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3717 return cpu_in_cpuset(cpu
, cpuset
);
3721 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3722 * depending on `param`. Parameter value is returned throuh `value`.
3724 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3727 char file
[11 + 6 + 1]; // cpu.cfs__us + quota/period + \0
3730 sprintf(file
, "cpu.cfs_%s_us", param
);
3732 if (!cgfs_get_value("cpu", cg
, file
, &str
))
3735 if (sscanf(str
, "%ld", value
) != 1)
3747 * Return the maximum number of visible CPUs based on CPU quotas.
3748 * If there is no quota set, zero is returned.
3750 int max_cpu_count(const char *cg
)
3753 int64_t cfs_quota
, cfs_period
;
3754 int nr_cpus_in_cpuset
= 0;
3755 char *cpuset
= NULL
;
3757 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3760 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3763 cpuset
= get_cpuset(cg
);
3765 nr_cpus_in_cpuset
= cpu_number_in_cpuset(cpuset
);
3767 if (cfs_quota
<= 0 || cfs_period
<= 0){
3768 if (nr_cpus_in_cpuset
> 0)
3769 return nr_cpus_in_cpuset
;
3774 rv
= cfs_quota
/ cfs_period
;
3776 /* In case quota/period does not yield a whole number, add one CPU for
3779 if ((cfs_quota
% cfs_period
) > 0)
3782 nprocs
= get_nprocs();
3787 /* use min value in cpu quota and cpuset */
3788 if (nr_cpus_in_cpuset
> 0 && nr_cpus_in_cpuset
< rv
)
3789 rv
= nr_cpus_in_cpuset
;
3795 * Return the exact number of visible CPUs based on CPU quotas.
3796 * If there is no quota set, zero is returned.
3798 static double exact_cpu_count(const char *cg
)
3802 int64_t cfs_quota
, cfs_period
;
3804 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3807 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3810 if (cfs_quota
<= 0 || cfs_period
<= 0)
3813 rv
= (double)cfs_quota
/ (double)cfs_period
;
3815 nprocs
= get_nprocs();
3824 * Determine whether CPU views should be used or not.
3826 bool use_cpuview(const char *cg
)
3831 tmpc
= find_mounted_controller("cpu", &cfd
);
3835 tmpc
= find_mounted_controller("cpuacct", &cfd
);
3843 * check whether this is a '^processor" line in /proc/cpuinfo
3845 static bool is_processor_line(const char *line
)
3849 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3854 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3855 struct fuse_file_info
*fi
)
3857 struct fuse_context
*fc
= fuse_get_context();
3858 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3860 char *cpuset
= NULL
;
3862 size_t linelen
= 0, total_len
= 0, rv
= 0;
3863 bool am_printing
= false, firstline
= true, is_s390x
= false;
3864 int curcpu
= -1, cpu
, max_cpus
= 0;
3866 char *cache
= d
->buf
;
3867 size_t cache_size
= d
->buflen
;
3871 if (offset
> d
->size
)
3875 int left
= d
->size
- offset
;
3876 total_len
= left
> size
? size
: left
;
3877 memcpy(buf
, cache
+ offset
, total_len
);
3881 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3882 if (initpid
<= 1 || is_shared_pidns(initpid
))
3884 cg
= get_pid_cgroup(initpid
, "cpuset");
3886 return read_file("proc/cpuinfo", buf
, size
, d
);
3887 prune_init_slice(cg
);
3889 cpuset
= get_cpuset(cg
);
3893 use_view
= use_cpuview(cg
);
3896 max_cpus
= max_cpu_count(cg
);
3898 f
= fopen("/proc/cpuinfo", "r");
3902 while (getline(&line
, &linelen
, f
) != -1) {
3906 if (strstr(line
, "IBM/S390") != NULL
) {
3912 if (strncmp(line
, "# processors:", 12) == 0)
3914 if (is_processor_line(line
)) {
3915 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3917 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3920 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3922 perror("Error writing to cache");
3926 if (l
>= cache_size
) {
3927 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3936 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3938 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3940 if (!cpu_in_cpuset(cpu
, cpuset
))
3943 p
= strchr(line
, ':');
3947 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3949 perror("Error writing to cache");
3953 if (l
>= cache_size
) {
3954 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3965 l
= snprintf(cache
, cache_size
, "%s", line
);
3967 perror("Error writing to cache");
3971 if (l
>= cache_size
) {
3972 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3983 char *origcache
= d
->buf
;
3986 d
->buf
= malloc(d
->buflen
);
3989 cache_size
= d
->buflen
;
3991 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3992 if (l
< 0 || l
>= cache_size
) {
3999 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
4000 if (l
< 0 || l
>= cache_size
) {
4007 l
= snprintf(cache
, cache_size
, "%s", origcache
);
4009 if (l
< 0 || l
>= cache_size
)
4015 d
->size
= total_len
;
4016 if (total_len
> size
) total_len
= size
;
4018 /* read from off 0 */
4019 memcpy(buf
, d
->buf
, total_len
);
4030 static uint64_t get_reaper_start_time(pid_t pid
)
4035 /* strlen("/proc/") = 6
4039 * strlen("/stat") = 5
4043 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
4044 char path
[__PROC_PID_STAT_LEN
];
4047 qpid
= lookup_initpid_in_store(pid
);
4049 /* Caller can check for EINVAL on 0. */
4054 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
4055 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
4056 /* Caller can check for EINVAL on 0. */
4061 f
= fopen(path
, "r");
4063 /* Caller can check for EINVAL on 0. */
4068 /* Note that the *scanf() argument supression requires that length
4069 * modifiers such as "l" are omitted. Otherwise some compilers will yell
4070 * at us. It's like telling someone you're not married and then asking
4071 * if you can bring your wife to the party.
4073 ret
= fscanf(f
, "%*d " /* (1) pid %d */
4074 "%*s " /* (2) comm %s */
4075 "%*c " /* (3) state %c */
4076 "%*d " /* (4) ppid %d */
4077 "%*d " /* (5) pgrp %d */
4078 "%*d " /* (6) session %d */
4079 "%*d " /* (7) tty_nr %d */
4080 "%*d " /* (8) tpgid %d */
4081 "%*u " /* (9) flags %u */
4082 "%*u " /* (10) minflt %lu */
4083 "%*u " /* (11) cminflt %lu */
4084 "%*u " /* (12) majflt %lu */
4085 "%*u " /* (13) cmajflt %lu */
4086 "%*u " /* (14) utime %lu */
4087 "%*u " /* (15) stime %lu */
4088 "%*d " /* (16) cutime %ld */
4089 "%*d " /* (17) cstime %ld */
4090 "%*d " /* (18) priority %ld */
4091 "%*d " /* (19) nice %ld */
4092 "%*d " /* (20) num_threads %ld */
4093 "%*d " /* (21) itrealvalue %ld */
4094 "%" PRIu64
, /* (22) starttime %llu */
4098 /* Caller can check for EINVAL on 0. */
4109 static double get_reaper_start_time_in_sec(pid_t pid
)
4111 uint64_t clockticks
, ticks_per_sec
;
4115 clockticks
= get_reaper_start_time(pid
);
4116 if (clockticks
== 0 && errno
== EINVAL
) {
4117 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
4121 ret
= sysconf(_SC_CLK_TCK
);
4122 if (ret
< 0 && errno
== EINVAL
) {
4125 "failed to determine number of clock ticks in a second");
4129 ticks_per_sec
= (uint64_t)ret
;
4130 res
= (double)clockticks
/ ticks_per_sec
;
4134 static double get_reaper_age(pid_t pid
)
4137 double procstart
, procage
;
4139 /* We need to substract the time the process has started since system
4140 * boot minus the time when the system has started to get the actual
4143 procstart
= get_reaper_start_time_in_sec(pid
);
4144 procage
= procstart
;
4145 if (procstart
> 0) {
4147 struct timespec spec
;
4149 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
4153 /* We could make this more precise here by using the tv_nsec
4154 * field in the timespec struct and convert it to milliseconds
4155 * and then create a double for the seconds and milliseconds but
4156 * that seems more work than it is worth.
4158 uptime_ms
= (spec
.tv_sec
* 1000) + (spec
.tv_nsec
* 1e-6);
4159 procage
= (uptime_ms
- (procstart
* 1000)) / 1000;
4166 * Returns 0 on success.
4167 * It is the caller's responsibility to free `return_usage`, unless this
4168 * function returns an error.
4170 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
, int *size
)
4172 int cpucount
= get_nprocs_conf();
4173 struct cpuacct_usage
*cpu_usage
;
4174 int rv
= 0, i
, j
, ret
;
4176 uint64_t cg_user
, cg_system
;
4177 int64_t ticks_per_sec
;
4178 char *usage_str
= NULL
;
4180 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4182 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4185 "read_cpuacct_usage_all failed to determine number of clock ticks "
4190 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
4194 memset(cpu_usage
, 0, sizeof(struct cpuacct_usage
) * cpucount
);
4195 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
4196 // read cpuacct.usage_percpu instead
4197 lxcfs_v("failed to read cpuacct.usage_all. reading cpuacct.usage_percpu instead\n%s", "");
4198 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_percpu", &usage_str
)) {
4202 lxcfs_v("usage_str: %s\n", usage_str
);
4204 // convert cpuacct.usage_percpu into cpuacct.usage_all
4205 lxcfs_v("converting cpuacct.usage_percpu into cpuacct.usage_all\n%s", "");
4208 size_t sz
= 0, asz
= 0;
4210 must_strcat(&data
, &sz
, &asz
, "cpu user system\n");
4212 int i
= 0, read_pos
= 0, read_cnt
=0;
4213 while (sscanf(usage_str
+ read_pos
, "%lu %n", &cg_user
, &read_cnt
) > 0) {
4214 lxcfs_debug("i: %d, cg_user: %lu, read_pos: %d, read_cnt: %d\n", i
, cg_user
, read_pos
, read_cnt
);
4215 must_strcat(&data
, &sz
, &asz
, "%d %lu 0\n", i
, cg_user
);
4217 read_pos
+= read_cnt
;
4223 lxcfs_v("usage_str: %s\n", usage_str
);
4226 int read_pos
= 0, read_cnt
=0;
4227 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
4228 lxcfs_error("read_cpuacct_usage_all reading first line from "
4229 "%s/cpuacct.usage_all failed.\n", cg
);
4234 read_pos
+= read_cnt
;
4236 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
4237 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
4238 &cg_system
, &read_cnt
);
4244 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
4250 read_pos
+= read_cnt
;
4252 /* Convert the time from nanoseconds to USER_HZ */
4253 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4254 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4259 *return_usage
= cpu_usage
;
4268 *return_usage
= NULL
;
4274 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
4277 unsigned long sum
= 0;
4279 for (i
= 0; i
< cpu_count
; i
++) {
4280 if (!newer
[i
].online
)
4283 /* When cpuset is changed on the fly, the CPUs might get reordered.
4284 * We could either reset all counters, or check that the substractions
4285 * below will return expected results.
4287 if (newer
[i
].user
> older
[i
].user
)
4288 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
4292 if (newer
[i
].system
> older
[i
].system
)
4293 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
4297 if (newer
[i
].idle
> older
[i
].idle
)
4298 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
4302 sum
+= diff
[i
].user
;
4303 sum
+= diff
[i
].system
;
4304 sum
+= diff
[i
].idle
;
4310 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
4312 unsigned long free_space
, to_add
;
4314 free_space
= threshold
- usage
->user
- usage
->system
;
4316 if (free_space
> usage
->idle
)
4317 free_space
= usage
->idle
;
4319 to_add
= free_space
> *surplus
? *surplus
: free_space
;
4322 usage
->idle
-= to_add
;
4326 static struct cg_proc_stat
*prune_proc_stat_list(struct cg_proc_stat
*node
)
4328 struct cg_proc_stat
*first
= NULL
, *prev
, *tmp
;
4330 for (prev
= NULL
; node
; ) {
4331 if (!cgfs_param_exist("cpu", node
->cg
, "cpu.shares")) {
4333 lxcfs_debug("Removing stat node for %s\n", node
->cg
);
4336 prev
->next
= node
->next
;
4341 free_proc_stat_node(tmp
);
4353 #define PROC_STAT_PRUNE_INTERVAL 10
4354 static void prune_proc_stat_history(void)
4357 time_t now
= time(NULL
);
4359 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
4360 pthread_rwlock_wrlock(&proc_stat_history
[i
]->lock
);
4362 if ((proc_stat_history
[i
]->lastcheck
+ PROC_STAT_PRUNE_INTERVAL
) > now
) {
4363 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4367 if (proc_stat_history
[i
]->next
) {
4368 proc_stat_history
[i
]->next
= prune_proc_stat_list(proc_stat_history
[i
]->next
);
4369 proc_stat_history
[i
]->lastcheck
= now
;
4372 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4376 static struct cg_proc_stat
*find_proc_stat_node(struct cg_proc_stat_head
*head
, const char *cg
)
4378 struct cg_proc_stat
*node
;
4380 pthread_rwlock_rdlock(&head
->lock
);
4383 pthread_rwlock_unlock(&head
->lock
);
4390 if (strcmp(cg
, node
->cg
) == 0)
4392 } while ((node
= node
->next
));
4397 pthread_rwlock_unlock(&head
->lock
);
4398 prune_proc_stat_history();
4402 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4404 struct cg_proc_stat
*node
;
4407 node
= malloc(sizeof(struct cg_proc_stat
));
4415 node
->cg
= malloc(strlen(cg
) + 1);
4419 strcpy(node
->cg
, cg
);
4421 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4425 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4427 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4431 node
->cpu_count
= cpu_count
;
4434 if (pthread_mutex_init(&node
->lock
, NULL
) != 0) {
4435 lxcfs_error("%s\n", "Failed to initialize node lock");
4439 for (i
= 0; i
< cpu_count
; i
++) {
4440 node
->view
[i
].user
= 0;
4441 node
->view
[i
].system
= 0;
4442 node
->view
[i
].idle
= 0;
4448 if (node
&& node
->cg
)
4450 if (node
&& node
->usage
)
4452 if (node
&& node
->view
)
4460 static struct cg_proc_stat
*add_proc_stat_node(struct cg_proc_stat
*new_node
)
4462 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4463 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4464 struct cg_proc_stat
*node
, *rv
= new_node
;
4466 pthread_rwlock_wrlock(&head
->lock
);
4469 head
->next
= new_node
;
4476 if (strcmp(node
->cg
, new_node
->cg
) == 0) {
4477 /* The node is already present, return it */
4478 free_proc_stat_node(new_node
);
4488 node
->next
= new_node
;
4493 pthread_rwlock_unlock(&head
->lock
);
4497 static bool expand_proc_stat_node(struct cg_proc_stat
*node
, int cpu_count
)
4499 struct cpuacct_usage
*new_usage
, *new_view
;
4502 /* Allocate new memory */
4503 new_usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4507 new_view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4513 /* Copy existing data & initialize new elements */
4514 for (i
= 0; i
< cpu_count
; i
++) {
4515 if (i
< node
->cpu_count
) {
4516 new_usage
[i
].user
= node
->usage
[i
].user
;
4517 new_usage
[i
].system
= node
->usage
[i
].system
;
4518 new_usage
[i
].idle
= node
->usage
[i
].idle
;
4520 new_view
[i
].user
= node
->view
[i
].user
;
4521 new_view
[i
].system
= node
->view
[i
].system
;
4522 new_view
[i
].idle
= node
->view
[i
].idle
;
4524 new_usage
[i
].user
= 0;
4525 new_usage
[i
].system
= 0;
4526 new_usage
[i
].idle
= 0;
4528 new_view
[i
].user
= 0;
4529 new_view
[i
].system
= 0;
4530 new_view
[i
].idle
= 0;
4537 node
->usage
= new_usage
;
4538 node
->view
= new_view
;
4539 node
->cpu_count
= cpu_count
;
4544 static struct cg_proc_stat
*find_or_create_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4546 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4547 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4548 struct cg_proc_stat
*node
;
4550 node
= find_proc_stat_node(head
, cg
);
4553 node
= new_proc_stat_node(usage
, cpu_count
, cg
);
4557 node
= add_proc_stat_node(node
);
4558 lxcfs_debug("New stat node (%d) for %s\n", cpu_count
, cg
);
4561 pthread_mutex_lock(&node
->lock
);
4563 /* If additional CPUs on the host have been enabled, CPU usage counter
4564 * arrays have to be expanded */
4565 if (node
->cpu_count
< cpu_count
) {
4566 lxcfs_debug("Expanding stat node %d->%d for %s\n",
4567 node
->cpu_count
, cpu_count
, cg
);
4569 if (!expand_proc_stat_node(node
, cpu_count
)) {
4570 pthread_mutex_unlock(&node
->lock
);
4571 lxcfs_debug("Unable to expand stat node %d->%d for %s\n",
4572 node
->cpu_count
, cpu_count
, cg
);
4580 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4584 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4585 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4587 for (i
= 0; i
< cpu_count
; i
++) {
4588 node
->view
[i
].user
= 0;
4589 node
->view
[i
].system
= 0;
4590 node
->view
[i
].idle
= 0;
4593 node
->cpu_count
= cpu_count
;
4596 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
)
4599 size_t linelen
= 0, total_len
= 0, rv
= 0, l
;
4600 int curcpu
= -1; /* cpu numbering starts at 0 */
4602 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4603 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4604 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4605 unsigned long user_surplus
= 0, system_surplus
= 0;
4606 unsigned long total_sum
, threshold
;
4607 struct cg_proc_stat
*stat_node
;
4608 struct cpuacct_usage
*diff
= NULL
;
4609 int nprocs
= get_nprocs_conf();
4611 if (cg_cpu_usage_size
< nprocs
)
4612 nprocs
= cg_cpu_usage_size
;
4614 /* Read all CPU stats and stop when we've encountered other lines */
4615 while (getline(&line
, &linelen
, f
) != -1) {
4617 char cpu_char
[10]; /* That's a lot of cores */
4618 uint64_t all_used
, cg_used
;
4620 if (strlen(line
) == 0)
4622 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4623 /* not a ^cpuN line containing a number N */
4627 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4630 if (physcpu
>= cg_cpu_usage_size
)
4636 if (!cpu_in_cpuset(physcpu
, cpuset
)) {
4637 for (i
= curcpu
; i
<= physcpu
; i
++) {
4638 cg_cpu_usage
[i
].online
= false;
4643 if (curcpu
< physcpu
) {
4644 /* Some CPUs may be disabled */
4645 for (i
= curcpu
; i
< physcpu
; i
++)
4646 cg_cpu_usage
[i
].online
= false;
4651 cg_cpu_usage
[curcpu
].online
= true;
4653 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4668 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4669 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4671 if (all_used
>= cg_used
) {
4672 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4675 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4676 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4677 curcpu
, cg
, all_used
, cg_used
);
4678 cg_cpu_usage
[curcpu
].idle
= idle
;
4682 /* Cannot use more CPUs than is available due to cpuset */
4683 if (max_cpus
> cpu_cnt
)
4686 stat_node
= find_or_create_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4689 lxcfs_error("unable to find/create stat node for %s\n", cg
);
4694 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4701 * If the new values are LOWER than values stored in memory, it means
4702 * the cgroup has been reset/recreated and we should reset too.
4704 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4705 if (!cg_cpu_usage
[curcpu
].online
)
4708 if (cg_cpu_usage
[curcpu
].user
< stat_node
->usage
[curcpu
].user
)
4709 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4714 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, nprocs
);
4716 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4717 stat_node
->usage
[curcpu
].online
= cg_cpu_usage
[curcpu
].online
;
4719 if (!stat_node
->usage
[curcpu
].online
)
4724 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4725 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4726 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4728 if (max_cpus
> 0 && i
>= max_cpus
) {
4729 user_surplus
+= diff
[curcpu
].user
;
4730 system_surplus
+= diff
[curcpu
].system
;
4734 /* Calculate usage counters of visible CPUs */
4736 /* threshold = maximum usage per cpu, including idle */
4737 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4739 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4740 if (!stat_node
->usage
[curcpu
].online
)
4748 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4758 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4761 /* If there is still room, add system */
4765 &diff
[curcpu
].system
,
4769 if (user_surplus
> 0)
4770 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4771 if (system_surplus
> 0)
4772 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4774 unsigned long diff_user
= 0;
4775 unsigned long diff_system
= 0;
4776 unsigned long diff_idle
= 0;
4777 unsigned long max_diff_idle
= 0;
4778 unsigned long max_diff_idle_index
= 0;
4779 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4780 if (!stat_node
->usage
[curcpu
].online
)
4788 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4789 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4790 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4792 user_sum
+= stat_node
->view
[curcpu
].user
;
4793 system_sum
+= stat_node
->view
[curcpu
].system
;
4794 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4796 diff_user
+= diff
[curcpu
].user
;
4797 diff_system
+= diff
[curcpu
].system
;
4798 diff_idle
+= diff
[curcpu
].idle
;
4799 if (diff
[curcpu
].idle
> max_diff_idle
) {
4800 max_diff_idle
= diff
[curcpu
].idle
;
4801 max_diff_idle_index
= curcpu
;
4804 lxcfs_v("curcpu: %d, diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", curcpu
, diff
[curcpu
].user
, diff
[curcpu
].system
, diff
[curcpu
].idle
);
4806 lxcfs_v("total. diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", diff_user
, diff_system
, diff_idle
);
4808 // revise cpu usage view to support partial cpu case
4809 double exact_cpus
= exact_cpu_count(cg
);
4810 if (exact_cpus
< (double)max_cpus
){
4811 lxcfs_v("revising cpu usage view to match the exact cpu count [%f]\n", exact_cpus
);
4812 unsigned long delta
= (unsigned long)((double)(diff_user
+ diff_system
+ diff_idle
) * (1 - exact_cpus
/ (double)max_cpus
));
4813 lxcfs_v("delta: %lu\n", delta
);
4814 lxcfs_v("idle_sum before: %lu\n", idle_sum
);
4815 idle_sum
= idle_sum
> delta
? idle_sum
- delta
: 0;
4816 lxcfs_v("idle_sum after: %lu\n", idle_sum
);
4818 curcpu
= max_diff_idle_index
;
4819 lxcfs_v("curcpu: %d, idle before: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4820 stat_node
->view
[curcpu
].idle
= stat_node
->view
[curcpu
].idle
> delta
? stat_node
->view
[curcpu
].idle
- delta
: 0;
4821 lxcfs_v("curcpu: %d, idle after: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4824 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4825 if (!stat_node
->usage
[curcpu
].online
)
4828 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4829 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4830 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4832 user_sum
+= stat_node
->view
[curcpu
].user
;
4833 system_sum
+= stat_node
->view
[curcpu
].system
;
4834 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4838 /* Render the file */
4840 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4844 lxcfs_v("cpu-all: %s\n", buf
);
4847 perror("Error writing to cache");
4851 if (l
>= buf_size
) {
4852 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4861 /* Render visible CPUs */
4862 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4863 if (!stat_node
->usage
[curcpu
].online
)
4868 if (max_cpus
> 0 && i
== max_cpus
)
4871 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4873 stat_node
->view
[curcpu
].user
,
4874 stat_node
->view
[curcpu
].system
,
4875 stat_node
->view
[curcpu
].idle
);
4876 lxcfs_v("cpu: %s\n", buf
);
4879 perror("Error writing to cache");
4884 if (l
>= buf_size
) {
4885 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4895 /* Pass the rest of /proc/stat, start with the last line read */
4896 l
= snprintf(buf
, buf_size
, "%s", line
);
4899 perror("Error writing to cache");
4904 if (l
>= buf_size
) {
4905 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4914 /* Pass the rest of the host's /proc/stat */
4915 while (getline(&line
, &linelen
, f
) != -1) {
4916 l
= snprintf(buf
, buf_size
, "%s", line
);
4918 perror("Error writing to cache");
4922 if (l
>= buf_size
) {
4923 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4936 pthread_mutex_unlock(&stat_node
->lock
);
4944 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4945 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4946 struct fuse_file_info
*fi
)
4948 struct fuse_context
*fc
= fuse_get_context();
4949 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4951 char *cpuset
= NULL
;
4953 size_t linelen
= 0, total_len
= 0, rv
= 0;
4954 int curcpu
= -1; /* cpu numbering starts at 0 */
4956 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4957 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
4958 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4959 char cpuall
[CPUALL_MAX_SIZE
];
4960 /* reserve for cpu all */
4961 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4962 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4964 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4965 int cg_cpu_usage_size
= 0;
4968 if (offset
> d
->size
)
4972 int left
= d
->size
- offset
;
4973 total_len
= left
> size
? size
: left
;
4974 memcpy(buf
, d
->buf
+ offset
, total_len
);
4978 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4979 lxcfs_v("initpid: %d\n", initpid
);
4984 * when container run with host pid namespace initpid == 1, cgroup will "/"
4985 * we should return host os's /proc contents.
4986 * in some case cpuacct_usage.all in "/" will larger then /proc/stat
4989 return read_file("/proc/stat", buf
, size
, d
);
4992 cg
= get_pid_cgroup(initpid
, "cpuset");
4993 lxcfs_v("cg: %s\n", cg
);
4995 return read_file("/proc/stat", buf
, size
, d
);
4996 prune_init_slice(cg
);
4998 cpuset
= get_cpuset(cg
);
5003 * Read cpuacct.usage_all for all CPUs.
5004 * If the cpuacct cgroup is present, it is used to calculate the container's
5005 * CPU usage. If not, values from the host's /proc/stat are used.
5007 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
, &cg_cpu_usage_size
) != 0) {
5008 lxcfs_v("%s\n", "proc_stat_read failed to read from cpuacct, "
5009 "falling back to the host's /proc/stat");
5012 f
= fopen("/proc/stat", "r");
5017 if (getline(&line
, &linelen
, f
) < 0) {
5018 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
5022 if (use_cpuview(cg
) && cg_cpu_usage
) {
5023 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, cg_cpu_usage_size
,
5024 f
, d
->buf
, d
->buflen
);
5028 while (getline(&line
, &linelen
, f
) != -1) {
5030 char cpu_char
[10]; /* That's a lot of cores */
5032 uint64_t all_used
, cg_used
, new_idle
;
5035 if (strlen(line
) == 0)
5037 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
5038 /* not a ^cpuN line containing a number N, just print it */
5039 l
= snprintf(cache
, cache_size
, "%s", line
);
5041 perror("Error writing to cache");
5045 if (l
>= cache_size
) {
5046 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5056 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
5058 if (!cpu_in_cpuset(physcpu
, cpuset
))
5062 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
5074 if (ret
!= 10 || !cg_cpu_usage
) {
5075 c
= strchr(line
, ' ');
5078 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
5080 perror("Error writing to cache");
5085 if (l
>= cache_size
) {
5086 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5100 if (physcpu
>= cg_cpu_usage_size
)
5103 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
5104 cg_used
= cg_cpu_usage
[physcpu
].user
+ cg_cpu_usage
[physcpu
].system
;
5106 if (all_used
>= cg_used
) {
5107 new_idle
= idle
+ (all_used
- cg_used
);
5110 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
5111 "%lu in cpuacct.usage_all; unable to determine idle time\n",
5112 curcpu
, cg
, all_used
, cg_used
);
5116 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
5117 curcpu
, cg_cpu_usage
[physcpu
].user
, cg_cpu_usage
[physcpu
].system
,
5121 perror("Error writing to cache");
5126 if (l
>= cache_size
) {
5127 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5136 user_sum
+= cg_cpu_usage
[physcpu
].user
;
5137 system_sum
+= cg_cpu_usage
[physcpu
].system
;
5138 idle_sum
+= new_idle
;
5143 system_sum
+= system
;
5145 iowait_sum
+= iowait
;
5147 softirq_sum
+= softirq
;
5150 guest_nice_sum
+= guest_nice
;
5156 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5167 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
5168 memcpy(cache
, cpuall
, cpuall_len
);
5169 cache
+= cpuall_len
;
5171 /* shouldn't happen */
5172 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
5176 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
5177 total_len
+= cpuall_len
;
5181 d
->size
= total_len
;
5182 if (total_len
> size
)
5185 memcpy(buf
, d
->buf
, total_len
);
5199 /* This function retrieves the busy time of a group of tasks by looking at
5200 * cpuacct.usage. Unfortunately, this only makes sense when the container has
5201 * been given it's own cpuacct cgroup. If not, this function will take the busy
5202 * time of all other taks that do not actually belong to the container into
5203 * account as well. If someone has a clever solution for this please send a
5206 static double get_reaper_busy(pid_t task
)
5208 pid_t initpid
= lookup_initpid_in_store(task
);
5209 char *cgroup
= NULL
, *usage_str
= NULL
;
5210 unsigned long usage
= 0;
5216 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
5219 prune_init_slice(cgroup
);
5220 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
5222 usage
= strtoul(usage_str
, NULL
, 10);
5223 res
= (double)usage
/ 1000000000;
5236 fd
= creat("/tmp/lxcfs-iwashere", 0644);
5243 * We read /proc/uptime and reuse its second field.
5244 * For the first field, we use the mtime for the reaper for
5245 * the calling pid as returned by getreaperage
5247 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
5248 struct fuse_file_info
*fi
)
5250 struct fuse_context
*fc
= fuse_get_context();
5251 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5252 double busytime
= get_reaper_busy(fc
->pid
);
5253 char *cache
= d
->buf
;
5254 ssize_t total_len
= 0;
5255 double idletime
, reaperage
;
5264 if (offset
> d
->size
)
5266 int left
= d
->size
- offset
;
5267 total_len
= left
> size
? size
: left
;
5268 memcpy(buf
, cache
+ offset
, total_len
);
5272 reaperage
= get_reaper_age(fc
->pid
);
5273 /* To understand why this is done, please read the comment to the
5274 * get_reaper_busy() function.
5276 idletime
= reaperage
;
5277 if (reaperage
>= busytime
)
5278 idletime
= reaperage
- busytime
;
5280 total_len
= snprintf(d
->buf
, d
->buflen
, "%.2lf %.2lf\n", reaperage
, idletime
);
5281 if (total_len
< 0 || total_len
>= d
->buflen
){
5282 lxcfs_error("%s\n", "failed to write to cache");
5286 d
->size
= (int)total_len
;
5289 if (total_len
> size
) total_len
= size
;
5291 memcpy(buf
, d
->buf
, total_len
);
5295 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
5296 struct fuse_file_info
*fi
)
5299 struct fuse_context
*fc
= fuse_get_context();
5300 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5302 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
5303 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
5304 unsigned long read
= 0, write
= 0;
5305 unsigned long read_merged
= 0, write_merged
= 0;
5306 unsigned long read_sectors
= 0, write_sectors
= 0;
5307 unsigned long read_ticks
= 0, write_ticks
= 0;
5308 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
5309 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
5310 char *cache
= d
->buf
;
5311 size_t cache_size
= d
->buflen
;
5313 size_t linelen
= 0, total_len
= 0, rv
= 0;
5314 unsigned int major
= 0, minor
= 0;
5319 if (offset
> d
->size
)
5323 int left
= d
->size
- offset
;
5324 total_len
= left
> size
? size
: left
;
5325 memcpy(buf
, cache
+ offset
, total_len
);
5329 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5330 if (initpid
<= 1 || is_shared_pidns(initpid
))
5332 cg
= get_pid_cgroup(initpid
, "blkio");
5334 return read_file("/proc/diskstats", buf
, size
, d
);
5335 prune_init_slice(cg
);
5337 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
5339 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
5341 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
5343 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
5345 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
5349 f
= fopen("/proc/diskstats", "r");
5353 while (getline(&line
, &linelen
, f
) != -1) {
5357 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
5361 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
5362 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
5363 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
5364 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
5365 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
5366 read_sectors
= read_sectors
/512;
5367 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
5368 write_sectors
= write_sectors
/512;
5370 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
5371 rd_svctm
= rd_svctm
/1000000;
5372 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
5373 rd_wait
= rd_wait
/1000000;
5374 read_ticks
= rd_svctm
+ rd_wait
;
5376 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
5377 wr_svctm
= wr_svctm
/1000000;
5378 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
5379 wr_wait
= wr_wait
/1000000;
5380 write_ticks
= wr_svctm
+ wr_wait
;
5382 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
5383 tot_ticks
= tot_ticks
/1000000;
5385 memset(lbuf
, 0, 256);
5386 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
5387 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5388 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
5389 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
5393 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
5395 perror("Error writing to fuse buf");
5399 if (l
>= cache_size
) {
5400 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5410 d
->size
= total_len
;
5411 if (total_len
> size
) total_len
= size
;
5412 memcpy(buf
, d
->buf
, total_len
);
5420 free(io_serviced_str
);
5421 free(io_merged_str
);
5422 free(io_service_bytes_str
);
5423 free(io_wait_time_str
);
5424 free(io_service_time_str
);
5428 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
5429 struct fuse_file_info
*fi
)
5431 struct fuse_context
*fc
= fuse_get_context();
5432 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5434 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
5435 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
5436 ssize_t total_len
= 0, rv
= 0;
5438 char *cache
= d
->buf
;
5441 if (offset
> d
->size
)
5445 int left
= d
->size
- offset
;
5446 total_len
= left
> size
? size
: left
;
5447 memcpy(buf
, cache
+ offset
, total_len
);
5451 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5452 if (initpid
<= 1 || is_shared_pidns(initpid
))
5454 cg
= get_pid_cgroup(initpid
, "memory");
5456 return read_file("/proc/swaps", buf
, size
, d
);
5457 prune_init_slice(cg
);
5459 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
5461 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
5464 memusage
= strtoul(memusage_str
, NULL
, 10);
5466 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
5467 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
5469 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
5470 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5472 swap_total
= (memswlimit
- memlimit
) / 1024;
5473 swap_free
= (memswusage
- memusage
) / 1024;
5476 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5478 /* When no mem + swap limit is specified or swapaccount=0*/
5482 FILE *f
= fopen("/proc/meminfo", "r");
5487 while (getline(&line
, &linelen
, f
) != -1) {
5488 if (startswith(line
, "SwapTotal:")) {
5489 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5490 } else if (startswith(line
, "SwapFree:")) {
5491 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5499 if (swap_total
> 0) {
5500 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5501 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5502 swap_total
, swap_free
);
5506 if (total_len
< 0 || l
< 0) {
5507 perror("Error writing to cache");
5513 d
->size
= (int)total_len
;
5515 if (total_len
> size
) total_len
= size
;
5516 memcpy(buf
, d
->buf
, total_len
);
5521 free(memswlimit_str
);
5524 free(memswusage_str
);
5528 * Find the process pid from cgroup path.
5529 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5530 * @pid_buf : put pid to pid_buf.
5531 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5532 * @depth : the depth of cgroup in container.
5533 * @sum : return the number of pid.
5534 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5536 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5540 struct dirent
*file
;
5545 char *path_dir
, *path
;
5548 /* path = dpath + "/cgroup.procs" + /0 */
5550 path
= malloc(strlen(dpath
) + 20);
5553 strcpy(path
, dpath
);
5554 fd
= openat(cfd
, path
, O_RDONLY
);
5558 dir
= fdopendir(fd
);
5564 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5565 if (strncmp(file
->d_name
, ".", 1) == 0)
5567 if (strncmp(file
->d_name
, "..", 1) == 0)
5569 if (file
->d_type
== DT_DIR
) {
5570 /* path + '/' + d_name +/0 */
5572 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5573 } while (!path_dir
);
5574 strcpy(path_dir
, path
);
5575 strcat(path_dir
, "/");
5576 strcat(path_dir
, file
->d_name
);
5578 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5584 strcat(path
, "/cgroup.procs");
5585 fd
= openat(cfd
, path
, O_RDONLY
);
5589 f
= fdopen(fd
, "r");
5595 while (getline(&line
, &linelen
, f
) != -1) {
5597 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5601 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5602 } while (*(*pid_buf
+ sum
) == NULL
);
5603 strcpy(*(*pid_buf
+ sum
), line
);
5614 * calc_load calculates the load according to the following formula:
5615 * load1 = load0 * exp + active * (1 - exp)
5617 * @load1: the new loadavg.
5618 * @load0: the former loadavg.
5619 * @active: the total number of running pid at this moment.
5620 * @exp: the fixed-point defined in the beginning.
5622 static unsigned long
5623 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5625 unsigned long newload
;
5627 active
= active
> 0 ? active
* FIXED_1
: 0;
5628 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5630 newload
+= FIXED_1
- 1;
5632 return newload
/ FIXED_1
;
5636 * Return 0 means that container p->cg is closed.
5637 * Return -1 means that error occurred in refresh.
5638 * Positive num equals the total number of pid.
5640 static int refresh_load(struct load_node
*p
, char *path
)
5644 char proc_path
[256];
5645 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5650 struct dirent
*file
;
5653 idbuf
= malloc(sizeof(char *));
5655 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5660 for (i
= 0; i
< sum
; i
++) {
5662 length
= strlen(idbuf
[i
])-1;
5663 idbuf
[i
][length
] = '\0';
5664 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5665 if (ret
< 0 || ret
> 255) {
5666 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5672 dp
= opendir(proc_path
);
5674 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5677 while ((file
= readdir(dp
)) != NULL
) {
5678 if (strncmp(file
->d_name
, ".", 1) == 0)
5680 if (strncmp(file
->d_name
, "..", 1) == 0)
5683 /* We make the biggest pid become last_pid.*/
5684 ret
= atof(file
->d_name
);
5685 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5687 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5688 if (ret
< 0 || ret
> 255) {
5689 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5695 f
= fopen(proc_path
, "r");
5697 while (getline(&line
, &linelen
, f
) != -1) {
5699 if ((line
[0] == 'S') && (line
[1] == 't'))
5702 if ((line
[7] == 'R') || (line
[7] == 'D'))
5709 /*Calculate the loadavg.*/
5710 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5711 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5712 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5713 p
->run_pid
= run_pid
;
5714 p
->total_pid
= total_pid
;
5715 p
->last_pid
= last_pid
;
5726 * Traverse the hash table and update it.
5728 void *load_begin(void *arg
)
5732 int i
, sum
, length
, ret
;
5733 struct load_node
*f
;
5735 clock_t time1
, time2
;
5738 if (loadavg_stop
== 1)
5742 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5743 pthread_mutex_lock(&load_hash
[i
].lock
);
5744 if (load_hash
[i
].next
== NULL
) {
5745 pthread_mutex_unlock(&load_hash
[i
].lock
);
5748 f
= load_hash
[i
].next
;
5751 length
= strlen(f
->cg
) + 2;
5753 /* strlen(f->cg) + '.' or '' + \0 */
5754 path
= malloc(length
);
5757 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
5758 if (ret
< 0 || ret
> length
- 1) {
5759 /* snprintf failed, ignore the node.*/
5760 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5763 sum
= refresh_load(f
, path
);
5770 /* load_hash[i].lock locks only on the first node.*/
5771 if (first_node
== 1) {
5773 pthread_mutex_unlock(&load_hash
[i
].lock
);
5778 if (loadavg_stop
== 1)
5782 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5786 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5787 struct fuse_file_info
*fi
)
5789 struct fuse_context
*fc
= fuse_get_context();
5790 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5793 size_t total_len
= 0;
5794 char *cache
= d
->buf
;
5795 struct load_node
*n
;
5798 unsigned long a
, b
, c
;
5801 if (offset
> d
->size
)
5805 int left
= d
->size
- offset
;
5806 total_len
= left
> size
? size
: left
;
5807 memcpy(buf
, cache
+ offset
, total_len
);
5811 return read_file("/proc/loadavg", buf
, size
, d
);
5813 initpid
= lookup_initpid_in_store(fc
->pid
);
5814 if (initpid
<= 1 || is_shared_pidns(initpid
))
5816 cg
= get_pid_cgroup(initpid
, "cpu");
5818 return read_file("/proc/loadavg", buf
, size
, d
);
5820 prune_init_slice(cg
);
5821 hash
= calc_hash(cg
) % LOAD_SIZE
;
5822 n
= locate_node(cg
, hash
);
5826 if (!find_mounted_controller("cpu", &cfd
)) {
5828 * In locate_node() above, pthread_rwlock_unlock() isn't used
5829 * because delete is not allowed before read has ended.
5831 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5836 n
= malloc(sizeof(struct load_node
));
5840 n
->cg
= malloc(strlen(cg
)+1);
5848 n
->last_pid
= initpid
;
5850 insert_node(&n
, hash
);
5852 a
= n
->avenrun
[0] + (FIXED_1
/200);
5853 b
= n
->avenrun
[1] + (FIXED_1
/200);
5854 c
= n
->avenrun
[2] + (FIXED_1
/200);
5855 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5856 LOAD_INT(a
), LOAD_FRAC(a
),
5857 LOAD_INT(b
), LOAD_FRAC(b
),
5858 LOAD_INT(c
), LOAD_FRAC(c
),
5859 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5860 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5861 if (total_len
< 0 || total_len
>= d
->buflen
) {
5862 lxcfs_error("%s\n", "Failed to write to cache");
5866 d
->size
= (int)total_len
;
5869 if (total_len
> size
)
5871 memcpy(buf
, d
->buf
, total_len
);
5878 /* Return a positive number on success, return 0 on failure.*/
5879 pthread_t
load_daemon(int load_use
)
5886 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5889 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5891 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5895 /* use loadavg, here loadavg = 1*/
5900 /* Returns 0 on success. */
5901 int stop_load_daemon(pthread_t pid
)
5905 /* Signal the thread to gracefully stop */
5908 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5910 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5920 static off_t
get_procfile_size(const char *which
)
5922 FILE *f
= fopen(which
, "r");
5925 ssize_t sz
, answer
= 0;
5929 while ((sz
= getline(&line
, &len
, f
)) != -1)
5937 int proc_getattr(const char *path
, struct stat
*sb
)
5939 struct timespec now
;
5941 memset(sb
, 0, sizeof(struct stat
));
5942 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5944 sb
->st_uid
= sb
->st_gid
= 0;
5945 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5946 if (strcmp(path
, "/proc") == 0) {
5947 sb
->st_mode
= S_IFDIR
| 00555;
5951 if (strcmp(path
, "/proc/meminfo") == 0 ||
5952 strcmp(path
, "/proc/cpuinfo") == 0 ||
5953 strcmp(path
, "/proc/uptime") == 0 ||
5954 strcmp(path
, "/proc/stat") == 0 ||
5955 strcmp(path
, "/proc/diskstats") == 0 ||
5956 strcmp(path
, "/proc/swaps") == 0 ||
5957 strcmp(path
, "/proc/loadavg") == 0) {
5959 sb
->st_mode
= S_IFREG
| 00444;
5967 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5968 struct fuse_file_info
*fi
)
5970 if (filler(buf
, ".", NULL
, 0) != 0 ||
5971 filler(buf
, "..", NULL
, 0) != 0 ||
5972 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5973 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5974 filler(buf
, "stat", NULL
, 0) != 0 ||
5975 filler(buf
, "uptime", NULL
, 0) != 0 ||
5976 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5977 filler(buf
, "swaps", NULL
, 0) != 0 ||
5978 filler(buf
, "loadavg", NULL
, 0) != 0)
5983 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5986 struct file_info
*info
;
5988 if (strcmp(path
, "/proc/meminfo") == 0)
5989 type
= LXC_TYPE_PROC_MEMINFO
;
5990 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5991 type
= LXC_TYPE_PROC_CPUINFO
;
5992 else if (strcmp(path
, "/proc/uptime") == 0)
5993 type
= LXC_TYPE_PROC_UPTIME
;
5994 else if (strcmp(path
, "/proc/stat") == 0)
5995 type
= LXC_TYPE_PROC_STAT
;
5996 else if (strcmp(path
, "/proc/diskstats") == 0)
5997 type
= LXC_TYPE_PROC_DISKSTATS
;
5998 else if (strcmp(path
, "/proc/swaps") == 0)
5999 type
= LXC_TYPE_PROC_SWAPS
;
6000 else if (strcmp(path
, "/proc/loadavg") == 0)
6001 type
= LXC_TYPE_PROC_LOADAVG
;
6005 info
= malloc(sizeof(*info
));
6009 memset(info
, 0, sizeof(*info
));
6012 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
6014 info
->buf
= malloc(info
->buflen
);
6015 } while (!info
->buf
);
6016 memset(info
->buf
, 0, info
->buflen
);
6017 /* set actual size to buffer size */
6018 info
->size
= info
->buflen
;
6020 fi
->fh
= (unsigned long)info
;
6024 int proc_access(const char *path
, int mask
)
6026 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
6029 /* these are all read-only */
6030 if ((mask
& ~R_OK
) != 0)
6035 int proc_release(const char *path
, struct fuse_file_info
*fi
)
6037 do_release_file_info(fi
);
6041 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
6042 struct fuse_file_info
*fi
)
6044 struct file_info
*f
= (struct file_info
*) fi
->fh
;
6047 case LXC_TYPE_PROC_MEMINFO
:
6048 return proc_meminfo_read(buf
, size
, offset
, fi
);
6049 case LXC_TYPE_PROC_CPUINFO
:
6050 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
6051 case LXC_TYPE_PROC_UPTIME
:
6052 return proc_uptime_read(buf
, size
, offset
, fi
);
6053 case LXC_TYPE_PROC_STAT
:
6054 return proc_stat_read(buf
, size
, offset
, fi
);
6055 case LXC_TYPE_PROC_DISKSTATS
:
6056 return proc_diskstats_read(buf
, size
, offset
, fi
);
6057 case LXC_TYPE_PROC_SWAPS
:
6058 return proc_swaps_read(buf
, size
, offset
, fi
);
6059 case LXC_TYPE_PROC_LOADAVG
:
6060 return proc_loadavg_read(buf
, size
, offset
, fi
);
6067 * Functions needed to setup cgroups in the __constructor__.
6070 static bool mkdir_p(const char *dir
, mode_t mode
)
6072 const char *tmp
= dir
;
6073 const char *orig
= dir
;
6077 dir
= tmp
+ strspn(tmp
, "/");
6078 tmp
= dir
+ strcspn(dir
, "/");
6079 makeme
= strndup(orig
, dir
- orig
);
6082 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
6083 lxcfs_error("Failed to create directory '%s': %s.\n",
6084 makeme
, strerror(errno
));
6089 } while(tmp
!= dir
);
6094 static bool umount_if_mounted(void)
6096 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
6097 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
6103 /* __typeof__ should be safe to use with all compilers. */
6104 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
6105 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
6107 return (fs
->f_type
== (fs_type_magic
)magic_val
);
6111 * looking at fs/proc_namespace.c, it appears we can
6112 * actually expect the rootfs entry to very specifically contain
6113 * " - rootfs rootfs "
6114 * IIUC, so long as we've chrooted so that rootfs is not our root,
6115 * the rootfs entry should always be skipped in mountinfo contents.
6117 static bool is_on_ramfs(void)
6125 f
= fopen("/proc/self/mountinfo", "r");
6129 while (getline(&line
, &len
, f
) != -1) {
6130 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
6131 p
= strchr(p
+ 1, ' ');
6134 p2
= strchr(p
+ 1, ' ');
6138 if (strcmp(p
+ 1, "/") == 0) {
6139 // this is '/'. is it the ramfs?
6140 p
= strchr(p2
+ 1, '-');
6141 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
6153 static int pivot_enter()
6155 int ret
= -1, oldroot
= -1, newroot
= -1;
6157 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
6159 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
6163 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
6165 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
6169 /* change into new root fs */
6170 if (fchdir(newroot
) < 0) {
6171 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
6175 /* pivot_root into our new root fs */
6176 if (pivot_root(".", ".") < 0) {
6177 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
6182 * At this point the old-root is mounted on top of our new-root.
6183 * To unmounted it we must not be chdir'd into it, so escape back
6186 if (fchdir(oldroot
) < 0) {
6187 lxcfs_error("%s\n", "Failed to enter old root.");
6191 if (umount2(".", MNT_DETACH
) < 0) {
6192 lxcfs_error("%s\n", "Failed to detach old root.");
6196 if (fchdir(newroot
) < 0) {
6197 lxcfs_error("%s\n", "Failed to re-enter new root.");
6212 static int chroot_enter()
6214 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
6215 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
6219 if (chroot(".") < 0) {
6220 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
6224 if (chdir("/") < 0) {
6225 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
6232 static int permute_and_enter(void)
6236 if (statfs("/", &sb
) < 0) {
6237 lxcfs_error("%s\n", "Could not stat / mountpoint.");
6241 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
6242 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
6243 * /proc/1/mountinfo. */
6244 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
6245 return chroot_enter();
6247 if (pivot_enter() < 0) {
6248 lxcfs_error("%s\n", "Could not perform pivot root.");
6255 /* Prepare our new clean root. */
6256 static int permute_prepare(void)
6258 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
6259 lxcfs_error("%s\n", "Failed to create directory for new root.");
6263 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
6264 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
6268 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
6269 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
6273 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
6274 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
6281 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
6282 static bool permute_root(void)
6284 /* Prepare new root. */
6285 if (permute_prepare() < 0)
6288 /* Pivot into new root. */
6289 if (permute_and_enter() < 0)
6295 static int preserve_mnt_ns(int pid
)
6298 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
6301 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
6302 if (ret
< 0 || (size_t)ret
>= len
)
6305 return open(path
, O_RDONLY
| O_CLOEXEC
);
6308 static bool cgfs_prepare_mounts(void)
6310 if (!mkdir_p(BASEDIR
, 0700)) {
6311 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
6315 if (!umount_if_mounted()) {
6316 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
6320 if (unshare(CLONE_NEWNS
) < 0) {
6321 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
6325 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
6326 if (cgroup_mount_ns_fd
< 0) {
6327 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
6331 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
6332 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
6336 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
6337 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
6344 static bool cgfs_mount_hierarchies(void)
6350 for (i
= 0; i
< num_hierarchies
; i
++) {
6351 char *controller
= hierarchies
[i
];
6353 clen
= strlen(controller
);
6354 len
= strlen(BASEDIR
) + clen
+ 2;
6355 target
= malloc(len
);
6359 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
6360 if (ret
< 0 || ret
>= len
) {
6364 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
6368 if (!strcmp(controller
, "unified"))
6369 ret
= mount("none", target
, "cgroup2", 0, NULL
);
6371 ret
= mount(controller
, target
, "cgroup", 0, controller
);
6373 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
6378 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
6379 if (fd_hierarchies
[i
] < 0) {
6388 static bool cgfs_setup_controllers(void)
6390 if (!cgfs_prepare_mounts())
6393 if (!cgfs_mount_hierarchies()) {
6394 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
6398 if (!permute_root())
6404 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
6407 char *cret
, *line
= NULL
;
6408 char cwd
[MAXPATHLEN
];
6410 int i
, init_ns
= -1;
6411 bool found_unified
= false;
6413 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
6414 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
6418 while (getline(&line
, &len
, f
) != -1) {
6421 p
= strchr(line
, ':');
6427 p2
= strrchr(p
, ':');
6432 /* With cgroupv2 /proc/self/cgroup can contain entries of the
6433 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
6434 * because it parses out the empty string "" and later on passes
6435 * it to mount(). Let's skip such entries.
6437 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
6438 found_unified
= true;
6442 if (!store_hierarchy(line
, p
))
6446 /* Preserve initial namespace. */
6447 init_ns
= preserve_mnt_ns(getpid());
6449 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
6453 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
6454 if (!fd_hierarchies
) {
6455 lxcfs_error("%s\n", strerror(errno
));
6459 for (i
= 0; i
< num_hierarchies
; i
++)
6460 fd_hierarchies
[i
] = -1;
6462 cret
= getcwd(cwd
, MAXPATHLEN
);
6464 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
6466 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
6467 * to privately mount lxcfs cgroups. */
6468 if (!cgfs_setup_controllers()) {
6469 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
6473 if (setns(init_ns
, 0) < 0) {
6474 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
6478 if (!cret
|| chdir(cwd
) < 0)
6479 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
6481 if (!init_cpuview()) {
6482 lxcfs_error("%s\n", "failed to init CPU view");
6495 static void __attribute__((destructor
)) free_subsystems(void)
6499 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
6501 for (i
= 0; i
< num_hierarchies
; i
++) {
6503 free(hierarchies
[i
]);
6504 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
6505 close(fd_hierarchies
[i
]);
6508 free(fd_hierarchies
);
6511 if (cgroup_mount_ns_fd
>= 0)
6512 close(cgroup_mount_ns_fd
);