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