]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/analyze/analyze.c
systemd-analyze: add new 'security' option to compare unit's overall exposure level...
[thirdparty/systemd.git] / src / analyze / analyze.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2013 Simon Peeters
4 ***/
5
6 #include <getopt.h>
7 #include <inttypes.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11
12 #include "sd-bus.h"
13
14 #include "alloc-util.h"
15 #include "analyze-condition.h"
16 #include "analyze-security.h"
17 #include "analyze-verify.h"
18 #include "bus-error.h"
19 #include "bus-locator.h"
20 #include "bus-map-properties.h"
21 #include "bus-unit-util.h"
22 #include "calendarspec.h"
23 #include "cap-list.h"
24 #include "capability-util.h"
25 #include "conf-files.h"
26 #include "copy.h"
27 #include "def.h"
28 #include "exit-status.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "format-table.h"
32 #include "glob-util.h"
33 #include "hashmap.h"
34 #include "locale-util.h"
35 #include "log.h"
36 #include "main-func.h"
37 #include "mount-util.h"
38 #include "nulstr-util.h"
39 #include "pager.h"
40 #include "parse-argument.h"
41 #include "parse-util.h"
42 #include "path-util.h"
43 #include "pretty-print.h"
44 #if HAVE_SECCOMP
45 # include "seccomp-util.h"
46 #endif
47 #include "sort-util.h"
48 #include "special.h"
49 #include "string-table.h"
50 #include "strv.h"
51 #include "strxcpyx.h"
52 #include "terminal-util.h"
53 #include "time-util.h"
54 #include "unit-name.h"
55 #include "util.h"
56 #include "verbs.h"
57 #include "version.h"
58
59 #define SCALE_X (0.1 / 1000.0) /* pixels per us */
60 #define SCALE_Y (20.0)
61
62 #define svg(...) printf(__VA_ARGS__)
63
64 #define svg_bar(class, x1, x2, y) \
65 svg(" <rect class=\"%s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n", \
66 (class), \
67 SCALE_X * (x1), SCALE_Y * (y), \
68 SCALE_X * ((x2) - (x1)), SCALE_Y - 1.0)
69
70 #define svg_text(b, x, y, format, ...) \
71 do { \
72 svg(" <text class=\"%s\" x=\"%.03f\" y=\"%.03f\">", (b) ? "left" : "right", SCALE_X * (x) + (b ? 5.0 : -5.0), SCALE_Y * (y) + 14.0); \
73 svg(format, ## __VA_ARGS__); \
74 svg("</text>\n"); \
75 } while (false)
76
77 static enum dot {
78 DEP_ALL,
79 DEP_ORDER,
80 DEP_REQUIRE
81 } arg_dot = DEP_ALL;
82 static char **arg_dot_from_patterns = NULL;
83 static char **arg_dot_to_patterns = NULL;
84 static usec_t arg_fuzz = 0;
85 static PagerFlags arg_pager_flags = 0;
86 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
87 static const char *arg_host = NULL;
88 static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
89 static RecursiveErrors arg_recursive_errors = RECURSIVE_ERRORS_YES;
90 static bool arg_man = true;
91 static bool arg_generators = false;
92 static char *arg_root = NULL;
93 static char *arg_image = NULL;
94 static bool arg_offline = false;
95 static unsigned arg_threshold = 100;
96 static unsigned arg_iterations = 1;
97 static usec_t arg_base_time = USEC_INFINITY;
98
99 STATIC_DESTRUCTOR_REGISTER(arg_dot_from_patterns, strv_freep);
100 STATIC_DESTRUCTOR_REGISTER(arg_dot_to_patterns, strv_freep);
101 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
102 STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
103
104 typedef struct BootTimes {
105 usec_t firmware_time;
106 usec_t loader_time;
107 usec_t kernel_time;
108 usec_t kernel_done_time;
109 usec_t initrd_time;
110 usec_t userspace_time;
111 usec_t finish_time;
112 usec_t security_start_time;
113 usec_t security_finish_time;
114 usec_t generators_start_time;
115 usec_t generators_finish_time;
116 usec_t unitsload_start_time;
117 usec_t unitsload_finish_time;
118 usec_t initrd_security_start_time;
119 usec_t initrd_security_finish_time;
120 usec_t initrd_generators_start_time;
121 usec_t initrd_generators_finish_time;
122 usec_t initrd_unitsload_start_time;
123 usec_t initrd_unitsload_finish_time;
124
125 /*
126 * If we're analyzing the user instance, all timestamps will be offset
127 * by its own start-up timestamp, which may be arbitrarily big.
128 * With "plot", this causes arbitrarily wide output SVG files which almost
129 * completely consist of empty space. Thus we cancel out this offset.
130 *
131 * This offset is subtracted from times above by acquire_boot_times(),
132 * but it still needs to be subtracted from unit-specific timestamps
133 * (so it is stored here for reference).
134 */
135 usec_t reverse_offset;
136 } BootTimes;
137
138 typedef struct UnitTimes {
139 bool has_data;
140 char *name;
141 usec_t activating;
142 usec_t activated;
143 usec_t deactivated;
144 usec_t deactivating;
145 usec_t time;
146 } UnitTimes;
147
148 typedef struct HostInfo {
149 char *hostname;
150 char *kernel_name;
151 char *kernel_release;
152 char *kernel_version;
153 char *os_pretty_name;
154 char *virtualization;
155 char *architecture;
156 } HostInfo;
157
158 static int acquire_bus(sd_bus **bus, bool *use_full_bus) {
159 bool user = arg_scope != UNIT_FILE_SYSTEM;
160 int r;
161
162 if (use_full_bus && *use_full_bus) {
163 r = bus_connect_transport(arg_transport, arg_host, user, bus);
164 if (IN_SET(r, 0, -EHOSTDOWN))
165 return r;
166
167 *use_full_bus = false;
168 }
169
170 return bus_connect_transport_systemd(arg_transport, arg_host, user, bus);
171 }
172
173 static int bus_get_uint64_property(sd_bus *bus, const char *path, const char *interface, const char *property, uint64_t *val) {
174 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
175 int r;
176
177 assert(bus);
178 assert(path);
179 assert(interface);
180 assert(property);
181 assert(val);
182
183 r = sd_bus_get_property_trivial(
184 bus,
185 "org.freedesktop.systemd1",
186 path,
187 interface,
188 property,
189 &error,
190 't', val);
191
192 if (r < 0)
193 return log_error_errno(r, "Failed to parse reply: %s", bus_error_message(&error, r));
194
195 return 0;
196 }
197
198 static int bus_get_unit_property_strv(sd_bus *bus, const char *path, const char *property, char ***strv) {
199 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
200 int r;
201
202 assert(bus);
203 assert(path);
204 assert(property);
205 assert(strv);
206
207 r = sd_bus_get_property_strv(
208 bus,
209 "org.freedesktop.systemd1",
210 path,
211 "org.freedesktop.systemd1.Unit",
212 property,
213 &error,
214 strv);
215 if (r < 0)
216 return log_error_errno(r, "Failed to get unit property %s: %s", property, bus_error_message(&error, r));
217
218 return 0;
219 }
220
221 static int compare_unit_start(const UnitTimes *a, const UnitTimes *b) {
222 return CMP(a->activating, b->activating);
223 }
224
225 static UnitTimes* unit_times_free_array(UnitTimes *t) {
226 for (UnitTimes *p = t; p && p->has_data; p++)
227 free(p->name);
228 return mfree(t);
229 }
230 DEFINE_TRIVIAL_CLEANUP_FUNC(UnitTimes*, unit_times_free_array);
231
232 static void subtract_timestamp(usec_t *a, usec_t b) {
233 assert(a);
234
235 if (*a > 0) {
236 assert(*a >= b);
237 *a -= b;
238 }
239 }
240
241 static int acquire_boot_times(sd_bus *bus, BootTimes **bt) {
242 static const struct bus_properties_map property_map[] = {
243 { "FirmwareTimestampMonotonic", "t", NULL, offsetof(BootTimes, firmware_time) },
244 { "LoaderTimestampMonotonic", "t", NULL, offsetof(BootTimes, loader_time) },
245 { "KernelTimestamp", "t", NULL, offsetof(BootTimes, kernel_time) },
246 { "InitRDTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_time) },
247 { "UserspaceTimestampMonotonic", "t", NULL, offsetof(BootTimes, userspace_time) },
248 { "FinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, finish_time) },
249 { "SecurityStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, security_start_time) },
250 { "SecurityFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, security_finish_time) },
251 { "GeneratorsStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, generators_start_time) },
252 { "GeneratorsFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, generators_finish_time) },
253 { "UnitsLoadStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, unitsload_start_time) },
254 { "UnitsLoadFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, unitsload_finish_time) },
255 { "InitRDSecurityStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_security_start_time) },
256 { "InitRDSecurityFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_security_finish_time) },
257 { "InitRDGeneratorsStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_generators_start_time) },
258 { "InitRDGeneratorsFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_generators_finish_time) },
259 { "InitRDUnitsLoadStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_unitsload_start_time) },
260 { "InitRDUnitsLoadFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_unitsload_finish_time) },
261 {},
262 };
263 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
264 static BootTimes times;
265 static bool cached = false;
266 int r;
267
268 if (cached)
269 goto finish;
270
271 assert_cc(sizeof(usec_t) == sizeof(uint64_t));
272
273 r = bus_map_all_properties(
274 bus,
275 "org.freedesktop.systemd1",
276 "/org/freedesktop/systemd1",
277 property_map,
278 BUS_MAP_STRDUP,
279 &error,
280 NULL,
281 &times);
282 if (r < 0)
283 return log_error_errno(r, "Failed to get timestamp properties: %s", bus_error_message(&error, r));
284
285 if (times.finish_time <= 0)
286 return log_error_errno(SYNTHETIC_ERRNO(EINPROGRESS),
287 "Bootup is not yet finished (org.freedesktop.systemd1.Manager.FinishTimestampMonotonic=%"PRIu64").\n"
288 "Please try again later.\n"
289 "Hint: Use 'systemctl%s list-jobs' to see active jobs",
290 times.finish_time,
291 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
292
293 if (arg_scope == UNIT_FILE_SYSTEM && times.security_start_time > 0) {
294 /* security_start_time is set when systemd is not running under container environment. */
295 if (times.initrd_time > 0)
296 times.kernel_done_time = times.initrd_time;
297 else
298 times.kernel_done_time = times.userspace_time;
299 } else {
300 /*
301 * User-instance-specific or container-system-specific timestamps processing
302 * (see comment to reverse_offset in BootTimes).
303 */
304 times.reverse_offset = times.userspace_time;
305
306 times.firmware_time = times.loader_time = times.kernel_time = times.initrd_time =
307 times.userspace_time = times.security_start_time = times.security_finish_time = 0;
308
309 subtract_timestamp(&times.finish_time, times.reverse_offset);
310
311 subtract_timestamp(&times.generators_start_time, times.reverse_offset);
312 subtract_timestamp(&times.generators_finish_time, times.reverse_offset);
313
314 subtract_timestamp(&times.unitsload_start_time, times.reverse_offset);
315 subtract_timestamp(&times.unitsload_finish_time, times.reverse_offset);
316 }
317
318 cached = true;
319
320 finish:
321 *bt = &times;
322 return 0;
323 }
324
325 static HostInfo* free_host_info(HostInfo *hi) {
326 if (!hi)
327 return NULL;
328
329 free(hi->hostname);
330 free(hi->kernel_name);
331 free(hi->kernel_release);
332 free(hi->kernel_version);
333 free(hi->os_pretty_name);
334 free(hi->virtualization);
335 free(hi->architecture);
336 return mfree(hi);
337 }
338
339 DEFINE_TRIVIAL_CLEANUP_FUNC(HostInfo *, free_host_info);
340
341 static int acquire_time_data(sd_bus *bus, UnitTimes **out) {
342 static const struct bus_properties_map property_map[] = {
343 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitTimes, activating) },
344 { "ActiveEnterTimestampMonotonic", "t", NULL, offsetof(UnitTimes, activated) },
345 { "ActiveExitTimestampMonotonic", "t", NULL, offsetof(UnitTimes, deactivating) },
346 { "InactiveEnterTimestampMonotonic", "t", NULL, offsetof(UnitTimes, deactivated) },
347 {},
348 };
349 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
350 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
351 _cleanup_(unit_times_free_arrayp) UnitTimes *unit_times = NULL;
352 BootTimes *boot_times = NULL;
353 size_t c = 0;
354 UnitInfo u;
355 int r;
356
357 r = acquire_boot_times(bus, &boot_times);
358 if (r < 0)
359 return r;
360
361 r = bus_call_method(bus, bus_systemd_mgr, "ListUnits", &error, &reply, NULL);
362 if (r < 0)
363 return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
364
365 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
366 if (r < 0)
367 return bus_log_parse_error(r);
368
369 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
370 UnitTimes *t;
371
372 if (!GREEDY_REALLOC(unit_times, c + 2))
373 return log_oom();
374
375 unit_times[c + 1].has_data = false;
376 t = &unit_times[c];
377 t->name = NULL;
378
379 assert_cc(sizeof(usec_t) == sizeof(uint64_t));
380
381 r = bus_map_all_properties(
382 bus,
383 "org.freedesktop.systemd1",
384 u.unit_path,
385 property_map,
386 BUS_MAP_STRDUP,
387 &error,
388 NULL,
389 t);
390 if (r < 0)
391 return log_error_errno(r, "Failed to get timestamp properties of unit %s: %s",
392 u.id, bus_error_message(&error, r));
393
394 subtract_timestamp(&t->activating, boot_times->reverse_offset);
395 subtract_timestamp(&t->activated, boot_times->reverse_offset);
396 subtract_timestamp(&t->deactivating, boot_times->reverse_offset);
397 subtract_timestamp(&t->deactivated, boot_times->reverse_offset);
398
399 if (t->activated >= t->activating)
400 t->time = t->activated - t->activating;
401 else if (t->deactivated >= t->activating)
402 t->time = t->deactivated - t->activating;
403 else
404 t->time = 0;
405
406 if (t->activating == 0)
407 continue;
408
409 t->name = strdup(u.id);
410 if (!t->name)
411 return log_oom();
412
413 t->has_data = true;
414 c++;
415 }
416 if (r < 0)
417 return bus_log_parse_error(r);
418
419 *out = TAKE_PTR(unit_times);
420 return c;
421 }
422
423 static int acquire_host_info(sd_bus *bus, HostInfo **hi) {
424 static const struct bus_properties_map hostname_map[] = {
425 { "Hostname", "s", NULL, offsetof(HostInfo, hostname) },
426 { "KernelName", "s", NULL, offsetof(HostInfo, kernel_name) },
427 { "KernelRelease", "s", NULL, offsetof(HostInfo, kernel_release) },
428 { "KernelVersion", "s", NULL, offsetof(HostInfo, kernel_version) },
429 { "OperatingSystemPrettyName", "s", NULL, offsetof(HostInfo, os_pretty_name) },
430 {}
431 };
432
433 static const struct bus_properties_map manager_map[] = {
434 { "Virtualization", "s", NULL, offsetof(HostInfo, virtualization) },
435 { "Architecture", "s", NULL, offsetof(HostInfo, architecture) },
436 {}
437 };
438
439 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
440 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *system_bus = NULL;
441 _cleanup_(free_host_infop) HostInfo *host = NULL;
442 int r;
443
444 host = new0(HostInfo, 1);
445 if (!host)
446 return log_oom();
447
448 if (arg_scope != UNIT_FILE_SYSTEM) {
449 r = bus_connect_transport(arg_transport, arg_host, false, &system_bus);
450 if (r < 0) {
451 log_debug_errno(r, "Failed to connect to system bus, ignoring: %m");
452 goto manager;
453 }
454 }
455
456 r = bus_map_all_properties(
457 system_bus ?: bus,
458 "org.freedesktop.hostname1",
459 "/org/freedesktop/hostname1",
460 hostname_map,
461 BUS_MAP_STRDUP,
462 &error,
463 NULL,
464 host);
465 if (r < 0) {
466 log_debug_errno(r, "Failed to get host information from systemd-hostnamed, ignoring: %s",
467 bus_error_message(&error, r));
468 sd_bus_error_free(&error);
469 }
470
471 manager:
472 r = bus_map_all_properties(
473 bus,
474 "org.freedesktop.systemd1",
475 "/org/freedesktop/systemd1",
476 manager_map,
477 BUS_MAP_STRDUP,
478 &error,
479 NULL,
480 host);
481 if (r < 0)
482 return log_error_errno(r, "Failed to get host information from systemd: %s",
483 bus_error_message(&error, r));
484
485 *hi = TAKE_PTR(host);
486 return 0;
487 }
488
489 static int pretty_boot_time(sd_bus *bus, char **_buf) {
490 BootTimes *t;
491 static char buf[4096];
492 size_t size;
493 char *ptr;
494 int r;
495 usec_t activated_time = USEC_INFINITY;
496 _cleanup_free_ char *path = NULL, *unit_id = NULL;
497 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
498
499 r = acquire_boot_times(bus, &t);
500 if (r < 0)
501 return r;
502
503 path = unit_dbus_path_from_name(SPECIAL_DEFAULT_TARGET);
504 if (!path)
505 return log_oom();
506
507 r = sd_bus_get_property_string(
508 bus,
509 "org.freedesktop.systemd1",
510 path,
511 "org.freedesktop.systemd1.Unit",
512 "Id",
513 &error,
514 &unit_id);
515 if (r < 0) {
516 log_error_errno(r, "default.target doesn't seem to exist: %s", bus_error_message(&error, r));
517 unit_id = NULL;
518 }
519
520 r = bus_get_uint64_property(bus, path,
521 "org.freedesktop.systemd1.Unit",
522 "ActiveEnterTimestampMonotonic",
523 &activated_time);
524 if (r < 0) {
525 log_info_errno(r, "Could not get time to reach default.target, ignoring: %m");
526 activated_time = USEC_INFINITY;
527 }
528
529 ptr = buf;
530 size = sizeof(buf);
531
532 size = strpcpyf(&ptr, size, "Startup finished in ");
533 if (t->firmware_time > 0)
534 size = strpcpyf(&ptr, size, "%s (firmware) + ", FORMAT_TIMESPAN(t->firmware_time - t->loader_time, USEC_PER_MSEC));
535 if (t->loader_time > 0)
536 size = strpcpyf(&ptr, size, "%s (loader) + ", FORMAT_TIMESPAN(t->loader_time, USEC_PER_MSEC));
537 if (t->kernel_done_time > 0)
538 size = strpcpyf(&ptr, size, "%s (kernel) + ", FORMAT_TIMESPAN(t->kernel_done_time, USEC_PER_MSEC));
539 if (t->initrd_time > 0)
540 size = strpcpyf(&ptr, size, "%s (initrd) + ", FORMAT_TIMESPAN(t->userspace_time - t->initrd_time, USEC_PER_MSEC));
541
542 size = strpcpyf(&ptr, size, "%s (userspace) ", FORMAT_TIMESPAN(t->finish_time - t->userspace_time, USEC_PER_MSEC));
543 if (t->kernel_done_time > 0)
544 strpcpyf(&ptr, size, "= %s ", FORMAT_TIMESPAN(t->firmware_time + t->finish_time, USEC_PER_MSEC));
545
546 if (unit_id && timestamp_is_set(activated_time)) {
547 usec_t base = t->userspace_time > 0 ? t->userspace_time : t->reverse_offset;
548
549 size = strpcpyf(&ptr, size, "\n%s reached after %s in userspace", unit_id,
550 FORMAT_TIMESPAN(activated_time - base, USEC_PER_MSEC));
551 } else if (unit_id && activated_time == 0)
552 size = strpcpyf(&ptr, size, "\n%s was never reached", unit_id);
553 else if (unit_id && activated_time == USEC_INFINITY)
554 size = strpcpyf(&ptr, size, "\nCould not get time to reach %s.", unit_id);
555 else if (!unit_id)
556 size = strpcpyf(&ptr, size, "\ncould not find default.target");
557
558 ptr = strdup(buf);
559 if (!ptr)
560 return log_oom();
561
562 *_buf = ptr;
563 return 0;
564 }
565
566 static void svg_graph_box(double height, double begin, double end) {
567 /* outside box, fill */
568 svg("<rect class=\"box\" x=\"0\" y=\"0\" width=\"%.03f\" height=\"%.03f\" />\n",
569 SCALE_X * (end - begin),
570 SCALE_Y * height);
571
572 for (long long i = ((long long) (begin / 100000)) * 100000; i <= end; i += 100000) {
573 /* lines for each second */
574 if (i % 5000000 == 0)
575 svg(" <line class=\"sec5\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
576 " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
577 SCALE_X * i,
578 SCALE_X * i,
579 SCALE_Y * height,
580 SCALE_X * i,
581 -5.0,
582 0.000001 * i);
583 else if (i % 1000000 == 0)
584 svg(" <line class=\"sec1\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
585 " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
586 SCALE_X * i,
587 SCALE_X * i,
588 SCALE_Y * height,
589 SCALE_X * i,
590 -5.0,
591 0.000001 * i);
592 else
593 svg(" <line class=\"sec01\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
594 SCALE_X * i,
595 SCALE_X * i,
596 SCALE_Y * height);
597 }
598 }
599
600 static int plot_unit_times(UnitTimes *u, double width, int y) {
601 bool b;
602
603 if (!u->name)
604 return 0;
605
606 svg_bar("activating", u->activating, u->activated, y);
607 svg_bar("active", u->activated, u->deactivating, y);
608 svg_bar("deactivating", u->deactivating, u->deactivated, y);
609
610 /* place the text on the left if we have passed the half of the svg width */
611 b = u->activating * SCALE_X < width / 2;
612 if (u->time)
613 svg_text(b, u->activating, y, "%s (%s)",
614 u->name, FORMAT_TIMESPAN(u->time, USEC_PER_MSEC));
615 else
616 svg_text(b, u->activating, y, "%s", u->name);
617
618 return 1;
619 }
620
621 static int analyze_plot(int argc, char *argv[], void *userdata) {
622 _cleanup_(free_host_infop) HostInfo *host = NULL;
623 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
624 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
625 _cleanup_free_ char *pretty_times = NULL;
626 bool use_full_bus = arg_scope == UNIT_FILE_SYSTEM;
627 BootTimes *boot;
628 UnitTimes *u;
629 int n, m = 1, y = 0, r;
630 double width;
631
632 r = acquire_bus(&bus, &use_full_bus);
633 if (r < 0)
634 return bus_log_connect_error(r);
635
636 n = acquire_boot_times(bus, &boot);
637 if (n < 0)
638 return n;
639
640 n = pretty_boot_time(bus, &pretty_times);
641 if (n < 0)
642 return n;
643
644 if (use_full_bus || arg_scope != UNIT_FILE_SYSTEM) {
645 n = acquire_host_info(bus, &host);
646 if (n < 0)
647 return n;
648 }
649
650 n = acquire_time_data(bus, &times);
651 if (n <= 0)
652 return n;
653
654 typesafe_qsort(times, n, compare_unit_start);
655
656 width = SCALE_X * (boot->firmware_time + boot->finish_time);
657 if (width < 800.0)
658 width = 800.0;
659
660 if (boot->firmware_time > boot->loader_time)
661 m++;
662 if (boot->loader_time > 0) {
663 m++;
664 if (width < 1000.0)
665 width = 1000.0;
666 }
667 if (boot->initrd_time > 0)
668 m++;
669 if (boot->kernel_done_time > 0)
670 m++;
671
672 for (u = times; u->has_data; u++) {
673 double text_start, text_width;
674
675 if (u->activating > boot->finish_time) {
676 u->name = mfree(u->name);
677 continue;
678 }
679
680 /* If the text cannot fit on the left side then
681 * increase the svg width so it fits on the right.
682 * TODO: calculate the text width more accurately */
683 text_width = 8.0 * strlen(u->name);
684 text_start = (boot->firmware_time + u->activating) * SCALE_X;
685 if (text_width > text_start && text_width + text_start > width)
686 width = text_width + text_start;
687
688 if (u->deactivated > u->activating &&
689 u->deactivated <= boot->finish_time &&
690 u->activated == 0 && u->deactivating == 0)
691 u->activated = u->deactivating = u->deactivated;
692 if (u->activated < u->activating || u->activated > boot->finish_time)
693 u->activated = boot->finish_time;
694 if (u->deactivating < u->activated || u->deactivating > boot->finish_time)
695 u->deactivating = boot->finish_time;
696 if (u->deactivated < u->deactivating || u->deactivated > boot->finish_time)
697 u->deactivated = boot->finish_time;
698 m++;
699 }
700
701 svg("<?xml version=\"1.0\" standalone=\"no\"?>\n"
702 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" "
703 "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
704
705 svg("<svg width=\"%.0fpx\" height=\"%.0fpx\" version=\"1.1\" "
706 "xmlns=\"http://www.w3.org/2000/svg\">\n\n",
707 80.0 + width, 150.0 + (m * SCALE_Y) +
708 5 * SCALE_Y /* legend */);
709
710 /* write some basic info as a comment, including some help */
711 svg("<!-- This file is a systemd-analyze SVG file. It is best rendered in a -->\n"
712 "<!-- browser such as Chrome, Chromium or Firefox. Other applications -->\n"
713 "<!-- that render these files properly but much slower are ImageMagick, -->\n"
714 "<!-- gimp, inkscape, etc. To display the files on your system, just -->\n"
715 "<!-- point your browser to this file. -->\n\n"
716 "<!-- This plot was generated by systemd-analyze version %-16.16s -->\n\n", GIT_VERSION);
717
718 /* style sheet */
719 svg("<defs>\n <style type=\"text/css\">\n <![CDATA[\n"
720 " rect { stroke-width: 1; stroke-opacity: 0; }\n"
721 " rect.background { fill: rgb(255,255,255); }\n"
722 " rect.activating { fill: rgb(255,0,0); fill-opacity: 0.7; }\n"
723 " rect.active { fill: rgb(200,150,150); fill-opacity: 0.7; }\n"
724 " rect.deactivating { fill: rgb(150,100,100); fill-opacity: 0.7; }\n"
725 " rect.kernel { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
726 " rect.initrd { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
727 " rect.firmware { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
728 " rect.loader { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
729 " rect.userspace { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
730 " rect.security { fill: rgb(144,238,144); fill-opacity: 0.7; }\n"
731 " rect.generators { fill: rgb(102,204,255); fill-opacity: 0.7; }\n"
732 " rect.unitsload { fill: rgb( 82,184,255); fill-opacity: 0.7; }\n"
733 " rect.box { fill: rgb(240,240,240); stroke: rgb(192,192,192); }\n"
734 " line { stroke: rgb(64,64,64); stroke-width: 1; }\n"
735 "// line.sec1 { }\n"
736 " line.sec5 { stroke-width: 2; }\n"
737 " line.sec01 { stroke: rgb(224,224,224); stroke-width: 1; }\n"
738 " text { font-family: Verdana, Helvetica; font-size: 14px; }\n"
739 " text.left { font-family: Verdana, Helvetica; font-size: 14px; text-anchor: start; }\n"
740 " text.right { font-family: Verdana, Helvetica; font-size: 14px; text-anchor: end; }\n"
741 " text.sec { font-size: 10px; }\n"
742 " ]]>\n </style>\n</defs>\n\n");
743
744 svg("<rect class=\"background\" width=\"100%%\" height=\"100%%\" />\n");
745 svg("<text x=\"20\" y=\"50\">%s</text>", pretty_times);
746 if (host)
747 svg("<text x=\"20\" y=\"30\">%s %s (%s %s %s) %s %s</text>",
748 isempty(host->os_pretty_name) ? "Linux" : host->os_pretty_name,
749 strempty(host->hostname),
750 strempty(host->kernel_name),
751 strempty(host->kernel_release),
752 strempty(host->kernel_version),
753 strempty(host->architecture),
754 strempty(host->virtualization));
755
756 svg("<g transform=\"translate(%.3f,100)\">\n", 20.0 + (SCALE_X * boot->firmware_time));
757 svg_graph_box(m, -(double) boot->firmware_time, boot->finish_time);
758
759 if (boot->firmware_time > 0) {
760 svg_bar("firmware", -(double) boot->firmware_time, -(double) boot->loader_time, y);
761 svg_text(true, -(double) boot->firmware_time, y, "firmware");
762 y++;
763 }
764 if (boot->loader_time > 0) {
765 svg_bar("loader", -(double) boot->loader_time, 0, y);
766 svg_text(true, -(double) boot->loader_time, y, "loader");
767 y++;
768 }
769 if (boot->kernel_done_time > 0) {
770 svg_bar("kernel", 0, boot->kernel_done_time, y);
771 svg_text(true, 0, y, "kernel");
772 y++;
773 }
774 if (boot->initrd_time > 0) {
775 svg_bar("initrd", boot->initrd_time, boot->userspace_time, y);
776 if (boot->initrd_security_start_time < boot->initrd_security_finish_time)
777 svg_bar("security", boot->initrd_security_start_time, boot->initrd_security_finish_time, y);
778 if (boot->initrd_generators_start_time < boot->initrd_generators_finish_time)
779 svg_bar("generators", boot->initrd_generators_start_time, boot->initrd_generators_finish_time, y);
780 if (boot->initrd_unitsload_start_time < boot->initrd_unitsload_finish_time)
781 svg_bar("unitsload", boot->initrd_unitsload_start_time, boot->initrd_unitsload_finish_time, y);
782 svg_text(true, boot->initrd_time, y, "initrd");
783 y++;
784 }
785
786 for (u = times; u->has_data; u++) {
787 if (u->activating >= boot->userspace_time)
788 break;
789
790 y += plot_unit_times(u, width, y);
791 }
792
793 svg_bar("active", boot->userspace_time, boot->finish_time, y);
794 if (boot->security_start_time > 0)
795 svg_bar("security", boot->security_start_time, boot->security_finish_time, y);
796 svg_bar("generators", boot->generators_start_time, boot->generators_finish_time, y);
797 svg_bar("unitsload", boot->unitsload_start_time, boot->unitsload_finish_time, y);
798 svg_text(true, boot->userspace_time, y, "systemd");
799 y++;
800
801 for (; u->has_data; u++)
802 y += plot_unit_times(u, width, y);
803
804 svg("</g>\n");
805
806 /* Legend */
807 svg("<g transform=\"translate(20,100)\">\n");
808 y++;
809 svg_bar("activating", 0, 300000, y);
810 svg_text(true, 400000, y, "Activating");
811 y++;
812 svg_bar("active", 0, 300000, y);
813 svg_text(true, 400000, y, "Active");
814 y++;
815 svg_bar("deactivating", 0, 300000, y);
816 svg_text(true, 400000, y, "Deactivating");
817 y++;
818 if (boot->security_start_time > 0) {
819 svg_bar("security", 0, 300000, y);
820 svg_text(true, 400000, y, "Setting up security module");
821 y++;
822 }
823 svg_bar("generators", 0, 300000, y);
824 svg_text(true, 400000, y, "Generators");
825 y++;
826 svg_bar("unitsload", 0, 300000, y);
827 svg_text(true, 400000, y, "Loading unit files");
828 y++;
829
830 svg("</g>\n\n");
831
832 svg("</svg>\n");
833
834 return 0;
835 }
836
837 static int list_dependencies_print(
838 const char *name,
839 unsigned level,
840 unsigned branches,
841 bool last,
842 UnitTimes *times,
843 BootTimes *boot) {
844
845 for (unsigned i = level; i != 0; i--)
846 printf("%s", special_glyph(branches & (1 << (i-1)) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE));
847
848 printf("%s", special_glyph(last ? SPECIAL_GLYPH_TREE_RIGHT : SPECIAL_GLYPH_TREE_BRANCH));
849
850 if (times) {
851 if (times->time > 0)
852 printf("%s%s @%s +%s%s", ansi_highlight_red(), name,
853 FORMAT_TIMESPAN(times->activating - boot->userspace_time, USEC_PER_MSEC),
854 FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
855 else if (times->activated > boot->userspace_time)
856 printf("%s @%s", name, FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
857 else
858 printf("%s", name);
859 } else
860 printf("%s", name);
861 printf("\n");
862
863 return 0;
864 }
865
866 static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***deps) {
867 _cleanup_free_ char *path = NULL;
868
869 assert(bus);
870 assert(name);
871 assert(deps);
872
873 path = unit_dbus_path_from_name(name);
874 if (!path)
875 return -ENOMEM;
876
877 return bus_get_unit_property_strv(bus, path, "After", deps);
878 }
879
880 static Hashmap *unit_times_hashmap;
881
882 static int list_dependencies_compare(char *const *a, char *const *b) {
883 usec_t usa = 0, usb = 0;
884 UnitTimes *times;
885
886 times = hashmap_get(unit_times_hashmap, *a);
887 if (times)
888 usa = times->activated;
889 times = hashmap_get(unit_times_hashmap, *b);
890 if (times)
891 usb = times->activated;
892
893 return CMP(usb, usa);
894 }
895
896 static bool times_in_range(const UnitTimes *times, const BootTimes *boot) {
897 return times && times->activated > 0 && times->activated <= boot->finish_time;
898 }
899
900 static int list_dependencies_one(sd_bus *bus, const char *name, unsigned level, char ***units, unsigned branches) {
901 _cleanup_strv_free_ char **deps = NULL;
902 char **c;
903 int r;
904 usec_t service_longest = 0;
905 int to_print = 0;
906 UnitTimes *times;
907 BootTimes *boot;
908
909 if (strv_extend(units, name))
910 return log_oom();
911
912 r = list_dependencies_get_dependencies(bus, name, &deps);
913 if (r < 0)
914 return r;
915
916 typesafe_qsort(deps, strv_length(deps), list_dependencies_compare);
917
918 r = acquire_boot_times(bus, &boot);
919 if (r < 0)
920 return r;
921
922 STRV_FOREACH(c, deps) {
923 times = hashmap_get(unit_times_hashmap, *c);
924 if (times_in_range(times, boot) && times->activated >= service_longest)
925 service_longest = times->activated;
926 }
927
928 if (service_longest == 0)
929 return r;
930
931 STRV_FOREACH(c, deps) {
932 times = hashmap_get(unit_times_hashmap, *c);
933 if (times_in_range(times, boot) && service_longest - times->activated <= arg_fuzz)
934 to_print++;
935 }
936
937 if (!to_print)
938 return r;
939
940 STRV_FOREACH(c, deps) {
941 times = hashmap_get(unit_times_hashmap, *c);
942 if (!times_in_range(times, boot) || service_longest - times->activated > arg_fuzz)
943 continue;
944
945 to_print--;
946
947 r = list_dependencies_print(*c, level, branches, to_print == 0, times, boot);
948 if (r < 0)
949 return r;
950
951 if (strv_contains(*units, *c)) {
952 r = list_dependencies_print("...", level + 1, (branches << 1) | (to_print ? 1 : 0),
953 true, NULL, boot);
954 if (r < 0)
955 return r;
956 continue;
957 }
958
959 r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (to_print ? 1 : 0));
960 if (r < 0)
961 return r;
962
963 if (to_print == 0)
964 break;
965 }
966 return 0;
967 }
968
969 static int list_dependencies(sd_bus *bus, const char *name) {
970 _cleanup_strv_free_ char **units = NULL;
971 UnitTimes *times;
972 int r;
973 const char *id;
974 _cleanup_free_ char *path = NULL;
975 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
976 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
977 BootTimes *boot;
978
979 assert(bus);
980
981 path = unit_dbus_path_from_name(name);
982 if (!path)
983 return -ENOMEM;
984
985 r = sd_bus_get_property(
986 bus,
987 "org.freedesktop.systemd1",
988 path,
989 "org.freedesktop.systemd1.Unit",
990 "Id",
991 &error,
992 &reply,
993 "s");
994 if (r < 0)
995 return log_error_errno(r, "Failed to get ID: %s", bus_error_message(&error, r));
996
997 r = sd_bus_message_read(reply, "s", &id);
998 if (r < 0)
999 return bus_log_parse_error(r);
1000
1001 times = hashmap_get(unit_times_hashmap, id);
1002
1003 r = acquire_boot_times(bus, &boot);
1004 if (r < 0)
1005 return r;
1006
1007 if (times) {
1008 if (times->time)
1009 printf("%s%s +%s%s\n", ansi_highlight_red(), id,
1010 FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
1011 else if (times->activated > boot->userspace_time)
1012 printf("%s @%s\n", id,
1013 FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
1014 else
1015 printf("%s\n", id);
1016 }
1017
1018 return list_dependencies_one(bus, name, 0, &units, 0);
1019 }
1020
1021 static int analyze_critical_chain(int argc, char *argv[], void *userdata) {
1022 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1023 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
1024 Hashmap *h;
1025 int n, r;
1026
1027 r = acquire_bus(&bus, NULL);
1028 if (r < 0)
1029 return bus_log_connect_error(r);
1030
1031 n = acquire_time_data(bus, &times);
1032 if (n <= 0)
1033 return n;
1034
1035 h = hashmap_new(&string_hash_ops);
1036 if (!h)
1037 return log_oom();
1038
1039 for (UnitTimes *u = times; u->has_data; u++) {
1040 r = hashmap_put(h, u->name, u);
1041 if (r < 0)
1042 return log_error_errno(r, "Failed to add entry to hashmap: %m");
1043 }
1044 unit_times_hashmap = h;
1045
1046 (void) pager_open(arg_pager_flags);
1047
1048 puts("The time when unit became active or started is printed after the \"@\" character.\n"
1049 "The time the unit took to start is printed after the \"+\" character.\n");
1050
1051 if (argc > 1) {
1052 char **name;
1053 STRV_FOREACH(name, strv_skip(argv, 1))
1054 list_dependencies(bus, *name);
1055 } else
1056 list_dependencies(bus, SPECIAL_DEFAULT_TARGET);
1057
1058 h = hashmap_free(h);
1059 return 0;
1060 }
1061
1062 static int analyze_blame(int argc, char *argv[], void *userdata) {
1063 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1064 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
1065 _cleanup_(table_unrefp) Table *table = NULL;
1066 TableCell *cell;
1067 int n, r;
1068
1069 r = acquire_bus(&bus, NULL);
1070 if (r < 0)
1071 return bus_log_connect_error(r);
1072
1073 n = acquire_time_data(bus, &times);
1074 if (n <= 0)
1075 return n;
1076
1077 table = table_new("time", "unit");
1078 if (!table)
1079 return log_oom();
1080
1081 table_set_header(table, false);
1082
1083 assert_se(cell = table_get_cell(table, 0, 0));
1084 r = table_set_ellipsize_percent(table, cell, 100);
1085 if (r < 0)
1086 return r;
1087
1088 r = table_set_align_percent(table, cell, 100);
1089 if (r < 0)
1090 return r;
1091
1092 assert_se(cell = table_get_cell(table, 0, 1));
1093 r = table_set_ellipsize_percent(table, cell, 100);
1094 if (r < 0)
1095 return r;
1096
1097 r = table_set_sort(table, (size_t) 0);
1098 if (r < 0)
1099 return r;
1100
1101 r = table_set_reverse(table, 0, true);
1102 if (r < 0)
1103 return r;
1104
1105 for (UnitTimes *u = times; u->has_data; u++) {
1106 if (u->time <= 0)
1107 continue;
1108
1109 r = table_add_many(table,
1110 TABLE_TIMESPAN_MSEC, u->time,
1111 TABLE_STRING, u->name);
1112 if (r < 0)
1113 return table_log_add_error(r);
1114 }
1115
1116 (void) pager_open(arg_pager_flags);
1117
1118 return table_print(table, NULL);
1119 }
1120
1121 static int analyze_time(int argc, char *argv[], void *userdata) {
1122 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1123 _cleanup_free_ char *buf = NULL;
1124 int r;
1125
1126 r = acquire_bus(&bus, NULL);
1127 if (r < 0)
1128 return bus_log_connect_error(r);
1129
1130 r = pretty_boot_time(bus, &buf);
1131 if (r < 0)
1132 return r;
1133
1134 puts(buf);
1135 return 0;
1136 }
1137
1138 static int graph_one_property(
1139 sd_bus *bus,
1140 const UnitInfo *u,
1141 const char *prop,
1142 const char *color,
1143 char *patterns[],
1144 char *from_patterns[],
1145 char *to_patterns[]) {
1146
1147 _cleanup_strv_free_ char **units = NULL;
1148 char **unit;
1149 int r;
1150 bool match_patterns;
1151
1152 assert(u);
1153 assert(prop);
1154 assert(color);
1155
1156 match_patterns = strv_fnmatch(patterns, u->id);
1157
1158 if (!strv_isempty(from_patterns) && !match_patterns && !strv_fnmatch(from_patterns, u->id))
1159 return 0;
1160
1161 r = bus_get_unit_property_strv(bus, u->unit_path, prop, &units);
1162 if (r < 0)
1163 return r;
1164
1165 STRV_FOREACH(unit, units) {
1166 bool match_patterns2;
1167
1168 match_patterns2 = strv_fnmatch(patterns, *unit);
1169
1170 if (!strv_isempty(to_patterns) && !match_patterns2 && !strv_fnmatch(to_patterns, *unit))
1171 continue;
1172
1173 if (!strv_isempty(patterns) && !match_patterns && !match_patterns2)
1174 continue;
1175
1176 printf("\t\"%s\"->\"%s\" [color=\"%s\"];\n", u->id, *unit, color);
1177 }
1178
1179 return 0;
1180 }
1181
1182 static int graph_one(sd_bus *bus, const UnitInfo *u, char *patterns[], char *from_patterns[], char *to_patterns[]) {
1183 int r;
1184
1185 assert(bus);
1186 assert(u);
1187
1188 if (IN_SET(arg_dot, DEP_ORDER, DEP_ALL)) {
1189 r = graph_one_property(bus, u, "After", "green", patterns, from_patterns, to_patterns);
1190 if (r < 0)
1191 return r;
1192 }
1193
1194 if (IN_SET(arg_dot, DEP_REQUIRE, DEP_ALL)) {
1195 r = graph_one_property(bus, u, "Requires", "black", patterns, from_patterns, to_patterns);
1196 if (r < 0)
1197 return r;
1198 r = graph_one_property(bus, u, "Requisite", "darkblue", patterns, from_patterns, to_patterns);
1199 if (r < 0)
1200 return r;
1201 r = graph_one_property(bus, u, "Wants", "grey66", patterns, from_patterns, to_patterns);
1202 if (r < 0)
1203 return r;
1204 r = graph_one_property(bus, u, "Conflicts", "red", patterns, from_patterns, to_patterns);
1205 if (r < 0)
1206 return r;
1207 }
1208
1209 return 0;
1210 }
1211
1212 static int expand_patterns(sd_bus *bus, char **patterns, char ***ret) {
1213 _cleanup_strv_free_ char **expanded_patterns = NULL;
1214 char **pattern;
1215 int r;
1216
1217 STRV_FOREACH(pattern, patterns) {
1218 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1219 _cleanup_free_ char *unit = NULL, *unit_id = NULL;
1220
1221 if (strv_extend(&expanded_patterns, *pattern) < 0)
1222 return log_oom();
1223
1224 if (string_is_glob(*pattern))
1225 continue;
1226
1227 unit = unit_dbus_path_from_name(*pattern);
1228 if (!unit)
1229 return log_oom();
1230
1231 r = sd_bus_get_property_string(
1232 bus,
1233 "org.freedesktop.systemd1",
1234 unit,
1235 "org.freedesktop.systemd1.Unit",
1236 "Id",
1237 &error,
1238 &unit_id);
1239 if (r < 0)
1240 return log_error_errno(r, "Failed to get ID: %s", bus_error_message(&error, r));
1241
1242 if (!streq(*pattern, unit_id)) {
1243 if (strv_extend(&expanded_patterns, unit_id) < 0)
1244 return log_oom();
1245 }
1246 }
1247
1248 *ret = TAKE_PTR(expanded_patterns); /* do not free */
1249
1250 return 0;
1251 }
1252
1253 static int dot(int argc, char *argv[], void *userdata) {
1254 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1255 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1256 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1257 _cleanup_strv_free_ char **expanded_patterns = NULL;
1258 _cleanup_strv_free_ char **expanded_from_patterns = NULL;
1259 _cleanup_strv_free_ char **expanded_to_patterns = NULL;
1260 int r;
1261 UnitInfo u;
1262
1263 r = acquire_bus(&bus, NULL);
1264 if (r < 0)
1265 return bus_log_connect_error(r);
1266
1267 r = expand_patterns(bus, strv_skip(argv, 1), &expanded_patterns);
1268 if (r < 0)
1269 return r;
1270
1271 r = expand_patterns(bus, arg_dot_from_patterns, &expanded_from_patterns);
1272 if (r < 0)
1273 return r;
1274
1275 r = expand_patterns(bus, arg_dot_to_patterns, &expanded_to_patterns);
1276 if (r < 0)
1277 return r;
1278
1279 r = bus_call_method(bus, bus_systemd_mgr, "ListUnits", &error, &reply, NULL);
1280 if (r < 0)
1281 log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
1282
1283 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
1284 if (r < 0)
1285 return bus_log_parse_error(r);
1286
1287 printf("digraph systemd {\n");
1288
1289 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
1290
1291 r = graph_one(bus, &u, expanded_patterns, expanded_from_patterns, expanded_to_patterns);
1292 if (r < 0)
1293 return r;
1294 }
1295 if (r < 0)
1296 return bus_log_parse_error(r);
1297
1298 printf("}\n");
1299
1300 log_info(" Color legend: black = Requires\n"
1301 " dark blue = Requisite\n"
1302 " dark grey = Wants\n"
1303 " red = Conflicts\n"
1304 " green = After\n");
1305
1306 if (on_tty())
1307 log_notice("-- You probably want to process this output with graphviz' dot tool.\n"
1308 "-- Try a shell pipeline like 'systemd-analyze dot | dot -Tsvg > systemd.svg'!\n");
1309
1310 return 0;
1311 }
1312
1313 static int dump_fallback(sd_bus *bus) {
1314 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1315 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1316 const char *text = NULL;
1317 int r;
1318
1319 assert(bus);
1320
1321 r = bus_call_method(bus, bus_systemd_mgr, "Dump", &error, &reply, NULL);
1322 if (r < 0)
1323 return log_error_errno(r, "Failed to issue method call Dump: %s", bus_error_message(&error, r));
1324
1325 r = sd_bus_message_read(reply, "s", &text);
1326 if (r < 0)
1327 return bus_log_parse_error(r);
1328
1329 fputs(text, stdout);
1330 return 0;
1331 }
1332
1333 static int dump(int argc, char *argv[], void *userdata) {
1334 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1335 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1336 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1337 int fd = -1;
1338 int r;
1339
1340 r = acquire_bus(&bus, NULL);
1341 if (r < 0)
1342 return bus_log_connect_error(r);
1343
1344 (void) pager_open(arg_pager_flags);
1345
1346 if (!sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD))
1347 return dump_fallback(bus);
1348
1349 r = bus_call_method(bus, bus_systemd_mgr, "DumpByFileDescriptor", &error, &reply, NULL);
1350 if (r < 0) {
1351 /* fall back to Dump if DumpByFileDescriptor is not supported */
1352 if (!IN_SET(r, -EACCES, -EBADR))
1353 return log_error_errno(r, "Failed to issue method call DumpByFileDescriptor: %s",
1354 bus_error_message(&error, r));
1355
1356 return dump_fallback(bus);
1357 }
1358
1359 r = sd_bus_message_read(reply, "h", &fd);
1360 if (r < 0)
1361 return bus_log_parse_error(r);
1362
1363 fflush(stdout);
1364 return copy_bytes(fd, STDOUT_FILENO, UINT64_MAX, 0);
1365 }
1366
1367 static int cat_config(int argc, char *argv[], void *userdata) {
1368 char **arg, **list;
1369 int r;
1370
1371 (void) pager_open(arg_pager_flags);
1372
1373 list = strv_skip(argv, 1);
1374 STRV_FOREACH(arg, list) {
1375 const char *t = NULL;
1376
1377 if (arg != list)
1378 print_separator();
1379
1380 if (path_is_absolute(*arg)) {
1381 const char *dir;
1382
1383 NULSTR_FOREACH(dir, CONF_PATHS_NULSTR("")) {
1384 t = path_startswith(*arg, dir);
1385 if (t)
1386 break;
1387 }
1388
1389 if (!t)
1390 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1391 "Path %s does not start with any known prefix.", *arg);
1392 } else
1393 t = *arg;
1394
1395 r = conf_files_cat(arg_root, t);
1396 if (r < 0)
1397 return r;
1398 }
1399
1400 return 0;
1401 }
1402
1403 static int set_log_level(int argc, char *argv[], void *userdata) {
1404 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1405 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1406 int r;
1407
1408 assert(argc == 2);
1409 assert(argv);
1410
1411 r = acquire_bus(&bus, NULL);
1412 if (r < 0)
1413 return bus_log_connect_error(r);
1414
1415 r = bus_set_property(bus, bus_systemd_mgr, "LogLevel", &error, "s", argv[1]);
1416 if (r < 0)
1417 return log_error_errno(r, "Failed to issue method call: %s", bus_error_message(&error, r));
1418
1419 return 0;
1420 }
1421
1422 static int get_log_level(int argc, char *argv[], void *userdata) {
1423 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1424 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1425 _cleanup_free_ char *level = NULL;
1426 int r;
1427
1428 r = acquire_bus(&bus, NULL);
1429 if (r < 0)
1430 return bus_log_connect_error(r);
1431
1432 r = bus_get_property_string(bus, bus_systemd_mgr, "LogLevel", &error, &level);
1433 if (r < 0)
1434 return log_error_errno(r, "Failed to get log level: %s", bus_error_message(&error, r));
1435
1436 puts(level);
1437 return 0;
1438 }
1439
1440 static int get_or_set_log_level(int argc, char *argv[], void *userdata) {
1441 return (argc == 1) ? get_log_level(argc, argv, userdata) : set_log_level(argc, argv, userdata);
1442 }
1443
1444 static int set_log_target(int argc, char *argv[], void *userdata) {
1445 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1446 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1447 int r;
1448
1449 assert(argc == 2);
1450 assert(argv);
1451
1452 r = acquire_bus(&bus, NULL);
1453 if (r < 0)
1454 return bus_log_connect_error(r);
1455
1456 r = bus_set_property(bus, bus_systemd_mgr, "LogTarget", &error, "s", argv[1]);
1457 if (r < 0)
1458 return log_error_errno(r, "Failed to issue method call: %s", bus_error_message(&error, r));
1459
1460 return 0;
1461 }
1462
1463 static int get_log_target(int argc, char *argv[], void *userdata) {
1464 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1465 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1466 _cleanup_free_ char *target = NULL;
1467 int r;
1468
1469 r = acquire_bus(&bus, NULL);
1470 if (r < 0)
1471 return bus_log_connect_error(r);
1472
1473 r = bus_get_property_string(bus, bus_systemd_mgr, "LogTarget", &error, &target);
1474 if (r < 0)
1475 return log_error_errno(r, "Failed to get log target: %s", bus_error_message(&error, r));
1476
1477 puts(target);
1478 return 0;
1479 }
1480
1481 static int get_or_set_log_target(int argc, char *argv[], void *userdata) {
1482 return (argc == 1) ? get_log_target(argc, argv, userdata) : set_log_target(argc, argv, userdata);
1483 }
1484
1485 static bool strv_fnmatch_strv_or_empty(char* const* patterns, char **strv, int flags) {
1486 char **s;
1487 STRV_FOREACH(s, strv)
1488 if (strv_fnmatch_or_empty(patterns, *s, flags))
1489 return true;
1490
1491 return false;
1492 }
1493
1494 static int do_unit_files(int argc, char *argv[], void *userdata) {
1495 _cleanup_(lookup_paths_free) LookupPaths lp = {};
1496 _cleanup_hashmap_free_ Hashmap *unit_ids = NULL;
1497 _cleanup_hashmap_free_ Hashmap *unit_names = NULL;
1498 char **patterns = strv_skip(argv, 1);
1499 const char *k, *dst;
1500 char **v;
1501 int r;
1502
1503 r = lookup_paths_init(&lp, arg_scope, 0, NULL);
1504 if (r < 0)
1505 return log_error_errno(r, "lookup_paths_init() failed: %m");
1506
1507 r = unit_file_build_name_map(&lp, NULL, &unit_ids, &unit_names, NULL);
1508 if (r < 0)
1509 return log_error_errno(r, "unit_file_build_name_map() failed: %m");
1510
1511 HASHMAP_FOREACH_KEY(dst, k, unit_ids) {
1512 if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) &&
1513 !strv_fnmatch_or_empty(patterns, dst, FNM_NOESCAPE))
1514 continue;
1515
1516 printf("ids: %s → %s\n", k, dst);
1517 }
1518
1519 HASHMAP_FOREACH_KEY(v, k, unit_names) {
1520 if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) &&
1521 !strv_fnmatch_strv_or_empty(patterns, v, FNM_NOESCAPE))
1522 continue;
1523
1524 _cleanup_free_ char *j = strv_join(v, ", ");
1525 printf("aliases: %s ← %s\n", k, j);
1526 }
1527
1528 return 0;
1529 }
1530
1531 static int dump_unit_paths(int argc, char *argv[], void *userdata) {
1532 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1533 int r;
1534 char **p;
1535
1536 r = lookup_paths_init(&paths, arg_scope, 0, NULL);
1537 if (r < 0)
1538 return log_error_errno(r, "lookup_paths_init() failed: %m");
1539
1540 STRV_FOREACH(p, paths.search_path)
1541 puts(*p);
1542
1543 return 0;
1544 }
1545
1546 static int dump_exit_status(int argc, char *argv[], void *userdata) {
1547 _cleanup_(table_unrefp) Table *table = NULL;
1548 int r;
1549
1550 table = table_new("name", "status", "class");
1551 if (!table)
1552 return log_oom();
1553
1554 r = table_set_align_percent(table, table_get_cell(table, 0, 1), 100);
1555 if (r < 0)
1556 return log_error_errno(r, "Failed to right-align status: %m");
1557
1558 if (strv_isempty(strv_skip(argv, 1)))
1559 for (size_t i = 0; i < ELEMENTSOF(exit_status_mappings); i++) {
1560 if (!exit_status_mappings[i].name)
1561 continue;
1562
1563 r = table_add_many(table,
1564 TABLE_STRING, exit_status_mappings[i].name,
1565 TABLE_INT, (int) i,
1566 TABLE_STRING, exit_status_class(i));
1567 if (r < 0)
1568 return table_log_add_error(r);
1569 }
1570 else
1571 for (int i = 1; i < argc; i++) {
1572 int status;
1573
1574 status = exit_status_from_string(argv[i]);
1575 if (status < 0)
1576 return log_error_errno(status, "Invalid exit status \"%s\".", argv[i]);
1577
1578 assert(status >= 0 && (size_t) status < ELEMENTSOF(exit_status_mappings));
1579 r = table_add_many(table,
1580 TABLE_STRING, exit_status_mappings[status].name ?: "-",
1581 TABLE_INT, status,
1582 TABLE_STRING, exit_status_class(status) ?: "-");
1583 if (r < 0)
1584 return table_log_add_error(r);
1585 }
1586
1587 (void) pager_open(arg_pager_flags);
1588
1589 return table_print(table, NULL);
1590 }
1591
1592 static int dump_capabilities(int argc, char *argv[], void *userdata) {
1593 _cleanup_(table_unrefp) Table *table = NULL;
1594 unsigned last_cap;
1595 int r;
1596
1597 table = table_new("name", "number");
1598 if (!table)
1599 return log_oom();
1600
1601 (void) table_set_align_percent(table, table_get_cell(table, 0, 1), 100);
1602
1603 /* Determine the maximum of the last cap known by the kernel and by us */
1604 last_cap = MAX((unsigned) CAP_LAST_CAP, cap_last_cap());
1605
1606 if (strv_isempty(strv_skip(argv, 1)))
1607 for (unsigned c = 0; c <= last_cap; c++) {
1608 r = table_add_many(table,
1609 TABLE_STRING, capability_to_name(c) ?: "cap_???",
1610 TABLE_UINT, c);
1611 if (r < 0)
1612 return table_log_add_error(r);
1613 }
1614 else {
1615 for (int i = 1; i < argc; i++) {
1616 int c;
1617
1618 c = capability_from_name(argv[i]);
1619 if (c < 0 || (unsigned) c > last_cap)
1620 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Capability \"%s\" not known.", argv[i]);
1621
1622 r = table_add_many(table,
1623 TABLE_STRING, capability_to_name(c) ?: "cap_???",
1624 TABLE_UINT, (unsigned) c);
1625 if (r < 0)
1626 return table_log_add_error(r);
1627 }
1628
1629 (void) table_set_sort(table, (size_t) 1);
1630 }
1631
1632 (void) pager_open(arg_pager_flags);
1633
1634 return table_print(table, NULL);
1635 }
1636
1637 #if HAVE_SECCOMP
1638
1639 static int load_kernel_syscalls(Set **ret) {
1640 _cleanup_set_free_ Set *syscalls = NULL;
1641 _cleanup_fclose_ FILE *f = NULL;
1642 int r;
1643
1644 /* Let's read the available system calls from the list of available tracing events. Slightly dirty,
1645 * but good enough for analysis purposes. */
1646
1647 f = fopen("/sys/kernel/tracing/available_events", "re");
1648 if (!f) {
1649 /* We tried the non-debugfs mount point and that didn't work. If it wasn't mounted, maybe the
1650 * old debugfs mount point works? */
1651 f = fopen("/sys/kernel/debug/tracing/available_events", "re");
1652 if (!f)
1653 return log_full_errno(IN_SET(errno, EPERM, EACCES, ENOENT) ? LOG_DEBUG : LOG_WARNING, errno,
1654 "Can't read open tracefs' available_events file: %m");
1655 }
1656
1657 for (;;) {
1658 _cleanup_free_ char *line = NULL;
1659 const char *e;
1660
1661 r = read_line(f, LONG_LINE_MAX, &line);
1662 if (r < 0)
1663 return log_error_errno(r, "Failed to read system call list: %m");
1664 if (r == 0)
1665 break;
1666
1667 e = startswith(line, "syscalls:sys_enter_");
1668 if (!e)
1669 continue;
1670
1671 /* These are named differently inside the kernel than their external name for historical
1672 * reasons. Let's hide them here. */
1673 if (STR_IN_SET(e, "newuname", "newfstat", "newstat", "newlstat", "sysctl"))
1674 continue;
1675
1676 r = set_put_strdup(&syscalls, e);
1677 if (r < 0)
1678 return log_error_errno(r, "Failed to add system call to list: %m");
1679 }
1680
1681 *ret = TAKE_PTR(syscalls);
1682 return 0;
1683 }
1684
1685 static void syscall_set_remove(Set *s, const SyscallFilterSet *set) {
1686 const char *syscall;
1687
1688 NULSTR_FOREACH(syscall, set->value) {
1689 if (syscall[0] == '@')
1690 continue;
1691
1692 free(set_remove(s, syscall));
1693 }
1694 }
1695
1696 static void dump_syscall_filter(const SyscallFilterSet *set) {
1697 const char *syscall;
1698
1699 printf("%s%s%s\n"
1700 " # %s\n",
1701 ansi_highlight(),
1702 set->name,
1703 ansi_normal(),
1704 set->help);
1705
1706 NULSTR_FOREACH(syscall, set->value)
1707 printf(" %s%s%s\n", syscall[0] == '@' ? ansi_underline() : "", syscall, ansi_normal());
1708 }
1709
1710 static int dump_syscall_filters(int argc, char *argv[], void *userdata) {
1711 bool first = true;
1712
1713 (void) pager_open(arg_pager_flags);
1714
1715 if (strv_isempty(strv_skip(argv, 1))) {
1716 _cleanup_set_free_ Set *kernel = NULL, *known = NULL;
1717 const char *sys;
1718 int k;
1719
1720 NULSTR_FOREACH(sys, syscall_filter_sets[SYSCALL_FILTER_SET_KNOWN].value)
1721 if (set_put_strdup(&known, sys) < 0)
1722 return log_oom();
1723
1724 k = load_kernel_syscalls(&kernel);
1725
1726 for (int i = 0; i < _SYSCALL_FILTER_SET_MAX; i++) {
1727 const SyscallFilterSet *set = syscall_filter_sets + i;
1728 if (!first)
1729 puts("");
1730
1731 dump_syscall_filter(set);
1732 syscall_set_remove(kernel, set);
1733 if (i != SYSCALL_FILTER_SET_KNOWN)
1734 syscall_set_remove(known, set);
1735 first = false;
1736 }
1737
1738 if (!set_isempty(known)) {
1739 _cleanup_free_ char **l = NULL;
1740 char **syscall;
1741
1742 printf("\n"
1743 "# %sUngrouped System Calls%s (known but not included in any of the groups except @known):\n",
1744 ansi_highlight(), ansi_normal());
1745
1746 l = set_get_strv(known);
1747 if (!l)
1748 return log_oom();
1749
1750 strv_sort(l);
1751
1752 STRV_FOREACH(syscall, l)
1753 printf("# %s\n", *syscall);
1754 }
1755
1756 if (k < 0) {
1757 fputc('\n', stdout);
1758 fflush(stdout);
1759 log_notice_errno(k, "# Not showing unlisted system calls, couldn't retrieve kernel system call list: %m");
1760 } else if (!set_isempty(kernel)) {
1761 _cleanup_free_ char **l = NULL;
1762 char **syscall;
1763
1764 printf("\n"
1765 "# %sUnlisted System Calls%s (supported by the local kernel, but not included in any of the groups listed above):\n",
1766 ansi_highlight(), ansi_normal());
1767
1768 l = set_get_strv(kernel);
1769 if (!l)
1770 return log_oom();
1771
1772 strv_sort(l);
1773
1774 STRV_FOREACH(syscall, l)
1775 printf("# %s\n", *syscall);
1776 }
1777 } else {
1778 char **name;
1779
1780 STRV_FOREACH(name, strv_skip(argv, 1)) {
1781 const SyscallFilterSet *set;
1782
1783 if (!first)
1784 puts("");
1785
1786 set = syscall_filter_set_find(*name);
1787 if (!set) {
1788 /* make sure the error appears below normal output */
1789 fflush(stdout);
1790
1791 return log_error_errno(SYNTHETIC_ERRNO(ENOENT),
1792 "Filter set \"%s\" not found.", *name);
1793 }
1794
1795 dump_syscall_filter(set);
1796 first = false;
1797 }
1798 }
1799
1800 return 0;
1801 }
1802
1803 #else
1804 static int dump_syscall_filters(int argc, char *argv[], void *userdata) {
1805 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Not compiled with syscall filters, sorry.");
1806 }
1807 #endif
1808
1809 static void parsing_hint(const char *p, bool calendar, bool timestamp, bool timespan) {
1810 if (calendar && calendar_spec_from_string(p, NULL) >= 0)
1811 log_notice("Hint: this expression is a valid calendar specification. "
1812 "Use 'systemd-analyze calendar \"%s\"' instead?", p);
1813 if (timestamp && parse_timestamp(p, NULL) >= 0)
1814 log_notice("Hint: this expression is a valid timestamp. "
1815 "Use 'systemd-analyze timestamp \"%s\"' instead?", p);
1816 if (timespan && parse_time(p, NULL, USEC_PER_SEC) >= 0)
1817 log_notice("Hint: this expression is a valid timespan. "
1818 "Use 'systemd-analyze timespan \"%s\"' instead?", p);
1819 }
1820
1821 static int dump_timespan(int argc, char *argv[], void *userdata) {
1822 char **input_timespan;
1823
1824 STRV_FOREACH(input_timespan, strv_skip(argv, 1)) {
1825 _cleanup_(table_unrefp) Table *table = NULL;
1826 usec_t output_usecs;
1827 TableCell *cell;
1828 int r;
1829
1830 r = parse_time(*input_timespan, &output_usecs, USEC_PER_SEC);
1831 if (r < 0) {
1832 log_error_errno(r, "Failed to parse time span '%s': %m", *input_timespan);
1833 parsing_hint(*input_timespan, true, true, false);
1834 return r;
1835 }
1836
1837 table = table_new("name", "value");
1838 if (!table)
1839 return log_oom();
1840
1841 table_set_header(table, false);
1842
1843 assert_se(cell = table_get_cell(table, 0, 0));
1844 r = table_set_ellipsize_percent(table, cell, 100);
1845 if (r < 0)
1846 return r;
1847
1848 r = table_set_align_percent(table, cell, 100);
1849 if (r < 0)
1850 return r;
1851
1852 assert_se(cell = table_get_cell(table, 0, 1));
1853 r = table_set_ellipsize_percent(table, cell, 100);
1854 if (r < 0)
1855 return r;
1856
1857 r = table_add_many(table,
1858 TABLE_STRING, "Original:",
1859 TABLE_STRING, *input_timespan);
1860 if (r < 0)
1861 return table_log_add_error(r);
1862
1863 r = table_add_cell_stringf(table, NULL, "%ss:", special_glyph(SPECIAL_GLYPH_MU));
1864 if (r < 0)
1865 return table_log_add_error(r);
1866
1867 r = table_add_many(table,
1868 TABLE_UINT64, output_usecs,
1869 TABLE_STRING, "Human:",
1870 TABLE_TIMESPAN, output_usecs,
1871 TABLE_SET_COLOR, ansi_highlight());
1872 if (r < 0)
1873 return table_log_add_error(r);
1874
1875 r = table_print(table, NULL);
1876 if (r < 0)
1877 return r;
1878
1879 if (input_timespan[1])
1880 putchar('\n');
1881 }
1882
1883 return EXIT_SUCCESS;
1884 }
1885
1886 static int test_timestamp_one(const char *p) {
1887 _cleanup_(table_unrefp) Table *table = NULL;
1888 TableCell *cell;
1889 usec_t usec;
1890 int r;
1891
1892 r = parse_timestamp(p, &usec);
1893 if (r < 0) {
1894 log_error_errno(r, "Failed to parse \"%s\": %m", p);
1895 parsing_hint(p, true, false, true);
1896 return r;
1897 }
1898
1899 table = table_new("name", "value");
1900 if (!table)
1901 return log_oom();
1902
1903 table_set_header(table, false);
1904
1905 assert_se(cell = table_get_cell(table, 0, 0));
1906 r = table_set_ellipsize_percent(table, cell, 100);
1907 if (r < 0)
1908 return r;
1909
1910 r = table_set_align_percent(table, cell, 100);
1911 if (r < 0)
1912 return r;
1913
1914 assert_se(cell = table_get_cell(table, 0, 1));
1915 r = table_set_ellipsize_percent(table, cell, 100);
1916 if (r < 0)
1917 return r;
1918
1919 r = table_add_many(table,
1920 TABLE_STRING, "Original form:",
1921 TABLE_STRING, p,
1922 TABLE_STRING, "Normalized form:",
1923 TABLE_TIMESTAMP, usec,
1924 TABLE_SET_COLOR, ansi_highlight_blue());
1925 if (r < 0)
1926 return table_log_add_error(r);
1927
1928 if (!in_utc_timezone()) {
1929 r = table_add_many(table,
1930 TABLE_STRING, "(in UTC):",
1931 TABLE_TIMESTAMP_UTC, usec);
1932 if (r < 0)
1933 return table_log_add_error(r);
1934 }
1935
1936 r = table_add_cell(table, NULL, TABLE_STRING, "UNIX seconds:");
1937 if (r < 0)
1938 return table_log_add_error(r);
1939
1940 if (usec % USEC_PER_SEC == 0)
1941 r = table_add_cell_stringf(table, NULL, "@%"PRI_USEC,
1942 usec / USEC_PER_SEC);
1943 else
1944 r = table_add_cell_stringf(table, NULL, "@%"PRI_USEC".%06"PRI_USEC"",
1945 usec / USEC_PER_SEC,
1946 usec % USEC_PER_SEC);
1947 if (r < 0)
1948 return r;
1949
1950 r = table_add_many(table,
1951 TABLE_STRING, "From now:",
1952 TABLE_TIMESTAMP_RELATIVE, usec);
1953 if (r < 0)
1954 return table_log_add_error(r);
1955
1956 return table_print(table, NULL);
1957 }
1958
1959 static int test_timestamp(int argc, char *argv[], void *userdata) {
1960 int ret = 0, r;
1961 char **p;
1962
1963 STRV_FOREACH(p, strv_skip(argv, 1)) {
1964 r = test_timestamp_one(*p);
1965 if (ret == 0 && r < 0)
1966 ret = r;
1967
1968 if (*(p + 1))
1969 putchar('\n');
1970 }
1971
1972 return ret;
1973 }
1974
1975 static int test_calendar_one(usec_t n, const char *p) {
1976 _cleanup_(calendar_spec_freep) CalendarSpec *spec = NULL;
1977 _cleanup_(table_unrefp) Table *table = NULL;
1978 _cleanup_free_ char *t = NULL;
1979 TableCell *cell;
1980 int r;
1981
1982 r = calendar_spec_from_string(p, &spec);
1983 if (r < 0) {
1984 log_error_errno(r, "Failed to parse calendar specification '%s': %m", p);
1985 parsing_hint(p, false, true, true);
1986 return r;
1987 }
1988
1989 r = calendar_spec_to_string(spec, &t);
1990 if (r < 0)
1991 return log_error_errno(r, "Failed to format calendar specification '%s': %m", p);
1992
1993 table = table_new("name", "value");
1994 if (!table)
1995 return log_oom();
1996
1997 table_set_header(table, false);
1998
1999 assert_se(cell = table_get_cell(table, 0, 0));
2000 r = table_set_ellipsize_percent(table, cell, 100);
2001 if (r < 0)
2002 return r;
2003
2004 r = table_set_align_percent(table, cell, 100);
2005 if (r < 0)
2006 return r;
2007
2008 assert_se(cell = table_get_cell(table, 0, 1));
2009 r = table_set_ellipsize_percent(table, cell, 100);
2010 if (r < 0)
2011 return r;
2012
2013 if (!streq(t, p)) {
2014 r = table_add_many(table,
2015 TABLE_STRING, "Original form:",
2016 TABLE_STRING, p);
2017 if (r < 0)
2018 return table_log_add_error(r);
2019 }
2020
2021 r = table_add_many(table,
2022 TABLE_STRING, "Normalized form:",
2023 TABLE_STRING, t);
2024 if (r < 0)
2025 return table_log_add_error(r);
2026
2027 for (unsigned i = 0; i < arg_iterations; i++) {
2028 usec_t next;
2029
2030 r = calendar_spec_next_usec(spec, n, &next);
2031 if (r == -ENOENT) {
2032 if (i == 0) {
2033 r = table_add_many(table,
2034 TABLE_STRING, "Next elapse:",
2035 TABLE_STRING, "never",
2036 TABLE_SET_COLOR, ansi_highlight_yellow());
2037 if (r < 0)
2038 return table_log_add_error(r);
2039 }
2040 break;
2041 }
2042 if (r < 0)
2043 return log_error_errno(r, "Failed to determine next elapse for '%s': %m", p);
2044
2045 if (i == 0) {
2046 r = table_add_many(table,
2047 TABLE_STRING, "Next elapse:",
2048 TABLE_TIMESTAMP, next,
2049 TABLE_SET_COLOR, ansi_highlight_blue());
2050 if (r < 0)
2051 return table_log_add_error(r);
2052 } else {
2053 int k = DECIMAL_STR_WIDTH(i + 1);
2054
2055 if (k < 8)
2056 k = 8 - k;
2057 else
2058 k = 0;
2059
2060 r = table_add_cell_stringf(table, NULL, "Iter. #%u:", i+1);
2061 if (r < 0)
2062 return table_log_add_error(r);
2063
2064 r = table_add_many(table,
2065 TABLE_TIMESTAMP, next,
2066 TABLE_SET_COLOR, ansi_highlight_blue());
2067 if (r < 0)
2068 return table_log_add_error(r);
2069 }
2070
2071 if (!in_utc_timezone()) {
2072 r = table_add_many(table,
2073 TABLE_STRING, "(in UTC):",
2074 TABLE_TIMESTAMP_UTC, next);
2075 if (r < 0)
2076 return table_log_add_error(r);
2077 }
2078
2079 r = table_add_many(table,
2080 TABLE_STRING, "From now:",
2081 TABLE_TIMESTAMP_RELATIVE, next);
2082 if (r < 0)
2083 return table_log_add_error(r);
2084
2085 n = next;
2086 }
2087
2088 return table_print(table, NULL);
2089 }
2090
2091 static int test_calendar(int argc, char *argv[], void *userdata) {
2092 int ret = 0, r;
2093 char **p;
2094 usec_t n;
2095
2096 if (arg_base_time != USEC_INFINITY)
2097 n = arg_base_time;
2098 else
2099 n = now(CLOCK_REALTIME); /* We want to use the same "base" for all expressions */
2100
2101 STRV_FOREACH(p, strv_skip(argv, 1)) {
2102 r = test_calendar_one(n, *p);
2103 if (ret == 0 && r < 0)
2104 ret = r;
2105
2106 if (*(p + 1))
2107 putchar('\n');
2108 }
2109
2110 return ret;
2111 }
2112
2113 static int service_watchdogs(int argc, char *argv[], void *userdata) {
2114 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2115 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2116 int b, r;
2117
2118 assert(IN_SET(argc, 1, 2));
2119 assert(argv);
2120
2121 r = acquire_bus(&bus, NULL);
2122 if (r < 0)
2123 return bus_log_connect_error(r);
2124
2125 if (argc == 1) {
2126 /* get ServiceWatchdogs */
2127 r = bus_get_property_trivial(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, 'b', &b);
2128 if (r < 0)
2129 return log_error_errno(r, "Failed to get service-watchdog state: %s", bus_error_message(&error, r));
2130
2131 printf("%s\n", yes_no(!!b));
2132
2133 } else {
2134 /* set ServiceWatchdogs */
2135 b = parse_boolean(argv[1]);
2136 if (b < 0)
2137 return log_error_errno(b, "Failed to parse service-watchdogs argument: %m");
2138
2139 r = bus_set_property(bus, bus_systemd_mgr, "ServiceWatchdogs", &error, "b", b);
2140 if (r < 0)
2141 return log_error_errno(r, "Failed to set service-watchdog state: %s", bus_error_message(&error, r));
2142 }
2143
2144 return 0;
2145 }
2146
2147 static int do_condition(int argc, char *argv[], void *userdata) {
2148 return verify_conditions(strv_skip(argv, 1), arg_scope);
2149 }
2150
2151 static int do_verify(int argc, char *argv[], void *userdata) {
2152 return verify_units(strv_skip(argv, 1), arg_scope, arg_man, arg_generators, arg_recursive_errors, arg_root);
2153 }
2154
2155 static int do_security(int argc, char *argv[], void *userdata) {
2156 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2157 int r;
2158
2159 r = acquire_bus(&bus, NULL);
2160 if (r < 0)
2161 return bus_log_connect_error(r);
2162
2163 (void) pager_open(arg_pager_flags);
2164
2165 return analyze_security(bus, strv_skip(argv, 1), arg_scope, arg_man, arg_generators, arg_offline, arg_threshold, arg_root, 0);
2166 }
2167
2168 static int help(int argc, char *argv[], void *userdata) {
2169 _cleanup_free_ char *link = NULL, *dot_link = NULL;
2170 int r;
2171
2172 (void) pager_open(arg_pager_flags);
2173
2174 r = terminal_urlify_man("systemd-analyze", "1", &link);
2175 if (r < 0)
2176 return log_oom();
2177
2178 /* Not using terminal_urlify_man() for this, since we don't want the "man page" text suffix in this case. */
2179 r = terminal_urlify("man:dot(1)", "dot(1)", &dot_link);
2180 if (r < 0)
2181 return log_oom();
2182
2183 printf("%s [OPTIONS...] COMMAND ...\n\n"
2184 "%sProfile systemd, show unit dependencies, check unit files.%s\n"
2185 "\nCommands:\n"
2186 " [time] Print time required to boot the machine\n"
2187 " blame Print list of running units ordered by\n"
2188 " time to init\n"
2189 " critical-chain [UNIT...] Print a tree of the time critical chain\n"
2190 " of units\n"
2191 " plot Output SVG graphic showing service\n"
2192 " initialization\n"
2193 " dot [UNIT...] Output dependency graph in %s format\n"
2194 " dump Output state serialization of service\n"
2195 " manager\n"
2196 " cat-config Show configuration file and drop-ins\n"
2197 " unit-files List files and symlinks for units\n"
2198 " unit-paths List load directories for units\n"
2199 " exit-status [STATUS...] List exit status definitions\n"
2200 " capability [CAP...] List capability definitions\n"
2201 " syscall-filter [NAME...] Print list of syscalls in seccomp\n"
2202 " filter\n"
2203 " condition CONDITION... Evaluate conditions and asserts\n"
2204 " verify FILE... Check unit files for correctness\n"
2205 " calendar SPEC... Validate repetitive calendar time\n"
2206 " events\n"
2207 " timestamp TIMESTAMP... Validate a timestamp\n"
2208 " timespan SPAN... Validate a time span\n"
2209 " security [UNIT...] Analyze security of unit\n"
2210 "\nOptions:\n"
2211 " -h --help Show this help\n"
2212 " --recursive-errors=MODE Control which units are verified\n"
2213 " --offline=BOOL Perform a security review on unit file(s)\n"
2214 " --threshold=N Exit with a non-zero status when overall\n"
2215 " exposure level is over threshold value\n"
2216 " --version Show package version\n"
2217 " --no-pager Do not pipe output into a pager\n"
2218 " --system Operate on system systemd instance\n"
2219 " --user Operate on user systemd instance\n"
2220 " --global Operate on global user configuration\n"
2221 " -H --host=[USER@]HOST Operate on remote host\n"
2222 " -M --machine=CONTAINER Operate on local container\n"
2223 " --order Show only order in the graph\n"
2224 " --require Show only requirement in the graph\n"
2225 " --from-pattern=GLOB Show only origins in the graph\n"
2226 " --to-pattern=GLOB Show only destinations in the graph\n"
2227 " --fuzz=SECONDS Also print services which finished SECONDS\n"
2228 " earlier than the latest in the branch\n"
2229 " --man[=BOOL] Do [not] check for existence of man pages\n"
2230 " --generators[=BOOL] Do [not] run unit generators\n"
2231 " (requires privileges)\n"
2232 " --iterations=N Show the specified number of iterations\n"
2233 " --base-time=TIMESTAMP Calculate calendar times relative to\n"
2234 " specified time\n"
2235 "\nSee the %s for details.\n",
2236 program_invocation_short_name,
2237 ansi_highlight(),
2238 ansi_normal(),
2239 dot_link,
2240 link);
2241
2242 /* When updating this list, including descriptions, apply changes to
2243 * shell-completion/bash/systemd-analyze and shell-completion/zsh/_systemd-analyze too. */
2244
2245 return 0;
2246 }
2247
2248 static int parse_argv(int argc, char *argv[]) {
2249 enum {
2250 ARG_VERSION = 0x100,
2251 ARG_ORDER,
2252 ARG_REQUIRE,
2253 ARG_ROOT,
2254 ARG_IMAGE,
2255 ARG_SYSTEM,
2256 ARG_USER,
2257 ARG_GLOBAL,
2258 ARG_DOT_FROM_PATTERN,
2259 ARG_DOT_TO_PATTERN,
2260 ARG_FUZZ,
2261 ARG_NO_PAGER,
2262 ARG_MAN,
2263 ARG_GENERATORS,
2264 ARG_ITERATIONS,
2265 ARG_BASE_TIME,
2266 ARG_RECURSIVE_ERRORS,
2267 ARG_OFFLINE,
2268 ARG_THRESHOLD,
2269 };
2270
2271 static const struct option options[] = {
2272 { "help", no_argument, NULL, 'h' },
2273 { "version", no_argument, NULL, ARG_VERSION },
2274 { "order", no_argument, NULL, ARG_ORDER },
2275 { "require", no_argument, NULL, ARG_REQUIRE },
2276 { "root", required_argument, NULL, ARG_ROOT },
2277 { "image", required_argument, NULL, ARG_IMAGE },
2278 { "recursive-errors", required_argument, NULL, ARG_RECURSIVE_ERRORS },
2279 { "offline", required_argument, NULL, ARG_OFFLINE },
2280 { "threshold", required_argument, NULL, ARG_THRESHOLD },
2281 { "system", no_argument, NULL, ARG_SYSTEM },
2282 { "user", no_argument, NULL, ARG_USER },
2283 { "global", no_argument, NULL, ARG_GLOBAL },
2284 { "from-pattern", required_argument, NULL, ARG_DOT_FROM_PATTERN },
2285 { "to-pattern", required_argument, NULL, ARG_DOT_TO_PATTERN },
2286 { "fuzz", required_argument, NULL, ARG_FUZZ },
2287 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
2288 { "man", optional_argument, NULL, ARG_MAN },
2289 { "generators", optional_argument, NULL, ARG_GENERATORS },
2290 { "host", required_argument, NULL, 'H' },
2291 { "machine", required_argument, NULL, 'M' },
2292 { "iterations", required_argument, NULL, ARG_ITERATIONS },
2293 { "base-time", required_argument, NULL, ARG_BASE_TIME },
2294 {}
2295 };
2296
2297 int r, c;
2298
2299 assert(argc >= 0);
2300 assert(argv);
2301
2302 while ((c = getopt_long(argc, argv, "hH:M:", options, NULL)) >= 0)
2303 switch (c) {
2304
2305 case 'h':
2306 return help(0, NULL, NULL);
2307
2308 case ARG_RECURSIVE_ERRORS:
2309 if (streq(optarg, "help")) {
2310 DUMP_STRING_TABLE(recursive_errors, RecursiveErrors, _RECURSIVE_ERRORS_MAX);
2311 return 0;
2312 }
2313 r = recursive_errors_from_string(optarg);
2314 if (r < 0)
2315 return log_error_errno(r, "Unknown mode passed to --recursive-errors='%s'.", optarg);
2316
2317 arg_recursive_errors = r;
2318 break;
2319
2320 case ARG_VERSION:
2321 return version();
2322
2323 case ARG_ROOT:
2324 r = parse_path_argument(optarg, /* suppress_root= */ true, &arg_root);
2325 if (r < 0)
2326 return r;
2327 break;
2328
2329 case ARG_IMAGE:
2330 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
2331 if (r < 0)
2332 return r;
2333 break;
2334
2335 case ARG_SYSTEM:
2336 arg_scope = UNIT_FILE_SYSTEM;
2337 break;
2338
2339 case ARG_USER:
2340 arg_scope = UNIT_FILE_USER;
2341 break;
2342
2343 case ARG_GLOBAL:
2344 arg_scope = UNIT_FILE_GLOBAL;
2345 break;
2346
2347 case ARG_ORDER:
2348 arg_dot = DEP_ORDER;
2349 break;
2350
2351 case ARG_REQUIRE:
2352 arg_dot = DEP_REQUIRE;
2353 break;
2354
2355 case ARG_DOT_FROM_PATTERN:
2356 if (strv_extend(&arg_dot_from_patterns, optarg) < 0)
2357 return log_oom();
2358
2359 break;
2360
2361 case ARG_DOT_TO_PATTERN:
2362 if (strv_extend(&arg_dot_to_patterns, optarg) < 0)
2363 return log_oom();
2364
2365 break;
2366
2367 case ARG_FUZZ:
2368 r = parse_sec(optarg, &arg_fuzz);
2369 if (r < 0)
2370 return r;
2371 break;
2372
2373 case ARG_NO_PAGER:
2374 arg_pager_flags |= PAGER_DISABLE;
2375 break;
2376
2377 case 'H':
2378 arg_transport = BUS_TRANSPORT_REMOTE;
2379 arg_host = optarg;
2380 break;
2381
2382 case 'M':
2383 arg_transport = BUS_TRANSPORT_MACHINE;
2384 arg_host = optarg;
2385 break;
2386
2387 case ARG_MAN:
2388 r = parse_boolean_argument("--man", optarg, &arg_man);
2389 if (r < 0)
2390 return r;
2391 break;
2392
2393 case ARG_GENERATORS:
2394 r = parse_boolean_argument("--generators", optarg, &arg_generators);
2395 if (r < 0)
2396 return r;
2397 break;
2398
2399 case ARG_OFFLINE:
2400 r = parse_boolean_argument("--offline", optarg, &arg_offline);
2401 if (r < 0)
2402 return r;
2403 break;
2404
2405 case ARG_THRESHOLD:
2406 r = safe_atou(optarg, &arg_threshold);
2407 if (r < 0 || arg_threshold > 100)
2408 return log_error_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse threshold: %s", optarg);
2409
2410 break;
2411
2412 case ARG_ITERATIONS:
2413 r = safe_atou(optarg, &arg_iterations);
2414 if (r < 0)
2415 return log_error_errno(r, "Failed to parse iterations: %s", optarg);
2416
2417 break;
2418
2419 case ARG_BASE_TIME:
2420 r = parse_timestamp(optarg, &arg_base_time);
2421 if (r < 0)
2422 return log_error_errno(r, "Failed to parse --base-time= parameter: %s", optarg);
2423
2424 break;
2425
2426 case '?':
2427 return -EINVAL;
2428
2429 default:
2430 assert_not_reached();
2431 }
2432
2433 if (arg_offline && !streq_ptr(argv[optind], "security"))
2434 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2435 "Option --offline= is only supported for security right now.");
2436
2437 if (arg_threshold != 100 && !streq_ptr(argv[optind], "security"))
2438 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2439 "Option --threshold= is only supported for security right now.");
2440
2441 if (arg_scope == UNIT_FILE_GLOBAL &&
2442 !STR_IN_SET(argv[optind] ?: "time", "dot", "unit-paths", "verify"))
2443 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2444 "Option --global only makes sense with verbs dot, unit-paths, verify.");
2445
2446 if (streq_ptr(argv[optind], "cat-config") && arg_scope == UNIT_FILE_USER)
2447 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2448 "Option --user is not supported for cat-config right now.");
2449
2450 if ((arg_root || arg_image) && (!STRPTR_IN_SET(argv[optind], "cat-config", "verify")) &&
2451 (!(streq_ptr(argv[optind], "security") && arg_offline)))
2452 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2453 "Options --root= and --image= are only supported for cat-config, verify and security when used with --offline= right now.");
2454
2455 /* Having both an image and a root is not supported by the code */
2456 if (arg_root && arg_image)
2457 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
2458
2459 return 1; /* work to do */
2460 }
2461
2462 static int run(int argc, char *argv[]) {
2463 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
2464 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
2465 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
2466
2467 static const Verb verbs[] = {
2468 { "help", VERB_ANY, VERB_ANY, 0, help },
2469 { "time", VERB_ANY, 1, VERB_DEFAULT, analyze_time },
2470 { "blame", VERB_ANY, 1, 0, analyze_blame },
2471 { "critical-chain", VERB_ANY, VERB_ANY, 0, analyze_critical_chain },
2472 { "plot", VERB_ANY, 1, 0, analyze_plot },
2473 { "dot", VERB_ANY, VERB_ANY, 0, dot },
2474 /* The following seven verbs are deprecated */
2475 { "log-level", VERB_ANY, 2, 0, get_or_set_log_level },
2476 { "log-target", VERB_ANY, 2, 0, get_or_set_log_target },
2477 { "set-log-level", 2, 2, 0, set_log_level },
2478 { "get-log-level", VERB_ANY, 1, 0, get_log_level },
2479 { "set-log-target", 2, 2, 0, set_log_target },
2480 { "get-log-target", VERB_ANY, 1, 0, get_log_target },
2481 { "service-watchdogs", VERB_ANY, 2, 0, service_watchdogs },
2482 { "dump", VERB_ANY, 1, 0, dump },
2483 { "cat-config", 2, VERB_ANY, 0, cat_config },
2484 { "unit-files", VERB_ANY, VERB_ANY, 0, do_unit_files },
2485 { "unit-paths", 1, 1, 0, dump_unit_paths },
2486 { "exit-status", VERB_ANY, VERB_ANY, 0, dump_exit_status },
2487 { "syscall-filter", VERB_ANY, VERB_ANY, 0, dump_syscall_filters },
2488 { "capability", VERB_ANY, VERB_ANY, 0, dump_capabilities },
2489 { "condition", 2, VERB_ANY, 0, do_condition },
2490 { "verify", 2, VERB_ANY, 0, do_verify },
2491 { "calendar", 2, VERB_ANY, 0, test_calendar },
2492 { "timestamp", 2, VERB_ANY, 0, test_timestamp },
2493 { "timespan", 2, VERB_ANY, 0, dump_timespan },
2494 { "security", VERB_ANY, VERB_ANY, 0, do_security },
2495 {}
2496 };
2497
2498 int r;
2499
2500 setlocale(LC_ALL, "");
2501 setlocale(LC_NUMERIC, "C"); /* we want to format/parse floats in C style */
2502
2503 log_setup();
2504
2505 r = parse_argv(argc, argv);
2506 if (r <= 0)
2507 return r;
2508
2509 /* Open up and mount the image */
2510 if (arg_image) {
2511 assert(!arg_root);
2512
2513 r = mount_image_privately_interactively(
2514 arg_image,
2515 DISSECT_IMAGE_GENERIC_ROOT |
2516 DISSECT_IMAGE_RELAX_VAR_CHECK |
2517 DISSECT_IMAGE_READ_ONLY,
2518 &unlink_dir,
2519 &loop_device,
2520 &decrypted_image);
2521 if (r < 0)
2522 return r;
2523
2524 arg_root = strdup(unlink_dir);
2525 if (!arg_root)
2526 return log_oom();
2527 }
2528
2529 return dispatch_verb(argc, argv, verbs, NULL);
2530 }
2531
2532 DEFINE_MAIN_FUNCTION(run);