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