]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/cgtop/cgtop.c
sd-bus: make strict asan shut up
[thirdparty/systemd.git] / src / cgtop / cgtop.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
8f2d43a0 2
8f2d43a0 3#include <alloca.h>
3f6fd1ba 4#include <errno.h>
8f2d43a0 5#include <getopt.h>
97b845b0 6#include <signal.h>
3f6fd1ba
LP
7#include <stdint.h>
8#include <stdlib.h>
9#include <string.h>
10#include <unistd.h>
8f2d43a0 11
96a6426f 12#include "sd-bus.h"
3f6fd1ba 13
b5efdb8a 14#include "alloc-util.h"
96a6426f 15#include "bus-error.h"
3f6fd1ba 16#include "bus-util.h"
d3e8277d 17#include "cgroup-show.h"
3f6fd1ba 18#include "cgroup-util.h"
3ffd4af2 19#include "fd-util.h"
3f6fd1ba
LP
20#include "fileio.h"
21#include "hashmap.h"
6bedfcbb 22#include "parse-util.h"
3f6fd1ba
LP
23#include "path-util.h"
24#include "process-util.h"
fe37a784 25#include "procfs-util.h"
d054f0a4 26#include "stdio-util.h"
e104fb80 27#include "strv.h"
3f6fd1ba 28#include "terminal-util.h"
96a6426f 29#include "unit-name.h"
3f6fd1ba 30#include "util.h"
ba4b1544 31#include "virt.h"
8f2d43a0
LP
32
33typedef 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
03a7b521 41 uint64_t n_tasks;
8f2d43a0
LP
42
43 unsigned cpu_iteration;
45d7a8bb
LP
44 nsec_t cpu_usage;
45 nsec_t cpu_timestamp;
8f2d43a0
LP
46 double cpu_fraction;
47
48 uint64_t memory;
49
50 unsigned io_iteration;
51 uint64_t io_input, io_output;
45d7a8bb 52 nsec_t io_timestamp;
8f2d43a0
LP
53 uint64_t io_input_bps, io_output_bps;
54} Group;
55
30edf116 56static unsigned arg_depth = 3;
45d7a8bb 57static unsigned arg_iterations = (unsigned) -1;
e66bb58b 58static bool arg_batch = false;
a2c9f631 59static bool arg_raw = false;
8f2d43a0 60static usec_t arg_delay = 1*USEC_PER_SEC;
96a6426f 61static char* arg_machine = NULL;
308253c5 62static char* arg_root = NULL;
dd422d1e 63static bool arg_recursive = true;
6d9f40d5 64static bool arg_recursive_unset = false;
03a7b521 65
dd422d1e 66static enum {
03a7b521
LP
67 COUNT_PIDS,
68 COUNT_USERSPACE_PROCESSES,
69 COUNT_ALL_PROCESSES,
70} arg_count = COUNT_PIDS;
8f2d43a0
LP
71
72static enum {
73 ORDER_PATH,
74 ORDER_TASKS,
75 ORDER_CPU,
76 ORDER_MEMORY,
03a7b521 77 ORDER_IO,
8f2d43a0
LP
78} arg_order = ORDER_CPU;
79
1e913bcb
UTL
80static enum {
81 CPU_PERCENT,
82 CPU_TIME,
83} arg_cpu_type = CPU_PERCENT;
84
8f2d43a0
LP
85static void group_free(Group *g) {
86 assert(g);
87
88 free(g->path);
89 free(g);
90}
91
92static void group_hashmap_clear(Hashmap *h) {
224b0e7a 93 hashmap_clear_with_destructor(h, group_free);
8f2d43a0
LP
94}
95
96static void group_hashmap_free(Hashmap *h) {
97 group_hashmap_clear(h);
98 hashmap_free(h);
99}
100
59f448cf 101static const char *maybe_format_bytes(char *buf, size_t l, bool is_valid, uint64_t t) {
a2c9f631
CD
102 if (!is_valid)
103 return "-";
104 if (arg_raw) {
557e3693 105 snprintf(buf, l, "%" PRIu64, t);
a2c9f631
CD
106 return buf;
107 }
108 return format_bytes(buf, l, t);
109}
110
a7e6de21 111static bool is_root_cgroup(const char *path) {
ba4b1544
LP
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
57ea45e1 132 return empty_or_root(path);
a7e6de21
LP
133}
134
3cb5beea
LP
135static int process(
136 const char *controller,
137 const char *path,
138 Hashmap *a,
139 Hashmap *b,
140 unsigned iteration,
141 Group **ret) {
142
8f2d43a0 143 Group *g;
b4cccbc1 144 int r, all_unified;
8f2d43a0
LP
145
146 assert(controller);
147 assert(path);
148 assert(a);
149
b4cccbc1
LP
150 all_unified = cg_all_unified();
151 if (all_unified < 0)
152 return all_unified;
153
8f2d43a0
LP
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 {
2d5c93c7
MS
174 r = hashmap_move_one(a, b, path);
175 if (r < 0)
176 return r;
45d7a8bb 177
8f2d43a0
LP
178 g->cpu_valid = g->memory_valid = g->io_valid = g->n_tasks_valid = false;
179 }
180 }
181
ba4b1544
LP
182 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER) &&
183 IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES)) {
45d7a8bb
LP
184 _cleanup_fclose_ FILE *f = NULL;
185 pid_t pid;
8f2d43a0 186
45d7a8bb
LP
187 r = cg_enumerate_processes(controller, path, &f);
188 if (r == -ENOENT)
189 return 0;
190 if (r < 0)
191 return r;
8f2d43a0 192
45d7a8bb 193 g->n_tasks = 0;
41ba8b6e
LP
194 while (cg_read_pid(f, &pid) > 0) {
195
03a7b521 196 if (arg_count == COUNT_USERSPACE_PROCESSES && is_kernel_thread(pid) > 0)
41ba8b6e
LP
197 continue;
198
45d7a8bb 199 g->n_tasks++;
41ba8b6e 200 }
8f2d43a0 201
45d7a8bb
LP
202 if (g->n_tasks > 0)
203 g->n_tasks_valid = true;
8f2d43a0 204
03a7b521 205 } else if (streq(controller, "pids") && arg_count == COUNT_PIDS) {
03a7b521 206
a7e6de21 207 if (is_root_cgroup(path)) {
fe37a784
LP
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;
03a7b521 213
fe37a784
LP
214 r = cg_get_path(controller, path, "pids.current", &p);
215 if (r < 0)
216 return r;
03a7b521 217
fe37a784
LP
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 }
03a7b521
LP
228
229 if (g->n_tasks > 0)
230 g->n_tasks_valid = true;
231
e104fb80 232 } else if (STR_IN_SET(controller, "cpu", "cpuacct")) {
45d7a8bb 233 _cleanup_free_ char *p = NULL, *v = NULL;
8f2d43a0 234 uint64_t new_usage;
45d7a8bb 235 nsec_t timestamp;
8f2d43a0 236
744c39ff
LP
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) {
66ebf6c0 242 _cleanup_free_ char *val = NULL;
8f2d43a0 243
66ebf6c0
TH
244 if (!streq(controller, "cpu"))
245 return 0;
8f2d43a0 246
b734a4ff
LP
247 r = cg_get_keyed_attribute("cpu", path, "cpu.stat", STRV_MAKE("usage_usec"), &val);
248 if (IN_SET(r, -ENOENT, -ENXIO))
66ebf6c0
TH
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 }
8f2d43a0 276
45d7a8bb 277 timestamp = now_nsec(CLOCK_MONOTONIC);
8f2d43a0 278
45d7a8bb
LP
279 if (g->cpu_iteration == iteration - 1 &&
280 (nsec_t) new_usage > g->cpu_usage) {
8f2d43a0 281
45d7a8bb 282 nsec_t x, y;
8f2d43a0 283
45d7a8bb
LP
284 x = timestamp - g->cpu_timestamp;
285 if (x < 1)
286 x = 1;
8f2d43a0 287
45d7a8bb
LP
288 y = (nsec_t) new_usage - g->cpu_usage;
289 g->cpu_fraction = (double) y / (double) x;
290 g->cpu_valid = true;
8f2d43a0
LP
291 }
292
45d7a8bb
LP
293 g->cpu_usage = (nsec_t) new_usage;
294 g->cpu_timestamp = timestamp;
8f2d43a0
LP
295 g->cpu_iteration = iteration;
296
297 } else if (streq(controller, "memory")) {
8f2d43a0 298
744c39ff
LP
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;
8f2d43a0 305
744c39ff
LP
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;
8f2d43a0 312
744c39ff
LP
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 }
8f2d43a0
LP
323
324 if (g->memory > 0)
325 g->memory_valid = true;
326
b4cccbc1
LP
327 } else if ((streq(controller, "io") && all_unified) ||
328 (streq(controller, "blkio") && !all_unified)) {
45d7a8bb
LP
329 _cleanup_fclose_ FILE *f = NULL;
330 _cleanup_free_ char *p = NULL;
8f2d43a0 331 uint64_t wr = 0, rd = 0;
45d7a8bb 332 nsec_t timestamp;
8f2d43a0 333
b4cccbc1 334 r = cg_get_path(controller, path, all_unified ? "io.stat" : "blkio.io_service_bytes", &p);
8f2d43a0
LP
335 if (r < 0)
336 return r;
337
338 f = fopen(p, "re");
45d7a8bb
LP
339 if (!f) {
340 if (errno == ENOENT)
341 return 0;
8f2d43a0 342 return -errno;
45d7a8bb 343 }
8f2d43a0
LP
344
345 for (;;) {
717e419b 346 _cleanup_free_ char *line = NULL;
8f2d43a0 347 uint64_t k, *q;
717e419b 348 char *l;
8f2d43a0 349
717e419b
LP
350 r = read_line(f, LONG_LINE_MAX, &line);
351 if (r < 0)
352 return r;
353 if (r == 0)
8f2d43a0
LP
354 break;
355
13c31542 356 /* Trim and skip the device */
8f2d43a0
LP
357 l = strstrip(line);
358 l += strcspn(l, WHITESPACE);
359 l += strspn(l, WHITESPACE);
360
b4cccbc1 361 if (all_unified) {
13c31542
TH
362 while (!isempty(l)) {
363 if (sscanf(l, "rbytes=%" SCNu64, &k))
364 rd += k;
365 else if (sscanf(l, "wbytes=%" SCNu64, &k))
366 wr += k;
367
368 l += strcspn(l, WHITESPACE);
369 l += strspn(l, WHITESPACE);
370 }
371 } else {
372 if (first_word(l, "Read")) {
373 l += 4;
374 q = &rd;
375 } else if (first_word(l, "Write")) {
376 l += 5;
377 q = &wr;
378 } else
379 continue;
380
381 l += strspn(l, WHITESPACE);
382 r = safe_atou64(l, &k);
383 if (r < 0)
384 continue;
385
386 *q += k;
387 }
8f2d43a0
LP
388 }
389
45d7a8bb 390 timestamp = now_nsec(CLOCK_MONOTONIC);
8f2d43a0
LP
391
392 if (g->io_iteration == iteration - 1) {
393 uint64_t x, yr, yw;
394
45d7a8bb
LP
395 x = (uint64_t) (timestamp - g->io_timestamp);
396 if (x < 1)
397 x = 1;
8f2d43a0 398
45d7a8bb
LP
399 if (rd > g->io_input)
400 yr = rd - g->io_input;
401 else
402 yr = 0;
403
404 if (wr > g->io_output)
405 yw = wr - g->io_output;
406 else
407 yw = 0;
8f2d43a0 408
45d7a8bb 409 if (yr > 0 || yw > 0) {
8f2d43a0
LP
410 g->io_input_bps = (yr * 1000000000ULL) / x;
411 g->io_output_bps = (yw * 1000000000ULL) / x;
412 g->io_valid = true;
8f2d43a0
LP
413 }
414 }
415
416 g->io_input = rd;
417 g->io_output = wr;
45d7a8bb 418 g->io_timestamp = timestamp;
8f2d43a0
LP
419 g->io_iteration = iteration;
420 }
421
3cb5beea
LP
422 if (ret)
423 *ret = g;
424
8f2d43a0
LP
425 return 0;
426}
427
428static int refresh_one(
429 const char *controller,
430 const char *path,
431 Hashmap *a,
432 Hashmap *b,
433 unsigned iteration,
3cb5beea
LP
434 unsigned depth,
435 Group **ret) {
8f2d43a0 436
45d7a8bb 437 _cleanup_closedir_ DIR *d = NULL;
80b2ab4b 438 Group *ours = NULL;
8f2d43a0
LP
439 int r;
440
441 assert(controller);
442 assert(path);
443 assert(a);
444
445 if (depth > arg_depth)
446 return 0;
447
3cb5beea 448 r = process(controller, path, a, b, iteration, &ours);
8f2d43a0
LP
449 if (r < 0)
450 return r;
451
452 r = cg_enumerate_subgroups(controller, path, &d);
45d7a8bb
LP
453 if (r == -ENOENT)
454 return 0;
455 if (r < 0)
8f2d43a0 456 return r;
8f2d43a0
LP
457
458 for (;;) {
45d7a8bb 459 _cleanup_free_ char *fn = NULL, *p = NULL;
3cb5beea 460 Group *child = NULL;
8f2d43a0
LP
461
462 r = cg_read_subgroup(d, &fn);
3cb5beea 463 if (r < 0)
45d7a8bb 464 return r;
3cb5beea
LP
465 if (r == 0)
466 break;
8f2d43a0 467
605405c6 468 p = strjoin(path, "/", fn);
45d7a8bb
LP
469 if (!p)
470 return -ENOMEM;
8f2d43a0 471
858d36c1 472 path_simplify(p, false);
8f2d43a0 473
3cb5beea 474 r = refresh_one(controller, p, a, b, iteration, depth + 1, &child);
8f2d43a0 475 if (r < 0)
45d7a8bb 476 return r;
3cb5beea
LP
477
478 if (arg_recursive &&
03a7b521 479 IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES) &&
3cb5beea
LP
480 child &&
481 child->n_tasks_valid &&
482 streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
483
484 /* Recursively sum up processes */
485
486 if (ours->n_tasks_valid)
487 ours->n_tasks += child->n_tasks;
488 else {
489 ours->n_tasks = child->n_tasks;
490 ours->n_tasks_valid = true;
491 }
492 }
8f2d43a0
LP
493 }
494
3cb5beea
LP
495 if (ret)
496 *ret = ours;
497
498 return 1;
8f2d43a0
LP
499}
500
03af6492 501static int refresh(const char *root, Hashmap *a, Hashmap *b, unsigned iteration) {
8f2d43a0
LP
502 int r;
503
504 assert(a);
505
3cb5beea 506 r = refresh_one(SYSTEMD_CGROUP_CONTROLLER, root, a, b, iteration, 0, NULL);
66ebf6c0
TH
507 if (r < 0)
508 return r;
509 r = refresh_one("cpu", root, a, b, iteration, 0, NULL);
8f2d43a0 510 if (r < 0)
45d7a8bb 511 return r;
3cb5beea 512 r = refresh_one("cpuacct", root, a, b, iteration, 0, NULL);
8f2d43a0 513 if (r < 0)
45d7a8bb 514 return r;
3cb5beea 515 r = refresh_one("memory", root, a, b, iteration, 0, NULL);
13c31542
TH
516 if (r < 0)
517 return r;
518 r = refresh_one("io", root, a, b, iteration, 0, NULL);
8f2d43a0 519 if (r < 0)
45d7a8bb 520 return r;
3cb5beea 521 r = refresh_one("blkio", root, a, b, iteration, 0, NULL);
03a7b521
LP
522 if (r < 0)
523 return r;
524 r = refresh_one("pids", root, a, b, iteration, 0, NULL);
63210a15 525 if (r < 0)
45d7a8bb
LP
526 return r;
527
63210a15 528 return 0;
8f2d43a0
LP
529}
530
93bab288
YW
531static int group_compare(Group * const *a, Group * const *b) {
532 const Group *x = *a, *y = *b;
533 int r;
8f2d43a0 534
3cb5beea 535 if (arg_order != ORDER_TASKS || arg_recursive) {
45d7a8bb 536 /* Let's make sure that the parent is always before
3cb5beea
LP
537 * the child. Except when ordering by tasks and
538 * recursive summing is off, since that is actually
539 * not accumulative for all children. */
45d7a8bb 540
945403e6 541 if (path_startswith(empty_to_root(y->path), empty_to_root(x->path)))
45d7a8bb 542 return -1;
945403e6 543 if (path_startswith(empty_to_root(x->path), empty_to_root(y->path)))
45d7a8bb
LP
544 return 1;
545 }
546
547 switch (arg_order) {
548
549 case ORDER_PATH:
550 break;
8f2d43a0 551
45d7a8bb 552 case ORDER_CPU:
1e913bcb
UTL
553 if (arg_cpu_type == CPU_PERCENT) {
554 if (x->cpu_valid && y->cpu_valid) {
93bab288
YW
555 r = CMP(y->cpu_fraction, x->cpu_fraction);
556 if (r != 0)
557 return r;
1e913bcb 558 } else if (x->cpu_valid)
8f2d43a0 559 return -1;
1e913bcb 560 else if (y->cpu_valid)
8f2d43a0 561 return 1;
1e913bcb 562 } else {
93bab288
YW
563 r = CMP(y->cpu_usage, x->cpu_usage);
564 if (r != 0)
565 return r;
1e913bcb 566 }
8f2d43a0 567
45d7a8bb 568 break;
8f2d43a0 569
45d7a8bb 570 case ORDER_TASKS:
8f2d43a0 571 if (x->n_tasks_valid && y->n_tasks_valid) {
93bab288
YW
572 r = CMP(y->n_tasks, x->n_tasks);
573 if (r != 0)
574 return r;
8f2d43a0
LP
575 } else if (x->n_tasks_valid)
576 return -1;
577 else if (y->n_tasks_valid)
578 return 1;
8f2d43a0 579
45d7a8bb
LP
580 break;
581
582 case ORDER_MEMORY:
8f2d43a0 583 if (x->memory_valid && y->memory_valid) {
93bab288
YW
584 r = CMP(y->memory, x->memory);
585 if (r != 0)
586 return r;
8f2d43a0
LP
587 } else if (x->memory_valid)
588 return -1;
589 else if (y->memory_valid)
590 return 1;
8f2d43a0 591
45d7a8bb
LP
592 break;
593
594 case ORDER_IO:
8f2d43a0 595 if (x->io_valid && y->io_valid) {
93bab288
YW
596 r = CMP(y->io_input_bps + y->io_output_bps, x->io_input_bps + x->io_output_bps);
597 if (r != 0)
598 return r;
8f2d43a0
LP
599 } else if (x->io_valid)
600 return -1;
601 else if (y->io_valid)
602 return 1;
603 }
604
45d7a8bb 605 return path_compare(x->path, y->path);
8f2d43a0
LP
606}
607
dcd71990 608static void display(Hashmap *a) {
8f2d43a0
LP
609 Iterator i;
610 Group *g;
611 Group **array;
1e913bcb 612 signed path_columns;
510c4a0f 613 unsigned rows, n = 0, j, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */
62b95b8b 614 char buffer[MAX3(21, FORMAT_BYTES_MAX, FORMAT_TIMESPAN_MAX)];
8f2d43a0
LP
615
616 assert(a);
617
ac96418b 618 if (!terminal_is_dumb())
1fc464f6 619 fputs(ANSI_HOME_CLEAR, stdout);
8f2d43a0 620
cf409d15 621 array = newa(Group*, hashmap_size(a));
8f2d43a0
LP
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
93bab288 627 typesafe_qsort(array, n, group_compare);
8f2d43a0 628
1e913bcb
UTL
629 /* Find the longest names in one run */
630 for (j = 0; j < n; j++) {
631 unsigned cputlen, pathtlen;
62b95b8b 632
45d7a8bb 633 format_timespan(buffer, sizeof(buffer), (usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0);
62b95b8b 634 cputlen = strlen(buffer);
1e913bcb 635 maxtcpu = MAX(maxtcpu, cputlen);
45d7a8bb 636
1e913bcb
UTL
637 pathtlen = strlen(array[j]->path);
638 maxtpath = MAX(maxtpath, pathtlen);
639 }
640
641 if (arg_cpu_type == CPU_PERCENT)
d054f0a4 642 xsprintf(buffer, "%6s", "%CPU");
1e913bcb 643 else
d054f0a4 644 xsprintf(buffer, "%*s", maxtcpu, "CPU Time");
1e913bcb 645
ed757c0c
LP
646 rows = lines();
647 if (rows <= 10)
648 rows = 10;
8f2d43a0 649
1e913bcb 650 if (on_tty()) {
1fc464f6
LP
651 const char *on, *off;
652
62b95b8b 653 path_columns = columns() - 36 - strlen(buffer);
1e913bcb
UTL
654 if (path_columns < 10)
655 path_columns = 10;
656
1fc464f6
LP
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());
1e913bcb
UTL
675 } else
676 path_columns = maxtpath;
8f2d43a0
LP
677
678 for (j = 0; j < n; j++) {
9660efb8
LP
679 _cleanup_free_ char *ellipsized = NULL;
680 const char *path;
8f2d43a0 681
08edf879 682 if (on_tty() && j + 6 > rows)
8f2d43a0
LP
683 break;
684
685 g = array[j];
686
945403e6 687 path = empty_to_root(g->path);
9660efb8
LP
688 ellipsized = ellipsize(path, path_columns, 33);
689 printf("%-*s", path_columns, ellipsized ?: path);
8f2d43a0
LP
690
691 if (g->n_tasks_valid)
03a7b521 692 printf(" %7" PRIu64, g->n_tasks);
8f2d43a0
LP
693 else
694 fputs(" -", stdout);
695
62b95b8b 696 if (arg_cpu_type == CPU_PERCENT) {
1e913bcb
UTL
697 if (g->cpu_valid)
698 printf(" %6.1f", g->cpu_fraction*100);
699 else
700 fputs(" -", stdout);
62b95b8b 701 } else
45d7a8bb 702 printf(" %*s", maxtcpu, format_timespan(buffer, sizeof(buffer), (usec_t) (g->cpu_usage / NSEC_PER_USEC), 0));
8f2d43a0 703
a2c9f631
CD
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));
8f2d43a0
LP
707
708 putchar('\n');
709 }
8f2d43a0
LP
710}
711
37ec0fdd
LP
712static 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
308253c5 720 printf("%s [OPTIONS...] [CGROUP]\n\n"
8f2d43a0
LP
721 "Show top control groups by their resource usage.\n\n"
722 " -h --help Show this help\n"
45d7a8bb
LP
723 " --version Show package version\n"
724 " -p --order=path Order by path\n"
03a7b521 725 " -t --order=tasks Order by number of tasks/processes\n"
45d7a8bb
LP
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"
a2c9f631 729 " -r --raw Provide raw (not human-readable) numbers\n"
45d7a8bb
LP
730 " --cpu=percentage Show CPU usage as percentage (default)\n"
731 " --cpu=time Show CPU usage as time\n"
03a7b521
LP
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"
1e913bcb 735 " -d --delay=DELAY Delay between updates\n"
a152771a 736 " -n --iterations=N Run for N iterations before exiting\n"
4fc9ffab 737 " -1 Shortcut for --iterations=1\n"
e66bb58b 738 " -b --batch Run in batch mode, accepting no input\n"
601185b4 739 " --depth=DEPTH Maximum traversal depth (default: %u)\n"
96a6426f 740 " -M --machine= Show container\n"
37ec0fdd
LP
741 "\nSee the %s for details.\n"
742 , program_invocation_short_name
743 , arg_depth
744 , link
745 );
746
747 return 0;
0d7e32fa
ZJS
748}
749
8f2d43a0
LP
750static int parse_argv(int argc, char *argv[]) {
751
752 enum {
0d7e32fa
ZJS
753 ARG_VERSION = 0x100,
754 ARG_DEPTH,
45d7a8bb
LP
755 ARG_CPU_TYPE,
756 ARG_ORDER,
3cb5beea 757 ARG_RECURSIVE,
8f2d43a0
LP
758 };
759
760 static const struct option options[] = {
3cb5beea
LP
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 },
96a6426f 771 { "machine", required_argument, NULL, 'M' },
eb9da376 772 {}
8f2d43a0
LP
773 };
774
3cb5beea 775 int c, r;
8f2d43a0
LP
776
777 assert(argc >= 1);
778 assert(argv);
779
4fc9ffab 780 while ((c = getopt_long(argc, argv, "hptcmin:brd:kPM:1", options, NULL)) >= 0)
8f2d43a0
LP
781
782 switch (c) {
783
784 case 'h':
37ec0fdd 785 return help();
8f2d43a0 786
0d7e32fa 787 case ARG_VERSION:
3f6fd1ba 788 return version();
0d7e32fa 789
1e913bcb
UTL
790 case ARG_CPU_TYPE:
791 if (optarg) {
45d7a8bb 792 if (streq(optarg, "time"))
1e913bcb 793 arg_cpu_type = CPU_TIME;
45d7a8bb 794 else if (streq(optarg, "percentage"))
1e913bcb 795 arg_cpu_type = CPU_PERCENT;
45d7a8bb
LP
796 else {
797 log_error("Unknown argument to --cpu=: %s", optarg);
1e913bcb 798 return -EINVAL;
45d7a8bb
LP
799 }
800 } else
801 arg_cpu_type = CPU_TIME;
802
1e913bcb
UTL
803 break;
804
8f2d43a0
LP
805 case ARG_DEPTH:
806 r = safe_atou(optarg, &arg_depth);
ad078b41 807 if (r < 0)
486d76bd 808 return log_error_errno(r, "Failed to parse depth parameter '%s': %m", optarg);
8f2d43a0
LP
809
810 break;
811
812 case 'd':
7f602784 813 r = parse_sec(optarg, &arg_delay);
486d76bd
YW
814 if (r < 0)
815 return log_error_errno(r, "Failed to parse delay parameter '%s': %m", optarg);
816 if (arg_delay <= 0) {
817 log_error("Invalid delay parameter '%s'", optarg);
8f2d43a0
LP
818 return -EINVAL;
819 }
820
821 break;
822
a152771a
DS
823 case 'n':
824 r = safe_atou(optarg, &arg_iterations);
ad078b41 825 if (r < 0)
486d76bd 826 return log_error_errno(r, "Failed to parse iterations parameter '%s': %m", optarg);
a152771a
DS
827
828 break;
829
4fc9ffab
LP
830 case '1':
831 arg_iterations = 1;
832 break;
833
e66bb58b
DS
834 case 'b':
835 arg_batch = true;
836 break;
837
a2c9f631
CD
838 case 'r':
839 arg_raw = true;
840 break;
841
8f2d43a0
LP
842 case 'p':
843 arg_order = ORDER_PATH;
844 break;
845
846 case 't':
847 arg_order = ORDER_TASKS;
848 break;
849
850 case 'c':
851 arg_order = ORDER_CPU;
852 break;
853
854 case 'm':
855 arg_order = ORDER_MEMORY;
856 break;
857
858 case 'i':
859 arg_order = ORDER_IO;
860 break;
861
45d7a8bb
LP
862 case ARG_ORDER:
863 if (streq(optarg, "path"))
864 arg_order = ORDER_PATH;
865 else if (streq(optarg, "tasks"))
866 arg_order = ORDER_TASKS;
867 else if (streq(optarg, "cpu"))
868 arg_order = ORDER_CPU;
869 else if (streq(optarg, "memory"))
870 arg_order = ORDER_MEMORY;
871 else if (streq(optarg, "io"))
872 arg_order = ORDER_IO;
873 else {
874 log_error("Invalid argument to --order=: %s", optarg);
875 return -EINVAL;
876 }
877 break;
878
41ba8b6e 879 case 'k':
03a7b521
LP
880 arg_count = COUNT_ALL_PROCESSES;
881 break;
882
883 case 'P':
884 arg_count = COUNT_USERSPACE_PROCESSES;
41ba8b6e
LP
885 break;
886
3cb5beea
LP
887 case ARG_RECURSIVE:
888 r = parse_boolean(optarg);
ad078b41 889 if (r < 0)
486d76bd 890 return log_error_errno(r, "Failed to parse --recursive= argument '%s': %m", optarg);
3cb5beea
LP
891
892 arg_recursive = r;
6d9f40d5 893 arg_recursive_unset = r == 0;
3cb5beea
LP
894 break;
895
96a6426f
EV
896 case 'M':
897 arg_machine = optarg;
898 break;
899
8f2d43a0
LP
900 case '?':
901 return -EINVAL;
902
903 default:
eb9da376 904 assert_not_reached("Unhandled option");
8f2d43a0 905 }
8f2d43a0 906
d3e8277d 907 if (optind == argc - 1)
308253c5 908 arg_root = argv[optind];
d3e8277d 909 else if (optind < argc) {
8f2d43a0
LP
910 log_error("Too many arguments.");
911 return -EINVAL;
912 }
913
914 return 1;
915}
916
03a7b521
LP
917static const char* counting_what(void) {
918 if (arg_count == COUNT_PIDS)
919 return "tasks";
920 else if (arg_count == COUNT_ALL_PROCESSES)
921 return "all processes (incl. kernel)";
922 else
923 return "userspace processes (excl. kernel)";
924}
925
8f2d43a0
LP
926int main(int argc, char *argv[]) {
927 int r;
928 Hashmap *a = NULL, *b = NULL;
929 unsigned iteration = 0;
930 usec_t last_refresh = 0;
931 bool quit = false, immediate_refresh = false;
03af6492 932 _cleanup_free_ char *root = NULL;
03a7b521 933 CGroupMask mask;
8f2d43a0
LP
934
935 log_parse_environment();
936 log_open();
937
6d9f40d5
ZJS
938 r = parse_argv(argc, argv);
939 if (r <= 0)
940 goto finish;
941
03a7b521
LP
942 r = cg_mask_supported(&mask);
943 if (r < 0) {
944 log_error_errno(r, "Failed to determine supported controllers: %m");
945 goto finish;
946 }
947
948 arg_count = (mask & CGROUP_MASK_PIDS) ? COUNT_PIDS : COUNT_USERSPACE_PROCESSES;
949
6d9f40d5
ZJS
950 if (arg_recursive_unset && arg_count == COUNT_PIDS) {
951 log_error("Non-recursive counting is only supported when counting processes, not tasks. Use -P or -k.");
952 return -EINVAL;
953 }
8f2d43a0 954
d3e8277d 955 r = show_cgroup_get_path_and_warn(arg_machine, arg_root, &root);
03af6492
LP
956 if (r < 0) {
957 log_error_errno(r, "Failed to get root control group path: %m");
958 goto finish;
d3e8277d
ZJS
959 } else
960 log_debug("Cgroup path: %s", root);
03af6492 961
548f6937
LP
962 a = hashmap_new(&path_hash_ops);
963 b = hashmap_new(&path_hash_ops);
8f2d43a0 964 if (!a || !b) {
0d0f0c50 965 r = log_oom();
8f2d43a0
LP
966 goto finish;
967 }
968
ed757c0c 969 signal(SIGWINCH, columns_lines_cache_reset);
28917d7d 970
45d7a8bb 971 if (arg_iterations == (unsigned) -1)
780fe62e 972 arg_iterations = on_tty() ? 0 : 1;
1e913bcb 973
8f2d43a0
LP
974 while (!quit) {
975 Hashmap *c;
976 usec_t t;
977 char key;
978 char h[FORMAT_TIMESPAN_MAX];
979
980 t = now(CLOCK_MONOTONIC);
981
982 if (t >= last_refresh + arg_delay || immediate_refresh) {
983
03af6492 984 r = refresh(root, a, b, iteration++);
dcd71990
LP
985 if (r < 0) {
986 log_error_errno(r, "Failed to refresh: %m");
8f2d43a0 987 goto finish;
dcd71990 988 }
8f2d43a0
LP
989
990 group_hashmap_clear(b);
991
992 c = a;
993 a = b;
994 b = c;
995
996 last_refresh = t;
997 immediate_refresh = false;
998 }
999
dcd71990 1000 display(b);
8f2d43a0 1001
a152771a
DS
1002 if (arg_iterations && iteration >= arg_iterations)
1003 break;
1004
dcc7aacd
CD
1005 if (!on_tty()) /* non-TTY: Empty newline as delimiter between polls */
1006 fputs("\n", stdout);
1007 fflush(stdout);
1008
45d7a8bb 1009 if (arg_batch)
dcd71990 1010 (void) usleep(last_refresh + arg_delay - t);
45d7a8bb
LP
1011 else {
1012 r = read_one_char(stdin, &key, last_refresh + arg_delay - t, NULL);
e66bb58b
DS
1013 if (r == -ETIMEDOUT)
1014 continue;
1015 if (r < 0) {
da927ba9 1016 log_error_errno(r, "Couldn't read key: %m");
e66bb58b
DS
1017 goto finish;
1018 }
8f2d43a0
LP
1019 }
1020
dcc7aacd
CD
1021 if (on_tty()) { /* TTY: Clear any user keystroke */
1022 fputs("\r \r", stdout);
1023 fflush(stdout);
1024 }
8f2d43a0 1025
e66bb58b
DS
1026 if (arg_batch)
1027 continue;
1028
8f2d43a0
LP
1029 switch (key) {
1030
1031 case ' ':
1032 immediate_refresh = true;
1033 break;
1034
1035 case 'q':
1036 quit = true;
1037 break;
1038
1039 case 'p':
1040 arg_order = ORDER_PATH;
1041 break;
1042
1043 case 't':
1044 arg_order = ORDER_TASKS;
1045 break;
1046
1047 case 'c':
1048 arg_order = ORDER_CPU;
1049 break;
1050
1051 case 'm':
1052 arg_order = ORDER_MEMORY;
1053 break;
1054
1055 case 'i':
1056 arg_order = ORDER_IO;
1057 break;
1058
2bfc1eda
ZJS
1059 case '%':
1060 arg_cpu_type = arg_cpu_type == CPU_TIME ? CPU_PERCENT : CPU_TIME;
1061 break;
1062
7fcfb7ee 1063 case 'k':
03a7b521
LP
1064 arg_count = arg_count != COUNT_ALL_PROCESSES ? COUNT_ALL_PROCESSES : COUNT_PIDS;
1065 fprintf(stdout, "\nCounting: %s.", counting_what());
1066 fflush(stdout);
1067 sleep(1);
1068 break;
1069
1070 case 'P':
1071 arg_count = arg_count != COUNT_USERSPACE_PROCESSES ? COUNT_USERSPACE_PROCESSES : COUNT_PIDS;
1072 fprintf(stdout, "\nCounting: %s.", counting_what());
7fcfb7ee
LP
1073 fflush(stdout);
1074 sleep(1);
1075 break;
1076
1077 case 'r':
03a7b521
LP
1078 if (arg_count == COUNT_PIDS)
1079 fprintf(stdout, "\n\aCannot toggle recursive counting, not available in task counting mode.");
1080 else {
1081 arg_recursive = !arg_recursive;
1082 fprintf(stdout, "\nRecursive process counting: %s", yes_no(arg_recursive));
1083 }
7fcfb7ee
LP
1084 fflush(stdout);
1085 sleep(1);
1086 break;
1087
8f2d43a0
LP
1088 case '+':
1089 if (arg_delay < USEC_PER_SEC)
1090 arg_delay += USEC_PER_MSEC*250;
1091 else
1092 arg_delay += USEC_PER_SEC;
1093
2fa4092c 1094 fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
8f2d43a0
LP
1095 fflush(stdout);
1096 sleep(1);
1097 break;
1098
1099 case '-':
1100 if (arg_delay <= USEC_PER_MSEC*500)
1101 arg_delay = USEC_PER_MSEC*250;
1102 else if (arg_delay < USEC_PER_MSEC*1250)
1103 arg_delay -= USEC_PER_MSEC*250;
1104 else
1105 arg_delay -= USEC_PER_SEC;
1106
2fa4092c 1107 fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0));
8f2d43a0
LP
1108 fflush(stdout);
1109 sleep(1);
1110 break;
1111
1112 case '?':
1113 case 'h':
1fc464f6
LP
1114
1115#define ON ANSI_HIGHLIGHT
1116#define OFF ANSI_NORMAL
1117
8f2d43a0 1118 fprintf(stdout,
03a7b521 1119 "\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"
7fcfb7ee 1120 "\t<" ON "+" OFF "> Inc. delay; <" ON "-" OFF "> Dec. delay; <" ON "%%" OFF "> Toggle time; <" ON "SPACE" OFF "> Refresh\n"
03a7b521
LP
1121 "\t<" ON "P" OFF "> Toggle count userspace processes; <" ON "k" OFF "> Toggle count all processes\n"
1122 "\t<" ON "r" OFF "> Count processes recursively; <" ON "q" OFF "> Quit");
8f2d43a0
LP
1123 fflush(stdout);
1124 sleep(3);
1125 break;
1126
1127 default:
45d7a8bb
LP
1128 if (key < ' ')
1129 fprintf(stdout, "\nUnknown key '\\x%x'. Ignoring.", key);
1130 else
1131 fprintf(stdout, "\nUnknown key '%c'. Ignoring.", key);
8f2d43a0
LP
1132 fflush(stdout);
1133 sleep(1);
1134 break;
1135 }
1136 }
1137
8f2d43a0
LP
1138 r = 0;
1139
1140finish:
1141 group_hashmap_free(a);
1142 group_hashmap_free(b);
1143
dcd71990 1144 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
8f2d43a0 1145}