]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cgtop/cgtop.c
de25aaae5d1db02df04b08a60596ab30e139eb6d
[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 Iterator i;
586 Group *g;
587 Group **array;
588 signed path_columns;
589 unsigned rows, n = 0, j, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */
590 char buffer[MAX3(21, FORMAT_BYTES_MAX, FORMAT_TIMESPAN_MAX)];
591
592 assert(a);
593
594 if (!terminal_is_dumb())
595 fputs(ANSI_HOME_CLEAR, stdout);
596
597 array = newa(Group*, hashmap_size(a));
598
599 HASHMAP_FOREACH(g, a, i)
600 if (g->n_tasks_valid || g->cpu_valid || g->memory_valid || g->io_valid)
601 array[n++] = g;
602
603 typesafe_qsort(array, n, group_compare);
604
605 /* Find the longest names in one run */
606 for (j = 0; j < n; j++) {
607 unsigned cputlen, pathtlen;
608
609 format_timespan(buffer, sizeof(buffer), (usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0);
610 cputlen = strlen(buffer);
611 maxtcpu = MAX(maxtcpu, cputlen);
612
613 pathtlen = strlen(array[j]->path);
614 maxtpath = MAX(maxtpath, pathtlen);
615 }
616
617 if (arg_cpu_type == CPU_PERCENT)
618 xsprintf(buffer, "%6s", "%CPU");
619 else
620 xsprintf(buffer, "%*s", maxtcpu, "CPU Time");
621
622 rows = lines();
623 if (rows <= 10)
624 rows = 10;
625
626 if (on_tty()) {
627 const char *on, *off;
628
629 path_columns = columns() - 36 - strlen(buffer);
630 if (path_columns < 10)
631 path_columns = 10;
632
633 on = ansi_highlight_underline();
634 off = ansi_underline();
635
636 printf("%s%s%-*s%s %s%7s%s %s%s%s %s%8s%s %s%8s%s %s%8s%s%s\n",
637 ansi_underline(),
638 arg_order == ORDER_PATH ? on : "", path_columns, "Control Group",
639 arg_order == ORDER_PATH ? off : "",
640 arg_order == ORDER_TASKS ? on : "", arg_count == COUNT_PIDS ? "Tasks" : arg_count == COUNT_USERSPACE_PROCESSES ? "Procs" : "Proc+",
641 arg_order == ORDER_TASKS ? off : "",
642 arg_order == ORDER_CPU ? on : "", buffer,
643 arg_order == ORDER_CPU ? off : "",
644 arg_order == ORDER_MEMORY ? on : "", "Memory",
645 arg_order == ORDER_MEMORY ? off : "",
646 arg_order == ORDER_IO ? on : "", "Input/s",
647 arg_order == ORDER_IO ? off : "",
648 arg_order == ORDER_IO ? on : "", "Output/s",
649 arg_order == ORDER_IO ? off : "",
650 ansi_normal());
651 } else
652 path_columns = maxtpath;
653
654 for (j = 0; j < n; j++) {
655 _cleanup_free_ char *ellipsized = NULL;
656 const char *path;
657
658 if (on_tty() && j + 6 > rows)
659 break;
660
661 g = array[j];
662
663 path = empty_to_root(g->path);
664 ellipsized = ellipsize(path, path_columns, 33);
665 printf("%-*s", path_columns, ellipsized ?: path);
666
667 if (g->n_tasks_valid)
668 printf(" %7" PRIu64, g->n_tasks);
669 else
670 fputs(" -", stdout);
671
672 if (arg_cpu_type == CPU_PERCENT) {
673 if (g->cpu_valid)
674 printf(" %6.1f", g->cpu_fraction*100);
675 else
676 fputs(" -", stdout);
677 } else
678 printf(" %*s", maxtcpu, format_timespan(buffer, sizeof(buffer), (usec_t) (g->cpu_usage / NSEC_PER_USEC), 0));
679
680 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->memory_valid, g->memory));
681 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_input_bps));
682 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_output_bps));
683
684 putchar('\n');
685 }
686 }
687
688 static int help(void) {
689 _cleanup_free_ char *link = NULL;
690 int r;
691
692 r = terminal_urlify_man("systemd-cgtop", "1", &link);
693 if (r < 0)
694 return log_oom();
695
696 printf("%s [OPTIONS...] [CGROUP]\n\n"
697 "Show top control groups by their resource usage.\n\n"
698 " -h --help Show this help\n"
699 " --version Show package version\n"
700 " -p --order=path Order by path\n"
701 " -t --order=tasks Order by number of tasks/processes\n"
702 " -c --order=cpu Order by CPU load (default)\n"
703 " -m --order=memory Order by memory load\n"
704 " -i --order=io Order by IO load\n"
705 " -r --raw Provide raw (not human-readable) numbers\n"
706 " --cpu=percentage Show CPU usage as percentage (default)\n"
707 " --cpu=time Show CPU usage as time\n"
708 " -P Count userspace processes instead of tasks (excl. kernel)\n"
709 " -k Count all processes instead of tasks (incl. kernel)\n"
710 " --recursive=BOOL Sum up process count recursively\n"
711 " -d --delay=DELAY Delay between updates\n"
712 " -n --iterations=N Run for N iterations before exiting\n"
713 " -1 Shortcut for --iterations=1\n"
714 " -b --batch Run in batch mode, accepting no input\n"
715 " --depth=DEPTH Maximum traversal depth (default: %u)\n"
716 " -M --machine= Show container\n"
717 "\nSee the %s for details.\n"
718 , program_invocation_short_name
719 , arg_depth
720 , link
721 );
722
723 return 0;
724 }
725
726 static int parse_argv(int argc, char *argv[]) {
727 enum {
728 ARG_VERSION = 0x100,
729 ARG_DEPTH,
730 ARG_CPU_TYPE,
731 ARG_ORDER,
732 ARG_RECURSIVE,
733 };
734
735 static const struct option options[] = {
736 { "help", no_argument, NULL, 'h' },
737 { "version", no_argument, NULL, ARG_VERSION },
738 { "delay", required_argument, NULL, 'd' },
739 { "iterations", required_argument, NULL, 'n' },
740 { "batch", no_argument, NULL, 'b' },
741 { "raw", no_argument, NULL, 'r' },
742 { "depth", required_argument, NULL, ARG_DEPTH },
743 { "cpu", optional_argument, NULL, ARG_CPU_TYPE },
744 { "order", required_argument, NULL, ARG_ORDER },
745 { "recursive", required_argument, NULL, ARG_RECURSIVE },
746 { "machine", required_argument, NULL, 'M' },
747 {}
748 };
749
750 int c, r;
751
752 assert(argc >= 1);
753 assert(argv);
754
755 while ((c = getopt_long(argc, argv, "hptcmin:brd:kPM:1", options, NULL)) >= 0)
756
757 switch (c) {
758
759 case 'h':
760 return help();
761
762 case ARG_VERSION:
763 return version();
764
765 case ARG_CPU_TYPE:
766 if (optarg) {
767 if (streq(optarg, "time"))
768 arg_cpu_type = CPU_TIME;
769 else if (streq(optarg, "percentage"))
770 arg_cpu_type = CPU_PERCENT;
771 else
772 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
773 "Unknown argument to --cpu=: %s",
774 optarg);
775 } else
776 arg_cpu_type = CPU_TIME;
777
778 break;
779
780 case ARG_DEPTH:
781 r = safe_atou(optarg, &arg_depth);
782 if (r < 0)
783 return log_error_errno(r, "Failed to parse depth parameter '%s': %m", optarg);
784
785 break;
786
787 case 'd':
788 r = parse_sec(optarg, &arg_delay);
789 if (r < 0)
790 return log_error_errno(r, "Failed to parse delay parameter '%s': %m", optarg);
791 if (arg_delay <= 0)
792 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
793 "Invalid delay parameter '%s'",
794 optarg);
795
796 break;
797
798 case 'n':
799 r = safe_atou(optarg, &arg_iterations);
800 if (r < 0)
801 return log_error_errno(r, "Failed to parse iterations parameter '%s': %m", optarg);
802
803 break;
804
805 case '1':
806 arg_iterations = 1;
807 break;
808
809 case 'b':
810 arg_batch = true;
811 break;
812
813 case 'r':
814 arg_raw = true;
815 break;
816
817 case 'p':
818 arg_order = ORDER_PATH;
819 break;
820
821 case 't':
822 arg_order = ORDER_TASKS;
823 break;
824
825 case 'c':
826 arg_order = ORDER_CPU;
827 break;
828
829 case 'm':
830 arg_order = ORDER_MEMORY;
831 break;
832
833 case 'i':
834 arg_order = ORDER_IO;
835 break;
836
837 case ARG_ORDER:
838 if (streq(optarg, "path"))
839 arg_order = ORDER_PATH;
840 else if (streq(optarg, "tasks"))
841 arg_order = ORDER_TASKS;
842 else if (streq(optarg, "cpu"))
843 arg_order = ORDER_CPU;
844 else if (streq(optarg, "memory"))
845 arg_order = ORDER_MEMORY;
846 else if (streq(optarg, "io"))
847 arg_order = ORDER_IO;
848 else
849 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
850 "Invalid argument to --order=: %s",
851 optarg);
852 break;
853
854 case 'k':
855 arg_count = COUNT_ALL_PROCESSES;
856 break;
857
858 case 'P':
859 arg_count = COUNT_USERSPACE_PROCESSES;
860 break;
861
862 case ARG_RECURSIVE:
863 r = parse_boolean(optarg);
864 if (r < 0)
865 return log_error_errno(r, "Failed to parse --recursive= argument '%s': %m", optarg);
866
867 arg_recursive = r;
868 arg_recursive_unset = r == 0;
869 break;
870
871 case 'M':
872 arg_machine = optarg;
873 break;
874
875 case '?':
876 return -EINVAL;
877
878 default:
879 assert_not_reached("Unhandled option");
880 }
881
882 if (optind == argc - 1)
883 arg_root = argv[optind];
884 else if (optind < argc)
885 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
886 "Too many arguments.");
887
888 return 1;
889 }
890
891 static const char* counting_what(void) {
892 if (arg_count == COUNT_PIDS)
893 return "tasks";
894 else if (arg_count == COUNT_ALL_PROCESSES)
895 return "all processes (incl. kernel)";
896 else
897 return "userspace processes (excl. kernel)";
898 }
899
900 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(group_hash_ops, char, path_hash_func, path_compare, Group, group_free);
901
902 static int run(int argc, char *argv[]) {
903 _cleanup_hashmap_free_ Hashmap *a = NULL, *b = NULL;
904 unsigned iteration = 0;
905 usec_t last_refresh = 0;
906 bool quit = false, immediate_refresh = false;
907 _cleanup_free_ char *root = NULL;
908 CGroupMask mask;
909 int r;
910
911 log_show_color(true);
912 log_parse_environment();
913 log_open();
914
915 r = parse_argv(argc, argv);
916 if (r <= 0)
917 return r;
918
919 r = cg_mask_supported(&mask);
920 if (r < 0)
921 return log_error_errno(r, "Failed to determine supported controllers: %m");
922
923 arg_count = (mask & CGROUP_MASK_PIDS) ? COUNT_PIDS : COUNT_USERSPACE_PROCESSES;
924
925 if (arg_recursive_unset && arg_count == COUNT_PIDS)
926 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
927 "Non-recursive counting is only supported when counting processes, not tasks. Use -P or -k.");
928
929 r = show_cgroup_get_path_and_warn(arg_machine, arg_root, &root);
930 if (r < 0)
931 return log_error_errno(r, "Failed to get root control group path: %m");
932 log_debug("CGroup path: %s", root);
933
934 a = hashmap_new(&group_hash_ops);
935 b = hashmap_new(&group_hash_ops);
936 if (!a || !b)
937 return log_oom();
938
939 signal(SIGWINCH, columns_lines_cache_reset);
940
941 if (arg_iterations == (unsigned) -1)
942 arg_iterations = on_tty() ? 0 : 1;
943
944 while (!quit) {
945 usec_t t;
946 char key;
947 char h[FORMAT_TIMESPAN_MAX];
948
949 t = now(CLOCK_MONOTONIC);
950
951 if (t >= last_refresh + arg_delay || immediate_refresh) {
952
953 r = refresh(root, a, b, iteration++);
954 if (r < 0)
955 return log_error_errno(r, "Failed to refresh: %m");
956
957 hashmap_clear(b);
958 SWAP_TWO(a, b);
959
960 last_refresh = t;
961 immediate_refresh = false;
962 }
963
964 display(b);
965
966 if (arg_iterations && iteration >= arg_iterations)
967 break;
968
969 if (!on_tty()) /* non-TTY: Empty newline as delimiter between polls */
970 fputs("\n", stdout);
971 fflush(stdout);
972
973 if (arg_batch)
974 (void) usleep(last_refresh + arg_delay - t);
975 else {
976 r = read_one_char(stdin, &key, last_refresh + arg_delay - t, NULL);
977 if (r == -ETIMEDOUT)
978 continue;
979 if (r < 0)
980 return log_error_errno(r, "Couldn't read key: %m");
981 }
982
983 if (on_tty()) { /* TTY: Clear any user keystroke */
984 fputs("\r \r", stdout);
985 fflush(stdout);
986 }
987
988 if (arg_batch)
989 continue;
990
991 switch (key) {
992
993 case ' ':
994 immediate_refresh = true;
995 break;
996
997 case 'q':
998 quit = true;
999 break;
1000
1001 case 'p':
1002 arg_order = ORDER_PATH;
1003 break;
1004
1005 case 't':
1006 arg_order = ORDER_TASKS;
1007 break;
1008
1009 case 'c':
1010 arg_order = ORDER_CPU;
1011 break;
1012
1013 case 'm':
1014 arg_order = ORDER_MEMORY;
1015 break;
1016
1017 case 'i':
1018 arg_order = ORDER_IO;
1019 break;
1020
1021 case '%':
1022 arg_cpu_type = arg_cpu_type == CPU_TIME ? CPU_PERCENT : CPU_TIME;
1023 break;
1024
1025 case 'k':
1026 arg_count = arg_count != COUNT_ALL_PROCESSES ? COUNT_ALL_PROCESSES : COUNT_PIDS;
1027 fprintf(stdout, "\nCounting: %s.", counting_what());
1028 fflush(stdout);
1029 sleep(1);
1030 break;
1031
1032 case 'P':
1033 arg_count = arg_count != COUNT_USERSPACE_PROCESSES ? COUNT_USERSPACE_PROCESSES : COUNT_PIDS;
1034 fprintf(stdout, "\nCounting: %s.", counting_what());
1035 fflush(stdout);
1036 sleep(1);
1037 break;
1038
1039 case 'r':
1040 if (arg_count == COUNT_PIDS)
1041 fprintf(stdout, "\n\aCannot toggle recursive counting, not available in task counting mode.");
1042 else {
1043 arg_recursive = !arg_recursive;
1044 fprintf(stdout, "\nRecursive process counting: %s", yes_no(arg_recursive));
1045 }
1046 fflush(stdout);
1047 sleep(1);
1048 break;
1049
1050 case '+':
1051 if (arg_delay < USEC_PER_SEC)
1052 arg_delay += USEC_PER_MSEC*250;
1053 else
1054 arg_delay += USEC_PER_SEC;
1055
1056 fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
1057 fflush(stdout);
1058 sleep(1);
1059 break;
1060
1061 case '-':
1062 if (arg_delay <= USEC_PER_MSEC*500)
1063 arg_delay = USEC_PER_MSEC*250;
1064 else if (arg_delay < USEC_PER_MSEC*1250)
1065 arg_delay -= USEC_PER_MSEC*250;
1066 else
1067 arg_delay -= USEC_PER_SEC;
1068
1069 fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
1070 fflush(stdout);
1071 sleep(1);
1072 break;
1073
1074 case '?':
1075 case 'h':
1076
1077 #define ON ANSI_HIGHLIGHT
1078 #define OFF ANSI_NORMAL
1079
1080 fprintf(stdout,
1081 "\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"
1082 "\t<" ON "+" OFF "> Inc. delay; <" ON "-" OFF "> Dec. delay; <" ON "%%" OFF "> Toggle time; <" ON "SPACE" OFF "> Refresh\n"
1083 "\t<" ON "P" OFF "> Toggle count userspace processes; <" ON "k" OFF "> Toggle count all processes\n"
1084 "\t<" ON "r" OFF "> Count processes recursively; <" ON "q" OFF "> Quit");
1085 fflush(stdout);
1086 sleep(3);
1087 break;
1088
1089 default:
1090 if (key < ' ')
1091 fprintf(stdout, "\nUnknown key '\\x%x'. Ignoring.", key);
1092 else
1093 fprintf(stdout, "\nUnknown key '%c'. Ignoring.", key);
1094 fflush(stdout);
1095 sleep(1);
1096 break;
1097 }
1098 }
1099
1100 return 0;
1101 }
1102
1103 DEFINE_MAIN_FUNCTION(run);