]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/analyze/analyze.c
analyze: highlight the range of deprecated verbs in comments a bit better
[thirdparty/systemd.git] / src / analyze / analyze.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
2265fbf7 2/***
96b2fb93 3 Copyright © 2013 Simon Peeters
2265fbf7
SP
4***/
5
2265fbf7 6#include <getopt.h>
3f1c1287 7#include <inttypes.h>
3f6fd1ba
LP
8#include <stdio.h>
9#include <stdlib.h>
ca78ad1d 10#include <unistd.h>
2265fbf7 11
048ecf5b 12#include "sd-bus.h"
3f6fd1ba 13
b5efdb8a 14#include "alloc-util.h"
30bddc06 15#include "analyze.h"
5229b03c 16#include "analyze-calendar.h"
edfea9fe 17#include "analyze-condition.h"
cccd2af6 18#include "analyze-dot.h"
25eb70af 19#include "analyze-dump.h"
917e6554 20#include "analyze-elf.h"
08e36480 21#include "analyze-filesystems.h"
ec16f3b6 22#include "analyze-security.h"
2b04e72c 23#include "analyze-service-watchdogs.h"
389638d3 24#include "analyze-syscall-filter.h"
30bddc06 25#include "analyze-timespan.h"
503ccaaa 26#include "analyze-timestamp.h"
3f6fd1ba 27#include "analyze-verify.h"
048ecf5b 28#include "bus-error.h"
9b71e4ab 29#include "bus-locator.h"
807542be 30#include "bus-map-properties.h"
20b16441 31#include "bus-unit-util.h"
6d86f4bd 32#include "calendarspec.h"
b2af819b
LP
33#include "cap-list.h"
34#include "capability-util.h"
854a42fb 35#include "conf-files.h"
c0a1bfac 36#include "copy.h"
90bea744 37#include "def.h"
76ed04d9 38#include "exit-status.h"
da845dab 39#include "extract-word.h"
c0a1bfac 40#include "fd-util.h"
cdf6258c 41#include "fileio.h"
b41711cd 42#include "filesystems.h"
d8bfdbe1 43#include "format-table.h"
7d50b32a 44#include "glob-util.h"
bb150966 45#include "hashmap.h"
8752c575 46#include "locale-util.h"
3f6fd1ba 47#include "log.h"
d665c7b2 48#include "main-func.h"
e5ea5c3a 49#include "mount-util.h"
d8b4d14d 50#include "nulstr-util.h"
9ea9d4cf 51#include "pager.h"
599c7c54 52#include "parse-argument.h"
6bedfcbb 53#include "parse-util.h"
854a42fb 54#include "path-util.h"
294bf0c3 55#include "pretty-print.h"
da845dab 56#include "rm-rf.h"
349cc4a5 57#if HAVE_SECCOMP
294bf0c3 58# include "seccomp-util.h"
0f734bdc 59#endif
760877e9 60#include "sort-util.h"
3f6fd1ba 61#include "special.h"
b41711cd 62#include "stat-util.h"
3cc3dc77 63#include "string-table.h"
3f6fd1ba
LP
64#include "strv.h"
65#include "strxcpyx.h"
288a74cc 66#include "terminal-util.h"
760877e9 67#include "time-util.h"
da845dab 68#include "tmpfile-util.h"
3f6fd1ba
LP
69#include "unit-name.h"
70#include "util.h"
a87b151a 71#include "verb-log-control.h"
a6bcef29 72#include "verbs.h"
47350c5f 73#include "version.h"
2265fbf7 74
1ace223c 75#define SCALE_X (0.1 / 1000.0) /* pixels per us */
a213b7e9 76#define SCALE_Y (20.0)
2f6eb835 77
2265fbf7 78#define svg(...) printf(__VA_ARGS__)
c170f3a4
LP
79
80#define svg_bar(class, x1, x2, y) \
2265fbf7 81 svg(" <rect class=\"%s\" x=\"%.03f\" y=\"%.03f\" width=\"%.03f\" height=\"%.03f\" />\n", \
c170f3a4 82 (class), \
2f6eb835
LP
83 SCALE_X * (x1), SCALE_Y * (y), \
84 SCALE_X * ((x2) - (x1)), SCALE_Y - 1.0)
c170f3a4
LP
85
86#define svg_text(b, x, y, format, ...) \
87 do { \
2f6eb835 88 svg(" <text class=\"%s\" x=\"%.03f\" y=\"%.03f\">", (b) ? "left" : "right", SCALE_X * (x) + (b ? 5.0 : -5.0), SCALE_Y * (y) + 14.0); \
c170f3a4
LP
89 svg(format, ## __VA_ARGS__); \
90 svg("</text>\n"); \
9ed794a3 91 } while (false)
2265fbf7 92
cccd2af6
LP
93DotMode arg_dot = DEP_ALL;
94char **arg_dot_from_patterns = NULL, **arg_dot_to_patterns = NULL;
9ea9d4cf 95static usec_t arg_fuzz = 0;
08e36480 96PagerFlags arg_pager_flags = 0;
25eb70af 97BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
f72b7018 98static const char *arg_host = NULL;
28b35ef2 99static UnitFileScope arg_scope = UNIT_FILE_SYSTEM;
3cc3dc77 100static RecursiveErrors arg_recursive_errors = RECURSIVE_ERRORS_YES;
1d3bc017 101static bool arg_man = true;
641c0fd1 102static bool arg_generators = false;
782671bc 103static char *arg_root = NULL;
e5ea5c3a 104static char *arg_image = NULL;
ecfd082b 105static char *arg_security_policy = NULL;
bb43d853 106static bool arg_offline = false;
dfbda879 107static unsigned arg_threshold = 100;
5229b03c
LP
108unsigned arg_iterations = 1;
109usec_t arg_base_time = USEC_INFINITY;
8de7929d 110static char *arg_unit = NULL;
4b4a8ef7 111static JsonFormatFlags arg_json_format_flags = JSON_FORMAT_OFF;
08e36480 112bool arg_quiet = false;
04469211 113static char *arg_profile = NULL;
bb150966 114
d665c7b2
YW
115STATIC_DESTRUCTOR_REGISTER(arg_dot_from_patterns, strv_freep);
116STATIC_DESTRUCTOR_REGISTER(arg_dot_to_patterns, strv_freep);
782671bc 117STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
e5ea5c3a 118STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
ecfd082b 119STATIC_DESTRUCTOR_REGISTER(arg_security_policy, freep);
8de7929d 120STATIC_DESTRUCTOR_REGISTER(arg_unit, freep);
04469211 121STATIC_DESTRUCTOR_REGISTER(arg_profile, freep);
d665c7b2 122
6aa601c5 123typedef struct BootTimes {
c170f3a4
LP
124 usec_t firmware_time;
125 usec_t loader_time;
126 usec_t kernel_time;
127 usec_t kernel_done_time;
128 usec_t initrd_time;
129 usec_t userspace_time;
130 usec_t finish_time;
c2e0d600
TA
131 usec_t security_start_time;
132 usec_t security_finish_time;
518d10e9
UTL
133 usec_t generators_start_time;
134 usec_t generators_finish_time;
d9acfb71
TA
135 usec_t unitsload_start_time;
136 usec_t unitsload_finish_time;
8c006565
YW
137 usec_t initrd_security_start_time;
138 usec_t initrd_security_finish_time;
139 usec_t initrd_generators_start_time;
140 usec_t initrd_generators_finish_time;
141 usec_t initrd_unitsload_start_time;
142 usec_t initrd_unitsload_finish_time;
06bef033
IS
143
144 /*
145 * If we're analyzing the user instance, all timestamps will be offset
146 * by its own start-up timestamp, which may be arbitrarily big.
147 * With "plot", this causes arbitrarily wide output SVG files which almost
148 * completely consist of empty space. Thus we cancel out this offset.
149 *
150 * This offset is subtracted from times above by acquire_boot_times(),
151 * but it still needs to be subtracted from unit-specific timestamps
152 * (so it is stored here for reference).
153 */
154 usec_t reverse_offset;
6aa601c5 155} BootTimes;
9ea9d4cf 156
6aa601c5 157typedef struct UnitTimes {
df560cf6 158 bool has_data;
2265fbf7 159 char *name;
cc27380c
TA
160 usec_t activating;
161 usec_t activated;
162 usec_t deactivated;
163 usec_t deactivating;
c170f3a4 164 usec_t time;
6aa601c5 165} UnitTimes;
2265fbf7 166
6aa601c5 167typedef struct HostInfo {
7e690cef
DH
168 char *hostname;
169 char *kernel_name;
170 char *kernel_release;
171 char *kernel_version;
172 char *os_pretty_name;
173 char *virtualization;
174 char *architecture;
6aa601c5 175} HostInfo;
7e690cef 176
25eb70af 177int acquire_bus(sd_bus **bus, bool *use_full_bus) {
5c69b31c 178 bool user = arg_scope != UNIT_FILE_SYSTEM;
fb507898 179 int r;
5c69b31c 180
f7e29336 181 if (use_full_bus && *use_full_bus) {
fb507898
YW
182 r = bus_connect_transport(arg_transport, arg_host, user, bus);
183 if (IN_SET(r, 0, -EHOSTDOWN))
184 return r;
5c69b31c
GJ
185
186 *use_full_bus = false;
187 }
188
f7e29336 189 return bus_connect_transport_systemd(arg_transport, arg_host, user, bus);
bf0e0a4d
ZJS
190}
191
048ecf5b 192static int bus_get_uint64_property(sd_bus *bus, const char *path, const char *interface, const char *property, uint64_t *val) {
4afd3348 193 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
c170f3a4 194 int r;
2265fbf7 195
988b9df2
LP
196 assert(bus);
197 assert(path);
198 assert(interface);
199 assert(property);
200 assert(val);
201
a936124f
TA
202 r = sd_bus_get_property_trivial(
203 bus,
204 "org.freedesktop.systemd1",
205 path,
206 interface,
207 property,
208 &error,
209 't', val);
048ecf5b 210
4ae25393 211 if (r < 0)
0ed3da7c 212 return log_error_errno(r, "Failed to parse reply: %s", bus_error_message(&error, r));
2265fbf7 213
2265fbf7
SP
214 return 0;
215}
216
cccd2af6 217int bus_get_unit_property_strv(sd_bus *bus, const char *path, const char *property, char ***strv) {
4afd3348 218 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
988b9df2
LP
219 int r;
220
221 assert(bus);
222 assert(path);
223 assert(property);
224 assert(strv);
225
226 r = sd_bus_get_property_strv(
227 bus,
228 "org.freedesktop.systemd1",
229 path,
230 "org.freedesktop.systemd1.Unit",
231 property,
232 &error,
233 strv);
4ae25393 234 if (r < 0)
0ed3da7c 235 return log_error_errno(r, "Failed to get unit property %s: %s", property, bus_error_message(&error, r));
988b9df2
LP
236
237 return 0;
238}
239
6aa601c5 240static int compare_unit_start(const UnitTimes *a, const UnitTimes *b) {
93bab288 241 return CMP(a->activating, b->activating);
2265fbf7
SP
242}
243
da845dab
AB
244static int process_aliases(char *argv[], char *tempdir, char ***ret) {
245 _cleanup_strv_free_ char **filenames = NULL;
246 char **filename;
247 int r;
248
249 assert(argv);
250 assert(tempdir);
251 assert(ret);
252
253 STRV_FOREACH(filename, strv_skip(argv, 1)) {
437346c9
AB
254 _cleanup_free_ char *src = NULL, *dst = NULL, *base = NULL;
255 const char *parse_arg;
da845dab 256
437346c9
AB
257 parse_arg = *filename;
258 r = extract_first_word(&parse_arg, &src, ":", EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_RETAIN_ESCAPE);
da845dab
AB
259 if (r < 0)
260 return r;
261
262 if (!parse_arg) {
437346c9 263 r = strv_consume(&filenames, TAKE_PTR(src));
da845dab 264 if (r < 0)
437346c9 265 return r;
da845dab
AB
266
267 continue;
268 }
269
437346c9
AB
270 r = path_extract_filename(parse_arg, &base);
271 if (r < 0)
272 return r;
273
274 dst = path_join(tempdir, base);
da845dab
AB
275 if (!dst)
276 return -ENOMEM;
277
278 r = copy_file(src, dst, 0, 0644, 0, 0, COPY_REFLINK);
279 if (r < 0)
280 return r;
281
282 r = strv_consume(&filenames, TAKE_PTR(dst));
283 if (r < 0)
437346c9 284 return r;
da845dab
AB
285 }
286
287 *ret = TAKE_PTR(filenames);
288 return 0;
289}
290
15567b3a 291static UnitTimes* unit_times_free_array(UnitTimes *t) {
75db809a 292 for (UnitTimes *p = t; p && p->has_data; p++)
c170f3a4 293 free(p->name);
75db809a 294 return mfree(t);
c170f3a4 295}
15567b3a 296DEFINE_TRIVIAL_CLEANUP_FUNC(UnitTimes*, unit_times_free_array);
df560cf6 297
06bef033
IS
298static void subtract_timestamp(usec_t *a, usec_t b) {
299 assert(a);
300
301 if (*a > 0) {
302 assert(*a >= b);
303 *a -= b;
304 }
305}
306
6aa601c5 307static int acquire_boot_times(sd_bus *bus, BootTimes **bt) {
cc0eb780 308 static const struct bus_properties_map property_map[] = {
6aa601c5
ZJS
309 { "FirmwareTimestampMonotonic", "t", NULL, offsetof(BootTimes, firmware_time) },
310 { "LoaderTimestampMonotonic", "t", NULL, offsetof(BootTimes, loader_time) },
311 { "KernelTimestamp", "t", NULL, offsetof(BootTimes, kernel_time) },
312 { "InitRDTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_time) },
313 { "UserspaceTimestampMonotonic", "t", NULL, offsetof(BootTimes, userspace_time) },
314 { "FinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, finish_time) },
315 { "SecurityStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, security_start_time) },
316 { "SecurityFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, security_finish_time) },
317 { "GeneratorsStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, generators_start_time) },
318 { "GeneratorsFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, generators_finish_time) },
319 { "UnitsLoadStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, unitsload_start_time) },
320 { "UnitsLoadFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, unitsload_finish_time) },
321 { "InitRDSecurityStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_security_start_time) },
322 { "InitRDSecurityFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_security_finish_time) },
323 { "InitRDGeneratorsStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_generators_start_time) },
324 { "InitRDGeneratorsFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_generators_finish_time) },
325 { "InitRDUnitsLoadStartTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_unitsload_start_time) },
326 { "InitRDUnitsLoadFinishTimestampMonotonic", "t", NULL, offsetof(BootTimes, initrd_unitsload_finish_time) },
cc0eb780
YW
327 {},
328 };
329 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6aa601c5 330 static BootTimes times;
2265fbf7 331 static bool cached = false;
cc0eb780 332 int r;
c170f3a4 333
2265fbf7 334 if (cached)
c170f3a4
LP
335 goto finish;
336
337 assert_cc(sizeof(usec_t) == sizeof(uint64_t));
2265fbf7 338
cc0eb780
YW
339 r = bus_map_all_properties(
340 bus,
341 "org.freedesktop.systemd1",
342 "/org/freedesktop/systemd1",
343 property_map,
344 BUS_MAP_STRDUP,
345 &error,
346 NULL,
347 &times);
348 if (r < 0)
349 return log_error_errno(r, "Failed to get timestamp properties: %s", bus_error_message(&error, r));
8c006565 350
c2953e08
ZJS
351 if (times.finish_time <= 0)
352 return log_error_errno(SYNTHETIC_ERRNO(EINPROGRESS),
353 "Bootup is not yet finished (org.freedesktop.systemd1.Manager.FinishTimestampMonotonic=%"PRIu64").\n"
354 "Please try again later.\n"
355 "Hint: Use 'systemctl%s list-jobs' to see active jobs",
356 times.finish_time,
357 arg_scope == UNIT_FILE_SYSTEM ? "" : " --user");
2265fbf7 358
eddb5037
YW
359 if (arg_scope == UNIT_FILE_SYSTEM && times.security_start_time > 0) {
360 /* security_start_time is set when systemd is not running under container environment. */
baa4880b 361 if (times.initrd_time > 0)
28b35ef2
ZJS
362 times.kernel_done_time = times.initrd_time;
363 else
364 times.kernel_done_time = times.userspace_time;
365 } else {
06bef033 366 /*
eddb5037 367 * User-instance-specific or container-system-specific timestamps processing
6aa601c5 368 * (see comment to reverse_offset in BootTimes).
06bef033
IS
369 */
370 times.reverse_offset = times.userspace_time;
371
1ace223c
SJ
372 times.firmware_time = times.loader_time = times.kernel_time = times.initrd_time =
373 times.userspace_time = times.security_start_time = times.security_finish_time = 0;
06bef033 374
79ecaae4 375 subtract_timestamp(&times.finish_time, times.reverse_offset);
06bef033
IS
376
377 subtract_timestamp(&times.generators_start_time, times.reverse_offset);
378 subtract_timestamp(&times.generators_finish_time, times.reverse_offset);
379
380 subtract_timestamp(&times.unitsload_start_time, times.reverse_offset);
381 subtract_timestamp(&times.unitsload_finish_time, times.reverse_offset);
06bef033 382 }
2265fbf7
SP
383
384 cached = true;
c170f3a4
LP
385
386finish:
387 *bt = &times;
388 return 0;
2265fbf7
SP
389}
390
75db809a 391static HostInfo* free_host_info(HostInfo *hi) {
b1b533a0 392 if (!hi)
75db809a 393 return NULL;
b1b533a0 394
7e690cef
DH
395 free(hi->hostname);
396 free(hi->kernel_name);
397 free(hi->kernel_release);
398 free(hi->kernel_version);
399 free(hi->os_pretty_name);
400 free(hi->virtualization);
401 free(hi->architecture);
75db809a 402 return mfree(hi);
7e690cef 403}
b1b533a0 404
6aa601c5 405DEFINE_TRIVIAL_CLEANUP_FUNC(HostInfo *, free_host_info);
7e690cef 406
6aa601c5 407static int acquire_time_data(sd_bus *bus, UnitTimes **out) {
cc0eb780 408 static const struct bus_properties_map property_map[] = {
6aa601c5
ZJS
409 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(UnitTimes, activating) },
410 { "ActiveEnterTimestampMonotonic", "t", NULL, offsetof(UnitTimes, activated) },
411 { "ActiveExitTimestampMonotonic", "t", NULL, offsetof(UnitTimes, deactivating) },
412 { "InactiveEnterTimestampMonotonic", "t", NULL, offsetof(UnitTimes, deactivated) },
cc0eb780
YW
413 {},
414 };
4afd3348
LP
415 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
416 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
15567b3a 417 _cleanup_(unit_times_free_arrayp) UnitTimes *unit_times = NULL;
6aa601c5 418 BootTimes *boot_times = NULL;
319a4f4b 419 size_t c = 0;
29b8b5ce 420 UnitInfo u;
97cec9ba 421 int r;
29b8b5ce 422
06bef033
IS
423 r = acquire_boot_times(bus, &boot_times);
424 if (r < 0)
df560cf6 425 return r;
06bef033 426
de770b60 427 r = bus_call_method(bus, bus_systemd_mgr, "ListUnits", &error, &reply, NULL);
4ae25393 428 if (r < 0)
0ed3da7c 429 return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
29b8b5ce
IS
430
431 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
df560cf6
FB
432 if (r < 0)
433 return bus_log_parse_error(r);
29b8b5ce
IS
434
435 while ((r = bus_parse_unit_info(reply, &u)) > 0) {
6aa601c5 436 UnitTimes *t;
29b8b5ce 437
319a4f4b 438 if (!GREEDY_REALLOC(unit_times, c + 2))
df560cf6 439 return log_oom();
29b8b5ce 440
1ace223c 441 unit_times[c + 1].has_data = false;
df560cf6 442 t = &unit_times[c];
29b8b5ce
IS
443 t->name = NULL;
444
445 assert_cc(sizeof(usec_t) == sizeof(uint64_t));
446
cc0eb780
YW
447 r = bus_map_all_properties(
448 bus,
449 "org.freedesktop.systemd1",
450 u.unit_path,
451 property_map,
452 BUS_MAP_STRDUP,
453 &error,
454 NULL,
455 t);
456 if (r < 0)
c2953e08
ZJS
457 return log_error_errno(r, "Failed to get timestamp properties of unit %s: %s",
458 u.id, bus_error_message(&error, r));
29b8b5ce 459
06bef033
IS
460 subtract_timestamp(&t->activating, boot_times->reverse_offset);
461 subtract_timestamp(&t->activated, boot_times->reverse_offset);
462 subtract_timestamp(&t->deactivating, boot_times->reverse_offset);
463 subtract_timestamp(&t->deactivated, boot_times->reverse_offset);
464
29b8b5ce
IS
465 if (t->activated >= t->activating)
466 t->time = t->activated - t->activating;
467 else if (t->deactivated >= t->activating)
468 t->time = t->deactivated - t->activating;
469 else
470 t->time = 0;
471
472 if (t->activating == 0)
473 continue;
474
475 t->name = strdup(u.id);
df560cf6
FB
476 if (!t->name)
477 return log_oom();
478
479 t->has_data = true;
29b8b5ce
IS
480 c++;
481 }
df560cf6
FB
482 if (r < 0)
483 return bus_log_parse_error(r);
29b8b5ce 484
df560cf6 485 *out = TAKE_PTR(unit_times);
29b8b5ce 486 return c;
29b8b5ce
IS
487}
488
6aa601c5 489static int acquire_host_info(sd_bus *bus, HostInfo **hi) {
7e690cef 490 static const struct bus_properties_map hostname_map[] = {
6aa601c5
ZJS
491 { "Hostname", "s", NULL, offsetof(HostInfo, hostname) },
492 { "KernelName", "s", NULL, offsetof(HostInfo, kernel_name) },
493 { "KernelRelease", "s", NULL, offsetof(HostInfo, kernel_release) },
494 { "KernelVersion", "s", NULL, offsetof(HostInfo, kernel_version) },
495 { "OperatingSystemPrettyName", "s", NULL, offsetof(HostInfo, os_pretty_name) },
7e690cef
DH
496 {}
497 };
498
499 static const struct bus_properties_map manager_map[] = {
6aa601c5
ZJS
500 { "Virtualization", "s", NULL, offsetof(HostInfo, virtualization) },
501 { "Architecture", "s", NULL, offsetof(HostInfo, architecture) },
7e690cef
DH
502 {}
503 };
504
4afd3348 505 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
4f481d76 506 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *system_bus = NULL;
75db809a 507 _cleanup_(free_host_infop) HostInfo *host = NULL;
b1b533a0
LP
508 int r;
509
6aa601c5 510 host = new0(HostInfo, 1);
7e690cef
DH
511 if (!host)
512 return log_oom();
513
4f481d76
YW
514 if (arg_scope != UNIT_FILE_SYSTEM) {
515 r = bus_connect_transport(arg_transport, arg_host, false, &system_bus);
516 if (r < 0) {
517 log_debug_errno(r, "Failed to connect to system bus, ignoring: %m");
518 goto manager;
519 }
520 }
521
1ace223c
SJ
522 r = bus_map_all_properties(
523 system_bus ?: bus,
524 "org.freedesktop.hostname1",
525 "/org/freedesktop/hostname1",
526 hostname_map,
527 BUS_MAP_STRDUP,
528 &error,
529 NULL,
530 host);
4f481d76 531 if (r < 0) {
c2953e08
ZJS
532 log_debug_errno(r, "Failed to get host information from systemd-hostnamed, ignoring: %s",
533 bus_error_message(&error, r));
4f481d76
YW
534 sd_bus_error_free(&error);
535 }
7e690cef 536
4f481d76 537manager:
1ace223c
SJ
538 r = bus_map_all_properties(
539 bus,
540 "org.freedesktop.systemd1",
541 "/org/freedesktop/systemd1",
542 manager_map,
543 BUS_MAP_STRDUP,
544 &error,
545 NULL,
546 host);
febda62a 547 if (r < 0)
c2953e08
ZJS
548 return log_error_errno(r, "Failed to get host information from systemd: %s",
549 bus_error_message(&error, r));
7e690cef 550
1cc6c93a 551 *hi = TAKE_PTR(host);
7e690cef 552 return 0;
7e690cef
DH
553}
554
048ecf5b 555static int pretty_boot_time(sd_bus *bus, char **_buf) {
6aa601c5 556 BootTimes *t;
2265fbf7 557 static char buf[4096];
c170f3a4
LP
558 size_t size;
559 char *ptr;
560 int r;
bd07d3d0 561 usec_t activated_time = USEC_INFINITY;
1ace223c 562 _cleanup_free_ char *path = NULL, *unit_id = NULL;
bd07d3d0 563 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
c170f3a4
LP
564
565 r = acquire_boot_times(bus, &t);
566 if (r < 0)
567 return r;
2265fbf7 568
bd07d3d0
JR
569 path = unit_dbus_path_from_name(SPECIAL_DEFAULT_TARGET);
570 if (!path)
571 return log_oom();
572
573 r = sd_bus_get_property_string(
574 bus,
575 "org.freedesktop.systemd1",
576 path,
577 "org.freedesktop.systemd1.Unit",
578 "Id",
579 &error,
580 &unit_id);
581 if (r < 0) {
582 log_error_errno(r, "default.target doesn't seem to exist: %s", bus_error_message(&error, r));
583 unit_id = NULL;
584 }
585
586 r = bus_get_uint64_property(bus, path,
587 "org.freedesktop.systemd1.Unit",
588 "ActiveEnterTimestampMonotonic",
589 &activated_time);
590 if (r < 0) {
0c753963 591 log_info_errno(r, "Could not get time to reach default.target, ignoring: %m");
bd07d3d0
JR
592 activated_time = USEC_INFINITY;
593 }
594
c170f3a4
LP
595 ptr = buf;
596 size = sizeof(buf);
2265fbf7
SP
597
598 size = strpcpyf(&ptr, size, "Startup finished in ");
baa4880b 599 if (t->firmware_time > 0)
5291f26d 600 size = strpcpyf(&ptr, size, "%s (firmware) + ", FORMAT_TIMESPAN(t->firmware_time - t->loader_time, USEC_PER_MSEC));
baa4880b 601 if (t->loader_time > 0)
5291f26d 602 size = strpcpyf(&ptr, size, "%s (loader) + ", FORMAT_TIMESPAN(t->loader_time, USEC_PER_MSEC));
02be0cca 603 if (t->kernel_done_time > 0)
5291f26d 604 size = strpcpyf(&ptr, size, "%s (kernel) + ", FORMAT_TIMESPAN(t->kernel_done_time, USEC_PER_MSEC));
2265fbf7 605 if (t->initrd_time > 0)
5291f26d 606 size = strpcpyf(&ptr, size, "%s (initrd) + ", FORMAT_TIMESPAN(t->userspace_time - t->initrd_time, USEC_PER_MSEC));
2265fbf7 607
5291f26d 608 size = strpcpyf(&ptr, size, "%s (userspace) ", FORMAT_TIMESPAN(t->finish_time - t->userspace_time, USEC_PER_MSEC));
02be0cca 609 if (t->kernel_done_time > 0)
5291f26d 610 strpcpyf(&ptr, size, "= %s ", FORMAT_TIMESPAN(t->firmware_time + t->finish_time, USEC_PER_MSEC));
2265fbf7 611
1f65fd49 612 if (unit_id && timestamp_is_set(activated_time)) {
b5d6f7ea
ZJS
613 usec_t base = t->userspace_time > 0 ? t->userspace_time : t->reverse_offset;
614
615 size = strpcpyf(&ptr, size, "\n%s reached after %s in userspace", unit_id,
5291f26d 616 FORMAT_TIMESPAN(activated_time - base, USEC_PER_MSEC));
eddb5037 617 } else if (unit_id && activated_time == 0)
da933f7d
JR
618 size = strpcpyf(&ptr, size, "\n%s was never reached", unit_id);
619 else if (unit_id && activated_time == USEC_INFINITY)
feb92776 620 size = strpcpyf(&ptr, size, "\nCould not get time to reach %s.", unit_id);
da933f7d
JR
621 else if (!unit_id)
622 size = strpcpyf(&ptr, size, "\ncould not find default.target");
623
c170f3a4
LP
624 ptr = strdup(buf);
625 if (!ptr)
626 return log_oom();
627
628 *_buf = ptr;
629 return 0;
2265fbf7
SP
630}
631
c170f3a4 632static void svg_graph_box(double height, double begin, double end) {
2265fbf7
SP
633 /* outside box, fill */
634 svg("<rect class=\"box\" x=\"0\" y=\"0\" width=\"%.03f\" height=\"%.03f\" />\n",
1ace223c
SJ
635 SCALE_X * (end - begin),
636 SCALE_Y * height);
2265fbf7 637
6aa601c5 638 for (long long i = ((long long) (begin / 100000)) * 100000; i <= end; i += 100000) {
2265fbf7 639 /* lines for each second */
c170f3a4 640 if (i % 5000000 == 0)
2265fbf7
SP
641 svg(" <line class=\"sec5\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
642 " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
1ace223c
SJ
643 SCALE_X * i,
644 SCALE_X * i,
645 SCALE_Y * height,
646 SCALE_X * i,
647 -5.0,
648 0.000001 * i);
c170f3a4 649 else if (i % 1000000 == 0)
2265fbf7
SP
650 svg(" <line class=\"sec1\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n"
651 " <text class=\"sec\" x=\"%.03f\" y=\"%.03f\" >%.01fs</text>\n",
1ace223c
SJ
652 SCALE_X * i,
653 SCALE_X * i,
654 SCALE_Y * height,
655 SCALE_X * i,
656 -5.0,
657 0.000001 * i);
2265fbf7
SP
658 else
659 svg(" <line class=\"sec01\" x1=\"%.03f\" y1=\"0\" x2=\"%.03f\" y2=\"%.03f\" />\n",
1ace223c
SJ
660 SCALE_X * i,
661 SCALE_X * i,
662 SCALE_Y * height);
2265fbf7
SP
663 }
664}
665
6aa601c5 666static int plot_unit_times(UnitTimes *u, double width, int y) {
7725fc11
YW
667 bool b;
668
669 if (!u->name)
670 return 0;
671
672 svg_bar("activating", u->activating, u->activated, y);
673 svg_bar("active", u->activated, u->deactivating, y);
674 svg_bar("deactivating", u->deactivating, u->deactivated, y);
675
676 /* place the text on the left if we have passed the half of the svg width */
677 b = u->activating * SCALE_X < width / 2;
678 if (u->time)
679 svg_text(b, u->activating, y, "%s (%s)",
5291f26d 680 u->name, FORMAT_TIMESPAN(u->time, USEC_PER_MSEC));
7725fc11
YW
681 else
682 svg_text(b, u->activating, y, "%s", u->name);
683
684 return 1;
685}
686
a6bcef29 687static int analyze_plot(int argc, char *argv[], void *userdata) {
6aa601c5 688 _cleanup_(free_host_infop) HostInfo *host = NULL;
a6bcef29 689 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
15567b3a 690 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
4f481d76
YW
691 _cleanup_free_ char *pretty_times = NULL;
692 bool use_full_bus = arg_scope == UNIT_FILE_SYSTEM;
6aa601c5
ZJS
693 BootTimes *boot;
694 UnitTimes *u;
a6bcef29 695 int n, m = 1, y = 0, r;
2265fbf7 696 double width;
2265fbf7 697
f7e29336 698 r = acquire_bus(&bus, &use_full_bus);
a6bcef29 699 if (r < 0)
10a7340a 700 return bus_log_connect_error(r, arg_transport);
a6bcef29 701
c170f3a4
LP
702 n = acquire_boot_times(bus, &boot);
703 if (n < 0)
704 return n;
2265fbf7 705
c170f3a4
LP
706 n = pretty_boot_time(bus, &pretty_times);
707 if (n < 0)
708 return n;
2265fbf7 709
4f481d76 710 if (use_full_bus || arg_scope != UNIT_FILE_SYSTEM) {
5c69b31c
GJ
711 n = acquire_host_info(bus, &host);
712 if (n < 0)
713 return n;
714 }
2265fbf7
SP
715
716 n = acquire_time_data(bus, &times);
c170f3a4 717 if (n <= 0)
19f462f2 718 return n;
2265fbf7 719
93bab288 720 typesafe_qsort(times, n, compare_unit_start);
2265fbf7 721
2f6eb835 722 width = SCALE_X * (boot->firmware_time + boot->finish_time);
2265fbf7
SP
723 if (width < 800.0)
724 width = 800.0;
725
726 if (boot->firmware_time > boot->loader_time)
727 m++;
baa4880b 728 if (boot->loader_time > 0) {
2265fbf7
SP
729 m++;
730 if (width < 1000.0)
731 width = 1000.0;
732 }
baa4880b 733 if (boot->initrd_time > 0)
2265fbf7 734 m++;
02be0cca 735 if (boot->kernel_done_time > 0)
2265fbf7
SP
736 m++;
737
df560cf6 738 for (u = times; u->has_data; u++) {
95168f7d 739 double text_start, text_width;
c170f3a4 740
7725fc11 741 if (u->activating > boot->finish_time) {
a1e58e8e 742 u->name = mfree(u->name);
2265fbf7
SP
743 continue;
744 }
95168f7d
TA
745
746 /* If the text cannot fit on the left side then
747 * increase the svg width so it fits on the right.
748 * TODO: calculate the text width more accurately */
749 text_width = 8.0 * strlen(u->name);
cc27380c 750 text_start = (boot->firmware_time + u->activating) * SCALE_X;
95168f7d
TA
751 if (text_width > text_start && text_width + text_start > width)
752 width = text_width + text_start;
2265fbf7 753
efe6112d
YW
754 if (u->deactivated > u->activating &&
755 u->deactivated <= boot->finish_time &&
756 u->activated == 0 && u->deactivating == 0)
cc27380c
TA
757 u->activated = u->deactivating = u->deactivated;
758 if (u->activated < u->activating || u->activated > boot->finish_time)
759 u->activated = boot->finish_time;
efe6112d 760 if (u->deactivating < u->activated || u->deactivating > boot->finish_time)
cc27380c
TA
761 u->deactivating = boot->finish_time;
762 if (u->deactivated < u->deactivating || u->deactivated > boot->finish_time)
763 u->deactivated = boot->finish_time;
2265fbf7
SP
764 m++;
765 }
766
767 svg("<?xml version=\"1.0\" standalone=\"no\"?>\n"
768 "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" "
769 "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
770
771 svg("<svg width=\"%.0fpx\" height=\"%.0fpx\" version=\"1.1\" "
772 "xmlns=\"http://www.w3.org/2000/svg\">\n\n",
518d10e9 773 80.0 + width, 150.0 + (m * SCALE_Y) +
d9acfb71 774 5 * SCALE_Y /* legend */);
2265fbf7
SP
775
776 /* write some basic info as a comment, including some help */
777 svg("<!-- This file is a systemd-analyze SVG file. It is best rendered in a -->\n"
778 "<!-- browser such as Chrome, Chromium or Firefox. Other applications -->\n"
779 "<!-- that render these files properly but much slower are ImageMagick, -->\n"
780 "<!-- gimp, inkscape, etc. To display the files on your system, just -->\n"
781 "<!-- point your browser to this file. -->\n\n"
681bd2c5 782 "<!-- This plot was generated by systemd-analyze version %-16.16s -->\n\n", GIT_VERSION);
2265fbf7
SP
783
784 /* style sheet */
785 svg("<defs>\n <style type=\"text/css\">\n <![CDATA[\n"
786 " rect { stroke-width: 1; stroke-opacity: 0; }\n"
418e3750 787 " rect.background { fill: rgb(255,255,255); }\n"
2265fbf7
SP
788 " rect.activating { fill: rgb(255,0,0); fill-opacity: 0.7; }\n"
789 " rect.active { fill: rgb(200,150,150); fill-opacity: 0.7; }\n"
790 " rect.deactivating { fill: rgb(150,100,100); fill-opacity: 0.7; }\n"
791 " rect.kernel { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
792 " rect.initrd { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
793 " rect.firmware { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
794 " rect.loader { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
795 " rect.userspace { fill: rgb(150,150,150); fill-opacity: 0.7; }\n"
c2e0d600 796 " rect.security { fill: rgb(144,238,144); fill-opacity: 0.7; }\n"
518d10e9 797 " rect.generators { fill: rgb(102,204,255); fill-opacity: 0.7; }\n"
d9acfb71 798 " rect.unitsload { fill: rgb( 82,184,255); fill-opacity: 0.7; }\n"
2265fbf7
SP
799 " rect.box { fill: rgb(240,240,240); stroke: rgb(192,192,192); }\n"
800 " line { stroke: rgb(64,64,64); stroke-width: 1; }\n"
801 "// line.sec1 { }\n"
802 " line.sec5 { stroke-width: 2; }\n"
803 " line.sec01 { stroke: rgb(224,224,224); stroke-width: 1; }\n"
2b7d6965
TA
804 " text { font-family: Verdana, Helvetica; font-size: 14px; }\n"
805 " text.left { font-family: Verdana, Helvetica; font-size: 14px; text-anchor: start; }\n"
806 " text.right { font-family: Verdana, Helvetica; font-size: 14px; text-anchor: end; }\n"
807 " text.sec { font-size: 10px; }\n"
2265fbf7
SP
808 " ]]>\n </style>\n</defs>\n\n");
809
418e3750 810 svg("<rect class=\"background\" width=\"100%%\" height=\"100%%\" />\n");
2265fbf7 811 svg("<text x=\"20\" y=\"50\">%s</text>", pretty_times);
4f481d76 812 if (host)
5c69b31c
GJ
813 svg("<text x=\"20\" y=\"30\">%s %s (%s %s %s) %s %s</text>",
814 isempty(host->os_pretty_name) ? "Linux" : host->os_pretty_name,
815 strempty(host->hostname),
816 strempty(host->kernel_name),
817 strempty(host->kernel_release),
818 strempty(host->kernel_version),
819 strempty(host->architecture),
820 strempty(host->virtualization));
2265fbf7 821
2f6eb835 822 svg("<g transform=\"translate(%.3f,100)\">\n", 20.0 + (SCALE_X * boot->firmware_time));
b5cfa740 823 svg_graph_box(m, -(double) boot->firmware_time, boot->finish_time);
2265fbf7 824
baa4880b 825 if (boot->firmware_time > 0) {
c170f3a4
LP
826 svg_bar("firmware", -(double) boot->firmware_time, -(double) boot->loader_time, y);
827 svg_text(true, -(double) boot->firmware_time, y, "firmware");
2265fbf7
SP
828 y++;
829 }
baa4880b 830 if (boot->loader_time > 0) {
c170f3a4
LP
831 svg_bar("loader", -(double) boot->loader_time, 0, y);
832 svg_text(true, -(double) boot->loader_time, y, "loader");
2265fbf7
SP
833 y++;
834 }
02be0cca 835 if (boot->kernel_done_time > 0) {
2265fbf7 836 svg_bar("kernel", 0, boot->kernel_done_time, y);
c170f3a4 837 svg_text(true, 0, y, "kernel");
2265fbf7
SP
838 y++;
839 }
baa4880b 840 if (boot->initrd_time > 0) {
2265fbf7 841 svg_bar("initrd", boot->initrd_time, boot->userspace_time, y);
8c006565
YW
842 if (boot->initrd_security_start_time < boot->initrd_security_finish_time)
843 svg_bar("security", boot->initrd_security_start_time, boot->initrd_security_finish_time, y);
844 if (boot->initrd_generators_start_time < boot->initrd_generators_finish_time)
845 svg_bar("generators", boot->initrd_generators_start_time, boot->initrd_generators_finish_time, y);
846 if (boot->initrd_unitsload_start_time < boot->initrd_unitsload_finish_time)
847 svg_bar("unitsload", boot->initrd_unitsload_start_time, boot->initrd_unitsload_finish_time, y);
c170f3a4 848 svg_text(true, boot->initrd_time, y, "initrd");
2265fbf7
SP
849 y++;
850 }
7725fc11
YW
851
852 for (u = times; u->has_data; u++) {
853 if (u->activating >= boot->userspace_time)
854 break;
855
856 y += plot_unit_times(u, width, y);
857 }
858
518d10e9 859 svg_bar("active", boot->userspace_time, boot->finish_time, y);
79ecaae4
YW
860 if (boot->security_start_time > 0)
861 svg_bar("security", boot->security_start_time, boot->security_finish_time, y);
518d10e9 862 svg_bar("generators", boot->generators_start_time, boot->generators_finish_time, y);
d9acfb71 863 svg_bar("unitsload", boot->unitsload_start_time, boot->unitsload_finish_time, y);
95168f7d 864 svg_text(true, boot->userspace_time, y, "systemd");
2265fbf7
SP
865 y++;
866
7725fc11
YW
867 for (; u->has_data; u++)
868 y += plot_unit_times(u, width, y);
518d10e9 869
b5cfa740
TA
870 svg("</g>\n");
871
518d10e9 872 /* Legend */
b5cfa740 873 svg("<g transform=\"translate(20,100)\">\n");
518d10e9
UTL
874 y++;
875 svg_bar("activating", 0, 300000, y);
95168f7d 876 svg_text(true, 400000, y, "Activating");
518d10e9
UTL
877 y++;
878 svg_bar("active", 0, 300000, y);
95168f7d 879 svg_text(true, 400000, y, "Active");
518d10e9
UTL
880 y++;
881 svg_bar("deactivating", 0, 300000, y);
95168f7d 882 svg_text(true, 400000, y, "Deactivating");
518d10e9 883 y++;
79ecaae4
YW
884 if (boot->security_start_time > 0) {
885 svg_bar("security", 0, 300000, y);
886 svg_text(true, 400000, y, "Setting up security module");
887 y++;
888 }
518d10e9 889 svg_bar("generators", 0, 300000, y);
95168f7d 890 svg_text(true, 400000, y, "Generators");
518d10e9 891 y++;
d9acfb71 892 svg_bar("unitsload", 0, 300000, y);
95168f7d 893 svg_text(true, 400000, y, "Loading unit files");
d9acfb71 894 y++;
518d10e9 895
2265fbf7
SP
896 svg("</g>\n\n");
897
988b9df2 898 svg("</svg>\n");
c170f3a4 899
df560cf6 900 return 0;
2265fbf7
SP
901}
902
1ace223c
SJ
903static int list_dependencies_print(
904 const char *name,
905 unsigned level,
906 unsigned branches,
907 bool last,
6aa601c5
ZJS
908 UnitTimes *times,
909 BootTimes *boot) {
1ace223c 910
6aa601c5 911 for (unsigned i = level; i != 0; i--)
9a6f746f 912 printf("%s", special_glyph(branches & (1 << (i-1)) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE));
bb150966 913
9a6f746f 914 printf("%s", special_glyph(last ? SPECIAL_GLYPH_TREE_RIGHT : SPECIAL_GLYPH_TREE_BRANCH));
bb150966
HH
915
916 if (times) {
baa4880b 917 if (times->time > 0)
54f8c958 918 printf("%s%s @%s +%s%s", ansi_highlight_red(), name,
5291f26d
ZJS
919 FORMAT_TIMESPAN(times->activating - boot->userspace_time, USEC_PER_MSEC),
920 FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
cc27380c 921 else if (times->activated > boot->userspace_time)
5291f26d 922 printf("%s @%s", name, FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
bb150966
HH
923 else
924 printf("%s", name);
988b9df2
LP
925 } else
926 printf("%s", name);
bb150966
HH
927 printf("\n");
928
929 return 0;
930}
931
048ecf5b 932static int list_dependencies_get_dependencies(sd_bus *bus, const char *name, char ***deps) {
988b9df2 933 _cleanup_free_ char *path = NULL;
bb150966
HH
934
935 assert(bus);
936 assert(name);
937 assert(deps);
938
939 path = unit_dbus_path_from_name(name);
234519ae 940 if (!path)
988b9df2 941 return -ENOMEM;
bb150966 942
988b9df2 943 return bus_get_unit_property_strv(bus, path, "After", deps);
bb150966
HH
944}
945
946static Hashmap *unit_times_hashmap;
947
1ace223c 948static int list_dependencies_compare(char *const *a, char *const *b) {
bb150966 949 usec_t usa = 0, usb = 0;
6aa601c5 950 UnitTimes *times;
bb150966
HH
951
952 times = hashmap_get(unit_times_hashmap, *a);
953 if (times)
cc27380c 954 usa = times->activated;
bb150966
HH
955 times = hashmap_get(unit_times_hashmap, *b);
956 if (times)
cc27380c 957 usb = times->activated;
bb150966 958
93bab288 959 return CMP(usb, usa);
bb150966
HH
960}
961
6aa601c5 962static bool times_in_range(const UnitTimes *times, const BootTimes *boot) {
1ace223c 963 return times && times->activated > 0 && times->activated <= boot->finish_time;
230cc99a
ZJS
964}
965
1ace223c 966static int list_dependencies_one(sd_bus *bus, const char *name, unsigned level, char ***units, unsigned branches) {
bb150966
HH
967 _cleanup_strv_free_ char **deps = NULL;
968 char **c;
05f7a068 969 int r;
bb150966
HH
970 usec_t service_longest = 0;
971 int to_print = 0;
6aa601c5
ZJS
972 UnitTimes *times;
973 BootTimes *boot;
bb150966 974
988b9df2 975 if (strv_extend(units, name))
bb150966
HH
976 return log_oom();
977
978 r = list_dependencies_get_dependencies(bus, name, &deps);
979 if (r < 0)
980 return r;
981
93bab288 982 typesafe_qsort(deps, strv_length(deps), list_dependencies_compare);
bb150966
HH
983
984 r = acquire_boot_times(bus, &boot);
985 if (r < 0)
986 return r;
987
988 STRV_FOREACH(c, deps) {
33b7988d 989 times = hashmap_get(unit_times_hashmap, *c); /* lgtm [cpp/inconsistent-null-check] */
1ace223c 990 if (times_in_range(times, boot) && times->activated >= service_longest)
cc27380c 991 service_longest = times->activated;
bb150966
HH
992 }
993
234519ae 994 if (service_longest == 0)
bb150966
HH
995 return r;
996
997 STRV_FOREACH(c, deps) {
33b7988d 998 times = hashmap_get(unit_times_hashmap, *c); /* lgtm [cpp/inconsistent-null-check] */
1ace223c 999 if (times_in_range(times, boot) && service_longest - times->activated <= arg_fuzz)
bb150966 1000 to_print++;
bb150966
HH
1001 }
1002
f168c273 1003 if (!to_print)
bb150966
HH
1004 return r;
1005
1006 STRV_FOREACH(c, deps) {
33b7988d 1007 times = hashmap_get(unit_times_hashmap, *c); /* lgtm [cpp/inconsistent-null-check] */
1ace223c 1008 if (!times_in_range(times, boot) || service_longest - times->activated > arg_fuzz)
bb150966
HH
1009 continue;
1010
1011 to_print--;
1012
1013 r = list_dependencies_print(*c, level, branches, to_print == 0, times, boot);
1014 if (r < 0)
1015 return r;
1016
1017 if (strv_contains(*units, *c)) {
1018 r = list_dependencies_print("...", level + 1, (branches << 1) | (to_print ? 1 : 0),
1019 true, NULL, boot);
872c8faa
ZJS
1020 if (r < 0)
1021 return r;
bb150966
HH
1022 continue;
1023 }
1024
1ace223c 1025 r = list_dependencies_one(bus, *c, level + 1, units, (branches << 1) | (to_print ? 1 : 0));
872c8faa 1026 if (r < 0)
bb150966
HH
1027 return r;
1028
baa4880b 1029 if (to_print == 0)
bb150966 1030 break;
bb150966
HH
1031 }
1032 return 0;
1033}
1034
048ecf5b 1035static int list_dependencies(sd_bus *bus, const char *name) {
bb150966 1036 _cleanup_strv_free_ char **units = NULL;
6aa601c5 1037 UnitTimes *times;
bb150966 1038 int r;
0ee9613d
TA
1039 const char *id;
1040 _cleanup_free_ char *path = NULL;
4afd3348
LP
1041 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1042 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6aa601c5 1043 BootTimes *boot;
bb150966
HH
1044
1045 assert(bus);
1046
805bf39c 1047 path = unit_dbus_path_from_name(name);
234519ae 1048 if (!path)
988b9df2 1049 return -ENOMEM;
bb150966 1050
a936124f
TA
1051 r = sd_bus_get_property(
1052 bus,
1053 "org.freedesktop.systemd1",
1054 path,
1055 "org.freedesktop.systemd1.Unit",
1056 "Id",
1057 &error,
1058 &reply,
1059 "s");
4ae25393 1060 if (r < 0)
0ed3da7c 1061 return log_error_errno(r, "Failed to get ID: %s", bus_error_message(&error, r));
bb150966 1062
048ecf5b 1063 r = sd_bus_message_read(reply, "s", &id);
5b30bef8
LP
1064 if (r < 0)
1065 return bus_log_parse_error(r);
bb150966 1066
bb150966
HH
1067 times = hashmap_get(unit_times_hashmap, id);
1068
1069 r = acquire_boot_times(bus, &boot);
1070 if (r < 0)
1071 return r;
1072
1073 if (times) {
1074 if (times->time)
54f8c958 1075 printf("%s%s +%s%s\n", ansi_highlight_red(), id,
5291f26d 1076 FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
cc27380c 1077 else if (times->activated > boot->userspace_time)
5291f26d
ZJS
1078 printf("%s @%s\n", id,
1079 FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
bb150966
HH
1080 else
1081 printf("%s\n", id);
1082 }
1083
805bf39c 1084 return list_dependencies_one(bus, name, 0, &units, 0);
bb150966
HH
1085}
1086
a6bcef29
LP
1087static int analyze_critical_chain(int argc, char *argv[], void *userdata) {
1088 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
15567b3a 1089 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
bb150966 1090 Hashmap *h;
988b9df2 1091 int n, r;
bb150966 1092
f7e29336 1093 r = acquire_bus(&bus, NULL);
a6bcef29 1094 if (r < 0)
10a7340a 1095 return bus_log_connect_error(r, arg_transport);
a6bcef29 1096
bb150966
HH
1097 n = acquire_time_data(bus, &times);
1098 if (n <= 0)
1099 return n;
1100
d5099efc 1101 h = hashmap_new(&string_hash_ops);
bb150966 1102 if (!h)
8efbce13 1103 return log_oom();
bb150966 1104
6aa601c5 1105 for (UnitTimes *u = times; u->has_data; u++) {
df560cf6 1106 r = hashmap_put(h, u->name, u);
bb150966 1107 if (r < 0)
8efbce13 1108 return log_error_errno(r, "Failed to add entry to hashmap: %m");
bb150966
HH
1109 }
1110 unit_times_hashmap = h;
1111
384c2c32 1112 pager_open(arg_pager_flags);
9ea9d4cf 1113
2fffb93b
ZJS
1114 puts("The time when unit became active or started is printed after the \"@\" character.\n"
1115 "The time the unit took to start is printed after the \"+\" character.\n");
bb150966 1116
a6bcef29 1117 if (argc > 1) {
805bf39c 1118 char **name;
a6bcef29 1119 STRV_FOREACH(name, strv_skip(argv, 1))
805bf39c 1120 list_dependencies(bus, *name);
9ea9d4cf 1121 } else
805bf39c 1122 list_dependencies(bus, SPECIAL_DEFAULT_TARGET);
bb150966 1123
a6bcef29 1124 h = hashmap_free(h);
bb150966
HH
1125 return 0;
1126}
1127
a6bcef29
LP
1128static int analyze_blame(int argc, char *argv[], void *userdata) {
1129 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
15567b3a 1130 _cleanup_(unit_times_free_arrayp) UnitTimes *times = NULL;
d8bfdbe1 1131 _cleanup_(table_unrefp) Table *table = NULL;
d8bfdbe1 1132 TableCell *cell;
a6bcef29
LP
1133 int n, r;
1134
f7e29336 1135 r = acquire_bus(&bus, NULL);
a6bcef29 1136 if (r < 0)
10a7340a 1137 return bus_log_connect_error(r, arg_transport);
c170f3a4
LP
1138
1139 n = acquire_time_data(bus, &times);
1140 if (n <= 0)
2265fbf7
SP
1141 return n;
1142
4252171a 1143 table = table_new("time", "unit");
d8bfdbe1
YW
1144 if (!table)
1145 return log_oom();
2265fbf7 1146
d8bfdbe1
YW
1147 table_set_header(table, false);
1148
1149 assert_se(cell = table_get_cell(table, 0, 0));
1150 r = table_set_ellipsize_percent(table, cell, 100);
1151 if (r < 0)
1152 return r;
1153
1154 r = table_set_align_percent(table, cell, 100);
1155 if (r < 0)
1156 return r;
1157
1158 assert_se(cell = table_get_cell(table, 0, 1));
1159 r = table_set_ellipsize_percent(table, cell, 100);
1160 if (r < 0)
1161 return r;
1162
ef1e0b9a 1163 r = table_set_sort(table, (size_t) 0);
d8bfdbe1
YW
1164 if (r < 0)
1165 return r;
1166
1167 r = table_set_reverse(table, 0, true);
1168 if (r < 0)
1169 return r;
9ea9d4cf 1170
6aa601c5 1171 for (UnitTimes *u = times; u->has_data; u++) {
d8bfdbe1
YW
1172 if (u->time <= 0)
1173 continue;
1174
9c46b437 1175 r = table_add_many(table,
47cc458e 1176 TABLE_TIMESPAN_MSEC, u->time,
9c46b437 1177 TABLE_STRING, u->name);
d8bfdbe1 1178 if (r < 0)
9c46b437 1179 return table_log_add_error(r);
2265fbf7 1180 }
c170f3a4 1181
384c2c32 1182 pager_open(arg_pager_flags);
d8bfdbe1
YW
1183
1184 return table_print(table, NULL);
2265fbf7
SP
1185}
1186
a6bcef29
LP
1187static int analyze_time(int argc, char *argv[], void *userdata) {
1188 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
c170f3a4
LP
1189 _cleanup_free_ char *buf = NULL;
1190 int r;
1191
f7e29336 1192 r = acquire_bus(&bus, NULL);
a6bcef29 1193 if (r < 0)
10a7340a 1194 return bus_log_connect_error(r, arg_transport);
a6bcef29 1195
c170f3a4
LP
1196 r = pretty_boot_time(bus, &buf);
1197 if (r < 0)
1198 return r;
1199
1200 puts(buf);
2265fbf7
SP
1201 return 0;
1202}
1203
854a42fb 1204static int cat_config(int argc, char *argv[], void *userdata) {
2987225c 1205 char **arg, **list;
854a42fb
ZJS
1206 int r;
1207
384c2c32 1208 pager_open(arg_pager_flags);
854a42fb 1209
2987225c
LP
1210 list = strv_skip(argv, 1);
1211 STRV_FOREACH(arg, list) {
971f6ea5
ZJS
1212 const char *t = NULL;
1213
2987225c 1214 if (arg != list)
cb91deaf 1215 print_separator();
854a42fb
ZJS
1216
1217 if (path_is_absolute(*arg)) {
971f6ea5
ZJS
1218 const char *dir;
1219
1220 NULSTR_FOREACH(dir, CONF_PATHS_NULSTR("")) {
1221 t = path_startswith(*arg, dir);
1222 if (t)
1223 break;
1224 }
1225
baaa35ad
ZJS
1226 if (!t)
1227 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
c2953e08 1228 "Path %s does not start with any known prefix.", *arg);
971f6ea5
ZJS
1229 } else
1230 t = *arg;
1231
1232 r = conf_files_cat(arg_root, t);
854a42fb
ZJS
1233 if (r < 0)
1234 return r;
1235 }
1236
1237 return 0;
1238}
1239
a87b151a 1240static int verb_log_control(int argc, char *argv[], void *userdata) {
a6bcef29 1241 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2ca2a91c
LP
1242 int r;
1243
b98416e1 1244 assert(IN_SET(argc, 1, 2));
2ca2a91c 1245
f7e29336 1246 r = acquire_bus(&bus, NULL);
a6bcef29 1247 if (r < 0)
10a7340a 1248 return bus_log_connect_error(r, arg_transport);
a65615ca 1249
a87b151a 1250 return verb_log_control_common(bus, "org.freedesktop.systemd1", argv[0], argc == 2 ? argv[1] : NULL);
90657286
YW
1251}
1252
e67cd21d
ZJS
1253static bool strv_fnmatch_strv_or_empty(char* const* patterns, char **strv, int flags) {
1254 char **s;
1255 STRV_FOREACH(s, strv)
1256 if (strv_fnmatch_or_empty(patterns, *s, flags))
1257 return true;
1258
1259 return false;
1260}
1261
1262static int do_unit_files(int argc, char *argv[], void *userdata) {
1263 _cleanup_(lookup_paths_free) LookupPaths lp = {};
1264 _cleanup_hashmap_free_ Hashmap *unit_ids = NULL;
1265 _cleanup_hashmap_free_ Hashmap *unit_names = NULL;
1266 char **patterns = strv_skip(argv, 1);
e67cd21d
ZJS
1267 const char *k, *dst;
1268 char **v;
1269 int r;
1270
1271 r = lookup_paths_init(&lp, arg_scope, 0, NULL);
1272 if (r < 0)
1273 return log_error_errno(r, "lookup_paths_init() failed: %m");
1274
91e0ee5f 1275 r = unit_file_build_name_map(&lp, NULL, &unit_ids, &unit_names, NULL);
e67cd21d
ZJS
1276 if (r < 0)
1277 return log_error_errno(r, "unit_file_build_name_map() failed: %m");
1278
90e74a66 1279 HASHMAP_FOREACH_KEY(dst, k, unit_ids) {
e67cd21d
ZJS
1280 if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) &&
1281 !strv_fnmatch_or_empty(patterns, dst, FNM_NOESCAPE))
1282 continue;
1283
1284 printf("ids: %s → %s\n", k, dst);
1285 }
1286
90e74a66 1287 HASHMAP_FOREACH_KEY(v, k, unit_names) {
e67cd21d
ZJS
1288 if (!strv_fnmatch_or_empty(patterns, k, FNM_NOESCAPE) &&
1289 !strv_fnmatch_strv_or_empty(patterns, v, FNM_NOESCAPE))
1290 continue;
1291
1292 _cleanup_free_ char *j = strv_join(v, ", ");
1293 printf("aliases: %s ← %s\n", k, j);
1294 }
1295
1296 return 0;
1297}
1298
31a5924e 1299static int dump_unit_paths(int argc, char *argv[], void *userdata) {
8e766630 1300 _cleanup_(lookup_paths_free) LookupPaths paths = {};
31a5924e
ZJS
1301 int r;
1302 char **p;
1303
1304 r = lookup_paths_init(&paths, arg_scope, 0, NULL);
1305 if (r < 0)
1306 return log_error_errno(r, "lookup_paths_init() failed: %m");
1307
1308 STRV_FOREACH(p, paths.search_path)
1309 puts(*p);
1310
1311 return 0;
1312}
1313
417b82e1
MG
1314static int dump_exit_status(int argc, char *argv[], void *userdata) {
1315 _cleanup_(table_unrefp) Table *table = NULL;
1316 int r;
1317
1318 table = table_new("name", "status", "class");
1319 if (!table)
1320 return log_oom();
1321
1322 r = table_set_align_percent(table, table_get_cell(table, 0, 1), 100);
1323 if (r < 0)
1324 return log_error_errno(r, "Failed to right-align status: %m");
1325
1326 if (strv_isempty(strv_skip(argv, 1)))
1327 for (size_t i = 0; i < ELEMENTSOF(exit_status_mappings); i++) {
1328 if (!exit_status_mappings[i].name)
1329 continue;
1330
1331 r = table_add_many(table,
1332 TABLE_STRING, exit_status_mappings[i].name,
1333 TABLE_INT, (int) i,
1334 TABLE_STRING, exit_status_class(i));
1335 if (r < 0)
9c46b437 1336 return table_log_add_error(r);
417b82e1
MG
1337 }
1338 else
1339 for (int i = 1; i < argc; i++) {
1340 int status;
1341
1342 status = exit_status_from_string(argv[i]);
1343 if (status < 0)
7211c853 1344 return log_error_errno(status, "Invalid exit status \"%s\".", argv[i]);
417b82e1
MG
1345
1346 assert(status >= 0 && (size_t) status < ELEMENTSOF(exit_status_mappings));
1347 r = table_add_many(table,
1348 TABLE_STRING, exit_status_mappings[status].name ?: "-",
1349 TABLE_INT, status,
1350 TABLE_STRING, exit_status_class(status) ?: "-");
1351 if (r < 0)
9c46b437 1352 return table_log_add_error(r);
417b82e1
MG
1353 }
1354
384c2c32 1355 pager_open(arg_pager_flags);
417b82e1
MG
1356
1357 return table_print(table, NULL);
1358}
1359
b2af819b
LP
1360static int dump_capabilities(int argc, char *argv[], void *userdata) {
1361 _cleanup_(table_unrefp) Table *table = NULL;
1362 unsigned last_cap;
1363 int r;
1364
1365 table = table_new("name", "number");
1366 if (!table)
1367 return log_oom();
1368
1369 (void) table_set_align_percent(table, table_get_cell(table, 0, 1), 100);
1370
1371 /* Determine the maximum of the last cap known by the kernel and by us */
1372 last_cap = MAX((unsigned) CAP_LAST_CAP, cap_last_cap());
1373
1374 if (strv_isempty(strv_skip(argv, 1)))
1375 for (unsigned c = 0; c <= last_cap; c++) {
1376 r = table_add_many(table,
1377 TABLE_STRING, capability_to_name(c) ?: "cap_???",
1378 TABLE_UINT, c);
1379 if (r < 0)
1380 return table_log_add_error(r);
1381 }
1382 else {
1383 for (int i = 1; i < argc; i++) {
1384 int c;
1385
1386 c = capability_from_name(argv[i]);
1387 if (c < 0 || (unsigned) c > last_cap)
1388 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Capability \"%s\" not known.", argv[i]);
1389
1390 r = table_add_many(table,
1391 TABLE_STRING, capability_to_name(c) ?: "cap_???",
1392 TABLE_UINT, (unsigned) c);
1393 if (r < 0)
1394 return table_log_add_error(r);
1395 }
1396
ef1e0b9a 1397 (void) table_set_sort(table, (size_t) 1);
b2af819b
LP
1398 }
1399
384c2c32 1400 pager_open(arg_pager_flags);
b2af819b
LP
1401
1402 return table_print(table, NULL);
1403}
1404
30bddc06 1405void time_parsing_hint(const char *p, bool calendar, bool timestamp, bool timespan) {
c269607f
ZJS
1406 if (calendar && calendar_spec_from_string(p, NULL) >= 0)
1407 log_notice("Hint: this expression is a valid calendar specification. "
1408 "Use 'systemd-analyze calendar \"%s\"' instead?", p);
1409 if (timestamp && parse_timestamp(p, NULL) >= 0)
1410 log_notice("Hint: this expression is a valid timestamp. "
1411 "Use 'systemd-analyze timestamp \"%s\"' instead?", p);
1412 if (timespan && parse_time(p, NULL, USEC_PER_SEC) >= 0)
1413 log_notice("Hint: this expression is a valid timespan. "
1414 "Use 'systemd-analyze timespan \"%s\"' instead?", p);
6d86f4bd
LP
1415}
1416
edfea9fe 1417static int do_condition(int argc, char *argv[], void *userdata) {
8de7929d 1418 return verify_conditions(strv_skip(argv, 1), arg_scope, arg_unit, arg_root);
edfea9fe
ZJS
1419}
1420
a6bcef29 1421static int do_verify(int argc, char *argv[], void *userdata) {
da845dab
AB
1422 _cleanup_strv_free_ char **filenames = NULL;
1423 _cleanup_(rm_rf_physical_and_freep) char *tempdir = NULL;
1424 int r;
1425
1426 r = mkdtemp_malloc("/tmp/systemd-analyze-XXXXXX", &tempdir);
1427 if (r < 0)
1428 return log_error_errno(r, "Failed to setup working directory: %m");
1429
1430 r = process_aliases(argv, tempdir, &filenames);
1431 if (r < 0)
1432 return log_error_errno(r, "Couldn't process aliases: %m");
1433
1434 return verify_units(filenames, arg_scope, arg_man, arg_generators, arg_recursive_errors, arg_root);
a6bcef29
LP
1435}
1436
ec16f3b6
LP
1437static int do_security(int argc, char *argv[], void *userdata) {
1438 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
ecfd082b 1439 _cleanup_(json_variant_unrefp) JsonVariant *policy = NULL;
ec16f3b6 1440 int r;
ecfd082b 1441 unsigned line, column;
ec16f3b6 1442
741c4c8d
LB
1443 if (!arg_offline) {
1444 r = acquire_bus(&bus, NULL);
1445 if (r < 0)
1446 return bus_log_connect_error(r, arg_transport);
1447 }
ec16f3b6 1448
384c2c32 1449 pager_open(arg_pager_flags);
ec16f3b6 1450
ecfd082b
MG
1451 if (arg_security_policy) {
1452 r = json_parse_file(/*f=*/ NULL, arg_security_policy, /*flags=*/ 0, &policy, &line, &column);
1453 if (r < 0)
1454 return log_error_errno(r, "Failed to parse '%s' at %u:%u: %m", arg_security_policy, line, column);
1455 } else {
1456 _cleanup_fclose_ FILE *f = NULL;
1457 _cleanup_free_ char *pp = NULL;
1458
1459 r = search_and_fopen_nulstr("systemd-analyze-security.policy", "re", /*root=*/ NULL, CONF_PATHS_NULSTR("systemd"), &f, &pp);
1460 if (r < 0 && r != -ENOENT)
1461 return r;
1462
b98416e1 1463 if (f) {
ecfd082b
MG
1464 r = json_parse_file(f, pp, /*flags=*/ 0, &policy, &line, &column);
1465 if (r < 0)
1466 return log_error_errno(r, "[%s:%u:%u] Failed to parse JSON policy: %m", pp, line, column);
1467 }
1468 }
1469
1470 return analyze_security(bus,
1471 strv_skip(argv, 1),
1472 policy,
1473 arg_scope,
1474 arg_man,
1475 arg_generators,
1476 arg_offline,
1477 arg_threshold,
1478 arg_root,
04469211 1479 arg_profile,
4b4a8ef7
MG
1480 arg_json_format_flags,
1481 arg_pager_flags,
ecfd082b 1482 /*flags=*/ 0);
ec16f3b6
LP
1483}
1484
917e6554
LB
1485static int do_elf_inspection(int argc, char *argv[], void *userdata) {
1486 pager_open(arg_pager_flags);
1487
1488 return analyze_elf(strv_skip(argv, 1), arg_json_format_flags);
1489}
1490
a6bcef29 1491static int help(int argc, char *argv[], void *userdata) {
49139a5d 1492 _cleanup_free_ char *link = NULL, *dot_link = NULL;
37ec0fdd 1493 int r;
9ea9d4cf 1494
384c2c32 1495 pager_open(arg_pager_flags);
9ea9d4cf 1496
37ec0fdd
LP
1497 r = terminal_urlify_man("systemd-analyze", "1", &link);
1498 if (r < 0)
1499 return log_oom();
1500
49139a5d
LP
1501 /* Not using terminal_urlify_man() for this, since we don't want the "man page" text suffix in this case. */
1502 r = terminal_urlify("man:dot(1)", "dot(1)", &dot_link);
1503 if (r < 0)
1504 return log_oom();
1505
353b2baa
LP
1506 printf("%s [OPTIONS...] COMMAND ...\n\n"
1507 "%sProfile systemd, show unit dependencies, check unit files.%s\n"
20a51f6a 1508 "\nCommands:\n"
3cc3dc77
MG
1509 " [time] Print time required to boot the machine\n"
1510 " blame Print list of running units ordered by\n"
1511 " time to init\n"
1512 " critical-chain [UNIT...] Print a tree of the time critical chain\n"
1513 " of units\n"
1514 " plot Output SVG graphic showing service\n"
1515 " initialization\n"
1516 " dot [UNIT...] Output dependency graph in %s format\n"
1517 " dump Output state serialization of service\n"
1518 " manager\n"
1519 " cat-config Show configuration file and drop-ins\n"
1520 " unit-files List files and symlinks for units\n"
1521 " unit-paths List load directories for units\n"
1522 " exit-status [STATUS...] List exit status definitions\n"
1523 " capability [CAP...] List capability definitions\n"
52117f5a
ZJS
1524 " syscall-filter [NAME...] List syscalls in seccomp filters\n"
1525 " filesystems [NAME...] List known filesystems\n"
3cc3dc77
MG
1526 " condition CONDITION... Evaluate conditions and asserts\n"
1527 " verify FILE... Check unit files for correctness\n"
1528 " calendar SPEC... Validate repetitive calendar time\n"
1529 " events\n"
1530 " timestamp TIMESTAMP... Validate a timestamp\n"
1531 " timespan SPAN... Validate a time span\n"
1532 " security [UNIT...] Analyze security of unit\n"
917e6554 1533 " inspect-elf FILE... Parse and print ELF package metadata\n"
353b2baa 1534 "\nOptions:\n"
3cc3dc77 1535 " --recursive-errors=MODE Control which units are verified\n"
bb43d853 1536 " --offline=BOOL Perform a security review on unit file(s)\n"
dfbda879
MG
1537 " --threshold=N Exit with a non-zero status when overall\n"
1538 " exposure level is over threshold value\n"
ecfd082b
MG
1539 " --security-policy=PATH Use custom JSON security policy instead\n"
1540 " of built-in one\n"
4b4a8ef7
MG
1541 " --json=pretty|short|off Generate JSON output of the security\n"
1542 " analysis table\n"
3cc3dc77
MG
1543 " --no-pager Do not pipe output into a pager\n"
1544 " --system Operate on system systemd instance\n"
1545 " --user Operate on user systemd instance\n"
1546 " --global Operate on global user configuration\n"
1547 " -H --host=[USER@]HOST Operate on remote host\n"
1548 " -M --machine=CONTAINER Operate on local container\n"
1549 " --order Show only order in the graph\n"
1550 " --require Show only requirement in the graph\n"
1551 " --from-pattern=GLOB Show only origins in the graph\n"
1552 " --to-pattern=GLOB Show only destinations in the graph\n"
1553 " --fuzz=SECONDS Also print services which finished SECONDS\n"
1554 " earlier than the latest in the branch\n"
1555 " --man[=BOOL] Do [not] check for existence of man pages\n"
1556 " --generators[=BOOL] Do [not] run unit generators\n"
1557 " (requires privileges)\n"
1558 " --iterations=N Show the specified number of iterations\n"
1559 " --base-time=TIMESTAMP Calculate calendar times relative to\n"
1560 " specified time\n"
04469211
LB
1561 " --profile=name|PATH Include the specified profile in the\n"
1562 " security review of the unit(s)\n"
52117f5a
ZJS
1563 " -h --help Show this help\n"
1564 " --version Show package version\n"
1565 " -q --quiet Do not emit hints\n"
bc556335
DDM
1566 "\nSee the %s for details.\n",
1567 program_invocation_short_name,
1568 ansi_highlight(),
1569 ansi_normal(),
1570 dot_link,
1571 link);
96de7c04 1572
1ace223c
SJ
1573 /* When updating this list, including descriptions, apply changes to
1574 * shell-completion/bash/systemd-analyze and shell-completion/zsh/_systemd-analyze too. */
a6bcef29
LP
1575
1576 return 0;
2265fbf7
SP
1577}
1578
9ea9d4cf 1579static int parse_argv(int argc, char *argv[]) {
2265fbf7
SP
1580 enum {
1581 ARG_VERSION = 0x100,
1700761b
SP
1582 ARG_ORDER,
1583 ARG_REQUIRE,
46d8646a 1584 ARG_ROOT,
e5ea5c3a 1585 ARG_IMAGE,
e55933db 1586 ARG_SYSTEM,
28b35ef2
ZJS
1587 ARG_USER,
1588 ARG_GLOBAL,
e55933db 1589 ARG_DOT_FROM_PATTERN,
bb150966 1590 ARG_DOT_TO_PATTERN,
9ea9d4cf 1591 ARG_FUZZ,
1d3bc017 1592 ARG_NO_PAGER,
dad29dff 1593 ARG_MAN,
641c0fd1 1594 ARG_GENERATORS,
f2ccf832 1595 ARG_ITERATIONS,
985c1880 1596 ARG_BASE_TIME,
3cc3dc77 1597 ARG_RECURSIVE_ERRORS,
bb43d853 1598 ARG_OFFLINE,
dfbda879 1599 ARG_THRESHOLD,
ecfd082b 1600 ARG_SECURITY_POLICY,
4b4a8ef7 1601 ARG_JSON,
04469211 1602 ARG_PROFILE,
2265fbf7
SP
1603 };
1604
1605 static const struct option options[] = {
3cc3dc77
MG
1606 { "help", no_argument, NULL, 'h' },
1607 { "version", no_argument, NULL, ARG_VERSION },
52117f5a 1608 { "quiet", no_argument, NULL, 'q' },
3cc3dc77
MG
1609 { "order", no_argument, NULL, ARG_ORDER },
1610 { "require", no_argument, NULL, ARG_REQUIRE },
1611 { "root", required_argument, NULL, ARG_ROOT },
1612 { "image", required_argument, NULL, ARG_IMAGE },
1613 { "recursive-errors", required_argument, NULL, ARG_RECURSIVE_ERRORS },
bb43d853 1614 { "offline", required_argument, NULL, ARG_OFFLINE },
dfbda879 1615 { "threshold", required_argument, NULL, ARG_THRESHOLD },
ecfd082b 1616 { "security-policy", required_argument, NULL, ARG_SECURITY_POLICY },
3cc3dc77
MG
1617 { "system", no_argument, NULL, ARG_SYSTEM },
1618 { "user", no_argument, NULL, ARG_USER },
1619 { "global", no_argument, NULL, ARG_GLOBAL },
1620 { "from-pattern", required_argument, NULL, ARG_DOT_FROM_PATTERN },
1621 { "to-pattern", required_argument, NULL, ARG_DOT_TO_PATTERN },
1622 { "fuzz", required_argument, NULL, ARG_FUZZ },
1623 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1624 { "man", optional_argument, NULL, ARG_MAN },
1625 { "generators", optional_argument, NULL, ARG_GENERATORS },
1626 { "host", required_argument, NULL, 'H' },
1627 { "machine", required_argument, NULL, 'M' },
1628 { "iterations", required_argument, NULL, ARG_ITERATIONS },
1629 { "base-time", required_argument, NULL, ARG_BASE_TIME },
8de7929d 1630 { "unit", required_argument, NULL, 'U' },
4b4a8ef7 1631 { "json", required_argument, NULL, ARG_JSON },
04469211 1632 { "profile", required_argument, NULL, ARG_PROFILE },
eb9da376 1633 {}
2265fbf7
SP
1634 };
1635
eb9da376
LP
1636 int r, c;
1637
2265fbf7
SP
1638 assert(argc >= 0);
1639 assert(argv);
1640
8de7929d 1641 while ((c = getopt_long(argc, argv, "hH:M:U:", options, NULL)) >= 0)
eb9da376 1642 switch (c) {
c170f3a4
LP
1643
1644 case 'h':
a6bcef29 1645 return help(0, NULL, NULL);
c170f3a4 1646
52117f5a
ZJS
1647 case ARG_VERSION:
1648 return version();
1649
1650 case 'q':
1651 arg_quiet = true;
1652 break;
1653
3cc3dc77
MG
1654 case ARG_RECURSIVE_ERRORS:
1655 if (streq(optarg, "help")) {
1656 DUMP_STRING_TABLE(recursive_errors, RecursiveErrors, _RECURSIVE_ERRORS_MAX);
1657 return 0;
1658 }
1659 r = recursive_errors_from_string(optarg);
1660 if (r < 0)
1661 return log_error_errno(r, "Unknown mode passed to --recursive-errors='%s'.", optarg);
1662
1663 arg_recursive_errors = r;
1664 break;
1665
46d8646a 1666 case ARG_ROOT:
782671bc
MG
1667 r = parse_path_argument(optarg, /* suppress_root= */ true, &arg_root);
1668 if (r < 0)
1669 return r;
46d8646a
ZJS
1670 break;
1671
e5ea5c3a
MG
1672 case ARG_IMAGE:
1673 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
1674 if (r < 0)
1675 return r;
1676 break;
1677
28b35ef2
ZJS
1678 case ARG_SYSTEM:
1679 arg_scope = UNIT_FILE_SYSTEM;
1680 break;
1681
c170f3a4 1682 case ARG_USER:
28b35ef2 1683 arg_scope = UNIT_FILE_USER;
c170f3a4
LP
1684 break;
1685
28b35ef2
ZJS
1686 case ARG_GLOBAL:
1687 arg_scope = UNIT_FILE_GLOBAL;
c170f3a4
LP
1688 break;
1689
1690 case ARG_ORDER:
1691 arg_dot = DEP_ORDER;
1692 break;
1693
1694 case ARG_REQUIRE:
1695 arg_dot = DEP_REQUIRE;
1696 break;
1697
e55933db 1698 case ARG_DOT_FROM_PATTERN:
903a0b07
LP
1699 if (strv_extend(&arg_dot_from_patterns, optarg) < 0)
1700 return log_oom();
1701
e55933db
ŁS
1702 break;
1703
1704 case ARG_DOT_TO_PATTERN:
903a0b07
LP
1705 if (strv_extend(&arg_dot_to_patterns, optarg) < 0)
1706 return log_oom();
1707
e55933db
ŁS
1708 break;
1709
bb150966
HH
1710 case ARG_FUZZ:
1711 r = parse_sec(optarg, &arg_fuzz);
1712 if (r < 0)
1713 return r;
1714 break;
1715
9ea9d4cf 1716 case ARG_NO_PAGER:
0221d68a 1717 arg_pager_flags |= PAGER_DISABLE;
9ea9d4cf
LP
1718 break;
1719
3cd26e7c
LP
1720 case 'H':
1721 arg_transport = BUS_TRANSPORT_REMOTE;
1722 arg_host = optarg;
1723 break;
1724
1725 case 'M':
de33fc62 1726 arg_transport = BUS_TRANSPORT_MACHINE;
3cd26e7c
LP
1727 arg_host = optarg;
1728 break;
1729
dad29dff 1730 case ARG_MAN:
599c7c54
ZJS
1731 r = parse_boolean_argument("--man", optarg, &arg_man);
1732 if (r < 0)
1733 return r;
1d3bc017
ZJS
1734 break;
1735
641c0fd1 1736 case ARG_GENERATORS:
599c7c54
ZJS
1737 r = parse_boolean_argument("--generators", optarg, &arg_generators);
1738 if (r < 0)
1739 return r;
641c0fd1
ZJS
1740 break;
1741
bb43d853
MG
1742 case ARG_OFFLINE:
1743 r = parse_boolean_argument("--offline", optarg, &arg_offline);
1744 if (r < 0)
1745 return r;
1746 break;
1747
dfbda879
MG
1748 case ARG_THRESHOLD:
1749 r = safe_atou(optarg, &arg_threshold);
1750 if (r < 0 || arg_threshold > 100)
1751 return log_error_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse threshold: %s", optarg);
1752
1753 break;
1754
ecfd082b
MG
1755 case ARG_SECURITY_POLICY:
1756 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_security_policy);
1757 if (r < 0)
1758 return r;
1759 break;
1760
4b4a8ef7
MG
1761 case ARG_JSON:
1762 r = parse_json_argument(optarg, &arg_json_format_flags);
1763 if (r <= 0)
1764 return r;
1765 break;
1766
f2ccf832
LP
1767 case ARG_ITERATIONS:
1768 r = safe_atou(optarg, &arg_iterations);
1769 if (r < 0)
1770 return log_error_errno(r, "Failed to parse iterations: %s", optarg);
1771
1772 break;
1773
985c1880
LP
1774 case ARG_BASE_TIME:
1775 r = parse_timestamp(optarg, &arg_base_time);
1776 if (r < 0)
1777 return log_error_errno(r, "Failed to parse --base-time= parameter: %s", optarg);
1778
1779 break;
1780
04469211
LB
1781 case ARG_PROFILE:
1782 if (isempty(optarg))
1783 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Profile file name is empty");
1784
1785 if (is_path(optarg)) {
1786 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_profile);
1787 if (r < 0)
1788 return r;
1789 if (!endswith(arg_profile, ".conf"))
1790 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Profile file name must end with .conf: %s", arg_profile);
1791 } else {
1792 r = free_and_strdup(&arg_profile, optarg);
1793 if (r < 0)
1794 return log_oom();
1795 }
1796
1797 break;
1798
8de7929d
DDM
1799 case 'U': {
1800 _cleanup_free_ char *mangled = NULL;
1801
1802 r = unit_name_mangle(optarg, UNIT_NAME_MANGLE_WARN, &mangled);
1803 if (r < 0)
1804 return log_error_errno(r, "Failed to mangle unit name %s: %m", optarg);
1805
1806 free_and_replace(arg_unit, mangled);
1807 break;
1808 }
c170f3a4
LP
1809 case '?':
1810 return -EINVAL;
1811
1812 default:
04499a70 1813 assert_not_reached();
2265fbf7 1814 }
eb9da376 1815
bb43d853
MG
1816 if (arg_offline && !streq_ptr(argv[optind], "security"))
1817 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1818 "Option --offline= is only supported for security right now.");
1819
917e6554 1820 if (arg_json_format_flags != JSON_FORMAT_OFF && !STRPTR_IN_SET(argv[optind], "security", "inspect-elf"))
4b4a8ef7 1821 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
c0f65909 1822 "Option --json= is only supported for security and inspect-elf right now.");
4b4a8ef7 1823
dfbda879
MG
1824 if (arg_threshold != 100 && !streq_ptr(argv[optind], "security"))
1825 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1826 "Option --threshold= is only supported for security right now.");
1827
31a5924e 1828 if (arg_scope == UNIT_FILE_GLOBAL &&
baaa35ad
ZJS
1829 !STR_IN_SET(argv[optind] ?: "time", "dot", "unit-paths", "verify"))
1830 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1831 "Option --global only makes sense with verbs dot, unit-paths, verify.");
31a5924e 1832
f1d9d36a
ZJS
1833 if (streq_ptr(argv[optind], "cat-config") && arg_scope == UNIT_FILE_USER)
1834 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1835 "Option --user is not supported for cat-config right now.");
1836
ecfd082b
MG
1837 if (arg_security_policy && !streq_ptr(argv[optind], "security"))
1838 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1839 "Option --security-policy= is only supported for security.");
1840
8de7929d 1841 if ((arg_root || arg_image) && (!STRPTR_IN_SET(argv[optind], "cat-config", "verify", "condition")) &&
bb43d853 1842 (!(streq_ptr(argv[optind], "security") && arg_offline)))
baaa35ad 1843 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
8de7929d 1844 "Options --root= and --image= are only supported for cat-config, verify, condition and security when used with --offline= right now.");
e5ea5c3a
MG
1845
1846 /* Having both an image and a root is not supported by the code */
1847 if (arg_root && arg_image)
1848 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
46d8646a 1849
8de7929d
DDM
1850 if (arg_unit && !streq_ptr(argv[optind], "condition"))
1851 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Option --unit= is only supported for condition");
1852
1853 if (streq_ptr(argv[optind], "condition") && !arg_unit && optind >= argc - 1)
1854 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too few arguments for condition");
1855
1856 if (streq_ptr(argv[optind], "condition") && arg_unit && optind < argc - 1)
1857 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No conditions can be passed if --unit= is used.");
1858
1d3bc017 1859 return 1; /* work to do */
2265fbf7
SP
1860}
1861
d665c7b2 1862static int run(int argc, char *argv[]) {
e5ea5c3a
MG
1863 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
1864 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
1865 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
a6bcef29
LP
1866
1867 static const Verb verbs[] = {
889d695d
JK
1868 { "help", VERB_ANY, VERB_ANY, 0, help },
1869 { "time", VERB_ANY, 1, VERB_DEFAULT, analyze_time },
1870 { "blame", VERB_ANY, 1, 0, analyze_blame },
1871 { "critical-chain", VERB_ANY, VERB_ANY, 0, analyze_critical_chain },
1872 { "plot", VERB_ANY, 1, 0, analyze_plot },
1873 { "dot", VERB_ANY, VERB_ANY, 0, dot },
ab86ccba 1874 /* ↓ The following seven verbs are deprecated, from here … ↓ */
a87b151a
DDM
1875 { "log-level", VERB_ANY, 2, 0, verb_log_control },
1876 { "log-target", VERB_ANY, 2, 0, verb_log_control },
1877 { "set-log-level", 2, 2, 0, verb_log_control },
1878 { "get-log-level", VERB_ANY, 1, 0, verb_log_control },
1879 { "set-log-target", 2, 2, 0, verb_log_control },
1880 { "get-log-target", VERB_ANY, 1, 0, verb_log_control },
26e1e973 1881 { "service-watchdogs", VERB_ANY, 2, 0, service_watchdogs },
ab86ccba 1882 /* ↑ … until here ↑ */
889d695d 1883 { "dump", VERB_ANY, 1, 0, dump },
854a42fb 1884 { "cat-config", 2, VERB_ANY, 0, cat_config },
e67cd21d 1885 { "unit-files", VERB_ANY, VERB_ANY, 0, do_unit_files },
31a5924e 1886 { "unit-paths", 1, 1, 0, dump_unit_paths },
5238d9a8 1887 { "exit-status", VERB_ANY, VERB_ANY, 0, dump_exit_status },
889d695d 1888 { "syscall-filter", VERB_ANY, VERB_ANY, 0, dump_syscall_filters },
b2af819b 1889 { "capability", VERB_ANY, VERB_ANY, 0, dump_capabilities },
b41711cd 1890 { "filesystems", VERB_ANY, VERB_ANY, 0, dump_filesystems },
8de7929d 1891 { "condition", VERB_ANY, VERB_ANY, 0, do_condition },
889d695d
JK
1892 { "verify", 2, VERB_ANY, 0, do_verify },
1893 { "calendar", 2, VERB_ANY, 0, test_calendar },
2cae4711 1894 { "timestamp", 2, VERB_ANY, 0, test_timestamp },
3f1c1287 1895 { "timespan", 2, VERB_ANY, 0, dump_timespan },
ec16f3b6 1896 { "security", VERB_ANY, VERB_ANY, 0, do_security },
917e6554 1897 { "inspect-elf", 2, VERB_ANY, 0, do_elf_inspection },
a6bcef29
LP
1898 {}
1899 };
1900
5220a6f3 1901 int r;
2265fbf7
SP
1902
1903 setlocale(LC_ALL, "");
c170f3a4 1904 setlocale(LC_NUMERIC, "C"); /* we want to format/parse floats in C style */
a6bcef29 1905
d2acb93d 1906 log_setup();
2265fbf7
SP
1907
1908 r = parse_argv(argc, argv);
9ea9d4cf 1909 if (r <= 0)
d665c7b2 1910 return r;
c170f3a4 1911
e5ea5c3a
MG
1912 /* Open up and mount the image */
1913 if (arg_image) {
1914 assert(!arg_root);
1915
1916 r = mount_image_privately_interactively(
1917 arg_image,
1918 DISSECT_IMAGE_GENERIC_ROOT |
1919 DISSECT_IMAGE_RELAX_VAR_CHECK |
1920 DISSECT_IMAGE_READ_ONLY,
1921 &unlink_dir,
1922 &loop_device,
1923 &decrypted_image);
1924 if (r < 0)
1925 return r;
1926
1927 arg_root = strdup(unlink_dir);
1928 if (!arg_root)
1929 return log_oom();
1930 }
1931
d665c7b2 1932 return dispatch_verb(argc, argv, verbs, NULL);
2265fbf7 1933}
d665c7b2
YW
1934
1935DEFINE_MAIN_FUNCTION(run);