]> git.proxmox.com Git - systemd.git/blame - src/cgtop/cgtop.c
New upstream version 249~rc1
[systemd.git] / src / cgtop / cgtop.c
CommitLineData
a032b68d 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
663996b3 2
6300502b 3#include <errno.h>
663996b3 4#include <getopt.h>
7035cd9e 5#include <signal.h>
6300502b
MP
6#include <stdint.h>
7#include <stdlib.h>
6300502b
MP
8#include <unistd.h>
9
10#include "sd-bus.h"
663996b3 11
db2df898 12#include "alloc-util.h"
6300502b
MP
13#include "bus-error.h"
14#include "bus-util.h"
2897b343 15#include "cgroup-show.h"
6300502b 16#include "cgroup-util.h"
db2df898 17#include "fd-util.h"
6300502b
MP
18#include "fileio.h"
19#include "hashmap.h"
6e866b33 20#include "main-func.h"
e1f67bc7 21#include "missing_sched.h"
3a6ce677 22#include "parse-argument.h"
db2df898 23#include "parse-util.h"
663996b3 24#include "path-util.h"
6e866b33 25#include "pretty-print.h"
d9dfd233 26#include "process-util.h"
1d42b86d 27#include "procfs-util.h"
bb4f798a 28#include "sort-util.h"
4c89c718 29#include "stdio-util.h"
1d42b86d 30#include "strv.h"
6300502b
MP
31#include "terminal-util.h"
32#include "unit-name.h"
98393f85 33#include "virt.h"
663996b3
MS
34
35typedef struct Group {
36 char *path;
37
38 bool n_tasks_valid:1;
39 bool cpu_valid:1;
40 bool memory_valid:1;
41 bool io_valid:1;
42
6300502b 43 uint64_t n_tasks;
663996b3
MS
44
45 unsigned cpu_iteration;
d9dfd233
MP
46 nsec_t cpu_usage;
47 nsec_t cpu_timestamp;
663996b3
MS
48 double cpu_fraction;
49
50 uint64_t memory;
51
52 unsigned io_iteration;
53 uint64_t io_input, io_output;
d9dfd233 54 nsec_t io_timestamp;
663996b3
MS
55 uint64_t io_input_bps, io_output_bps;
56} Group;
57
58static unsigned arg_depth = 3;
3a6ce677 59static unsigned arg_iterations = UINT_MAX;
663996b3 60static bool arg_batch = false;
86f210e9 61static bool arg_raw = false;
663996b3 62static usec_t arg_delay = 1*USEC_PER_SEC;
6300502b 63static char* arg_machine = NULL;
5a920b42 64static char* arg_root = NULL;
aa27b158 65static bool arg_recursive = true;
81c58355 66static bool arg_recursive_unset = false;
6300502b 67
aa27b158 68static enum {
6300502b
MP
69 COUNT_PIDS,
70 COUNT_USERSPACE_PROCESSES,
71 COUNT_ALL_PROCESSES,
72} arg_count = COUNT_PIDS;
663996b3
MS
73
74static enum {
75 ORDER_PATH,
76 ORDER_TASKS,
77 ORDER_CPU,
78 ORDER_MEMORY,
6300502b 79 ORDER_IO,
663996b3
MS
80} arg_order = ORDER_CPU;
81
82static enum {
83 CPU_PERCENT,
84 CPU_TIME,
85} arg_cpu_type = CPU_PERCENT;
86
6e866b33
MB
87static Group *group_free(Group *g) {
88 if (!g)
89 return NULL;
663996b3
MS
90
91 free(g->path);
6e866b33 92 return mfree(g);
663996b3
MS
93}
94
a032b68d
MB
95
96static const char *maybe_format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
97 if (arg_raw) {
98 snprintf(buf, l, USEC_FMT, t);
99 return buf;
100 }
101 return format_timespan(buf, l, t, accuracy);
102}
103
6300502b 104static const char *maybe_format_bytes(char *buf, size_t l, bool is_valid, uint64_t t) {
86f210e9
MP
105 if (!is_valid)
106 return "-";
107 if (arg_raw) {
81c58355 108 snprintf(buf, l, "%" PRIu64, t);
86f210e9
MP
109 return buf;
110 }
111 return format_bytes(buf, l, t);
112}
113
98393f85
MB
114static bool is_root_cgroup(const char *path) {
115
7c20daf6 116 /* Returns true if the specified path belongs to the root cgroup. The root cgroup is special on cgroup v2 as it
98393f85
MB
117 * carries only very few attributes in order not to export multiple truth about system state as most
118 * information is available elsewhere in /proc anyway. We need to be able to deal with that, and need to get
119 * our data from different sources in that case.
120 *
121 * There's one extra complication in all of this, though 😣: if the path to the cgroup indicates we are in the
122 * root cgroup this might actually not be the case, because cgroup namespacing might be in effect
f2dec872 123 * (CLONE_NEWCGROUP). Since there's no nice way to distinguish a real cgroup root from a fake namespaced one we
98393f85
MB
124 * do an explicit container check here, under the assumption that CLONE_NEWCGROUP is generally used when
125 * container managers are used too.
126 *
127 * Note that checking for a container environment is kinda ugly, since in theory people could use cgtop from
128 * inside a container where cgroup namespacing is turned off to watch the host system. However, that's mostly a
129 * theoretic usecase, and if people actually try all they'll lose is accounting for the top-level cgroup. Which
130 * isn't too bad. */
131
132 if (detect_container() > 0)
133 return false;
134
b012e921 135 return empty_or_root(path);
98393f85
MB
136}
137
d9dfd233
MP
138static int process(
139 const char *controller,
140 const char *path,
141 Hashmap *a,
142 Hashmap *b,
143 unsigned iteration,
144 Group **ret) {
145
663996b3 146 Group *g;
2897b343 147 int r, all_unified;
663996b3
MS
148
149 assert(controller);
150 assert(path);
151 assert(a);
152
2897b343
MP
153 all_unified = cg_all_unified();
154 if (all_unified < 0)
155 return all_unified;
156
663996b3
MS
157 g = hashmap_get(a, path);
158 if (!g) {
159 g = hashmap_get(b, path);
160 if (!g) {
161 g = new0(Group, 1);
162 if (!g)
163 return -ENOMEM;
164
165 g->path = strdup(path);
166 if (!g->path) {
167 group_free(g);
168 return -ENOMEM;
169 }
170
171 r = hashmap_put(a, g->path, g);
172 if (r < 0) {
173 group_free(g);
174 return r;
175 }
176 } else {
5eef597e
MP
177 r = hashmap_move_one(a, b, path);
178 if (r < 0)
179 return r;
d9dfd233 180
663996b3
MS
181 g->cpu_valid = g->memory_valid = g->io_valid = g->n_tasks_valid = false;
182 }
183 }
184
98393f85
MB
185 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER) &&
186 IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES)) {
d9dfd233
MP
187 _cleanup_fclose_ FILE *f = NULL;
188 pid_t pid;
663996b3 189
d9dfd233
MP
190 r = cg_enumerate_processes(controller, path, &f);
191 if (r == -ENOENT)
192 return 0;
193 if (r < 0)
194 return r;
663996b3 195
d9dfd233
MP
196 g->n_tasks = 0;
197 while (cg_read_pid(f, &pid) > 0) {
663996b3 198
6300502b 199 if (arg_count == COUNT_USERSPACE_PROCESSES && is_kernel_thread(pid) > 0)
d9dfd233 200 continue;
663996b3 201
d9dfd233
MP
202 g->n_tasks++;
203 }
663996b3 204
d9dfd233
MP
205 if (g->n_tasks > 0)
206 g->n_tasks_valid = true;
207
6300502b 208 } else if (streq(controller, "pids") && arg_count == COUNT_PIDS) {
6300502b 209
98393f85 210 if (is_root_cgroup(path)) {
1d42b86d
MB
211 r = procfs_tasks_get_current(&g->n_tasks);
212 if (r < 0)
213 return r;
214 } else {
215 _cleanup_free_ char *p = NULL, *v = NULL;
6300502b 216
1d42b86d
MB
217 r = cg_get_path(controller, path, "pids.current", &p);
218 if (r < 0)
219 return r;
6300502b 220
1d42b86d
MB
221 r = read_one_line_file(p, &v);
222 if (r == -ENOENT)
223 return 0;
224 if (r < 0)
225 return r;
226
227 r = safe_atou64(v, &g->n_tasks);
228 if (r < 0)
229 return r;
230 }
6300502b
MP
231
232 if (g->n_tasks > 0)
233 g->n_tasks_valid = true;
234
663996b3 235 } else if (streq(controller, "memory")) {
663996b3 236
98393f85 237 if (is_root_cgroup(path)) {
7c20daf6 238 r = procfs_memory_get_used(&g->memory);
98393f85
MB
239 if (r < 0)
240 return r;
241 } else {
242 _cleanup_free_ char *p = NULL, *v = NULL;
663996b3 243
98393f85
MB
244 if (all_unified)
245 r = cg_get_path(controller, path, "memory.current", &p);
246 else
247 r = cg_get_path(controller, path, "memory.usage_in_bytes", &p);
248 if (r < 0)
249 return r;
663996b3 250
98393f85
MB
251 r = read_one_line_file(p, &v);
252 if (r == -ENOENT)
253 return 0;
254 if (r < 0)
255 return r;
256
257 r = safe_atou64(v, &g->memory);
258 if (r < 0)
259 return r;
260 }
663996b3
MS
261
262 if (g->memory > 0)
263 g->memory_valid = true;
264
2897b343
MP
265 } else if ((streq(controller, "io") && all_unified) ||
266 (streq(controller, "blkio") && !all_unified)) {
d9dfd233
MP
267 _cleanup_fclose_ FILE *f = NULL;
268 _cleanup_free_ char *p = NULL;
663996b3 269 uint64_t wr = 0, rd = 0;
d9dfd233 270 nsec_t timestamp;
663996b3 271
2897b343 272 r = cg_get_path(controller, path, all_unified ? "io.stat" : "blkio.io_service_bytes", &p);
663996b3
MS
273 if (r < 0)
274 return r;
275
276 f = fopen(p, "re");
d9dfd233
MP
277 if (!f) {
278 if (errno == ENOENT)
279 return 0;
663996b3 280 return -errno;
d9dfd233 281 }
663996b3
MS
282
283 for (;;) {
6e866b33 284 _cleanup_free_ char *line = NULL;
663996b3 285 uint64_t k, *q;
6e866b33 286 char *l;
663996b3 287
6e866b33
MB
288 r = read_line(f, LONG_LINE_MAX, &line);
289 if (r < 0)
290 return r;
291 if (r == 0)
663996b3
MS
292 break;
293
aa27b158 294 /* Trim and skip the device */
663996b3
MS
295 l = strstrip(line);
296 l += strcspn(l, WHITESPACE);
297 l += strspn(l, WHITESPACE);
298
2897b343 299 if (all_unified) {
aa27b158
MP
300 while (!isempty(l)) {
301 if (sscanf(l, "rbytes=%" SCNu64, &k))
302 rd += k;
303 else if (sscanf(l, "wbytes=%" SCNu64, &k))
304 wr += k;
305
306 l += strcspn(l, WHITESPACE);
307 l += strspn(l, WHITESPACE);
308 }
309 } else {
310 if (first_word(l, "Read")) {
311 l += 4;
312 q = &rd;
313 } else if (first_word(l, "Write")) {
314 l += 5;
315 q = &wr;
316 } else
317 continue;
318
319 l += strspn(l, WHITESPACE);
320 r = safe_atou64(l, &k);
321 if (r < 0)
322 continue;
323
324 *q += k;
325 }
663996b3
MS
326 }
327
d9dfd233 328 timestamp = now_nsec(CLOCK_MONOTONIC);
663996b3
MS
329
330 if (g->io_iteration == iteration - 1) {
331 uint64_t x, yr, yw;
332
d9dfd233
MP
333 x = (uint64_t) (timestamp - g->io_timestamp);
334 if (x < 1)
335 x = 1;
663996b3 336
d9dfd233
MP
337 if (rd > g->io_input)
338 yr = rd - g->io_input;
339 else
340 yr = 0;
341
342 if (wr > g->io_output)
343 yw = wr - g->io_output;
344 else
345 yw = 0;
663996b3 346
d9dfd233 347 if (yr > 0 || yw > 0) {
663996b3
MS
348 g->io_input_bps = (yr * 1000000000ULL) / x;
349 g->io_output_bps = (yw * 1000000000ULL) / x;
350 g->io_valid = true;
663996b3
MS
351 }
352 }
353
354 g->io_input = rd;
355 g->io_output = wr;
d9dfd233 356 g->io_timestamp = timestamp;
663996b3 357 g->io_iteration = iteration;
bb4f798a
MB
358 } else if (STR_IN_SET(controller, "cpu", "cpuacct") || cpu_accounting_is_cheap()) {
359 _cleanup_free_ char *p = NULL, *v = NULL;
360 uint64_t new_usage;
361 nsec_t timestamp;
362
363 if (is_root_cgroup(path)) {
364 r = procfs_cpu_get_usage(&new_usage);
365 if (r < 0)
366 return r;
367 } else if (all_unified) {
368 _cleanup_free_ char *val = NULL;
369
370 if (!streq(controller, "cpu"))
371 return 0;
372
373 r = cg_get_keyed_attribute("cpu", path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
374 if (IN_SET(r, -ENOENT, -ENXIO))
375 return 0;
376 if (r < 0)
377 return r;
378
379 r = safe_atou64(val, &new_usage);
380 if (r < 0)
381 return r;
382
383 new_usage *= NSEC_PER_USEC;
384 } else {
385 if (!streq(controller, "cpuacct"))
386 return 0;
387
388 r = cg_get_path(controller, path, "cpuacct.usage", &p);
389 if (r < 0)
390 return r;
391
392 r = read_one_line_file(p, &v);
393 if (r == -ENOENT)
394 return 0;
395 if (r < 0)
396 return r;
397
398 r = safe_atou64(v, &new_usage);
399 if (r < 0)
400 return r;
401 }
402
403 timestamp = now_nsec(CLOCK_MONOTONIC);
404
405 if (g->cpu_iteration == iteration - 1 &&
406 (nsec_t) new_usage > g->cpu_usage) {
407
408 nsec_t x, y;
409
410 x = timestamp - g->cpu_timestamp;
411 if (x < 1)
412 x = 1;
413
414 y = (nsec_t) new_usage - g->cpu_usage;
415 g->cpu_fraction = (double) y / (double) x;
416 g->cpu_valid = true;
417 }
418
419 g->cpu_usage = (nsec_t) new_usage;
420 g->cpu_timestamp = timestamp;
421 g->cpu_iteration = iteration;
422
663996b3
MS
423 }
424
d9dfd233
MP
425 if (ret)
426 *ret = g;
427
663996b3
MS
428 return 0;
429}
430
431static int refresh_one(
432 const char *controller,
433 const char *path,
434 Hashmap *a,
435 Hashmap *b,
436 unsigned iteration,
d9dfd233
MP
437 unsigned depth,
438 Group **ret) {
663996b3 439
d9dfd233 440 _cleanup_closedir_ DIR *d = NULL;
aa27b158 441 Group *ours = NULL;
663996b3
MS
442 int r;
443
444 assert(controller);
445 assert(path);
446 assert(a);
447
448 if (depth > arg_depth)
449 return 0;
450
d9dfd233 451 r = process(controller, path, a, b, iteration, &ours);
663996b3
MS
452 if (r < 0)
453 return r;
454
455 r = cg_enumerate_subgroups(controller, path, &d);
d9dfd233
MP
456 if (r == -ENOENT)
457 return 0;
458 if (r < 0)
663996b3 459 return r;
663996b3
MS
460
461 for (;;) {
d9dfd233
MP
462 _cleanup_free_ char *fn = NULL, *p = NULL;
463 Group *child = NULL;
663996b3
MS
464
465 r = cg_read_subgroup(d, &fn);
d9dfd233
MP
466 if (r < 0)
467 return r;
468 if (r == 0)
469 break;
663996b3 470
f2dec872 471 p = path_join(path, fn);
d9dfd233
MP
472 if (!p)
473 return -ENOMEM;
663996b3 474
8b3d4ff0 475 path_simplify(p);
663996b3 476
d9dfd233 477 r = refresh_one(controller, p, a, b, iteration, depth + 1, &child);
663996b3 478 if (r < 0)
d9dfd233
MP
479 return r;
480
481 if (arg_recursive &&
6300502b 482 IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES) &&
d9dfd233
MP
483 child &&
484 child->n_tasks_valid &&
485 streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
486
487 /* Recursively sum up processes */
488
489 if (ours->n_tasks_valid)
490 ours->n_tasks += child->n_tasks;
491 else {
492 ours->n_tasks = child->n_tasks;
493 ours->n_tasks_valid = true;
494 }
495 }
663996b3
MS
496 }
497
d9dfd233
MP
498 if (ret)
499 *ret = ours;
663996b3 500
d9dfd233 501 return 1;
663996b3
MS
502}
503
d9dfd233 504static int refresh(const char *root, Hashmap *a, Hashmap *b, unsigned iteration) {
6e866b33 505 const char *c;
663996b3
MS
506 int r;
507
6e866b33
MB
508 FOREACH_STRING(c, SYSTEMD_CGROUP_CONTROLLER, "cpu", "cpuacct", "memory", "io", "blkio", "pids") {
509 r = refresh_one(c, root, a, b, iteration, 0, NULL);
510 if (r < 0)
511 return r;
512 }
d9dfd233 513
663996b3
MS
514 return 0;
515}
516
6e866b33
MB
517static int group_compare(Group * const *a, Group * const *b) {
518 const Group *x = *a, *y = *b;
519 int r;
663996b3 520
d9dfd233
MP
521 if (arg_order != ORDER_TASKS || arg_recursive) {
522 /* Let's make sure that the parent is always before
523 * the child. Except when ordering by tasks and
524 * recursive summing is off, since that is actually
525 * not accumulative for all children. */
526
b012e921 527 if (path_startswith(empty_to_root(y->path), empty_to_root(x->path)))
d9dfd233 528 return -1;
b012e921 529 if (path_startswith(empty_to_root(x->path), empty_to_root(y->path)))
d9dfd233
MP
530 return 1;
531 }
532
533 switch (arg_order) {
534
535 case ORDER_PATH:
536 break;
663996b3 537
d9dfd233 538 case ORDER_CPU:
663996b3
MS
539 if (arg_cpu_type == CPU_PERCENT) {
540 if (x->cpu_valid && y->cpu_valid) {
6e866b33
MB
541 r = CMP(y->cpu_fraction, x->cpu_fraction);
542 if (r != 0)
543 return r;
663996b3
MS
544 } else if (x->cpu_valid)
545 return -1;
546 else if (y->cpu_valid)
547 return 1;
548 } else {
6e866b33
MB
549 r = CMP(y->cpu_usage, x->cpu_usage);
550 if (r != 0)
551 return r;
663996b3 552 }
663996b3 553
d9dfd233 554 break;
663996b3 555
d9dfd233 556 case ORDER_TASKS:
663996b3 557 if (x->n_tasks_valid && y->n_tasks_valid) {
6e866b33
MB
558 r = CMP(y->n_tasks, x->n_tasks);
559 if (r != 0)
560 return r;
663996b3
MS
561 } else if (x->n_tasks_valid)
562 return -1;
563 else if (y->n_tasks_valid)
564 return 1;
663996b3 565
d9dfd233
MP
566 break;
567
568 case ORDER_MEMORY:
663996b3 569 if (x->memory_valid && y->memory_valid) {
6e866b33
MB
570 r = CMP(y->memory, x->memory);
571 if (r != 0)
572 return r;
663996b3
MS
573 } else if (x->memory_valid)
574 return -1;
575 else if (y->memory_valid)
576 return 1;
663996b3 577
d9dfd233
MP
578 break;
579
580 case ORDER_IO:
663996b3 581 if (x->io_valid && y->io_valid) {
6e866b33
MB
582 r = CMP(y->io_input_bps + y->io_output_bps, x->io_input_bps + x->io_output_bps);
583 if (r != 0)
584 return r;
663996b3
MS
585 } else if (x->io_valid)
586 return -1;
587 else if (y->io_valid)
588 return 1;
589 }
590
d9dfd233 591 return path_compare(x->path, y->path);
663996b3
MS
592}
593
d9dfd233 594static void display(Hashmap *a) {
663996b3
MS
595 Group *g;
596 Group **array;
597 signed path_columns;
e3bff60a 598 unsigned rows, n = 0, j, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */
a032b68d 599 char buffer[MAX4(21U, FORMAT_BYTES_MAX, FORMAT_TIMESPAN_MAX, DECIMAL_STR_MAX(usec_t))];
663996b3
MS
600
601 assert(a);
602
5a920b42 603 if (!terminal_is_dumb())
6300502b 604 fputs(ANSI_HOME_CLEAR, stdout);
663996b3 605
b012e921 606 array = newa(Group*, hashmap_size(a));
663996b3 607
a032b68d 608 HASHMAP_FOREACH(g, a)
663996b3
MS
609 if (g->n_tasks_valid || g->cpu_valid || g->memory_valid || g->io_valid)
610 array[n++] = g;
611
6e866b33 612 typesafe_qsort(array, n, group_compare);
663996b3
MS
613
614 /* Find the longest names in one run */
615 for (j = 0; j < n; j++) {
616 unsigned cputlen, pathtlen;
617
a032b68d 618 maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0);
663996b3
MS
619 cputlen = strlen(buffer);
620 maxtcpu = MAX(maxtcpu, cputlen);
d9dfd233 621
663996b3
MS
622 pathtlen = strlen(array[j]->path);
623 maxtpath = MAX(maxtpath, pathtlen);
624 }
625
626 if (arg_cpu_type == CPU_PERCENT)
4c89c718 627 xsprintf(buffer, "%6s", "%CPU");
663996b3 628 else
4c89c718 629 xsprintf(buffer, "%*s", maxtcpu, "CPU Time");
663996b3
MS
630
631 rows = lines();
632 if (rows <= 10)
633 rows = 10;
634
635 if (on_tty()) {
6300502b
MP
636 const char *on, *off;
637
663996b3
MS
638 path_columns = columns() - 36 - strlen(buffer);
639 if (path_columns < 10)
640 path_columns = 10;
641
6300502b
MP
642 on = ansi_highlight_underline();
643 off = ansi_underline();
644
645 printf("%s%s%-*s%s %s%7s%s %s%s%s %s%8s%s %s%8s%s %s%8s%s%s\n",
646 ansi_underline(),
647 arg_order == ORDER_PATH ? on : "", path_columns, "Control Group",
648 arg_order == ORDER_PATH ? off : "",
649 arg_order == ORDER_TASKS ? on : "", arg_count == COUNT_PIDS ? "Tasks" : arg_count == COUNT_USERSPACE_PROCESSES ? "Procs" : "Proc+",
650 arg_order == ORDER_TASKS ? off : "",
651 arg_order == ORDER_CPU ? on : "", buffer,
652 arg_order == ORDER_CPU ? off : "",
653 arg_order == ORDER_MEMORY ? on : "", "Memory",
654 arg_order == ORDER_MEMORY ? off : "",
655 arg_order == ORDER_IO ? on : "", "Input/s",
656 arg_order == ORDER_IO ? off : "",
657 arg_order == ORDER_IO ? on : "", "Output/s",
658 arg_order == ORDER_IO ? off : "",
659 ansi_normal());
663996b3
MS
660 } else
661 path_columns = maxtpath;
662
663 for (j = 0; j < n; j++) {
d9dfd233
MP
664 _cleanup_free_ char *ellipsized = NULL;
665 const char *path;
663996b3 666
6300502b 667 if (on_tty() && j + 6 > rows)
663996b3
MS
668 break;
669
670 g = array[j];
671
b012e921 672 path = empty_to_root(g->path);
d9dfd233
MP
673 ellipsized = ellipsize(path, path_columns, 33);
674 printf("%-*s", path_columns, ellipsized ?: path);
663996b3
MS
675
676 if (g->n_tasks_valid)
6300502b 677 printf(" %7" PRIu64, g->n_tasks);
663996b3
MS
678 else
679 fputs(" -", stdout);
680
681 if (arg_cpu_type == CPU_PERCENT) {
682 if (g->cpu_valid)
683 printf(" %6.1f", g->cpu_fraction*100);
684 else
685 fputs(" -", stdout);
686 } else
a032b68d 687 printf(" %*s", maxtcpu, maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (g->cpu_usage / NSEC_PER_USEC), 0));
663996b3 688
86f210e9
MP
689 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->memory_valid, g->memory));
690 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_input_bps));
691 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_output_bps));
663996b3
MS
692
693 putchar('\n');
694 }
663996b3
MS
695}
696
6e866b33
MB
697static int help(void) {
698 _cleanup_free_ char *link = NULL;
699 int r;
700
701 r = terminal_urlify_man("systemd-cgtop", "1", &link);
702 if (r < 0)
703 return log_oom();
704
5a920b42 705 printf("%s [OPTIONS...] [CGROUP]\n\n"
663996b3
MS
706 "Show top control groups by their resource usage.\n\n"
707 " -h --help Show this help\n"
d9dfd233
MP
708 " --version Show package version\n"
709 " -p --order=path Order by path\n"
6300502b 710 " -t --order=tasks Order by number of tasks/processes\n"
d9dfd233
MP
711 " -c --order=cpu Order by CPU load (default)\n"
712 " -m --order=memory Order by memory load\n"
713 " -i --order=io Order by IO load\n"
86f210e9 714 " -r --raw Provide raw (not human-readable) numbers\n"
d9dfd233
MP
715 " --cpu=percentage Show CPU usage as percentage (default)\n"
716 " --cpu=time Show CPU usage as time\n"
6300502b
MP
717 " -P Count userspace processes instead of tasks (excl. kernel)\n"
718 " -k Count all processes instead of tasks (incl. kernel)\n"
719 " --recursive=BOOL Sum up process count recursively\n"
663996b3
MS
720 " -d --delay=DELAY Delay between updates\n"
721 " -n --iterations=N Run for N iterations before exiting\n"
98393f85 722 " -1 Shortcut for --iterations=1\n"
663996b3 723 " -b --batch Run in batch mode, accepting no input\n"
5eef597e 724 " --depth=DEPTH Maximum traversal depth (default: %u)\n"
6300502b 725 " -M --machine= Show container\n"
3a6ce677
BR
726 "\nSee the %s for details.\n",
727 program_invocation_short_name,
728 arg_depth,
729 link);
6e866b33
MB
730
731 return 0;
663996b3
MS
732}
733
734static int parse_argv(int argc, char *argv[]) {
663996b3
MS
735 enum {
736 ARG_VERSION = 0x100,
737 ARG_DEPTH,
d9dfd233
MP
738 ARG_CPU_TYPE,
739 ARG_ORDER,
740 ARG_RECURSIVE,
663996b3
MS
741 };
742
743 static const struct option options[] = {
d9dfd233
MP
744 { "help", no_argument, NULL, 'h' },
745 { "version", no_argument, NULL, ARG_VERSION },
746 { "delay", required_argument, NULL, 'd' },
747 { "iterations", required_argument, NULL, 'n' },
748 { "batch", no_argument, NULL, 'b' },
749 { "raw", no_argument, NULL, 'r' },
750 { "depth", required_argument, NULL, ARG_DEPTH },
751 { "cpu", optional_argument, NULL, ARG_CPU_TYPE },
752 { "order", required_argument, NULL, ARG_ORDER },
753 { "recursive", required_argument, NULL, ARG_RECURSIVE },
6300502b 754 { "machine", required_argument, NULL, 'M' },
60f067b4 755 {}
663996b3
MS
756 };
757
d9dfd233 758 int c, r;
663996b3
MS
759
760 assert(argc >= 1);
761 assert(argv);
762
98393f85 763 while ((c = getopt_long(argc, argv, "hptcmin:brd:kPM:1", options, NULL)) >= 0)
663996b3
MS
764
765 switch (c) {
766
767 case 'h':
6e866b33 768 return help();
663996b3
MS
769
770 case ARG_VERSION:
6300502b 771 return version();
663996b3
MS
772
773 case ARG_CPU_TYPE:
774 if (optarg) {
d9dfd233 775 if (streq(optarg, "time"))
663996b3 776 arg_cpu_type = CPU_TIME;
d9dfd233 777 else if (streq(optarg, "percentage"))
663996b3 778 arg_cpu_type = CPU_PERCENT;
6e866b33
MB
779 else
780 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
781 "Unknown argument to --cpu=: %s",
782 optarg);
d9dfd233
MP
783 } else
784 arg_cpu_type = CPU_TIME;
785
663996b3
MS
786 break;
787
788 case ARG_DEPTH:
789 r = safe_atou(optarg, &arg_depth);
98393f85 790 if (r < 0)
6e866b33 791 return log_error_errno(r, "Failed to parse depth parameter '%s': %m", optarg);
663996b3
MS
792
793 break;
794
795 case 'd':
796 r = parse_sec(optarg, &arg_delay);
6e866b33
MB
797 if (r < 0)
798 return log_error_errno(r, "Failed to parse delay parameter '%s': %m", optarg);
799 if (arg_delay <= 0)
800 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
801 "Invalid delay parameter '%s'",
802 optarg);
663996b3
MS
803
804 break;
805
806 case 'n':
807 r = safe_atou(optarg, &arg_iterations);
98393f85 808 if (r < 0)
6e866b33 809 return log_error_errno(r, "Failed to parse iterations parameter '%s': %m", optarg);
663996b3
MS
810
811 break;
812
98393f85
MB
813 case '1':
814 arg_iterations = 1;
815 break;
816
663996b3
MS
817 case 'b':
818 arg_batch = true;
819 break;
820
86f210e9
MP
821 case 'r':
822 arg_raw = true;
823 break;
824
663996b3
MS
825 case 'p':
826 arg_order = ORDER_PATH;
827 break;
828
829 case 't':
830 arg_order = ORDER_TASKS;
831 break;
832
833 case 'c':
834 arg_order = ORDER_CPU;
835 break;
836
837 case 'm':
838 arg_order = ORDER_MEMORY;
839 break;
840
841 case 'i':
842 arg_order = ORDER_IO;
843 break;
844
d9dfd233
MP
845 case ARG_ORDER:
846 if (streq(optarg, "path"))
847 arg_order = ORDER_PATH;
848 else if (streq(optarg, "tasks"))
849 arg_order = ORDER_TASKS;
850 else if (streq(optarg, "cpu"))
851 arg_order = ORDER_CPU;
852 else if (streq(optarg, "memory"))
853 arg_order = ORDER_MEMORY;
854 else if (streq(optarg, "io"))
855 arg_order = ORDER_IO;
6e866b33
MB
856 else
857 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
858 "Invalid argument to --order=: %s",
859 optarg);
d9dfd233
MP
860 break;
861
862 case 'k':
6300502b
MP
863 arg_count = COUNT_ALL_PROCESSES;
864 break;
865
866 case 'P':
867 arg_count = COUNT_USERSPACE_PROCESSES;
d9dfd233
MP
868 break;
869
870 case ARG_RECURSIVE:
3a6ce677 871 r = parse_boolean_argument("--recursive=", optarg, &arg_recursive);
98393f85 872 if (r < 0)
3a6ce677 873 return r;
d9dfd233 874
3a6ce677 875 arg_recursive_unset = !r;
6300502b
MP
876 break;
877
878 case 'M':
879 arg_machine = optarg;
d9dfd233
MP
880 break;
881
663996b3
MS
882 case '?':
883 return -EINVAL;
884
885 default:
60f067b4 886 assert_not_reached("Unhandled option");
663996b3 887 }
663996b3 888
2897b343 889 if (optind == argc - 1)
5a920b42 890 arg_root = argv[optind];
6e866b33
MB
891 else if (optind < argc)
892 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
893 "Too many arguments.");
663996b3
MS
894
895 return 1;
896}
897
6300502b
MP
898static const char* counting_what(void) {
899 if (arg_count == COUNT_PIDS)
900 return "tasks";
901 else if (arg_count == COUNT_ALL_PROCESSES)
902 return "all processes (incl. kernel)";
903 else
904 return "userspace processes (excl. kernel)";
905}
906
e1f67bc7 907DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(group_hash_ops, char, path_hash_func, path_compare, Group, group_free);
6e866b33
MB
908
909static int run(int argc, char *argv[]) {
910 _cleanup_hashmap_free_ Hashmap *a = NULL, *b = NULL;
663996b3
MS
911 unsigned iteration = 0;
912 usec_t last_refresh = 0;
913 bool quit = false, immediate_refresh = false;
d9dfd233 914 _cleanup_free_ char *root = NULL;
6300502b 915 CGroupMask mask;
6e866b33 916 int r;
663996b3 917
3a6ce677 918 log_setup();
663996b3 919
81c58355
MB
920 r = parse_argv(argc, argv);
921 if (r <= 0)
6e866b33 922 return r;
81c58355 923
6300502b 924 r = cg_mask_supported(&mask);
6e866b33
MB
925 if (r < 0)
926 return log_error_errno(r, "Failed to determine supported controllers: %m");
6300502b
MP
927
928 arg_count = (mask & CGROUP_MASK_PIDS) ? COUNT_PIDS : COUNT_USERSPACE_PROCESSES;
929
bb4f798a
MB
930 if (arg_recursive_unset && arg_count == COUNT_PIDS)
931 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
932 "Non-recursive counting is only supported when counting processes, not tasks. Use -P or -k.");
663996b3 933
2897b343 934 r = show_cgroup_get_path_and_warn(arg_machine, arg_root, &root);
6e866b33
MB
935 if (r < 0)
936 return log_error_errno(r, "Failed to get root control group path: %m");
f2dec872 937 log_debug("CGroup path: %s", root);
d9dfd233 938
6e866b33
MB
939 a = hashmap_new(&group_hash_ops);
940 b = hashmap_new(&group_hash_ops);
941 if (!a || !b)
942 return log_oom();
663996b3
MS
943
944 signal(SIGWINCH, columns_lines_cache_reset);
945
3a6ce677 946 if (arg_iterations == UINT_MAX)
86f210e9 947 arg_iterations = on_tty() ? 0 : 1;
663996b3
MS
948
949 while (!quit) {
663996b3
MS
950 usec_t t;
951 char key;
952 char h[FORMAT_TIMESPAN_MAX];
953
954 t = now(CLOCK_MONOTONIC);
955
3a6ce677 956 if (t >= usec_add(last_refresh, arg_delay) || immediate_refresh) {
663996b3 957
d9dfd233 958 r = refresh(root, a, b, iteration++);
6e866b33
MB
959 if (r < 0)
960 return log_error_errno(r, "Failed to refresh: %m");
663996b3 961
6e866b33
MB
962 hashmap_clear(b);
963 SWAP_TWO(a, b);
663996b3
MS
964
965 last_refresh = t;
966 immediate_refresh = false;
967 }
968
d9dfd233 969 display(b);
663996b3
MS
970
971 if (arg_iterations && iteration >= arg_iterations)
972 break;
973
86f210e9
MP
974 if (!on_tty()) /* non-TTY: Empty newline as delimiter between polls */
975 fputs("\n", stdout);
976 fflush(stdout);
977
d9dfd233 978 if (arg_batch)
3a6ce677 979 (void) usleep(usec_add(usec_sub_unsigned(last_refresh, t), arg_delay));
d9dfd233 980 else {
3a6ce677 981 r = read_one_char(stdin, &key, usec_add(usec_sub_unsigned(last_refresh, t), arg_delay), NULL);
663996b3
MS
982 if (r == -ETIMEDOUT)
983 continue;
6e866b33
MB
984 if (r < 0)
985 return log_error_errno(r, "Couldn't read key: %m");
663996b3
MS
986 }
987
86f210e9
MP
988 if (on_tty()) { /* TTY: Clear any user keystroke */
989 fputs("\r \r", stdout);
990 fflush(stdout);
991 }
663996b3
MS
992
993 if (arg_batch)
994 continue;
995
996 switch (key) {
997
998 case ' ':
999 immediate_refresh = true;
1000 break;
1001
1002 case 'q':
1003 quit = true;
1004 break;
1005
1006 case 'p':
1007 arg_order = ORDER_PATH;
1008 break;
1009
1010 case 't':
1011 arg_order = ORDER_TASKS;
1012 break;
1013
1014 case 'c':
1015 arg_order = ORDER_CPU;
1016 break;
1017
1018 case 'm':
1019 arg_order = ORDER_MEMORY;
1020 break;
1021
1022 case 'i':
1023 arg_order = ORDER_IO;
1024 break;
1025
1026 case '%':
1027 arg_cpu_type = arg_cpu_type == CPU_TIME ? CPU_PERCENT : CPU_TIME;
1028 break;
1029
d9dfd233 1030 case 'k':
6300502b
MP
1031 arg_count = arg_count != COUNT_ALL_PROCESSES ? COUNT_ALL_PROCESSES : COUNT_PIDS;
1032 fprintf(stdout, "\nCounting: %s.", counting_what());
1033 fflush(stdout);
1034 sleep(1);
1035 break;
1036
1037 case 'P':
1038 arg_count = arg_count != COUNT_USERSPACE_PROCESSES ? COUNT_USERSPACE_PROCESSES : COUNT_PIDS;
1039 fprintf(stdout, "\nCounting: %s.", counting_what());
d9dfd233
MP
1040 fflush(stdout);
1041 sleep(1);
1042 break;
1043
1044 case 'r':
6300502b
MP
1045 if (arg_count == COUNT_PIDS)
1046 fprintf(stdout, "\n\aCannot toggle recursive counting, not available in task counting mode.");
1047 else {
1048 arg_recursive = !arg_recursive;
1049 fprintf(stdout, "\nRecursive process counting: %s", yes_no(arg_recursive));
1050 }
d9dfd233
MP
1051 fflush(stdout);
1052 sleep(1);
1053 break;
1054
663996b3 1055 case '+':
3a6ce677 1056 arg_delay = usec_add(arg_delay, arg_delay < USEC_PER_SEC ? USEC_PER_MSEC * 250 : USEC_PER_SEC);
663996b3
MS
1057
1058 fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
1059 fflush(stdout);
1060 sleep(1);
1061 break;
1062
1063 case '-':
1064 if (arg_delay <= USEC_PER_MSEC*500)
1065 arg_delay = USEC_PER_MSEC*250;
663996b3 1066 else
3a6ce677 1067 arg_delay = usec_sub_unsigned(arg_delay, arg_delay < USEC_PER_MSEC * 1250 ? USEC_PER_MSEC * 250 : USEC_PER_SEC);
663996b3
MS
1068
1069 fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
1070 fflush(stdout);
1071 sleep(1);
1072 break;
1073
1074 case '?':
1075 case 'h':
6300502b 1076
663996b3 1077 fprintf(stdout,
3a6ce677
BR
1078 "\t<%1$sp%2$s> By path; <%1$st%2$s> By tasks/procs; <%1$sc%2$s> By CPU; <%1$sm%2$s> By memory; <%1$si%2$s> By I/O\n"
1079 "\t<%1$s+%2$s> Inc. delay; <%1$s-%2$s> Dec. delay; <%1$s%%%2$s> Toggle time; <%1$sSPACE%2$s> Refresh\n"
1080 "\t<%1$sP%2$s> Toggle count userspace processes; <%1$sk%2$s> Toggle count all processes\n"
1081 "\t<%1$sr%2$s> Count processes recursively; <%1$sq%2$s> Quit",
1082 ansi_highlight(), ansi_normal());
663996b3
MS
1083 fflush(stdout);
1084 sleep(3);
1085 break;
1086
1087 default:
d9dfd233
MP
1088 if (key < ' ')
1089 fprintf(stdout, "\nUnknown key '\\x%x'. Ignoring.", key);
1090 else
1091 fprintf(stdout, "\nUnknown key '%c'. Ignoring.", key);
663996b3
MS
1092 fflush(stdout);
1093 sleep(1);
1094 break;
1095 }
1096 }
1097
6e866b33 1098 return 0;
663996b3 1099}
6e866b33
MB
1100
1101DEFINE_MAIN_FUNCTION(run);