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