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