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