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