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