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