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