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