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