]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/cgtop/cgtop.c
tree-wide: use UINT64_MAX or friends
[thirdparty/systemd.git] / src / cgtop / cgtop.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <getopt.h>
5 #include <signal.h>
6 #include <stdint.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9
10 #include "sd-bus.h"
11
12 #include "alloc-util.h"
13 #include "bus-error.h"
14 #include "bus-util.h"
15 #include "cgroup-show.h"
16 #include "cgroup-util.h"
17 #include "fd-util.h"
18 #include "fileio.h"
19 #include "hashmap.h"
20 #include "main-func.h"
21 #include "missing_sched.h"
22 #include "parse-argument.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "pretty-print.h"
26 #include "process-util.h"
27 #include "procfs-util.h"
28 #include "sort-util.h"
29 #include "stdio-util.h"
30 #include "strv.h"
31 #include "terminal-util.h"
32 #include "unit-name.h"
33 #include "virt.h"
34
35 typedef struct Group {
36 char *path;
37
38 bool n_tasks_valid:1;
39 bool cpu_valid:1;
40 bool memory_valid:1;
41 bool io_valid:1;
42
43 uint64_t n_tasks;
44
45 unsigned cpu_iteration;
46 nsec_t cpu_usage;
47 nsec_t cpu_timestamp;
48 double cpu_fraction;
49
50 uint64_t memory;
51
52 unsigned io_iteration;
53 uint64_t io_input, io_output;
54 nsec_t io_timestamp;
55 uint64_t io_input_bps, io_output_bps;
56 } Group;
57
58 static unsigned arg_depth = 3;
59 static unsigned arg_iterations = UINT_MAX;
60 static bool arg_batch = false;
61 static bool arg_raw = false;
62 static usec_t arg_delay = 1*USEC_PER_SEC;
63 static char* arg_machine = NULL;
64 static char* arg_root = NULL;
65 static bool arg_recursive = true;
66 static bool arg_recursive_unset = false;
67
68 static enum {
69 COUNT_PIDS,
70 COUNT_USERSPACE_PROCESSES,
71 COUNT_ALL_PROCESSES,
72 } arg_count = COUNT_PIDS;
73
74 static enum {
75 ORDER_PATH,
76 ORDER_TASKS,
77 ORDER_CPU,
78 ORDER_MEMORY,
79 ORDER_IO,
80 } arg_order = ORDER_CPU;
81
82 static enum {
83 CPU_PERCENT,
84 CPU_TIME,
85 } arg_cpu_type = CPU_PERCENT;
86
87 static Group *group_free(Group *g) {
88 if (!g)
89 return NULL;
90
91 free(g->path);
92 return mfree(g);
93 }
94
95
96 static const char *maybe_format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) {
97 if (arg_raw) {
98 snprintf(buf, l, USEC_FMT, t);
99 return buf;
100 }
101 return format_timespan(buf, l, t, accuracy);
102 }
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 cgroup v2 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 distinguish 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 (streq(controller, "memory")) {
236
237 if (is_root_cgroup(path)) {
238 r = procfs_memory_get_used(&g->memory);
239 if (r < 0)
240 return r;
241 } else {
242 _cleanup_free_ char *p = NULL, *v = NULL;
243
244 if (all_unified)
245 r = cg_get_path(controller, path, "memory.current", &p);
246 else
247 r = cg_get_path(controller, path, "memory.usage_in_bytes", &p);
248 if (r < 0)
249 return r;
250
251 r = read_one_line_file(p, &v);
252 if (r == -ENOENT)
253 return 0;
254 if (r < 0)
255 return r;
256
257 r = safe_atou64(v, &g->memory);
258 if (r < 0)
259 return r;
260 }
261
262 if (g->memory > 0)
263 g->memory_valid = true;
264
265 } else if ((streq(controller, "io") && all_unified) ||
266 (streq(controller, "blkio") && !all_unified)) {
267 _cleanup_fclose_ FILE *f = NULL;
268 _cleanup_free_ char *p = NULL;
269 uint64_t wr = 0, rd = 0;
270 nsec_t timestamp;
271
272 r = cg_get_path(controller, path, all_unified ? "io.stat" : "blkio.io_service_bytes", &p);
273 if (r < 0)
274 return r;
275
276 f = fopen(p, "re");
277 if (!f) {
278 if (errno == ENOENT)
279 return 0;
280 return -errno;
281 }
282
283 for (;;) {
284 _cleanup_free_ char *line = NULL;
285 uint64_t k, *q;
286 char *l;
287
288 r = read_line(f, LONG_LINE_MAX, &line);
289 if (r < 0)
290 return r;
291 if (r == 0)
292 break;
293
294 /* Trim and skip the device */
295 l = strstrip(line);
296 l += strcspn(l, WHITESPACE);
297 l += strspn(l, WHITESPACE);
298
299 if (all_unified) {
300 while (!isempty(l)) {
301 if (sscanf(l, "rbytes=%" SCNu64, &k))
302 rd += k;
303 else if (sscanf(l, "wbytes=%" SCNu64, &k))
304 wr += k;
305
306 l += strcspn(l, WHITESPACE);
307 l += strspn(l, WHITESPACE);
308 }
309 } else {
310 if (first_word(l, "Read")) {
311 l += 4;
312 q = &rd;
313 } else if (first_word(l, "Write")) {
314 l += 5;
315 q = &wr;
316 } else
317 continue;
318
319 l += strspn(l, WHITESPACE);
320 r = safe_atou64(l, &k);
321 if (r < 0)
322 continue;
323
324 *q += k;
325 }
326 }
327
328 timestamp = now_nsec(CLOCK_MONOTONIC);
329
330 if (g->io_iteration == iteration - 1) {
331 uint64_t x, yr, yw;
332
333 x = (uint64_t) (timestamp - g->io_timestamp);
334 if (x < 1)
335 x = 1;
336
337 if (rd > g->io_input)
338 yr = rd - g->io_input;
339 else
340 yr = 0;
341
342 if (wr > g->io_output)
343 yw = wr - g->io_output;
344 else
345 yw = 0;
346
347 if (yr > 0 || yw > 0) {
348 g->io_input_bps = (yr * 1000000000ULL) / x;
349 g->io_output_bps = (yw * 1000000000ULL) / x;
350 g->io_valid = true;
351 }
352 }
353
354 g->io_input = rd;
355 g->io_output = wr;
356 g->io_timestamp = timestamp;
357 g->io_iteration = iteration;
358 } else if (STR_IN_SET(controller, "cpu", "cpuacct") || cpu_accounting_is_cheap()) {
359 _cleanup_free_ char *p = NULL, *v = NULL;
360 uint64_t new_usage;
361 nsec_t timestamp;
362
363 if (is_root_cgroup(path)) {
364 r = procfs_cpu_get_usage(&new_usage);
365 if (r < 0)
366 return r;
367 } else if (all_unified) {
368 _cleanup_free_ char *val = NULL;
369
370 if (!streq(controller, "cpu"))
371 return 0;
372
373 r = cg_get_keyed_attribute("cpu", path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
374 if (IN_SET(r, -ENOENT, -ENXIO))
375 return 0;
376 if (r < 0)
377 return r;
378
379 r = safe_atou64(val, &new_usage);
380 if (r < 0)
381 return r;
382
383 new_usage *= NSEC_PER_USEC;
384 } else {
385 if (!streq(controller, "cpuacct"))
386 return 0;
387
388 r = cg_get_path(controller, path, "cpuacct.usage", &p);
389 if (r < 0)
390 return r;
391
392 r = read_one_line_file(p, &v);
393 if (r == -ENOENT)
394 return 0;
395 if (r < 0)
396 return r;
397
398 r = safe_atou64(v, &new_usage);
399 if (r < 0)
400 return r;
401 }
402
403 timestamp = now_nsec(CLOCK_MONOTONIC);
404
405 if (g->cpu_iteration == iteration - 1 &&
406 (nsec_t) new_usage > g->cpu_usage) {
407
408 nsec_t x, y;
409
410 x = timestamp - g->cpu_timestamp;
411 if (x < 1)
412 x = 1;
413
414 y = (nsec_t) new_usage - g->cpu_usage;
415 g->cpu_fraction = (double) y / (double) x;
416 g->cpu_valid = true;
417 }
418
419 g->cpu_usage = (nsec_t) new_usage;
420 g->cpu_timestamp = timestamp;
421 g->cpu_iteration = iteration;
422
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 = path_join(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 Group *g;
596 Group **array;
597 signed path_columns;
598 unsigned rows, n = 0, j, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */
599 char buffer[MAX4(21U, FORMAT_BYTES_MAX, FORMAT_TIMESPAN_MAX, DECIMAL_STR_MAX(usec_t))];
600
601 assert(a);
602
603 if (!terminal_is_dumb())
604 fputs(ANSI_HOME_CLEAR, stdout);
605
606 array = newa(Group*, hashmap_size(a));
607
608 HASHMAP_FOREACH(g, a)
609 if (g->n_tasks_valid || g->cpu_valid || g->memory_valid || g->io_valid)
610 array[n++] = g;
611
612 typesafe_qsort(array, n, group_compare);
613
614 /* Find the longest names in one run */
615 for (j = 0; j < n; j++) {
616 unsigned cputlen, pathtlen;
617
618 maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0);
619 cputlen = strlen(buffer);
620 maxtcpu = MAX(maxtcpu, cputlen);
621
622 pathtlen = strlen(array[j]->path);
623 maxtpath = MAX(maxtpath, pathtlen);
624 }
625
626 if (arg_cpu_type == CPU_PERCENT)
627 xsprintf(buffer, "%6s", "%CPU");
628 else
629 xsprintf(buffer, "%*s", maxtcpu, "CPU Time");
630
631 rows = lines();
632 if (rows <= 10)
633 rows = 10;
634
635 if (on_tty()) {
636 const char *on, *off;
637
638 path_columns = columns() - 36 - strlen(buffer);
639 if (path_columns < 10)
640 path_columns = 10;
641
642 on = ansi_highlight_underline();
643 off = ansi_underline();
644
645 printf("%s%s%-*s%s %s%7s%s %s%s%s %s%8s%s %s%8s%s %s%8s%s%s\n",
646 ansi_underline(),
647 arg_order == ORDER_PATH ? on : "", path_columns, "Control Group",
648 arg_order == ORDER_PATH ? off : "",
649 arg_order == ORDER_TASKS ? on : "", arg_count == COUNT_PIDS ? "Tasks" : arg_count == COUNT_USERSPACE_PROCESSES ? "Procs" : "Proc+",
650 arg_order == ORDER_TASKS ? off : "",
651 arg_order == ORDER_CPU ? on : "", buffer,
652 arg_order == ORDER_CPU ? off : "",
653 arg_order == ORDER_MEMORY ? on : "", "Memory",
654 arg_order == ORDER_MEMORY ? off : "",
655 arg_order == ORDER_IO ? on : "", "Input/s",
656 arg_order == ORDER_IO ? off : "",
657 arg_order == ORDER_IO ? on : "", "Output/s",
658 arg_order == ORDER_IO ? off : "",
659 ansi_normal());
660 } else
661 path_columns = maxtpath;
662
663 for (j = 0; j < n; j++) {
664 _cleanup_free_ char *ellipsized = NULL;
665 const char *path;
666
667 if (on_tty() && j + 6 > rows)
668 break;
669
670 g = array[j];
671
672 path = empty_to_root(g->path);
673 ellipsized = ellipsize(path, path_columns, 33);
674 printf("%-*s", path_columns, ellipsized ?: path);
675
676 if (g->n_tasks_valid)
677 printf(" %7" PRIu64, g->n_tasks);
678 else
679 fputs(" -", stdout);
680
681 if (arg_cpu_type == CPU_PERCENT) {
682 if (g->cpu_valid)
683 printf(" %6.1f", g->cpu_fraction*100);
684 else
685 fputs(" -", stdout);
686 } else
687 printf(" %*s", maxtcpu, maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (g->cpu_usage / NSEC_PER_USEC), 0));
688
689 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->memory_valid, g->memory));
690 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_input_bps));
691 printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_output_bps));
692
693 putchar('\n');
694 }
695 }
696
697 static int help(void) {
698 _cleanup_free_ char *link = NULL;
699 int r;
700
701 r = terminal_urlify_man("systemd-cgtop", "1", &link);
702 if (r < 0)
703 return log_oom();
704
705 printf("%s [OPTIONS...] [CGROUP]\n\n"
706 "Show top control groups by their resource usage.\n\n"
707 " -h --help Show this help\n"
708 " --version Show package version\n"
709 " -p --order=path Order by path\n"
710 " -t --order=tasks Order by number of tasks/processes\n"
711 " -c --order=cpu Order by CPU load (default)\n"
712 " -m --order=memory Order by memory load\n"
713 " -i --order=io Order by IO load\n"
714 " -r --raw Provide raw (not human-readable) numbers\n"
715 " --cpu=percentage Show CPU usage as percentage (default)\n"
716 " --cpu=time Show CPU usage as time\n"
717 " -P Count userspace processes instead of tasks (excl. kernel)\n"
718 " -k Count all processes instead of tasks (incl. kernel)\n"
719 " --recursive=BOOL Sum up process count recursively\n"
720 " -d --delay=DELAY Delay between updates\n"
721 " -n --iterations=N Run for N iterations before exiting\n"
722 " -1 Shortcut for --iterations=1\n"
723 " -b --batch Run in batch mode, accepting no input\n"
724 " --depth=DEPTH Maximum traversal depth (default: %u)\n"
725 " -M --machine= Show container\n"
726 "\nSee the %s for details.\n",
727 program_invocation_short_name,
728 arg_depth,
729 link);
730
731 return 0;
732 }
733
734 static int parse_argv(int argc, char *argv[]) {
735 enum {
736 ARG_VERSION = 0x100,
737 ARG_DEPTH,
738 ARG_CPU_TYPE,
739 ARG_ORDER,
740 ARG_RECURSIVE,
741 };
742
743 static const struct option options[] = {
744 { "help", no_argument, NULL, 'h' },
745 { "version", no_argument, NULL, ARG_VERSION },
746 { "delay", required_argument, NULL, 'd' },
747 { "iterations", required_argument, NULL, 'n' },
748 { "batch", no_argument, NULL, 'b' },
749 { "raw", no_argument, NULL, 'r' },
750 { "depth", required_argument, NULL, ARG_DEPTH },
751 { "cpu", optional_argument, NULL, ARG_CPU_TYPE },
752 { "order", required_argument, NULL, ARG_ORDER },
753 { "recursive", required_argument, NULL, ARG_RECURSIVE },
754 { "machine", required_argument, NULL, 'M' },
755 {}
756 };
757
758 int c, r;
759
760 assert(argc >= 1);
761 assert(argv);
762
763 while ((c = getopt_long(argc, argv, "hptcmin:brd:kPM:1", options, NULL)) >= 0)
764
765 switch (c) {
766
767 case 'h':
768 return help();
769
770 case ARG_VERSION:
771 return version();
772
773 case ARG_CPU_TYPE:
774 if (optarg) {
775 if (streq(optarg, "time"))
776 arg_cpu_type = CPU_TIME;
777 else if (streq(optarg, "percentage"))
778 arg_cpu_type = CPU_PERCENT;
779 else
780 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
781 "Unknown argument to --cpu=: %s",
782 optarg);
783 } else
784 arg_cpu_type = CPU_TIME;
785
786 break;
787
788 case ARG_DEPTH:
789 r = safe_atou(optarg, &arg_depth);
790 if (r < 0)
791 return log_error_errno(r, "Failed to parse depth parameter '%s': %m", optarg);
792
793 break;
794
795 case 'd':
796 r = parse_sec(optarg, &arg_delay);
797 if (r < 0)
798 return log_error_errno(r, "Failed to parse delay parameter '%s': %m", optarg);
799 if (arg_delay <= 0)
800 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
801 "Invalid delay parameter '%s'",
802 optarg);
803
804 break;
805
806 case 'n':
807 r = safe_atou(optarg, &arg_iterations);
808 if (r < 0)
809 return log_error_errno(r, "Failed to parse iterations parameter '%s': %m", optarg);
810
811 break;
812
813 case '1':
814 arg_iterations = 1;
815 break;
816
817 case 'b':
818 arg_batch = true;
819 break;
820
821 case 'r':
822 arg_raw = true;
823 break;
824
825 case 'p':
826 arg_order = ORDER_PATH;
827 break;
828
829 case 't':
830 arg_order = ORDER_TASKS;
831 break;
832
833 case 'c':
834 arg_order = ORDER_CPU;
835 break;
836
837 case 'm':
838 arg_order = ORDER_MEMORY;
839 break;
840
841 case 'i':
842 arg_order = ORDER_IO;
843 break;
844
845 case ARG_ORDER:
846 if (streq(optarg, "path"))
847 arg_order = ORDER_PATH;
848 else if (streq(optarg, "tasks"))
849 arg_order = ORDER_TASKS;
850 else if (streq(optarg, "cpu"))
851 arg_order = ORDER_CPU;
852 else if (streq(optarg, "memory"))
853 arg_order = ORDER_MEMORY;
854 else if (streq(optarg, "io"))
855 arg_order = ORDER_IO;
856 else
857 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
858 "Invalid argument to --order=: %s",
859 optarg);
860 break;
861
862 case 'k':
863 arg_count = COUNT_ALL_PROCESSES;
864 break;
865
866 case 'P':
867 arg_count = COUNT_USERSPACE_PROCESSES;
868 break;
869
870 case ARG_RECURSIVE:
871 r = parse_boolean_argument("--recursive=", optarg, &arg_recursive);
872 if (r < 0)
873 return r;
874
875 arg_recursive_unset = !r;
876 break;
877
878 case 'M':
879 arg_machine = optarg;
880 break;
881
882 case '?':
883 return -EINVAL;
884
885 default:
886 assert_not_reached("Unhandled option");
887 }
888
889 if (optind == argc - 1)
890 arg_root = argv[optind];
891 else if (optind < argc)
892 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
893 "Too many arguments.");
894
895 return 1;
896 }
897
898 static const char* counting_what(void) {
899 if (arg_count == COUNT_PIDS)
900 return "tasks";
901 else if (arg_count == COUNT_ALL_PROCESSES)
902 return "all processes (incl. kernel)";
903 else
904 return "userspace processes (excl. kernel)";
905 }
906
907 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(group_hash_ops, char, path_hash_func, path_compare, Group, group_free);
908
909 static int run(int argc, char *argv[]) {
910 _cleanup_hashmap_free_ Hashmap *a = NULL, *b = NULL;
911 unsigned iteration = 0;
912 usec_t last_refresh = 0;
913 bool quit = false, immediate_refresh = false;
914 _cleanup_free_ char *root = NULL;
915 CGroupMask mask;
916 int r;
917
918 log_setup();
919
920 r = parse_argv(argc, argv);
921 if (r <= 0)
922 return r;
923
924 r = cg_mask_supported(&mask);
925 if (r < 0)
926 return log_error_errno(r, "Failed to determine supported controllers: %m");
927
928 arg_count = (mask & CGROUP_MASK_PIDS) ? COUNT_PIDS : COUNT_USERSPACE_PROCESSES;
929
930 if (arg_recursive_unset && arg_count == COUNT_PIDS)
931 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
932 "Non-recursive counting is only supported when counting processes, not tasks. Use -P or -k.");
933
934 r = show_cgroup_get_path_and_warn(arg_machine, arg_root, &root);
935 if (r < 0)
936 return log_error_errno(r, "Failed to get root control group path: %m");
937 log_debug("CGroup path: %s", root);
938
939 a = hashmap_new(&group_hash_ops);
940 b = hashmap_new(&group_hash_ops);
941 if (!a || !b)
942 return log_oom();
943
944 signal(SIGWINCH, columns_lines_cache_reset);
945
946 if (arg_iterations == UINT_MAX)
947 arg_iterations = on_tty() ? 0 : 1;
948
949 while (!quit) {
950 usec_t t;
951 char key;
952 char h[FORMAT_TIMESPAN_MAX];
953
954 t = now(CLOCK_MONOTONIC);
955
956 if (t >= usec_add(last_refresh, arg_delay) || immediate_refresh) {
957
958 r = refresh(root, a, b, iteration++);
959 if (r < 0)
960 return log_error_errno(r, "Failed to refresh: %m");
961
962 hashmap_clear(b);
963 SWAP_TWO(a, b);
964
965 last_refresh = t;
966 immediate_refresh = false;
967 }
968
969 display(b);
970
971 if (arg_iterations && iteration >= arg_iterations)
972 break;
973
974 if (!on_tty()) /* non-TTY: Empty newline as delimiter between polls */
975 fputs("\n", stdout);
976 fflush(stdout);
977
978 if (arg_batch)
979 (void) usleep(usec_add(usec_sub_unsigned(last_refresh, t), arg_delay));
980 else {
981 r = read_one_char(stdin, &key, usec_add(usec_sub_unsigned(last_refresh, t), arg_delay), NULL);
982 if (r == -ETIMEDOUT)
983 continue;
984 if (r < 0)
985 return log_error_errno(r, "Couldn't read key: %m");
986 }
987
988 if (on_tty()) { /* TTY: Clear any user keystroke */
989 fputs("\r \r", stdout);
990 fflush(stdout);
991 }
992
993 if (arg_batch)
994 continue;
995
996 switch (key) {
997
998 case ' ':
999 immediate_refresh = true;
1000 break;
1001
1002 case 'q':
1003 quit = true;
1004 break;
1005
1006 case 'p':
1007 arg_order = ORDER_PATH;
1008 break;
1009
1010 case 't':
1011 arg_order = ORDER_TASKS;
1012 break;
1013
1014 case 'c':
1015 arg_order = ORDER_CPU;
1016 break;
1017
1018 case 'm':
1019 arg_order = ORDER_MEMORY;
1020 break;
1021
1022 case 'i':
1023 arg_order = ORDER_IO;
1024 break;
1025
1026 case '%':
1027 arg_cpu_type = arg_cpu_type == CPU_TIME ? CPU_PERCENT : CPU_TIME;
1028 break;
1029
1030 case 'k':
1031 arg_count = arg_count != COUNT_ALL_PROCESSES ? COUNT_ALL_PROCESSES : COUNT_PIDS;
1032 fprintf(stdout, "\nCounting: %s.", counting_what());
1033 fflush(stdout);
1034 sleep(1);
1035 break;
1036
1037 case 'P':
1038 arg_count = arg_count != COUNT_USERSPACE_PROCESSES ? COUNT_USERSPACE_PROCESSES : COUNT_PIDS;
1039 fprintf(stdout, "\nCounting: %s.", counting_what());
1040 fflush(stdout);
1041 sleep(1);
1042 break;
1043
1044 case 'r':
1045 if (arg_count == COUNT_PIDS)
1046 fprintf(stdout, "\n\aCannot toggle recursive counting, not available in task counting mode.");
1047 else {
1048 arg_recursive = !arg_recursive;
1049 fprintf(stdout, "\nRecursive process counting: %s", yes_no(arg_recursive));
1050 }
1051 fflush(stdout);
1052 sleep(1);
1053 break;
1054
1055 case '+':
1056 arg_delay = usec_add(arg_delay, arg_delay < USEC_PER_SEC ? USEC_PER_MSEC * 250 : USEC_PER_SEC);
1057
1058 fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
1059 fflush(stdout);
1060 sleep(1);
1061 break;
1062
1063 case '-':
1064 if (arg_delay <= USEC_PER_MSEC*500)
1065 arg_delay = USEC_PER_MSEC*250;
1066 else
1067 arg_delay = usec_sub_unsigned(arg_delay, arg_delay < USEC_PER_MSEC * 1250 ? USEC_PER_MSEC * 250 : 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 fprintf(stdout,
1078 "\t<%1$sp%2$s> By path; <%1$st%2$s> By tasks/procs; <%1$sc%2$s> By CPU; <%1$sm%2$s> By memory; <%1$si%2$s> By I/O\n"
1079 "\t<%1$s+%2$s> Inc. delay; <%1$s-%2$s> Dec. delay; <%1$s%%%2$s> Toggle time; <%1$sSPACE%2$s> Refresh\n"
1080 "\t<%1$sP%2$s> Toggle count userspace processes; <%1$sk%2$s> Toggle count all processes\n"
1081 "\t<%1$sr%2$s> Count processes recursively; <%1$sq%2$s> Quit",
1082 ansi_highlight(), ansi_normal());
1083 fflush(stdout);
1084 sleep(3);
1085 break;
1086
1087 default:
1088 if (key < ' ')
1089 fprintf(stdout, "\nUnknown key '\\x%x'. Ignoring.", key);
1090 else
1091 fprintf(stdout, "\nUnknown key '%c'. Ignoring.", key);
1092 fflush(stdout);
1093 sleep(1);
1094 break;
1095 }
1096 }
1097
1098 return 0;
1099 }
1100
1101 DEFINE_MAIN_FUNCTION(run);