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 "config.h" // for VERSION
43 /* Define pivot_root() if missing from the C library */
44 #ifndef HAVE_PIVOT_ROOT
45 static int pivot_root(const char * new_root
, const char * put_old
)
47 #ifdef __NR_pivot_root
48 return syscall(__NR_pivot_root
, new_root
, put_old
);
55 extern int pivot_root(const char * new_root
, const char * put_old
);
58 struct cpuacct_usage
{
65 /* The function of hash table.*/
66 #define LOAD_SIZE 100 /*the size of hash_table */
67 #define FLUSH_TIME 5 /*the flush rate */
68 #define DEPTH_DIR 3 /*the depth of per cgroup */
69 /* The function of calculate loadavg .*/
70 #define FSHIFT 11 /* nr of bits of precision */
71 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
72 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
73 #define EXP_5 2014 /* 1/exp(5sec/5min) */
74 #define EXP_15 2037 /* 1/exp(5sec/15min) */
75 #define LOAD_INT(x) ((x) >> FSHIFT)
76 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
78 * This parameter is used for proc_loadavg_read().
79 * 1 means use loadavg, 0 means not use.
81 static int loadavg
= 0;
82 static volatile sig_atomic_t loadavg_stop
= 0;
83 static int calc_hash(const char *name
)
85 unsigned int hash
= 0;
87 /* ELFHash algorithm. */
89 hash
= (hash
<< 4) + *name
++;
90 x
= hash
& 0xf0000000;
95 return (hash
& 0x7fffffff);
100 unsigned long avenrun
[3]; /* Load averages */
101 unsigned int run_pid
;
102 unsigned int total_pid
;
103 unsigned int last_pid
;
104 int cfd
; /* The file descriptor of the mounted cgroup */
105 struct load_node
*next
;
106 struct load_node
**pre
;
111 * The lock is about insert load_node and refresh load_node.To the first
112 * load_node of each hash bucket, insert and refresh in this hash bucket is
113 * mutually exclusive.
115 pthread_mutex_t lock
;
117 * The rdlock is about read loadavg and delete load_node.To each hash
118 * bucket, read and delete is mutually exclusive. But at the same time, we
119 * allow paratactic read operation. This rdlock is at list level.
121 pthread_rwlock_t rdlock
;
123 * The rilock is about read loadavg and insert load_node.To the first
124 * load_node of each hash bucket, read and insert is mutually exclusive.
125 * But at the same time, we allow paratactic read operation.
127 pthread_rwlock_t rilock
;
128 struct load_node
*next
;
131 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
133 * init_load initialize the hash table.
134 * Return 0 on success, return -1 on failure.
136 static int init_load(void)
141 for (i
= 0; i
< LOAD_SIZE
; i
++) {
142 load_hash
[i
].next
= NULL
;
143 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
145 lxcfs_error("%s\n", "Failed to initialize lock");
148 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
150 lxcfs_error("%s\n", "Failed to initialize rdlock");
153 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
155 lxcfs_error("%s\n", "Failed to initialize rilock");
161 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
163 pthread_mutex_destroy(&load_hash
[i
].lock
);
167 pthread_mutex_destroy(&load_hash
[i
].lock
);
168 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
169 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
174 static void insert_node(struct load_node
**n
, int locate
)
178 pthread_mutex_lock(&load_hash
[locate
].lock
);
179 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
180 f
= load_hash
[locate
].next
;
181 load_hash
[locate
].next
= *n
;
183 (*n
)->pre
= &(load_hash
[locate
].next
);
185 f
->pre
= &((*n
)->next
);
187 pthread_mutex_unlock(&load_hash
[locate
].lock
);
188 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
191 * locate_node() finds special node. Not return NULL means success.
192 * It should be noted that rdlock isn't unlocked at the end of code
193 * because this function is used to read special node. Delete is not
194 * allowed before read has ended.
195 * unlock rdlock only in proc_loadavg_read().
197 static struct load_node
*locate_node(char *cg
, int locate
)
199 struct load_node
*f
= NULL
;
202 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
203 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
204 if (load_hash
[locate
].next
== NULL
) {
205 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
208 f
= load_hash
[locate
].next
;
209 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
210 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
214 /* Delete the load_node n and return the next node of it. */
215 static struct load_node
*del_node(struct load_node
*n
, int locate
)
219 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
220 if (n
->next
== NULL
) {
224 n
->next
->pre
= n
->pre
;
229 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
233 static void load_free(void)
236 struct load_node
*f
, *p
;
238 for (i
= 0; i
< LOAD_SIZE
; i
++) {
239 pthread_mutex_lock(&load_hash
[i
].lock
);
240 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
241 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
242 if (load_hash
[i
].next
== NULL
) {
243 pthread_mutex_unlock(&load_hash
[i
].lock
);
244 pthread_mutex_destroy(&load_hash
[i
].lock
);
245 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
246 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
247 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
248 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
251 for (f
= load_hash
[i
].next
; f
; ) {
257 pthread_mutex_unlock(&load_hash
[i
].lock
);
258 pthread_mutex_destroy(&load_hash
[i
].lock
);
259 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
260 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
261 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
262 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
266 /* Data for CPU view */
267 struct cg_proc_stat
{
269 struct cpuacct_usage
*usage
; // Real usage as read from the host's /proc/stat
270 struct cpuacct_usage
*view
; // Usage stats reported to the container
272 pthread_mutex_t lock
; // For node manipulation
273 struct cg_proc_stat
*next
;
276 struct cg_proc_stat_head
{
277 struct cg_proc_stat
*next
;
281 * For access to the list. Reading can be parallel, pruning is exclusive.
283 pthread_rwlock_t lock
;
286 #define CPUVIEW_HASH_SIZE 100
287 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
289 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
291 *head
= malloc(sizeof(struct cg_proc_stat_head
));
293 lxcfs_error("%s\n", strerror(errno
));
297 (*head
)->lastcheck
= time(NULL
);
298 (*head
)->next
= NULL
;
300 if (pthread_rwlock_init(&(*head
)->lock
, NULL
) != 0) {
301 lxcfs_error("%s\n", "Failed to initialize list lock");
309 static bool init_cpuview()
313 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
314 proc_stat_history
[i
] = NULL
;
316 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
317 if (!cpuview_init_head(&proc_stat_history
[i
]))
324 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
325 if (proc_stat_history
[i
]) {
326 free(proc_stat_history
[i
]);
327 proc_stat_history
[i
] = NULL
;
334 static void free_proc_stat_node(struct cg_proc_stat
*node
)
336 pthread_mutex_destroy(&node
->lock
);
343 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
345 struct cg_proc_stat
*node
, *tmp
;
353 free_proc_stat_node(tmp
);
360 pthread_rwlock_destroy(&head
->lock
);
364 static void free_cpuview()
368 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
369 if (proc_stat_history
[i
])
370 cpuview_free_head(proc_stat_history
[i
]);
375 * A table caching which pid is init for a pid namespace.
376 * When looking up which pid is init for $qpid, we first
377 * 1. Stat /proc/$qpid/ns/pid.
378 * 2. Check whether the ino_t is in our store.
379 * a. if not, fork a child in qpid's ns to send us
380 * ucred.pid = 1, and read the initpid. Cache
381 * initpid and creation time for /proc/initpid
382 * in a new store entry.
383 * b. if so, verify that /proc/initpid still matches
384 * what we have saved. If not, clear the store
385 * entry and go back to a. If so, return the
388 struct pidns_init_store
{
389 ino_t ino
; // inode number for /proc/$pid/ns/pid
390 pid_t initpid
; // the pid of nit in that ns
391 long int ctime
; // the time at which /proc/$initpid was created
392 struct pidns_init_store
*next
;
396 /* lol - look at how they are allocated in the kernel */
397 #define PIDNS_HASH_SIZE 4096
398 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
400 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
401 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
402 static void lock_mutex(pthread_mutex_t
*l
)
406 if ((ret
= pthread_mutex_lock(l
)) != 0) {
407 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
412 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
413 * Number of hierarchies mounted. */
414 static int num_hierarchies
;
416 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
417 * Hierachies mounted {cpuset, blkio, ...}:
418 * Initialized via __constructor__ collect_and_mount_subsystems(). */
419 static char **hierarchies
;
421 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
422 * Open file descriptors:
423 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
424 * private mount namespace.
425 * Initialized via __constructor__ collect_and_mount_subsystems().
426 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
427 * mounts and respective files in the private namespace even when located in
428 * another namespace using the *at() family of functions
429 * {openat(), fchownat(), ...}. */
430 static int *fd_hierarchies
;
431 static int cgroup_mount_ns_fd
= -1;
433 static void unlock_mutex(pthread_mutex_t
*l
)
437 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
438 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
443 static void store_lock(void)
445 lock_mutex(&pidns_store_mutex
);
448 static void store_unlock(void)
450 unlock_mutex(&pidns_store_mutex
);
453 /* Must be called under store_lock */
454 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
459 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
460 if (stat(fnam
, &initsb
) < 0)
463 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
464 initsb
.st_ctime
, e
->initpid
);
466 if (e
->ctime
!= initsb
.st_ctime
)
471 /* Must be called under store_lock */
472 static void remove_initpid(struct pidns_init_store
*e
)
474 struct pidns_init_store
*tmp
;
477 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
480 if (pidns_hash_table
[h
] == e
) {
481 pidns_hash_table
[h
] = e
->next
;
486 tmp
= pidns_hash_table
[h
];
488 if (tmp
->next
== e
) {
498 /* Must be called under store_lock */
499 static void prune_initpid_store(void)
501 static long int last_prune
= 0;
502 struct pidns_init_store
*e
, *prev
, *delme
;
503 long int now
, threshold
;
507 last_prune
= time(NULL
);
511 if (now
< last_prune
+ PURGE_SECS
)
514 lxcfs_debug("%s\n", "Pruning.");
517 threshold
= now
- 2 * PURGE_SECS
;
519 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
520 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
521 if (e
->lastcheck
< threshold
) {
523 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
527 prev
->next
= e
->next
;
529 pidns_hash_table
[i
] = e
->next
;
540 /* Must be called under store_lock */
541 static void save_initpid(struct stat
*sb
, pid_t pid
)
543 struct pidns_init_store
*e
;
548 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
550 snprintf(fpath
, 100, "/proc/%d", pid
);
551 if (stat(fpath
, &procsb
) < 0)
554 e
= malloc(sizeof(*e
));
558 e
->ctime
= procsb
.st_ctime
;
560 e
->next
= pidns_hash_table
[h
];
561 e
->lastcheck
= time(NULL
);
562 pidns_hash_table
[h
] = e
;
566 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
567 * entry for the inode number and creation time. Verify that the init pid
568 * is still valid. If not, remove it. Return the entry if valid, NULL
570 * Must be called under store_lock
572 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
574 int h
= HASH(sb
->st_ino
);
575 struct pidns_init_store
*e
= pidns_hash_table
[h
];
578 if (e
->ino
== sb
->st_ino
) {
579 if (initpid_still_valid(e
, sb
)) {
580 e
->lastcheck
= time(NULL
);
592 static int is_dir(const char *path
, int fd
)
595 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
596 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
601 static char *must_copy_string(const char *str
)
613 static inline void drop_trailing_newlines(char *s
)
617 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
621 #define BATCH_SIZE 50
622 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
624 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
625 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
627 if (!*mem
|| newbatches
> oldbatches
) {
630 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
635 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
637 size_t newlen
= *len
+ linelen
;
638 dorealloc(contents
, *len
, newlen
+ 1);
639 memcpy(*contents
+ *len
, line
, linelen
+1);
643 static char *slurp_file(const char *from
, int fd
)
646 char *contents
= NULL
;
647 FILE *f
= fdopen(fd
, "r");
648 size_t len
= 0, fulllen
= 0;
654 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
655 append_line(&contents
, &fulllen
, line
, linelen
);
660 drop_trailing_newlines(contents
);
665 static bool write_string(const char *fnam
, const char *string
, int fd
)
674 len
= strlen(string
);
675 ret
= fwrite(string
, 1, len
, f
);
677 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
678 strerror(errno
), string
, fnam
);
684 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
698 static bool store_hierarchy(char *stridx
, char *h
)
700 if (num_hierarchies
% ALLOC_NUM
== 0) {
701 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
703 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
705 lxcfs_error("%s\n", strerror(errno
));
711 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
715 static void print_subsystems(void)
719 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
720 fprintf(stderr
, "hierarchies:\n");
721 for (i
= 0; i
< num_hierarchies
; i
++) {
723 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
724 fd_hierarchies
[i
], hierarchies
[i
]);
728 static bool in_comma_list(const char *needle
, const char *haystack
)
730 const char *s
= haystack
, *e
;
731 size_t nlen
= strlen(needle
);
733 while (*s
&& (e
= strchr(s
, ','))) {
738 if (strncmp(needle
, s
, nlen
) == 0)
742 if (strcmp(needle
, s
) == 0)
747 /* do we need to do any massaging here? I'm not sure... */
748 /* Return the mounted controller and store the corresponding open file descriptor
749 * referring to the controller mountpoint in the private lxcfs namespace in
752 static char *find_mounted_controller(const char *controller
, int *cfd
)
756 for (i
= 0; i
< num_hierarchies
; i
++) {
759 if (strcmp(hierarchies
[i
], controller
) == 0) {
760 *cfd
= fd_hierarchies
[i
];
761 return hierarchies
[i
];
763 if (in_comma_list(controller
, hierarchies
[i
])) {
764 *cfd
= fd_hierarchies
[i
];
765 return hierarchies
[i
];
772 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
779 tmpc
= find_mounted_controller(controller
, &cfd
);
783 /* Make sure we pass a relative path to *at() family of functions.
784 * . + /cgroup + / + file + \0
786 len
= strlen(cgroup
) + strlen(file
) + 3;
788 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
789 if (ret
< 0 || (size_t)ret
>= len
)
792 fd
= openat(cfd
, fnam
, O_WRONLY
);
796 return write_string(fnam
, value
, fd
);
799 // Chown all the files in the cgroup directory. We do this when we create
800 // a cgroup on behalf of a user.
801 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
803 struct dirent
*direntp
;
804 char path
[MAXPATHLEN
];
809 len
= strlen(dirname
);
810 if (len
>= MAXPATHLEN
) {
811 lxcfs_error("Pathname too long: %s\n", dirname
);
815 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
821 lxcfs_error("Failed to open %s\n", dirname
);
825 while ((direntp
= readdir(d
))) {
826 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
828 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
829 if (ret
< 0 || ret
>= MAXPATHLEN
) {
830 lxcfs_error("Pathname too long under %s\n", dirname
);
833 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
834 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
839 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
845 tmpc
= find_mounted_controller(controller
, &cfd
);
849 /* Make sure we pass a relative path to *at() family of functions.
852 len
= strlen(cg
) + 2;
853 dirnam
= alloca(len
);
854 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
856 if (mkdirat(cfd
, dirnam
, 0755) < 0)
859 if (uid
== 0 && gid
== 0)
862 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
865 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
870 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
872 struct dirent
*direntp
;
875 char pathname
[MAXPATHLEN
];
878 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
882 dir
= fdopendir(dupfd
);
884 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
889 while ((direntp
= readdir(dir
))) {
893 if (!strcmp(direntp
->d_name
, ".") ||
894 !strcmp(direntp
->d_name
, ".."))
897 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
898 if (rc
< 0 || rc
>= MAXPATHLEN
) {
899 lxcfs_error("%s\n", "Pathname too long.");
903 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
905 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
908 if (S_ISDIR(mystat
.st_mode
))
909 if (!recursive_rmdir(pathname
, fd
, cfd
))
910 lxcfs_debug("Error removing %s.\n", pathname
);
914 if (closedir(dir
) < 0) {
915 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
919 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
920 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
929 bool cgfs_remove(const char *controller
, const char *cg
)
936 tmpc
= find_mounted_controller(controller
, &cfd
);
940 /* Make sure we pass a relative path to *at() family of functions.
943 len
= strlen(cg
) + 2;
944 dirnam
= alloca(len
);
945 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
947 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
951 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
956 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
960 char *pathname
, *tmpc
;
962 tmpc
= find_mounted_controller(controller
, &cfd
);
966 /* Make sure we pass a relative path to *at() family of functions.
969 len
= strlen(file
) + 2;
970 pathname
= alloca(len
);
971 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
972 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
977 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
982 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
984 snprintf(fname
, len
, "%s/tasks", dirname
);
985 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
987 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
988 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
993 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
997 char *pathname
, *tmpc
;
999 tmpc
= find_mounted_controller(controller
, &cfd
);
1003 /* Make sure we pass a relative path to *at() family of functions.
1006 len
= strlen(file
) + 2;
1007 pathname
= alloca(len
);
1008 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1009 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
1012 if (is_dir(pathname
, cfd
))
1013 // like cgmanager did, we want to chown the tasks file as well
1014 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
1019 FILE *open_pids_file(const char *controller
, const char *cgroup
)
1023 char *pathname
, *tmpc
;
1025 tmpc
= find_mounted_controller(controller
, &cfd
);
1029 /* Make sure we pass a relative path to *at() family of functions.
1030 * . + /cgroup + / "cgroup.procs" + \0
1032 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
1033 pathname
= alloca(len
);
1034 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
1036 fd
= openat(cfd
, pathname
, O_WRONLY
);
1040 return fdopen(fd
, "w");
1043 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
1044 void ***list
, size_t typesize
,
1045 void* (*iterator
)(const char*, const char*, const char*))
1050 char pathname
[MAXPATHLEN
];
1051 size_t sz
= 0, asz
= 0;
1052 struct dirent
*dirent
;
1055 tmpc
= find_mounted_controller(controller
, &cfd
);
1060 /* Make sure we pass a relative path to *at() family of functions. */
1061 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
1063 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
1064 if (ret
< 0 || (size_t)ret
>= len
) {
1065 lxcfs_error("Pathname too long under %s\n", cgroup
);
1069 fd
= openat(cfd
, cg
, O_DIRECTORY
);
1073 dir
= fdopendir(fd
);
1077 while ((dirent
= readdir(dir
))) {
1080 if (!strcmp(dirent
->d_name
, ".") ||
1081 !strcmp(dirent
->d_name
, ".."))
1084 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1085 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1086 lxcfs_error("Pathname too long under %s\n", cg
);
1090 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1092 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1095 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1096 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1103 tmp
= realloc(*list
, asz
* typesize
);
1107 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1108 (*list
)[sz
+1] = NULL
;
1111 if (closedir(dir
) < 0) {
1112 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1118 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1122 dup
= strdup(dir_entry
);
1127 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1129 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1132 void free_key(struct cgfs_files
*k
)
1140 void free_keys(struct cgfs_files
**keys
)
1146 for (i
= 0; keys
[i
]; i
++) {
1152 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1158 tmpc
= find_mounted_controller(controller
, &cfd
);
1162 /* Make sure we pass a relative path to *at() family of functions.
1163 * . + /cgroup + / + file + \0
1165 len
= strlen(cgroup
) + strlen(file
) + 3;
1167 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1168 if (ret
< 0 || (size_t)ret
>= len
)
1171 fd
= openat(cfd
, fnam
, O_RDONLY
);
1175 *value
= slurp_file(fnam
, fd
);
1176 return *value
!= NULL
;
1179 bool cgfs_param_exist(const char *controller
, const char *cgroup
, const char *file
)
1185 tmpc
= find_mounted_controller(controller
, &cfd
);
1189 /* Make sure we pass a relative path to *at() family of functions.
1190 * . + /cgroup + / + file + \0
1192 len
= strlen(cgroup
) + strlen(file
) + 3;
1194 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1195 if (ret
< 0 || (size_t)ret
>= len
)
1198 return (faccessat(cfd
, fnam
, F_OK
, 0) == 0);
1201 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1207 struct cgfs_files
*newkey
;
1209 tmpc
= find_mounted_controller(controller
, &cfd
);
1213 if (file
&& *file
== '/')
1216 if (file
&& strchr(file
, '/'))
1219 /* Make sure we pass a relative path to *at() family of functions.
1220 * . + /cgroup + / + file + \0
1222 len
= strlen(cgroup
) + 3;
1224 len
+= strlen(file
) + 1;
1226 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1227 file
? "/" : "", file
? file
: "");
1229 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1234 newkey
= malloc(sizeof(struct cgfs_files
));
1237 newkey
->name
= must_copy_string(file
);
1238 else if (strrchr(cgroup
, '/'))
1239 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1241 newkey
->name
= must_copy_string(cgroup
);
1242 newkey
->uid
= sb
.st_uid
;
1243 newkey
->gid
= sb
.st_gid
;
1244 newkey
->mode
= sb
.st_mode
;
1249 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1251 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1253 lxcfs_error("Error getting files under %s:%s\n", controller
,
1259 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1261 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1264 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1272 tmpc
= find_mounted_controller(controller
, &cfd
);
1276 /* Make sure we pass a relative path to *at() family of functions.
1277 * . + /cgroup + / + f + \0
1279 len
= strlen(cgroup
) + strlen(f
) + 3;
1281 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1282 if (ret
< 0 || (size_t)ret
>= len
)
1285 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1286 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1292 #define SEND_CREDS_OK 0
1293 #define SEND_CREDS_NOTSK 1
1294 #define SEND_CREDS_FAIL 2
1295 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1296 static int wait_for_pid(pid_t pid
);
1297 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1298 static int send_creds_clone_wrapper(void *arg
);
1301 * clone a task which switches to @task's namespace and writes '1'.
1302 * over a unix sock so we can read the task's reaper's pid in our
1305 * Note: glibc's fork() does not respect pidns, which can lead to failed
1306 * assertions inside glibc (and thus failed forks) if the child's pid in
1307 * the pidns and the parent pid outside are identical. Using clone prevents
1310 static void write_task_init_pid_exit(int sock
, pid_t target
)
1315 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1316 void *stack
= alloca(stack_size
);
1318 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1319 if (ret
< 0 || ret
>= sizeof(fnam
))
1322 fd
= open(fnam
, O_RDONLY
);
1324 perror("write_task_init_pid_exit open of ns/pid");
1328 perror("write_task_init_pid_exit setns 1");
1332 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1336 if (!wait_for_pid(pid
))
1342 static int send_creds_clone_wrapper(void *arg
) {
1345 int sock
= *(int *)arg
;
1347 /* we are the child */
1352 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1357 static pid_t
get_init_pid_for_task(pid_t task
)
1365 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1366 perror("socketpair");
1375 write_task_init_pid_exit(sock
[0], task
);
1379 if (!recv_creds(sock
[1], &cred
, &v
))
1391 pid_t
lookup_initpid_in_store(pid_t qpid
)
1395 struct pidns_init_store
*e
;
1398 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1400 if (stat(fnam
, &sb
) < 0)
1402 e
= lookup_verify_initpid(&sb
);
1404 answer
= e
->initpid
;
1407 answer
= get_init_pid_for_task(qpid
);
1409 save_initpid(&sb
, answer
);
1412 /* we prune at end in case we are returning
1413 * the value we were about to return */
1414 prune_initpid_store();
1419 static int wait_for_pid(pid_t pid
)
1427 ret
= waitpid(pid
, &status
, 0);
1435 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1441 * append the given formatted string to *src.
1442 * src: a pointer to a char* in which to append the formatted string.
1443 * sz: the number of characters printed so far, minus trailing \0.
1444 * asz: the allocated size so far
1445 * format: string format. See printf for details.
1446 * ...: varargs. See printf for details.
1448 static void must_strcat(char **src
, size_t *sz
, size_t *asz
, const char *format
, ...)
1450 char tmp
[BUF_RESERVE_SIZE
];
1453 va_start (args
, format
);
1454 int tmplen
= vsnprintf(tmp
, BUF_RESERVE_SIZE
, format
, args
);
1457 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1460 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1463 *asz
+= BUF_RESERVE_SIZE
;
1465 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1470 * append pid to *src.
1471 * src: a pointer to a char* in which ot append the pid.
1472 * sz: the number of characters printed so far, minus trailing \0.
1473 * asz: the allocated size so far
1474 * pid: the pid to append
1476 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1478 must_strcat(src
, sz
, asz
, "%d\n", (int)pid
);
1482 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1483 * valid in the caller's namespace, return the id mapped into
1485 * Returns the mapped id, or -1 on error.
1488 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1490 unsigned int nsuid
, // base id for a range in the idfile's namespace
1491 hostuid
, // base id for a range in the caller's namespace
1492 count
; // number of ids in this range
1496 fseek(idfile
, 0L, SEEK_SET
);
1497 while (fgets(line
, 400, idfile
)) {
1498 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1501 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1503 * uids wrapped around - unexpected as this is a procfile,
1506 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1507 nsuid
, hostuid
, count
, line
);
1510 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1512 * now since hostuid <= in_id < hostuid+count, and
1513 * hostuid+count and nsuid+count do not wrap around,
1514 * we know that nsuid+(in_id-hostuid) which must be
1515 * less that nsuid+(count) must not wrap around
1517 return (in_id
- hostuid
) + nsuid
;
1526 * for is_privileged_over,
1527 * specify whether we require the calling uid to be root in his
1530 #define NS_ROOT_REQD true
1531 #define NS_ROOT_OPT false
1535 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1537 char fpath
[PROCLEN
];
1539 bool answer
= false;
1542 if (victim
== -1 || uid
== -1)
1546 * If the request is one not requiring root in the namespace,
1547 * then having the same uid suffices. (i.e. uid 1000 has write
1548 * access to files owned by uid 1000
1550 if (!req_ns_root
&& uid
== victim
)
1553 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1554 if (ret
< 0 || ret
>= PROCLEN
)
1556 FILE *f
= fopen(fpath
, "r");
1560 /* if caller's not root in his namespace, reject */
1561 nsuid
= convert_id_to_ns(f
, uid
);
1566 * If victim is not mapped into caller's ns, reject.
1567 * XXX I'm not sure this check is needed given that fuse
1568 * will be sending requests where the vfs has converted
1570 nsuid
= convert_id_to_ns(f
, victim
);
1581 static bool perms_include(int fmode
, mode_t req_mode
)
1585 switch (req_mode
& O_ACCMODE
) {
1593 r
= S_IROTH
| S_IWOTH
;
1598 return ((fmode
& r
) == r
);
1604 * querycg is /a/b/c/d/e
1607 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1611 if (strlen(taskcg
) <= strlen(querycg
)) {
1612 lxcfs_error("%s\n", "I was fed bad input.");
1616 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1617 start
= strdup(taskcg
+ 1);
1619 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1622 end
= strchr(start
, '/');
1628 static void stripnewline(char *x
)
1630 size_t l
= strlen(x
);
1631 if (l
&& x
[l
-1] == '\n')
1635 char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1640 char *answer
= NULL
;
1644 const char *h
= find_mounted_controller(contrl
, &cfd
);
1648 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1649 if (ret
< 0 || ret
>= PROCLEN
)
1651 if (!(f
= fopen(fnam
, "r")))
1654 while (getline(&line
, &len
, f
) != -1) {
1658 c1
= strchr(line
, ':');
1662 c2
= strchr(c1
, ':');
1666 if (strcmp(c1
, h
) != 0)
1671 answer
= strdup(c2
);
1683 * check whether a fuse context may access a cgroup dir or file
1685 * If file is not null, it is a cgroup file to check under cg.
1686 * If file is null, then we are checking perms on cg itself.
1688 * For files we can check the mode of the list_keys result.
1689 * For cgroups, we must make assumptions based on the files under the
1690 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1693 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1695 struct cgfs_files
*k
= NULL
;
1698 k
= cgfs_get_key(contrl
, cg
, file
);
1702 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1703 if (perms_include(k
->mode
>> 6, mode
)) {
1708 if (fc
->gid
== k
->gid
) {
1709 if (perms_include(k
->mode
>> 3, mode
)) {
1714 ret
= perms_include(k
->mode
, mode
);
1721 #define INITSCOPE "/init.scope"
1722 void prune_init_slice(char *cg
)
1725 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1727 if (cg_len
< initscope_len
)
1730 point
= cg
+ cg_len
- initscope_len
;
1731 if (strcmp(point
, INITSCOPE
) == 0) {
1740 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1741 * If pid is in /a, he may act on /a/b, but not on /b.
1742 * if the answer is false and nextcg is not NULL, then *nextcg will point
1743 * to a string containing the next cgroup directory under cg, which must be
1744 * freed by the caller.
1746 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1748 bool answer
= false;
1749 char *c2
= get_pid_cgroup(pid
, contrl
);
1754 prune_init_slice(c2
);
1757 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1758 * they pass in a cgroup without leading '/'
1760 * The original line here was:
1761 * linecmp = *cg == '/' ? c2 : c2+1;
1762 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1763 * Serge, do you know?
1765 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1769 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1771 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1783 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1785 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1787 bool answer
= false;
1789 size_t target_len
, task_len
;
1791 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1794 c2
= get_pid_cgroup(pid
, contrl
);
1797 prune_init_slice(c2
);
1800 target_len
= strlen(cg
);
1801 task_len
= strlen(task_cg
);
1802 if (task_len
== 0) {
1803 /* Task is in the root cg, it can see everything. This case is
1804 * not handled by the strmcps below, since they test for the
1805 * last /, but that is the first / that we've chopped off
1811 if (strcmp(cg
, task_cg
) == 0) {
1815 if (target_len
< task_len
) {
1816 /* looking up a parent dir */
1817 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1821 if (target_len
> task_len
) {
1822 /* looking up a child dir */
1823 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1834 * given /cgroup/freezer/a/b, return "freezer".
1835 * the returned char* should NOT be freed.
1837 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1840 char *contr
, *slash
;
1842 if (strlen(path
) < 9) {
1846 if (*(path
+ 7) != '/') {
1851 contr
= strdupa(p1
);
1856 slash
= strstr(contr
, "/");
1861 for (i
= 0; i
< num_hierarchies
; i
++) {
1862 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1863 return hierarchies
[i
];
1870 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1871 * Note that the returned value may include files (keynames) etc
1873 static const char *find_cgroup_in_path(const char *path
)
1877 if (strlen(path
) < 9) {
1881 p1
= strstr(path
+ 8, "/");
1891 * split the last path element from the path in @cg.
1892 * @dir is newly allocated and should be freed, @last not
1894 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1901 *last
= strrchr(cg
, '/');
1906 p
= strrchr(*dir
, '/');
1911 * FUSE ops for /cgroup
1914 int cg_getattr(const char *path
, struct stat
*sb
)
1916 struct timespec now
;
1917 struct fuse_context
*fc
= fuse_get_context();
1918 char * cgdir
= NULL
;
1919 char *last
= NULL
, *path1
, *path2
;
1920 struct cgfs_files
*k
= NULL
;
1922 const char *controller
= NULL
;
1929 memset(sb
, 0, sizeof(struct stat
));
1931 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1934 sb
->st_uid
= sb
->st_gid
= 0;
1935 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1938 if (strcmp(path
, "/cgroup") == 0) {
1939 sb
->st_mode
= S_IFDIR
| 00755;
1944 controller
= pick_controller_from_path(fc
, path
);
1947 cgroup
= find_cgroup_in_path(path
);
1949 /* this is just /cgroup/controller, return it as a dir */
1950 sb
->st_mode
= S_IFDIR
| 00755;
1955 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1965 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1968 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1969 * Then check that caller's cgroup is under path if last is a child
1970 * cgroup, or cgdir if last is a file */
1972 if (is_child_cgroup(controller
, path1
, path2
)) {
1973 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1977 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1978 /* this is just /cgroup/controller, return it as a dir */
1979 sb
->st_mode
= S_IFDIR
| 00555;
1984 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1989 // get uid, gid, from '/tasks' file and make up a mode
1990 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1991 sb
->st_mode
= S_IFDIR
| 00755;
1992 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1994 sb
->st_uid
= sb
->st_gid
= 0;
1996 sb
->st_uid
= k
->uid
;
1997 sb
->st_gid
= k
->gid
;
2005 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
2006 sb
->st_mode
= S_IFREG
| k
->mode
;
2008 sb
->st_uid
= k
->uid
;
2009 sb
->st_gid
= k
->gid
;
2012 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2024 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
2026 struct fuse_context
*fc
= fuse_get_context();
2028 struct file_info
*dir_info
;
2029 char *controller
= NULL
;
2034 if (strcmp(path
, "/cgroup") == 0) {
2038 // return list of keys for the controller, and list of child cgroups
2039 controller
= pick_controller_from_path(fc
, path
);
2043 cgroup
= find_cgroup_in_path(path
);
2045 /* this is just /cgroup/controller, return its contents */
2050 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2054 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
2056 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
2060 /* we'll free this at cg_releasedir */
2061 dir_info
= malloc(sizeof(*dir_info
));
2064 dir_info
->controller
= must_copy_string(controller
);
2065 dir_info
->cgroup
= must_copy_string(cgroup
);
2066 dir_info
->type
= LXC_TYPE_CGDIR
;
2067 dir_info
->buf
= NULL
;
2068 dir_info
->file
= NULL
;
2069 dir_info
->buflen
= 0;
2071 fi
->fh
= (unsigned long)dir_info
;
2075 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2076 struct fuse_file_info
*fi
)
2078 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2079 struct cgfs_files
**list
= NULL
;
2081 char *nextcg
= NULL
;
2082 struct fuse_context
*fc
= fuse_get_context();
2083 char **clist
= NULL
;
2085 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
2088 if (d
->type
!= LXC_TYPE_CGDIR
) {
2089 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
2092 if (!d
->cgroup
&& !d
->controller
) {
2093 // ls /var/lib/lxcfs/cgroup - just show list of controllers
2096 for (i
= 0; i
< num_hierarchies
; i
++) {
2097 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
2104 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
2105 // not a valid cgroup
2110 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2113 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
2115 ret
= filler(buf
, nextcg
, NULL
, 0);
2126 for (i
= 0; list
&& list
[i
]; i
++) {
2127 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2133 // now get the list of child cgroups
2135 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2140 for (i
= 0; clist
[i
]; i
++) {
2141 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2152 for (i
= 0; clist
[i
]; i
++)
2159 void do_release_file_info(struct fuse_file_info
*fi
)
2161 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2168 free(f
->controller
);
2169 f
->controller
= NULL
;
2180 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2182 do_release_file_info(fi
);
2186 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2189 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2190 struct cgfs_files
*k
= NULL
;
2191 struct file_info
*file_info
;
2192 struct fuse_context
*fc
= fuse_get_context();
2198 controller
= pick_controller_from_path(fc
, path
);
2201 cgroup
= find_cgroup_in_path(path
);
2205 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2214 k
= cgfs_get_key(controller
, path1
, path2
);
2221 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2224 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2228 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2233 /* we'll free this at cg_release */
2234 file_info
= malloc(sizeof(*file_info
));
2239 file_info
->controller
= must_copy_string(controller
);
2240 file_info
->cgroup
= must_copy_string(path1
);
2241 file_info
->file
= must_copy_string(path2
);
2242 file_info
->type
= LXC_TYPE_CGFILE
;
2243 file_info
->buf
= NULL
;
2244 file_info
->buflen
= 0;
2246 fi
->fh
= (unsigned long)file_info
;
2254 int cg_access(const char *path
, int mode
)
2258 char *path1
, *path2
, *controller
;
2259 char *last
= NULL
, *cgdir
= NULL
;
2260 struct cgfs_files
*k
= NULL
;
2261 struct fuse_context
*fc
= fuse_get_context();
2263 if (strcmp(path
, "/cgroup") == 0)
2269 controller
= pick_controller_from_path(fc
, path
);
2272 cgroup
= find_cgroup_in_path(path
);
2274 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2275 if ((mode
& W_OK
) == 0)
2280 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2289 k
= cgfs_get_key(controller
, path1
, path2
);
2291 if ((mode
& W_OK
) == 0)
2299 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2302 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2306 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2318 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2320 do_release_file_info(fi
);
2324 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2326 static bool wait_for_sock(int sock
, int timeout
)
2328 struct epoll_event ev
;
2329 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2331 if ((starttime
= time(NULL
)) < 0)
2334 if ((epfd
= epoll_create(1)) < 0) {
2335 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2339 ev
.events
= POLLIN_SET
;
2341 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2342 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2348 if ((now
= time(NULL
)) < 0) {
2353 deltatime
= (starttime
+ timeout
) - now
;
2354 if (deltatime
< 0) { // timeout
2359 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2360 if (ret
< 0 && errno
== EINTR
)
2362 saved_errno
= errno
;
2366 errno
= saved_errno
;
2372 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2374 if (!wait_for_sock(sockfd
, 2))
2376 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2379 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2381 struct msghdr msg
= { 0 };
2383 struct cmsghdr
*cmsg
;
2384 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2389 if (msgrecv(sock
, buf
, 1) != 1) {
2390 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2391 return SEND_CREDS_FAIL
;
2395 msg
.msg_control
= cmsgbuf
;
2396 msg
.msg_controllen
= sizeof(cmsgbuf
);
2398 cmsg
= CMSG_FIRSTHDR(&msg
);
2399 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2400 cmsg
->cmsg_level
= SOL_SOCKET
;
2401 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2402 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2404 msg
.msg_name
= NULL
;
2405 msg
.msg_namelen
= 0;
2409 iov
.iov_len
= sizeof(buf
);
2413 if (sendmsg(sock
, &msg
, 0) < 0) {
2414 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2416 return SEND_CREDS_NOTSK
;
2417 return SEND_CREDS_FAIL
;
2420 return SEND_CREDS_OK
;
2423 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2425 struct msghdr msg
= { 0 };
2427 struct cmsghdr
*cmsg
;
2428 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2439 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2440 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2444 if (write(sock
, buf
, 1) != 1) {
2445 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2449 msg
.msg_name
= NULL
;
2450 msg
.msg_namelen
= 0;
2451 msg
.msg_control
= cmsgbuf
;
2452 msg
.msg_controllen
= sizeof(cmsgbuf
);
2455 iov
.iov_len
= sizeof(buf
);
2459 if (!wait_for_sock(sock
, 2)) {
2460 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2463 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2465 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2469 cmsg
= CMSG_FIRSTHDR(&msg
);
2471 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2472 cmsg
->cmsg_level
== SOL_SOCKET
&&
2473 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2474 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2481 struct pid_ns_clone_args
{
2485 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2489 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2490 * with clone(). This simply writes '1' as ACK back to the parent
2491 * before calling the actual wrapped function.
2493 static int pid_ns_clone_wrapper(void *arg
) {
2494 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2497 close(args
->cpipe
[0]);
2498 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2499 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2500 close(args
->cpipe
[1]);
2501 return args
->wrapped(args
->sock
, args
->tpid
);
2505 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2506 * int value back over the socket. This shifts the pid from the
2507 * sender's pidns into tpid's pidns.
2509 static int pid_to_ns(int sock
, pid_t tpid
)
2514 while (recv_creds(sock
, &cred
, &v
)) {
2517 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2525 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2526 * in your old pidns. Only children which you clone will be in the target
2527 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2528 * actually convert pids.
2530 * Note: glibc's fork() does not respect pidns, which can lead to failed
2531 * assertions inside glibc (and thus failed forks) if the child's pid in
2532 * the pidns and the parent pid outside are identical. Using clone prevents
2535 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2537 int newnsfd
= -1, ret
, cpipe
[2];
2542 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2543 if (ret
< 0 || ret
>= sizeof(fnam
))
2545 newnsfd
= open(fnam
, O_RDONLY
);
2548 if (setns(newnsfd
, 0) < 0)
2552 if (pipe(cpipe
) < 0)
2555 struct pid_ns_clone_args args
= {
2559 .wrapped
= &pid_to_ns
2561 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2562 void *stack
= alloca(stack_size
);
2564 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2568 // give the child 1 second to be done forking and
2570 if (!wait_for_sock(cpipe
[0], 1))
2572 ret
= read(cpipe
[0], &v
, 1);
2573 if (ret
!= sizeof(char) || v
!= '1')
2576 if (!wait_for_pid(cpid
))
2582 * To read cgroup files with a particular pid, we will setns into the child
2583 * pidns, open a pipe, fork a child - which will be the first to really be in
2584 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2586 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2588 int sock
[2] = {-1, -1};
2589 char *tmpdata
= NULL
;
2591 pid_t qpid
, cpid
= -1;
2592 bool answer
= false;
2595 size_t sz
= 0, asz
= 0;
2597 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2601 * Now we read the pids from returned data one by one, pass
2602 * them into a child in the target namespace, read back the
2603 * translated pids, and put them into our to-return data
2606 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2607 perror("socketpair");
2616 if (!cpid
) // child - exits when done
2617 pid_to_ns_wrapper(sock
[1], tpid
);
2619 char *ptr
= tmpdata
;
2622 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2624 ret
= send_creds(sock
[0], &cred
, v
, true);
2626 if (ret
== SEND_CREDS_NOTSK
)
2628 if (ret
== SEND_CREDS_FAIL
)
2631 // read converted results
2632 if (!wait_for_sock(sock
[0], 2)) {
2633 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2636 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2637 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2640 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2642 ptr
= strchr(ptr
, '\n');
2648 cred
.pid
= getpid();
2650 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2651 // failed to ask child to exit
2652 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2662 if (sock
[0] != -1) {
2669 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2670 struct fuse_file_info
*fi
)
2672 struct fuse_context
*fc
= fuse_get_context();
2673 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2674 struct cgfs_files
*k
= NULL
;
2679 if (f
->type
!= LXC_TYPE_CGFILE
) {
2680 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2693 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2699 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2704 if (strcmp(f
->file
, "tasks") == 0 ||
2705 strcmp(f
->file
, "/tasks") == 0 ||
2706 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2707 strcmp(f
->file
, "cgroup.procs") == 0)
2708 // special case - we have to translate the pids
2709 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2711 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2725 memcpy(buf
, data
, s
);
2726 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2736 static int pid_from_ns(int sock
, pid_t tpid
)
2746 if (!wait_for_sock(sock
, 2)) {
2747 lxcfs_error("%s\n", "Timeout reading from parent.");
2750 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2751 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2754 if (vpid
== -1) // done
2758 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2760 cred
.pid
= getpid();
2761 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2768 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2770 int newnsfd
= -1, ret
, cpipe
[2];
2775 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2776 if (ret
< 0 || ret
>= sizeof(fnam
))
2778 newnsfd
= open(fnam
, O_RDONLY
);
2781 if (setns(newnsfd
, 0) < 0)
2785 if (pipe(cpipe
) < 0)
2788 struct pid_ns_clone_args args
= {
2792 .wrapped
= &pid_from_ns
2794 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2795 void *stack
= alloca(stack_size
);
2797 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2801 // give the child 1 second to be done forking and
2803 if (!wait_for_sock(cpipe
[0], 1))
2805 ret
= read(cpipe
[0], &v
, 1);
2806 if (ret
!= sizeof(char) || v
!= '1')
2809 if (!wait_for_pid(cpid
))
2815 * Given host @uid, return the uid to which it maps in
2816 * @pid's user namespace, or -1 if none.
2818 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2823 sprintf(line
, "/proc/%d/uid_map", pid
);
2824 if ((f
= fopen(line
, "r")) == NULL
) {
2828 *answer
= convert_id_to_ns(f
, uid
);
2837 * get_pid_creds: get the real uid and gid of @pid from
2839 * (XXX should we use euid here?)
2841 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2850 sprintf(line
, "/proc/%d/status", pid
);
2851 if ((f
= fopen(line
, "r")) == NULL
) {
2852 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2855 while (fgets(line
, 400, f
)) {
2856 if (strncmp(line
, "Uid:", 4) == 0) {
2857 if (sscanf(line
+4, "%u", &u
) != 1) {
2858 lxcfs_error("bad uid line for pid %u\n", pid
);
2863 } else if (strncmp(line
, "Gid:", 4) == 0) {
2864 if (sscanf(line
+4, "%u", &g
) != 1) {
2865 lxcfs_error("bad gid line for pid %u\n", pid
);
2876 * May the requestor @r move victim @v to a new cgroup?
2877 * This is allowed if
2878 * . they are the same task
2879 * . they are ownedy by the same uid
2880 * . @r is root on the host, or
2881 * . @v's uid is mapped into @r's where @r is root.
2883 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2885 uid_t v_uid
, tmpuid
;
2892 get_pid_creds(v
, &v_uid
, &v_gid
);
2895 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2896 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2901 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2902 const char *file
, const char *buf
)
2904 int sock
[2] = {-1, -1};
2905 pid_t qpid
, cpid
= -1;
2906 FILE *pids_file
= NULL
;
2907 bool answer
= false, fail
= false;
2909 pids_file
= open_pids_file(contrl
, cg
);
2914 * write the pids to a socket, have helper in writer's pidns
2915 * call movepid for us
2917 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2918 perror("socketpair");
2926 if (!cpid
) { // child
2928 pid_from_ns_wrapper(sock
[1], tpid
);
2931 const char *ptr
= buf
;
2932 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2936 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2937 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2941 if (recv_creds(sock
[0], &cred
, &v
)) {
2943 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2947 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2952 ptr
= strchr(ptr
, '\n');
2958 /* All good, write the value */
2960 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2961 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2969 if (sock
[0] != -1) {
2974 if (fclose(pids_file
) != 0)
2980 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2981 struct fuse_file_info
*fi
)
2983 struct fuse_context
*fc
= fuse_get_context();
2984 char *localbuf
= NULL
;
2985 struct cgfs_files
*k
= NULL
;
2986 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2989 if (f
->type
!= LXC_TYPE_CGFILE
) {
2990 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
3000 localbuf
= alloca(size
+1);
3001 localbuf
[size
] = '\0';
3002 memcpy(localbuf
, buf
, size
);
3004 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
3009 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
3014 if (strcmp(f
->file
, "tasks") == 0 ||
3015 strcmp(f
->file
, "/tasks") == 0 ||
3016 strcmp(f
->file
, "/cgroup.procs") == 0 ||
3017 strcmp(f
->file
, "cgroup.procs") == 0)
3018 // special case - we have to translate the pids
3019 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3021 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3031 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
3033 struct fuse_context
*fc
= fuse_get_context();
3034 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3035 struct cgfs_files
*k
= NULL
;
3042 if (strcmp(path
, "/cgroup") == 0)
3045 controller
= pick_controller_from_path(fc
, path
);
3047 return errno
== ENOENT
? -EPERM
: -errno
;
3049 cgroup
= find_cgroup_in_path(path
);
3051 /* this is just /cgroup/controller */
3054 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3064 if (is_child_cgroup(controller
, path1
, path2
)) {
3065 // get uid, gid, from '/tasks' file and make up a mode
3066 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3067 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3070 k
= cgfs_get_key(controller
, path1
, path2
);
3078 * This being a fuse request, the uid and gid must be valid
3079 * in the caller's namespace. So we can just check to make
3080 * sure that the caller is root in his uid, and privileged
3081 * over the file's current owner.
3083 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
3088 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
3097 int cg_chmod(const char *path
, mode_t mode
)
3099 struct fuse_context
*fc
= fuse_get_context();
3100 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3101 struct cgfs_files
*k
= NULL
;
3108 if (strcmp(path
, "/cgroup") == 0)
3111 controller
= pick_controller_from_path(fc
, path
);
3113 return errno
== ENOENT
? -EPERM
: -errno
;
3115 cgroup
= find_cgroup_in_path(path
);
3117 /* this is just /cgroup/controller */
3120 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3130 if (is_child_cgroup(controller
, path1
, path2
)) {
3131 // get uid, gid, from '/tasks' file and make up a mode
3132 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3133 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3136 k
= cgfs_get_key(controller
, path1
, path2
);
3144 * This being a fuse request, the uid and gid must be valid
3145 * in the caller's namespace. So we can just check to make
3146 * sure that the caller is root in his uid, and privileged
3147 * over the file's current owner.
3149 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3154 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3166 int cg_mkdir(const char *path
, mode_t mode
)
3168 struct fuse_context
*fc
= fuse_get_context();
3169 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3176 controller
= pick_controller_from_path(fc
, path
);
3178 return errno
== ENOENT
? -EPERM
: -errno
;
3180 cgroup
= find_cgroup_in_path(path
);
3184 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3190 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3193 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3196 else if (last
&& strcmp(next
, last
) == 0)
3203 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3207 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3212 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3220 int cg_rmdir(const char *path
)
3222 struct fuse_context
*fc
= fuse_get_context();
3223 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3230 controller
= pick_controller_from_path(fc
, path
);
3231 if (!controller
) /* Someone's trying to delete "/cgroup". */
3234 cgroup
= find_cgroup_in_path(path
);
3235 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3238 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3240 /* Someone's trying to delete a cgroup on the same level as the
3241 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3242 * rmdir "/cgroup/blkio/init.slice".
3248 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3251 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3252 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3259 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3263 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3268 if (!cgfs_remove(controller
, cgroup
)) {
3281 static bool startswith(const char *line
, const char *pref
)
3283 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3288 static void parse_memstat(char *memstat
, unsigned long *cached
,
3289 unsigned long *active_anon
, unsigned long *inactive_anon
,
3290 unsigned long *active_file
, unsigned long *inactive_file
,
3291 unsigned long *unevictable
, unsigned long *shmem
)
3296 if (startswith(memstat
, "total_cache")) {
3297 sscanf(memstat
+ 11, "%lu", cached
);
3299 } else if (startswith(memstat
, "total_active_anon")) {
3300 sscanf(memstat
+ 17, "%lu", active_anon
);
3301 *active_anon
/= 1024;
3302 } else if (startswith(memstat
, "total_inactive_anon")) {
3303 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3304 *inactive_anon
/= 1024;
3305 } else if (startswith(memstat
, "total_active_file")) {
3306 sscanf(memstat
+ 17, "%lu", active_file
);
3307 *active_file
/= 1024;
3308 } else if (startswith(memstat
, "total_inactive_file")) {
3309 sscanf(memstat
+ 19, "%lu", inactive_file
);
3310 *inactive_file
/= 1024;
3311 } else if (startswith(memstat
, "total_unevictable")) {
3312 sscanf(memstat
+ 17, "%lu", unevictable
);
3313 *unevictable
/= 1024;
3314 } else if (startswith(memstat
, "total_shmem")) {
3315 sscanf(memstat
+ 11, "%lu", shmem
);
3318 eol
= strchr(memstat
, '\n');
3325 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3331 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3333 size_t len
= strlen(key
);
3337 if (startswith(str
, key
)) {
3338 sscanf(str
+ len
, "%lu", v
);
3341 eol
= strchr(str
, '\n');
3348 int read_file(const char *path
, char *buf
, size_t size
, struct file_info
*d
)
3350 size_t linelen
= 0, total_len
= 0, rv
= 0;
3352 char *cache
= d
->buf
;
3353 size_t cache_size
= d
->buflen
;
3354 FILE *f
= fopen(path
, "r");
3358 while (getline(&line
, &linelen
, f
) != -1) {
3359 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3361 perror("Error writing to cache");
3365 if (l
>= cache_size
) {
3366 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3375 d
->size
= total_len
;
3376 if (total_len
> size
)
3379 /* read from off 0 */
3380 memcpy(buf
, d
->buf
, total_len
);
3389 * FUSE ops for /proc
3392 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3394 char *memlimit_str
= NULL
;
3395 unsigned long memlimit
= -1;
3397 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3398 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3405 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3407 char *copy
= strdupa(cgroup
);
3408 unsigned long memlimit
= 0, retlimit
;
3410 retlimit
= get_memlimit(copy
, file
);
3412 while (strcmp(copy
, "/") != 0) {
3413 copy
= dirname(copy
);
3414 memlimit
= get_memlimit(copy
, file
);
3415 if (memlimit
!= -1 && memlimit
< retlimit
)
3416 retlimit
= memlimit
;
3422 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3423 struct fuse_file_info
*fi
)
3425 struct fuse_context
*fc
= fuse_get_context();
3426 struct lxcfs_opts
*opts
= (struct lxcfs_opts
*) fuse_get_context()->private_data
;
3427 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3429 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3430 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3431 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3432 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3433 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3436 size_t linelen
= 0, total_len
= 0, rv
= 0;
3437 char *cache
= d
->buf
;
3438 size_t cache_size
= d
->buflen
;
3442 if (offset
> d
->size
)
3446 int left
= d
->size
- offset
;
3447 total_len
= left
> size
? size
: left
;
3448 memcpy(buf
, cache
+ offset
, total_len
);
3452 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3455 cg
= get_pid_cgroup(initpid
, "memory");
3457 return read_file("/proc/meminfo", buf
, size
, d
);
3458 prune_init_slice(cg
);
3460 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3461 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3463 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3466 // Following values are allowed to fail, because swapaccount might be turned
3467 // off for current kernel
3468 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3469 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3471 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3472 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3474 memswlimit
= memswlimit
/ 1024;
3475 memswusage
= memswusage
/ 1024;
3478 memusage
= strtoul(memusage_str
, NULL
, 10);
3482 parse_memstat(memstat_str
, &cached
, &active_anon
,
3483 &inactive_anon
, &active_file
, &inactive_file
,
3484 &unevictable
, &shmem
);
3486 f
= fopen("/proc/meminfo", "r");
3490 while (getline(&line
, &linelen
, f
) != -1) {
3492 char *printme
, lbuf
[100];
3494 memset(lbuf
, 0, 100);
3495 if (startswith(line
, "MemTotal:")) {
3496 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3497 if (hosttotal
< memlimit
)
3498 memlimit
= hosttotal
;
3499 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3501 } else if (startswith(line
, "MemFree:")) {
3502 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3504 } else if (startswith(line
, "MemAvailable:")) {
3505 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3507 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0 && opts
&& opts
->swap_off
== false) {
3508 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3509 if (hostswtotal
< memswlimit
)
3510 memswlimit
= hostswtotal
;
3511 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3513 } else if (startswith(line
, "SwapTotal:") && opts
&& opts
->swap_off
== true) {
3514 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", 0UL);
3516 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0 && opts
&& opts
->swap_off
== false) {
3517 unsigned long swaptotal
= memswlimit
,
3518 swapusage
= memswusage
- memusage
,
3519 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3520 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3522 } else if (startswith(line
, "SwapFree:") && opts
&& opts
->swap_off
== true) {
3523 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", 0UL);
3525 } else if (startswith(line
, "Slab:")) {
3526 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3528 } else if (startswith(line
, "Buffers:")) {
3529 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3531 } else if (startswith(line
, "Cached:")) {
3532 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3534 } else if (startswith(line
, "SwapCached:")) {
3535 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3537 } else if (startswith(line
, "Active:")) {
3538 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3539 active_anon
+ active_file
);
3541 } else if (startswith(line
, "Inactive:")) {
3542 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3543 inactive_anon
+ inactive_file
);
3545 } else if (startswith(line
, "Active(anon)")) {
3546 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3548 } else if (startswith(line
, "Inactive(anon)")) {
3549 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3551 } else if (startswith(line
, "Active(file)")) {
3552 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3554 } else if (startswith(line
, "Inactive(file)")) {
3555 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3557 } else if (startswith(line
, "Unevictable")) {
3558 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3560 } else if (startswith(line
, "SReclaimable")) {
3561 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3563 } else if (startswith(line
, "SUnreclaim")) {
3564 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3566 } else if (startswith(line
, "Shmem:")) {
3567 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3569 } else if (startswith(line
, "ShmemHugePages")) {
3570 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3572 } else if (startswith(line
, "ShmemPmdMapped")) {
3573 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3578 l
= snprintf(cache
, cache_size
, "%s", printme
);
3580 perror("Error writing to cache");
3585 if (l
>= cache_size
) {
3586 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3597 d
->size
= total_len
;
3598 if (total_len
> size
) total_len
= size
;
3599 memcpy(buf
, d
->buf
, total_len
);
3608 free(memswlimit_str
);
3609 free(memswusage_str
);
3615 * Read the cpuset.cpus for cg
3616 * Return the answer in a newly allocated string which must be freed
3618 char *get_cpuset(const char *cg
)
3622 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3627 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3629 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3633 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3635 return cpu_in_cpuset(cpu
, cpuset
);
3639 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3640 * depending on `param`. Parameter value is returned throuh `value`.
3642 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3645 char file
[11 + 6 + 1]; // cpu.cfs__us + quota/period + \0
3648 sprintf(file
, "cpu.cfs_%s_us", param
);
3650 if (!cgfs_get_value("cpu", cg
, file
, &str
))
3653 if (sscanf(str
, "%ld", value
) != 1)
3665 * Return the maximum number of visible CPUs based on CPU quotas.
3666 * If there is no quota set, zero is returned.
3668 int max_cpu_count(const char *cg
)
3671 int64_t cfs_quota
, cfs_period
;
3673 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3676 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3679 if (cfs_quota
<= 0 || cfs_period
<= 0)
3682 rv
= cfs_quota
/ cfs_period
;
3684 /* In case quota/period does not yield a whole number, add one CPU for
3687 if ((cfs_quota
% cfs_period
) > 0)
3690 nprocs
= get_nprocs();
3699 * Return the exact number of visible CPUs based on CPU quotas.
3700 * If there is no quota set, zero is returned.
3702 static double exact_cpu_count(const char *cg
)
3706 int64_t cfs_quota
, cfs_period
;
3708 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3711 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3714 if (cfs_quota
<= 0 || cfs_period
<= 0)
3717 rv
= (double)cfs_quota
/ (double)cfs_period
;
3719 nprocs
= get_nprocs();
3728 * Determine whether CPU views should be used or not.
3730 bool use_cpuview(const char *cg
)
3735 tmpc
= find_mounted_controller("cpu", &cfd
);
3739 tmpc
= find_mounted_controller("cpuacct", &cfd
);
3747 * check whether this is a '^processor" line in /proc/cpuinfo
3749 static bool is_processor_line(const char *line
)
3753 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3758 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3759 struct fuse_file_info
*fi
)
3761 struct fuse_context
*fc
= fuse_get_context();
3762 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3764 char *cpuset
= NULL
;
3766 size_t linelen
= 0, total_len
= 0, rv
= 0;
3767 bool am_printing
= false, firstline
= true, is_s390x
= false;
3768 int curcpu
= -1, cpu
, max_cpus
= 0;
3770 char *cache
= d
->buf
;
3771 size_t cache_size
= d
->buflen
;
3775 if (offset
> d
->size
)
3779 int left
= d
->size
- offset
;
3780 total_len
= left
> size
? size
: left
;
3781 memcpy(buf
, cache
+ offset
, total_len
);
3785 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3788 cg
= get_pid_cgroup(initpid
, "cpuset");
3790 return read_file("proc/cpuinfo", buf
, size
, d
);
3791 prune_init_slice(cg
);
3793 cpuset
= get_cpuset(cg
);
3797 use_view
= use_cpuview(cg
);
3800 max_cpus
= max_cpu_count(cg
);
3802 f
= fopen("/proc/cpuinfo", "r");
3806 while (getline(&line
, &linelen
, f
) != -1) {
3810 if (strstr(line
, "IBM/S390") != NULL
) {
3816 if (strncmp(line
, "# processors:", 12) == 0)
3818 if (is_processor_line(line
)) {
3819 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3821 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3824 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3826 perror("Error writing to cache");
3830 if (l
>= cache_size
) {
3831 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3840 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3842 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3844 if (!cpu_in_cpuset(cpu
, cpuset
))
3847 p
= strchr(line
, ':');
3851 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3853 perror("Error writing to cache");
3857 if (l
>= cache_size
) {
3858 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3869 l
= snprintf(cache
, cache_size
, "%s", line
);
3871 perror("Error writing to cache");
3875 if (l
>= cache_size
) {
3876 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3887 char *origcache
= d
->buf
;
3890 d
->buf
= malloc(d
->buflen
);
3893 cache_size
= d
->buflen
;
3895 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3896 if (l
< 0 || l
>= cache_size
) {
3903 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3904 if (l
< 0 || l
>= cache_size
) {
3911 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3913 if (l
< 0 || l
>= cache_size
)
3919 d
->size
= total_len
;
3920 if (total_len
> size
) total_len
= size
;
3922 /* read from off 0 */
3923 memcpy(buf
, d
->buf
, total_len
);
3934 static uint64_t get_reaper_start_time(pid_t pid
)
3939 /* strlen("/proc/") = 6
3943 * strlen("/stat") = 5
3947 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3948 char path
[__PROC_PID_STAT_LEN
];
3951 qpid
= lookup_initpid_in_store(pid
);
3953 /* Caller can check for EINVAL on 0. */
3958 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3959 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3960 /* Caller can check for EINVAL on 0. */
3965 f
= fopen(path
, "r");
3967 /* Caller can check for EINVAL on 0. */
3972 /* Note that the *scanf() argument supression requires that length
3973 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3974 * at us. It's like telling someone you're not married and then asking
3975 * if you can bring your wife to the party.
3977 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3978 "%*s " /* (2) comm %s */
3979 "%*c " /* (3) state %c */
3980 "%*d " /* (4) ppid %d */
3981 "%*d " /* (5) pgrp %d */
3982 "%*d " /* (6) session %d */
3983 "%*d " /* (7) tty_nr %d */
3984 "%*d " /* (8) tpgid %d */
3985 "%*u " /* (9) flags %u */
3986 "%*u " /* (10) minflt %lu */
3987 "%*u " /* (11) cminflt %lu */
3988 "%*u " /* (12) majflt %lu */
3989 "%*u " /* (13) cmajflt %lu */
3990 "%*u " /* (14) utime %lu */
3991 "%*u " /* (15) stime %lu */
3992 "%*d " /* (16) cutime %ld */
3993 "%*d " /* (17) cstime %ld */
3994 "%*d " /* (18) priority %ld */
3995 "%*d " /* (19) nice %ld */
3996 "%*d " /* (20) num_threads %ld */
3997 "%*d " /* (21) itrealvalue %ld */
3998 "%" PRIu64
, /* (22) starttime %llu */
4002 /* Caller can check for EINVAL on 0. */
4013 static double get_reaper_start_time_in_sec(pid_t pid
)
4015 uint64_t clockticks
, ticks_per_sec
;
4019 clockticks
= get_reaper_start_time(pid
);
4020 if (clockticks
== 0 && errno
== EINVAL
) {
4021 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
4025 ret
= sysconf(_SC_CLK_TCK
);
4026 if (ret
< 0 && errno
== EINVAL
) {
4029 "failed to determine number of clock ticks in a second");
4033 ticks_per_sec
= (uint64_t)ret
;
4034 res
= (double)clockticks
/ ticks_per_sec
;
4038 static double get_reaper_age(pid_t pid
)
4041 double procstart
, procage
;
4043 /* We need to substract the time the process has started since system
4044 * boot minus the time when the system has started to get the actual
4047 procstart
= get_reaper_start_time_in_sec(pid
);
4048 procage
= procstart
;
4049 if (procstart
> 0) {
4051 struct timespec spec
;
4053 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
4057 /* We could make this more precise here by using the tv_nsec
4058 * field in the timespec struct and convert it to milliseconds
4059 * and then create a double for the seconds and milliseconds but
4060 * that seems more work than it is worth.
4062 uptime_ms
= (spec
.tv_sec
* 1000) + (spec
.tv_nsec
* 1e-6);
4063 procage
= (uptime_ms
- (procstart
* 1000)) / 1000;
4070 * Returns 0 on success.
4071 * It is the caller's responsibility to free `return_usage`, unless this
4072 * function returns an error.
4074 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
, int *size
)
4076 int cpucount
= get_nprocs_conf();
4077 struct cpuacct_usage
*cpu_usage
;
4078 int rv
= 0, i
, j
, ret
;
4080 uint64_t cg_user
, cg_system
;
4081 int64_t ticks_per_sec
;
4082 char *usage_str
= NULL
;
4084 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4086 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4089 "read_cpuacct_usage_all failed to determine number of clock ticks "
4094 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
4098 memset(cpu_usage
, 0, sizeof(struct cpuacct_usage
) * cpucount
);
4099 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
4100 // read cpuacct.usage_percpu instead
4101 lxcfs_v("failed to read cpuacct.usage_all. reading cpuacct.usage_percpu instead\n%s", "");
4102 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_percpu", &usage_str
)) {
4106 lxcfs_v("usage_str: %s\n", usage_str
);
4108 // convert cpuacct.usage_percpu into cpuacct.usage_all
4109 lxcfs_v("converting cpuacct.usage_percpu into cpuacct.usage_all\n%s", "");
4112 size_t sz
= 0, asz
= 0;
4114 must_strcat(&data
, &sz
, &asz
, "cpu user system\n");
4116 int i
= 0, read_pos
= 0, read_cnt
=0;
4117 while (sscanf(usage_str
+ read_pos
, "%lu %n", &cg_user
, &read_cnt
) > 0) {
4118 lxcfs_debug("i: %d, cg_user: %lu, read_pos: %d, read_cnt: %d\n", i
, cg_user
, read_pos
, read_cnt
);
4119 must_strcat(&data
, &sz
, &asz
, "%d %lu 0\n", i
, cg_user
);
4121 read_pos
+= read_cnt
;
4127 lxcfs_v("usage_str: %s\n", usage_str
);
4130 int read_pos
= 0, read_cnt
=0;
4131 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
4132 lxcfs_error("read_cpuacct_usage_all reading first line from "
4133 "%s/cpuacct.usage_all failed.\n", cg
);
4138 read_pos
+= read_cnt
;
4140 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
4141 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
4142 &cg_system
, &read_cnt
);
4148 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
4154 read_pos
+= read_cnt
;
4156 /* Convert the time from nanoseconds to USER_HZ */
4157 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4158 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4163 *return_usage
= cpu_usage
;
4172 *return_usage
= NULL
;
4178 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
4181 unsigned long sum
= 0;
4183 for (i
= 0; i
< cpu_count
; i
++) {
4184 if (!newer
[i
].online
)
4187 /* When cpuset is changed on the fly, the CPUs might get reordered.
4188 * We could either reset all counters, or check that the substractions
4189 * below will return expected results.
4191 if (newer
[i
].user
> older
[i
].user
)
4192 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
4196 if (newer
[i
].system
> older
[i
].system
)
4197 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
4201 if (newer
[i
].idle
> older
[i
].idle
)
4202 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
4206 sum
+= diff
[i
].user
;
4207 sum
+= diff
[i
].system
;
4208 sum
+= diff
[i
].idle
;
4214 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
4216 unsigned long free_space
, to_add
;
4218 free_space
= threshold
- usage
->user
- usage
->system
;
4220 if (free_space
> usage
->idle
)
4221 free_space
= usage
->idle
;
4223 to_add
= free_space
> *surplus
? *surplus
: free_space
;
4226 usage
->idle
-= to_add
;
4230 static struct cg_proc_stat
*prune_proc_stat_list(struct cg_proc_stat
*node
)
4232 struct cg_proc_stat
*first
= NULL
, *prev
, *tmp
;
4234 for (prev
= NULL
; node
; ) {
4235 if (!cgfs_param_exist("cpu", node
->cg
, "cpu.shares")) {
4237 lxcfs_debug("Removing stat node for %s\n", node
->cg
);
4240 prev
->next
= node
->next
;
4245 free_proc_stat_node(tmp
);
4257 #define PROC_STAT_PRUNE_INTERVAL 10
4258 static void prune_proc_stat_history(void)
4261 time_t now
= time(NULL
);
4263 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
4264 pthread_rwlock_wrlock(&proc_stat_history
[i
]->lock
);
4266 if ((proc_stat_history
[i
]->lastcheck
+ PROC_STAT_PRUNE_INTERVAL
) > now
) {
4267 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4271 if (proc_stat_history
[i
]->next
) {
4272 proc_stat_history
[i
]->next
= prune_proc_stat_list(proc_stat_history
[i
]->next
);
4273 proc_stat_history
[i
]->lastcheck
= now
;
4276 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4280 static struct cg_proc_stat
*find_proc_stat_node(struct cg_proc_stat_head
*head
, const char *cg
)
4282 struct cg_proc_stat
*node
;
4284 pthread_rwlock_rdlock(&head
->lock
);
4287 pthread_rwlock_unlock(&head
->lock
);
4294 if (strcmp(cg
, node
->cg
) == 0)
4296 } while ((node
= node
->next
));
4301 pthread_rwlock_unlock(&head
->lock
);
4302 prune_proc_stat_history();
4306 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4308 struct cg_proc_stat
*node
;
4311 node
= malloc(sizeof(struct cg_proc_stat
));
4319 node
->cg
= malloc(strlen(cg
) + 1);
4323 strcpy(node
->cg
, cg
);
4325 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4329 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4331 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4335 node
->cpu_count
= cpu_count
;
4338 if (pthread_mutex_init(&node
->lock
, NULL
) != 0) {
4339 lxcfs_error("%s\n", "Failed to initialize node lock");
4343 for (i
= 0; i
< cpu_count
; i
++) {
4344 node
->view
[i
].user
= 0;
4345 node
->view
[i
].system
= 0;
4346 node
->view
[i
].idle
= 0;
4352 if (node
&& node
->cg
)
4354 if (node
&& node
->usage
)
4356 if (node
&& node
->view
)
4364 static struct cg_proc_stat
*add_proc_stat_node(struct cg_proc_stat
*new_node
)
4366 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4367 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4368 struct cg_proc_stat
*node
, *rv
= new_node
;
4370 pthread_rwlock_wrlock(&head
->lock
);
4373 head
->next
= new_node
;
4380 if (strcmp(node
->cg
, new_node
->cg
) == 0) {
4381 /* The node is already present, return it */
4382 free_proc_stat_node(new_node
);
4392 node
->next
= new_node
;
4397 pthread_rwlock_unlock(&head
->lock
);
4401 static bool expand_proc_stat_node(struct cg_proc_stat
*node
, int cpu_count
)
4403 struct cpuacct_usage
*new_usage
, *new_view
;
4406 /* Allocate new memory */
4407 new_usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4411 new_view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4417 /* Copy existing data & initialize new elements */
4418 for (i
= 0; i
< cpu_count
; i
++) {
4419 if (i
< node
->cpu_count
) {
4420 new_usage
[i
].user
= node
->usage
[i
].user
;
4421 new_usage
[i
].system
= node
->usage
[i
].system
;
4422 new_usage
[i
].idle
= node
->usage
[i
].idle
;
4424 new_view
[i
].user
= node
->view
[i
].user
;
4425 new_view
[i
].system
= node
->view
[i
].system
;
4426 new_view
[i
].idle
= node
->view
[i
].idle
;
4428 new_usage
[i
].user
= 0;
4429 new_usage
[i
].system
= 0;
4430 new_usage
[i
].idle
= 0;
4432 new_view
[i
].user
= 0;
4433 new_view
[i
].system
= 0;
4434 new_view
[i
].idle
= 0;
4441 node
->usage
= new_usage
;
4442 node
->view
= new_view
;
4443 node
->cpu_count
= cpu_count
;
4448 static struct cg_proc_stat
*find_or_create_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4450 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4451 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4452 struct cg_proc_stat
*node
;
4454 node
= find_proc_stat_node(head
, cg
);
4457 node
= new_proc_stat_node(usage
, cpu_count
, cg
);
4461 node
= add_proc_stat_node(node
);
4462 lxcfs_debug("New stat node (%d) for %s\n", cpu_count
, cg
);
4465 pthread_mutex_lock(&node
->lock
);
4467 /* If additional CPUs on the host have been enabled, CPU usage counter
4468 * arrays have to be expanded */
4469 if (node
->cpu_count
< cpu_count
) {
4470 lxcfs_debug("Expanding stat node %d->%d for %s\n",
4471 node
->cpu_count
, cpu_count
, cg
);
4473 if (!expand_proc_stat_node(node
, cpu_count
)) {
4474 pthread_mutex_unlock(&node
->lock
);
4475 lxcfs_debug("Unable to expand stat node %d->%d for %s\n",
4476 node
->cpu_count
, cpu_count
, cg
);
4484 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4488 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4489 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4491 for (i
= 0; i
< cpu_count
; i
++) {
4492 node
->view
[i
].user
= 0;
4493 node
->view
[i
].system
= 0;
4494 node
->view
[i
].idle
= 0;
4497 node
->cpu_count
= cpu_count
;
4500 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
)
4503 size_t linelen
= 0, total_len
= 0, rv
= 0, l
;
4504 int curcpu
= -1; /* cpu numbering starts at 0 */
4506 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4507 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4508 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4509 unsigned long user_surplus
= 0, system_surplus
= 0;
4510 unsigned long total_sum
, threshold
;
4511 struct cg_proc_stat
*stat_node
;
4512 struct cpuacct_usage
*diff
= NULL
;
4513 int nprocs
= get_nprocs_conf();
4515 if (cg_cpu_usage_size
< nprocs
)
4516 nprocs
= cg_cpu_usage_size
;
4518 /* Read all CPU stats and stop when we've encountered other lines */
4519 while (getline(&line
, &linelen
, f
) != -1) {
4521 char cpu_char
[10]; /* That's a lot of cores */
4522 uint64_t all_used
, cg_used
;
4524 if (strlen(line
) == 0)
4526 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4527 /* not a ^cpuN line containing a number N */
4531 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4534 if (physcpu
>= cg_cpu_usage_size
)
4540 if (!cpu_in_cpuset(physcpu
, cpuset
)) {
4541 for (i
= curcpu
; i
<= physcpu
; i
++) {
4542 cg_cpu_usage
[i
].online
= false;
4547 if (curcpu
< physcpu
) {
4548 /* Some CPUs may be disabled */
4549 for (i
= curcpu
; i
< physcpu
; i
++)
4550 cg_cpu_usage
[i
].online
= false;
4555 cg_cpu_usage
[curcpu
].online
= true;
4557 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4572 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4573 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4575 if (all_used
>= cg_used
) {
4576 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4579 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4580 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4581 curcpu
, cg
, all_used
, cg_used
);
4582 cg_cpu_usage
[curcpu
].idle
= idle
;
4586 /* Cannot use more CPUs than is available due to cpuset */
4587 if (max_cpus
> cpu_cnt
)
4590 stat_node
= find_or_create_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4593 lxcfs_error("unable to find/create stat node for %s\n", cg
);
4598 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4605 * If the new values are LOWER than values stored in memory, it means
4606 * the cgroup has been reset/recreated and we should reset too.
4608 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4609 if (!cg_cpu_usage
[curcpu
].online
)
4612 if (cg_cpu_usage
[curcpu
].user
< stat_node
->usage
[curcpu
].user
)
4613 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4618 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, nprocs
);
4620 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4621 stat_node
->usage
[curcpu
].online
= cg_cpu_usage
[curcpu
].online
;
4623 if (!stat_node
->usage
[curcpu
].online
)
4628 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4629 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4630 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4632 if (max_cpus
> 0 && i
>= max_cpus
) {
4633 user_surplus
+= diff
[curcpu
].user
;
4634 system_surplus
+= diff
[curcpu
].system
;
4638 /* Calculate usage counters of visible CPUs */
4640 /* threshold = maximum usage per cpu, including idle */
4641 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4643 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4644 if (!stat_node
->usage
[curcpu
].online
)
4652 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4662 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4665 /* If there is still room, add system */
4669 &diff
[curcpu
].system
,
4673 if (user_surplus
> 0)
4674 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4675 if (system_surplus
> 0)
4676 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4678 unsigned long diff_user
= 0;
4679 unsigned long diff_system
= 0;
4680 unsigned long diff_idle
= 0;
4681 unsigned long max_diff_idle
= 0;
4682 unsigned long max_diff_idle_index
= 0;
4683 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4684 if (!stat_node
->usage
[curcpu
].online
)
4692 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4693 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4694 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4696 user_sum
+= stat_node
->view
[curcpu
].user
;
4697 system_sum
+= stat_node
->view
[curcpu
].system
;
4698 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4700 diff_user
+= diff
[curcpu
].user
;
4701 diff_system
+= diff
[curcpu
].system
;
4702 diff_idle
+= diff
[curcpu
].idle
;
4703 if (diff
[curcpu
].idle
> max_diff_idle
) {
4704 max_diff_idle
= diff
[curcpu
].idle
;
4705 max_diff_idle_index
= curcpu
;
4708 lxcfs_v("curcpu: %d, diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", curcpu
, diff
[curcpu
].user
, diff
[curcpu
].system
, diff
[curcpu
].idle
);
4710 lxcfs_v("total. diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", diff_user
, diff_system
, diff_idle
);
4712 // revise cpu usage view to support partial cpu case
4713 double exact_cpus
= exact_cpu_count(cg
);
4714 if (exact_cpus
< (double)max_cpus
){
4715 lxcfs_v("revising cpu usage view to match the exact cpu count [%f]\n", exact_cpus
);
4716 unsigned long delta
= (unsigned long)((double)(diff_user
+ diff_system
+ diff_idle
) * (1 - exact_cpus
/ (double)max_cpus
));
4717 lxcfs_v("delta: %lu\n", delta
);
4718 lxcfs_v("idle_sum before: %lu\n", idle_sum
);
4719 idle_sum
= idle_sum
> delta
? idle_sum
- delta
: 0;
4720 lxcfs_v("idle_sum after: %lu\n", idle_sum
);
4722 curcpu
= max_diff_idle_index
;
4723 lxcfs_v("curcpu: %d, idle before: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4724 stat_node
->view
[curcpu
].idle
= stat_node
->view
[curcpu
].idle
> delta
? stat_node
->view
[curcpu
].idle
- delta
: 0;
4725 lxcfs_v("curcpu: %d, idle after: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4728 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4729 if (!stat_node
->usage
[curcpu
].online
)
4732 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4733 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4734 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4736 user_sum
+= stat_node
->view
[curcpu
].user
;
4737 system_sum
+= stat_node
->view
[curcpu
].system
;
4738 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4742 /* Render the file */
4744 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4748 lxcfs_v("cpu-all: %s\n", buf
);
4751 perror("Error writing to cache");
4755 if (l
>= buf_size
) {
4756 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4765 /* Render visible CPUs */
4766 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4767 if (!stat_node
->usage
[curcpu
].online
)
4772 if (max_cpus
> 0 && i
== max_cpus
)
4775 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4777 stat_node
->view
[curcpu
].user
,
4778 stat_node
->view
[curcpu
].system
,
4779 stat_node
->view
[curcpu
].idle
);
4780 lxcfs_v("cpu: %s\n", buf
);
4783 perror("Error writing to cache");
4788 if (l
>= buf_size
) {
4789 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4799 /* Pass the rest of /proc/stat, start with the last line read */
4800 l
= snprintf(buf
, buf_size
, "%s", line
);
4803 perror("Error writing to cache");
4808 if (l
>= buf_size
) {
4809 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4818 /* Pass the rest of the host's /proc/stat */
4819 while (getline(&line
, &linelen
, f
) != -1) {
4820 l
= snprintf(buf
, buf_size
, "%s", line
);
4822 perror("Error writing to cache");
4826 if (l
>= buf_size
) {
4827 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4840 pthread_mutex_unlock(&stat_node
->lock
);
4848 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4849 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4850 struct fuse_file_info
*fi
)
4852 struct fuse_context
*fc
= fuse_get_context();
4853 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4855 char *cpuset
= NULL
;
4857 size_t linelen
= 0, total_len
= 0, rv
= 0;
4858 int curcpu
= -1; /* cpu numbering starts at 0 */
4860 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4861 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
4862 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4863 char cpuall
[CPUALL_MAX_SIZE
];
4864 /* reserve for cpu all */
4865 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4866 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4868 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4869 int cg_cpu_usage_size
= 0;
4872 if (offset
> d
->size
)
4876 int left
= d
->size
- offset
;
4877 total_len
= left
> size
? size
: left
;
4878 memcpy(buf
, d
->buf
+ offset
, total_len
);
4882 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4883 lxcfs_v("initpid: %d\n", initpid
);
4886 cg
= get_pid_cgroup(initpid
, "cpuset");
4887 lxcfs_v("cg: %s\n", cg
);
4889 return read_file("/proc/stat", buf
, size
, d
);
4890 prune_init_slice(cg
);
4892 cpuset
= get_cpuset(cg
);
4897 * Read cpuacct.usage_all for all CPUs.
4898 * If the cpuacct cgroup is present, it is used to calculate the container's
4899 * CPU usage. If not, values from the host's /proc/stat are used.
4901 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
, &cg_cpu_usage_size
) != 0) {
4902 lxcfs_v("%s\n", "proc_stat_read failed to read from cpuacct, "
4903 "falling back to the host's /proc/stat");
4906 f
= fopen("/proc/stat", "r");
4911 if (getline(&line
, &linelen
, f
) < 0) {
4912 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
4916 if (use_cpuview(cg
) && cg_cpu_usage
) {
4917 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, cg_cpu_usage_size
,
4918 f
, d
->buf
, d
->buflen
);
4922 while (getline(&line
, &linelen
, f
) != -1) {
4924 char cpu_char
[10]; /* That's a lot of cores */
4926 uint64_t all_used
, cg_used
, new_idle
;
4929 if (strlen(line
) == 0)
4931 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4932 /* not a ^cpuN line containing a number N, just print it */
4933 l
= snprintf(cache
, cache_size
, "%s", line
);
4935 perror("Error writing to cache");
4939 if (l
>= cache_size
) {
4940 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4950 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4952 if (!cpu_in_cpuset(physcpu
, cpuset
))
4956 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4968 if (ret
!= 10 || !cg_cpu_usage
) {
4969 c
= strchr(line
, ' ');
4972 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4974 perror("Error writing to cache");
4979 if (l
>= cache_size
) {
4980 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4994 if (physcpu
>= cg_cpu_usage_size
)
4997 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4998 cg_used
= cg_cpu_usage
[physcpu
].user
+ cg_cpu_usage
[physcpu
].system
;
5000 if (all_used
>= cg_used
) {
5001 new_idle
= idle
+ (all_used
- cg_used
);
5004 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
5005 "%lu in cpuacct.usage_all; unable to determine idle time\n",
5006 curcpu
, cg
, all_used
, cg_used
);
5010 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
5011 curcpu
, cg_cpu_usage
[physcpu
].user
, cg_cpu_usage
[physcpu
].system
,
5015 perror("Error writing to cache");
5020 if (l
>= cache_size
) {
5021 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5030 user_sum
+= cg_cpu_usage
[physcpu
].user
;
5031 system_sum
+= cg_cpu_usage
[physcpu
].system
;
5032 idle_sum
+= new_idle
;
5037 system_sum
+= system
;
5039 iowait_sum
+= iowait
;
5041 softirq_sum
+= softirq
;
5044 guest_nice_sum
+= guest_nice
;
5050 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5061 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
5062 memcpy(cache
, cpuall
, cpuall_len
);
5063 cache
+= cpuall_len
;
5065 /* shouldn't happen */
5066 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
5070 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
5071 total_len
+= cpuall_len
;
5075 d
->size
= total_len
;
5076 if (total_len
> size
)
5079 memcpy(buf
, d
->buf
, total_len
);
5093 /* This function retrieves the busy time of a group of tasks by looking at
5094 * cpuacct.usage. Unfortunately, this only makes sense when the container has
5095 * been given it's own cpuacct cgroup. If not, this function will take the busy
5096 * time of all other taks that do not actually belong to the container into
5097 * account as well. If someone has a clever solution for this please send a
5100 static double get_reaper_busy(pid_t task
)
5102 pid_t initpid
= lookup_initpid_in_store(task
);
5103 char *cgroup
= NULL
, *usage_str
= NULL
;
5104 unsigned long usage
= 0;
5110 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
5113 prune_init_slice(cgroup
);
5114 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
5116 usage
= strtoul(usage_str
, NULL
, 10);
5117 res
= (double)usage
/ 1000000000;
5130 fd
= creat("/tmp/lxcfs-iwashere", 0644);
5137 * We read /proc/uptime and reuse its second field.
5138 * For the first field, we use the mtime for the reaper for
5139 * the calling pid as returned by getreaperage
5141 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
5142 struct fuse_file_info
*fi
)
5144 struct fuse_context
*fc
= fuse_get_context();
5145 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5146 double busytime
= get_reaper_busy(fc
->pid
);
5147 char *cache
= d
->buf
;
5148 ssize_t total_len
= 0;
5149 double idletime
, reaperage
;
5158 if (offset
> d
->size
)
5160 int left
= d
->size
- offset
;
5161 total_len
= left
> size
? size
: left
;
5162 memcpy(buf
, cache
+ offset
, total_len
);
5166 reaperage
= get_reaper_age(fc
->pid
);
5167 /* To understand why this is done, please read the comment to the
5168 * get_reaper_busy() function.
5170 idletime
= reaperage
;
5171 if (reaperage
>= busytime
)
5172 idletime
= reaperage
- busytime
;
5174 total_len
= snprintf(d
->buf
, d
->buflen
, "%.2lf %.2lf\n", reaperage
, idletime
);
5175 if (total_len
< 0 || total_len
>= d
->buflen
){
5176 lxcfs_error("%s\n", "failed to write to cache");
5180 d
->size
= (int)total_len
;
5183 if (total_len
> size
) total_len
= size
;
5185 memcpy(buf
, d
->buf
, total_len
);
5189 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
5190 struct fuse_file_info
*fi
)
5193 struct fuse_context
*fc
= fuse_get_context();
5194 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5196 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
5197 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
5198 unsigned long read
= 0, write
= 0;
5199 unsigned long read_merged
= 0, write_merged
= 0;
5200 unsigned long read_sectors
= 0, write_sectors
= 0;
5201 unsigned long read_ticks
= 0, write_ticks
= 0;
5202 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
5203 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
5204 char *cache
= d
->buf
;
5205 size_t cache_size
= d
->buflen
;
5207 size_t linelen
= 0, total_len
= 0, rv
= 0;
5208 unsigned int major
= 0, minor
= 0;
5213 if (offset
> d
->size
)
5217 int left
= d
->size
- offset
;
5218 total_len
= left
> size
? size
: left
;
5219 memcpy(buf
, cache
+ offset
, total_len
);
5223 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5226 cg
= get_pid_cgroup(initpid
, "blkio");
5228 return read_file("/proc/diskstats", buf
, size
, d
);
5229 prune_init_slice(cg
);
5231 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
5233 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
5235 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
5237 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
5239 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
5243 f
= fopen("/proc/diskstats", "r");
5247 while (getline(&line
, &linelen
, f
) != -1) {
5251 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
5255 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
5256 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
5257 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
5258 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
5259 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
5260 read_sectors
= read_sectors
/512;
5261 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
5262 write_sectors
= write_sectors
/512;
5264 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
5265 rd_svctm
= rd_svctm
/1000000;
5266 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
5267 rd_wait
= rd_wait
/1000000;
5268 read_ticks
= rd_svctm
+ rd_wait
;
5270 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
5271 wr_svctm
= wr_svctm
/1000000;
5272 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
5273 wr_wait
= wr_wait
/1000000;
5274 write_ticks
= wr_svctm
+ wr_wait
;
5276 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
5277 tot_ticks
= tot_ticks
/1000000;
5279 memset(lbuf
, 0, 256);
5280 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
5281 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5282 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
5283 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
5287 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
5289 perror("Error writing to fuse buf");
5293 if (l
>= cache_size
) {
5294 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5304 d
->size
= total_len
;
5305 if (total_len
> size
) total_len
= size
;
5306 memcpy(buf
, d
->buf
, total_len
);
5314 free(io_serviced_str
);
5315 free(io_merged_str
);
5316 free(io_service_bytes_str
);
5317 free(io_wait_time_str
);
5318 free(io_service_time_str
);
5322 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
5323 struct fuse_file_info
*fi
)
5325 struct fuse_context
*fc
= fuse_get_context();
5326 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5328 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
5329 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
5330 ssize_t total_len
= 0, rv
= 0;
5332 char *cache
= d
->buf
;
5335 if (offset
> d
->size
)
5339 int left
= d
->size
- offset
;
5340 total_len
= left
> size
? size
: left
;
5341 memcpy(buf
, cache
+ offset
, total_len
);
5345 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5348 cg
= get_pid_cgroup(initpid
, "memory");
5350 return read_file("/proc/swaps", buf
, size
, d
);
5351 prune_init_slice(cg
);
5353 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
5355 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
5358 memusage
= strtoul(memusage_str
, NULL
, 10);
5360 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
5361 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
5363 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
5364 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5366 swap_total
= (memswlimit
- memlimit
) / 1024;
5367 swap_free
= (memswusage
- memusage
) / 1024;
5370 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5372 /* When no mem + swap limit is specified or swapaccount=0*/
5376 FILE *f
= fopen("/proc/meminfo", "r");
5381 while (getline(&line
, &linelen
, f
) != -1) {
5382 if (startswith(line
, "SwapTotal:")) {
5383 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5384 } else if (startswith(line
, "SwapFree:")) {
5385 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5393 if (swap_total
> 0) {
5394 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5395 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5396 swap_total
, swap_free
);
5400 if (total_len
< 0 || l
< 0) {
5401 perror("Error writing to cache");
5407 d
->size
= (int)total_len
;
5409 if (total_len
> size
) total_len
= size
;
5410 memcpy(buf
, d
->buf
, total_len
);
5415 free(memswlimit_str
);
5418 free(memswusage_str
);
5422 * Find the process pid from cgroup path.
5423 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5424 * @pid_buf : put pid to pid_buf.
5425 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5426 * @depth : the depth of cgroup in container.
5427 * @sum : return the number of pid.
5428 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5430 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5434 struct dirent
*file
;
5439 char *path_dir
, *path
;
5442 /* path = dpath + "/cgroup.procs" + /0 */
5444 path
= malloc(strlen(dpath
) + 20);
5447 strcpy(path
, dpath
);
5448 fd
= openat(cfd
, path
, O_RDONLY
);
5452 dir
= fdopendir(fd
);
5458 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5459 if (strncmp(file
->d_name
, ".", 1) == 0)
5461 if (strncmp(file
->d_name
, "..", 1) == 0)
5463 if (file
->d_type
== DT_DIR
) {
5464 /* path + '/' + d_name +/0 */
5466 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5467 } while (!path_dir
);
5468 strcpy(path_dir
, path
);
5469 strcat(path_dir
, "/");
5470 strcat(path_dir
, file
->d_name
);
5472 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5478 strcat(path
, "/cgroup.procs");
5479 fd
= openat(cfd
, path
, O_RDONLY
);
5483 f
= fdopen(fd
, "r");
5489 while (getline(&line
, &linelen
, f
) != -1) {
5491 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5495 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5496 } while (*(*pid_buf
+ sum
) == NULL
);
5497 strcpy(*(*pid_buf
+ sum
), line
);
5508 * calc_load calculates the load according to the following formula:
5509 * load1 = load0 * exp + active * (1 - exp)
5511 * @load1: the new loadavg.
5512 * @load0: the former loadavg.
5513 * @active: the total number of running pid at this moment.
5514 * @exp: the fixed-point defined in the beginning.
5516 static unsigned long
5517 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5519 unsigned long newload
;
5521 active
= active
> 0 ? active
* FIXED_1
: 0;
5522 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5524 newload
+= FIXED_1
- 1;
5526 return newload
/ FIXED_1
;
5530 * Return 0 means that container p->cg is closed.
5531 * Return -1 means that error occurred in refresh.
5532 * Positive num equals the total number of pid.
5534 static int refresh_load(struct load_node
*p
, char *path
)
5538 char proc_path
[256];
5539 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5544 struct dirent
*file
;
5547 idbuf
= malloc(sizeof(char *));
5549 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5554 for (i
= 0; i
< sum
; i
++) {
5556 length
= strlen(idbuf
[i
])-1;
5557 idbuf
[i
][length
] = '\0';
5558 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5559 if (ret
< 0 || ret
> 255) {
5560 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5566 dp
= opendir(proc_path
);
5568 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5571 while ((file
= readdir(dp
)) != NULL
) {
5572 if (strncmp(file
->d_name
, ".", 1) == 0)
5574 if (strncmp(file
->d_name
, "..", 1) == 0)
5577 /* We make the biggest pid become last_pid.*/
5578 ret
= atof(file
->d_name
);
5579 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5581 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5582 if (ret
< 0 || ret
> 255) {
5583 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5589 f
= fopen(proc_path
, "r");
5591 while (getline(&line
, &linelen
, f
) != -1) {
5593 if ((line
[0] == 'S') && (line
[1] == 't'))
5596 if ((line
[7] == 'R') || (line
[7] == 'D'))
5603 /*Calculate the loadavg.*/
5604 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5605 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5606 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5607 p
->run_pid
= run_pid
;
5608 p
->total_pid
= total_pid
;
5609 p
->last_pid
= last_pid
;
5620 * Traverse the hash table and update it.
5622 void *load_begin(void *arg
)
5626 int i
, sum
, length
, ret
;
5627 struct load_node
*f
;
5629 clock_t time1
, time2
;
5632 if (loadavg_stop
== 1)
5636 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5637 pthread_mutex_lock(&load_hash
[i
].lock
);
5638 if (load_hash
[i
].next
== NULL
) {
5639 pthread_mutex_unlock(&load_hash
[i
].lock
);
5642 f
= load_hash
[i
].next
;
5645 length
= strlen(f
->cg
) + 2;
5647 /* strlen(f->cg) + '.' or '' + \0 */
5648 path
= malloc(length
);
5651 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
5652 if (ret
< 0 || ret
> length
- 1) {
5653 /* snprintf failed, ignore the node.*/
5654 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5657 sum
= refresh_load(f
, path
);
5664 /* load_hash[i].lock locks only on the first node.*/
5665 if (first_node
== 1) {
5667 pthread_mutex_unlock(&load_hash
[i
].lock
);
5672 if (loadavg_stop
== 1)
5676 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5680 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5681 struct fuse_file_info
*fi
)
5683 struct fuse_context
*fc
= fuse_get_context();
5684 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5687 size_t total_len
= 0;
5688 char *cache
= d
->buf
;
5689 struct load_node
*n
;
5692 unsigned long a
, b
, c
;
5695 if (offset
> d
->size
)
5699 int left
= d
->size
- offset
;
5700 total_len
= left
> size
? size
: left
;
5701 memcpy(buf
, cache
+ offset
, total_len
);
5705 return read_file("/proc/loadavg", buf
, size
, d
);
5707 initpid
= lookup_initpid_in_store(fc
->pid
);
5710 cg
= get_pid_cgroup(initpid
, "cpu");
5712 return read_file("/proc/loadavg", buf
, size
, d
);
5714 prune_init_slice(cg
);
5715 hash
= calc_hash(cg
) % LOAD_SIZE
;
5716 n
= locate_node(cg
, hash
);
5720 if (!find_mounted_controller("cpu", &cfd
)) {
5722 * In locate_node() above, pthread_rwlock_unlock() isn't used
5723 * because delete is not allowed before read has ended.
5725 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5730 n
= malloc(sizeof(struct load_node
));
5734 n
->cg
= malloc(strlen(cg
)+1);
5742 n
->last_pid
= initpid
;
5744 insert_node(&n
, hash
);
5746 a
= n
->avenrun
[0] + (FIXED_1
/200);
5747 b
= n
->avenrun
[1] + (FIXED_1
/200);
5748 c
= n
->avenrun
[2] + (FIXED_1
/200);
5749 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5750 LOAD_INT(a
), LOAD_FRAC(a
),
5751 LOAD_INT(b
), LOAD_FRAC(b
),
5752 LOAD_INT(c
), LOAD_FRAC(c
),
5753 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5754 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5755 if (total_len
< 0 || total_len
>= d
->buflen
) {
5756 lxcfs_error("%s\n", "Failed to write to cache");
5760 d
->size
= (int)total_len
;
5763 if (total_len
> size
)
5765 memcpy(buf
, d
->buf
, total_len
);
5772 /* Return a positive number on success, return 0 on failure.*/
5773 pthread_t
load_daemon(int load_use
)
5780 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5783 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5785 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5789 /* use loadavg, here loadavg = 1*/
5794 /* Returns 0 on success. */
5795 int stop_load_daemon(pthread_t pid
)
5799 /* Signal the thread to gracefully stop */
5802 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5804 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5814 static off_t
get_procfile_size(const char *which
)
5816 FILE *f
= fopen(which
, "r");
5819 ssize_t sz
, answer
= 0;
5823 while ((sz
= getline(&line
, &len
, f
)) != -1)
5831 int proc_getattr(const char *path
, struct stat
*sb
)
5833 struct timespec now
;
5835 memset(sb
, 0, sizeof(struct stat
));
5836 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5838 sb
->st_uid
= sb
->st_gid
= 0;
5839 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5840 if (strcmp(path
, "/proc") == 0) {
5841 sb
->st_mode
= S_IFDIR
| 00555;
5845 if (strcmp(path
, "/proc/meminfo") == 0 ||
5846 strcmp(path
, "/proc/cpuinfo") == 0 ||
5847 strcmp(path
, "/proc/uptime") == 0 ||
5848 strcmp(path
, "/proc/stat") == 0 ||
5849 strcmp(path
, "/proc/diskstats") == 0 ||
5850 strcmp(path
, "/proc/swaps") == 0 ||
5851 strcmp(path
, "/proc/loadavg") == 0) {
5853 sb
->st_mode
= S_IFREG
| 00444;
5861 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5862 struct fuse_file_info
*fi
)
5864 if (filler(buf
, ".", NULL
, 0) != 0 ||
5865 filler(buf
, "..", NULL
, 0) != 0 ||
5866 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5867 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5868 filler(buf
, "stat", NULL
, 0) != 0 ||
5869 filler(buf
, "uptime", NULL
, 0) != 0 ||
5870 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5871 filler(buf
, "swaps", NULL
, 0) != 0 ||
5872 filler(buf
, "loadavg", NULL
, 0) != 0)
5877 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5880 struct file_info
*info
;
5882 if (strcmp(path
, "/proc/meminfo") == 0)
5883 type
= LXC_TYPE_PROC_MEMINFO
;
5884 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5885 type
= LXC_TYPE_PROC_CPUINFO
;
5886 else if (strcmp(path
, "/proc/uptime") == 0)
5887 type
= LXC_TYPE_PROC_UPTIME
;
5888 else if (strcmp(path
, "/proc/stat") == 0)
5889 type
= LXC_TYPE_PROC_STAT
;
5890 else if (strcmp(path
, "/proc/diskstats") == 0)
5891 type
= LXC_TYPE_PROC_DISKSTATS
;
5892 else if (strcmp(path
, "/proc/swaps") == 0)
5893 type
= LXC_TYPE_PROC_SWAPS
;
5894 else if (strcmp(path
, "/proc/loadavg") == 0)
5895 type
= LXC_TYPE_PROC_LOADAVG
;
5899 info
= malloc(sizeof(*info
));
5903 memset(info
, 0, sizeof(*info
));
5906 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
5908 info
->buf
= malloc(info
->buflen
);
5909 } while (!info
->buf
);
5910 memset(info
->buf
, 0, info
->buflen
);
5911 /* set actual size to buffer size */
5912 info
->size
= info
->buflen
;
5914 fi
->fh
= (unsigned long)info
;
5918 int proc_access(const char *path
, int mask
)
5920 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
5923 /* these are all read-only */
5924 if ((mask
& ~R_OK
) != 0)
5929 int proc_release(const char *path
, struct fuse_file_info
*fi
)
5931 do_release_file_info(fi
);
5935 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
5936 struct fuse_file_info
*fi
)
5938 struct file_info
*f
= (struct file_info
*) fi
->fh
;
5941 case LXC_TYPE_PROC_MEMINFO
:
5942 return proc_meminfo_read(buf
, size
, offset
, fi
);
5943 case LXC_TYPE_PROC_CPUINFO
:
5944 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
5945 case LXC_TYPE_PROC_UPTIME
:
5946 return proc_uptime_read(buf
, size
, offset
, fi
);
5947 case LXC_TYPE_PROC_STAT
:
5948 return proc_stat_read(buf
, size
, offset
, fi
);
5949 case LXC_TYPE_PROC_DISKSTATS
:
5950 return proc_diskstats_read(buf
, size
, offset
, fi
);
5951 case LXC_TYPE_PROC_SWAPS
:
5952 return proc_swaps_read(buf
, size
, offset
, fi
);
5953 case LXC_TYPE_PROC_LOADAVG
:
5954 return proc_loadavg_read(buf
, size
, offset
, fi
);
5961 * Functions needed to setup cgroups in the __constructor__.
5964 static bool mkdir_p(const char *dir
, mode_t mode
)
5966 const char *tmp
= dir
;
5967 const char *orig
= dir
;
5971 dir
= tmp
+ strspn(tmp
, "/");
5972 tmp
= dir
+ strcspn(dir
, "/");
5973 makeme
= strndup(orig
, dir
- orig
);
5976 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
5977 lxcfs_error("Failed to create directory '%s': %s.\n",
5978 makeme
, strerror(errno
));
5983 } while(tmp
!= dir
);
5988 static bool umount_if_mounted(void)
5990 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5991 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5997 /* __typeof__ should be safe to use with all compilers. */
5998 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5999 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
6001 return (fs
->f_type
== (fs_type_magic
)magic_val
);
6005 * looking at fs/proc_namespace.c, it appears we can
6006 * actually expect the rootfs entry to very specifically contain
6007 * " - rootfs rootfs "
6008 * IIUC, so long as we've chrooted so that rootfs is not our root,
6009 * the rootfs entry should always be skipped in mountinfo contents.
6011 static bool is_on_ramfs(void)
6019 f
= fopen("/proc/self/mountinfo", "r");
6023 while (getline(&line
, &len
, f
) != -1) {
6024 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
6025 p
= strchr(p
+ 1, ' ');
6028 p2
= strchr(p
+ 1, ' ');
6032 if (strcmp(p
+ 1, "/") == 0) {
6033 // this is '/'. is it the ramfs?
6034 p
= strchr(p2
+ 1, '-');
6035 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
6047 static int pivot_enter()
6049 int ret
= -1, oldroot
= -1, newroot
= -1;
6051 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
6053 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
6057 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
6059 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
6063 /* change into new root fs */
6064 if (fchdir(newroot
) < 0) {
6065 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
6069 /* pivot_root into our new root fs */
6070 if (pivot_root(".", ".") < 0) {
6071 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
6076 * At this point the old-root is mounted on top of our new-root.
6077 * To unmounted it we must not be chdir'd into it, so escape back
6080 if (fchdir(oldroot
) < 0) {
6081 lxcfs_error("%s\n", "Failed to enter old root.");
6085 if (umount2(".", MNT_DETACH
) < 0) {
6086 lxcfs_error("%s\n", "Failed to detach old root.");
6090 if (fchdir(newroot
) < 0) {
6091 lxcfs_error("%s\n", "Failed to re-enter new root.");
6106 static int chroot_enter()
6108 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
6109 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
6113 if (chroot(".") < 0) {
6114 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
6118 if (chdir("/") < 0) {
6119 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
6126 static int permute_and_enter(void)
6130 if (statfs("/", &sb
) < 0) {
6131 lxcfs_error("%s\n", "Could not stat / mountpoint.");
6135 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
6136 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
6137 * /proc/1/mountinfo. */
6138 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
6139 return chroot_enter();
6141 if (pivot_enter() < 0) {
6142 lxcfs_error("%s\n", "Could not perform pivot root.");
6149 /* Prepare our new clean root. */
6150 static int permute_prepare(void)
6152 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
6153 lxcfs_error("%s\n", "Failed to create directory for new root.");
6157 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
6158 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
6162 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
6163 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
6167 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
6168 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
6175 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
6176 static bool permute_root(void)
6178 /* Prepare new root. */
6179 if (permute_prepare() < 0)
6182 /* Pivot into new root. */
6183 if (permute_and_enter() < 0)
6189 static int preserve_mnt_ns(int pid
)
6192 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
6195 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
6196 if (ret
< 0 || (size_t)ret
>= len
)
6199 return open(path
, O_RDONLY
| O_CLOEXEC
);
6202 static bool cgfs_prepare_mounts(void)
6204 if (!mkdir_p(BASEDIR
, 0700)) {
6205 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
6209 if (!umount_if_mounted()) {
6210 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
6214 if (unshare(CLONE_NEWNS
) < 0) {
6215 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
6219 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
6220 if (cgroup_mount_ns_fd
< 0) {
6221 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
6225 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
6226 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
6230 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
6231 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
6238 static bool cgfs_mount_hierarchies(void)
6244 for (i
= 0; i
< num_hierarchies
; i
++) {
6245 char *controller
= hierarchies
[i
];
6247 clen
= strlen(controller
);
6248 len
= strlen(BASEDIR
) + clen
+ 2;
6249 target
= malloc(len
);
6253 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
6254 if (ret
< 0 || ret
>= len
) {
6258 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
6262 if (!strcmp(controller
, "unified"))
6263 ret
= mount("none", target
, "cgroup2", 0, NULL
);
6265 ret
= mount(controller
, target
, "cgroup", 0, controller
);
6267 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
6272 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
6273 if (fd_hierarchies
[i
] < 0) {
6282 static bool cgfs_setup_controllers(void)
6284 if (!cgfs_prepare_mounts())
6287 if (!cgfs_mount_hierarchies()) {
6288 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
6292 if (!permute_root())
6298 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
6301 char *cret
, *line
= NULL
;
6302 char cwd
[MAXPATHLEN
];
6304 int i
, init_ns
= -1;
6305 bool found_unified
= false;
6307 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
6308 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
6312 while (getline(&line
, &len
, f
) != -1) {
6315 p
= strchr(line
, ':');
6321 p2
= strrchr(p
, ':');
6326 /* With cgroupv2 /proc/self/cgroup can contain entries of the
6327 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
6328 * because it parses out the empty string "" and later on passes
6329 * it to mount(). Let's skip such entries.
6331 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
6332 found_unified
= true;
6336 if (!store_hierarchy(line
, p
))
6340 /* Preserve initial namespace. */
6341 init_ns
= preserve_mnt_ns(getpid());
6343 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
6347 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
6348 if (!fd_hierarchies
) {
6349 lxcfs_error("%s\n", strerror(errno
));
6353 for (i
= 0; i
< num_hierarchies
; i
++)
6354 fd_hierarchies
[i
] = -1;
6356 cret
= getcwd(cwd
, MAXPATHLEN
);
6358 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
6360 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
6361 * to privately mount lxcfs cgroups. */
6362 if (!cgfs_setup_controllers()) {
6363 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
6367 if (setns(init_ns
, 0) < 0) {
6368 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
6372 if (!cret
|| chdir(cwd
) < 0)
6373 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
6375 if (!init_cpuview()) {
6376 lxcfs_error("%s\n", "failed to init CPU view");
6389 static void __attribute__((destructor
)) free_subsystems(void)
6393 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
6395 for (i
= 0; i
< num_hierarchies
; i
++) {
6397 free(hierarchies
[i
]);
6398 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
6399 close(fd_hierarchies
[i
]);
6402 free(fd_hierarchies
);
6405 if (cgroup_mount_ns_fd
>= 0)
6406 close(cgroup_mount_ns_fd
);