Debian Codegraph @

src/systemctl/systemctl-start-unit.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-bus.h"
4
5 #include "alloc-util.h"
6 #include "ansi-color.h"
7 #include "bus-common-errors.h"
8 #include "bus-error.h"
9 #include "bus-locator.h"
10 #include "bus-util.h"
11 #include "bus-wait-for-jobs.h"
12 #include "bus-wait-for-units.h"
13 #include "fork-notify.h"
14 #include "pidref.h"
15 #include "runtime-scope.h"
16 #include "special.h"
17 #include "string-util.h"
18 #include "strv.h"
19 #include "systemctl.h"
20 #include "systemctl-start-unit.h"
21 #include "systemctl-util.h"
22
23 static const struct {
24 const char *verb; /* systemctl verb */
25 const char *method; /* Name of the specific D-Bus method */
26 const char *job_type; /* Job type when passing to the generic EnqueueUnitJob() method */
27 } unit_actions[] = {
28 { "start", "StartUnit", "start" },
29 { "stop", "StopUnit", "stop" },
30 { "condstop", "StopUnit", "stop" }, /* legacy alias */
31 { "reload", "ReloadUnit", "reload" },
32 { "restart", "RestartUnit", "restart" },
33 { "try-restart", "TryRestartUnit", "try-restart" },
34 { "condrestart", "TryRestartUnit", "try-restart" }, /* legacy alias */
35 { "reload-or-restart", "ReloadOrRestartUnit", "reload-or-restart" },
36 { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
37 { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
38 { "condreload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
39 { "force-reload", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
40 };
41
42 static const char* verb_to_method(const char *verb) {
43 assert(verb);
44
45 FOREACH_ELEMENT(i, unit_actions)
46 if (streq(i->verb, verb))
47 return i->method;
48
49 return "StartUnit";
50 }
51
52 static const char* verb_to_job_type(const char *verb) {
53 assert(verb);
54
55 FOREACH_ELEMENT(i, unit_actions)
56 if (streq(i->verb, verb))
57 return i->job_type;
58
59 return "start";
60 }
61
62 static int start_unit_one(
63 sd_bus *bus,
64 const char *method, /* When using classic per-job bus methods */
65 const char *job_type, /* When using new-style EnqueueUnitJob() */
66 const char *name,
67 const char *mode,
68 sd_bus_error *error,
69 BusWaitForJobs *w,
70 BusWaitForUnits *wu) {
71
72 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
73 const char *path;
74 bool done = false;
75 int r;
76
77 assert(method);
78 assert(name);
79 assert(mode);
80 assert(error);
81
82 log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
83 arg_dry_run ? "Would execute" : "Executing",
84 method, name, mode);
85
86 if (arg_dry_run)
87 return 0;
88
89 if (arg_show_transaction) {
90 _cleanup_(sd_bus_error_free) sd_bus_error enqueue_error = SD_BUS_ERROR_NULL;
91
92 /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
93 r = bus_call_method(
94 bus,
95 bus_systemd_mgr,
96 "EnqueueUnitJob",
97 &enqueue_error,
98 &reply,
99 "sss",
100 name, job_type, mode);
101 if (r < 0) {
102 if (!sd_bus_error_has_name(&enqueue_error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
103 (void) sd_bus_error_move(error, &enqueue_error);
104 goto fail;
105 }
106
107 /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
108 log_notice("--show-transaction not supported by this service manager, proceeding without.");
109 } else {
110 const char *u, *jt;
111 uint32_t id;
112
113 r = sd_bus_message_read(reply, "uosos", &id, &path, &u, NULL, &jt);
114 if (r < 0)
115 return bus_log_parse_error(r);
116
117 log_info("Enqueued anchor job %" PRIu32 " %s/%s.", id, u, jt);
118
119 r = sd_bus_message_enter_container(reply, 'a', "(uosos)");
120 if (r < 0)
121 return bus_log_parse_error(r);
122 for (;;) {
123 r = sd_bus_message_read(reply, "(uosos)", &id, NULL, &u, NULL, &jt);
124 if (r < 0)
125 return bus_log_parse_error(r);
126 if (r == 0)
127 break;
128
129 log_info("Enqueued auxiliary job %" PRIu32 " %s/%s.", id, u, jt);
130 }
131
132 r = sd_bus_message_exit_container(reply);
133 if (r < 0)
134 return bus_log_parse_error(r);
135
136 done = true;
137 }
138 }
139
140 if (!done) {
141 r = bus_call_method(bus, bus_systemd_mgr, method, error, &reply, "ss", name, mode);
142 if (r < 0)
143 goto fail;
144
145 r = sd_bus_message_read(reply, "o", &path);
146 if (r < 0)
147 return bus_log_parse_error(r);
148 }
149
150 if (need_daemon_reload(bus, name) > 0)
151 warn_unit_file_changed(name);
152
153 if (w) {
154 log_debug("Adding %s to the set", path);
155 r = bus_wait_for_jobs_add(w, path);
156 if (r < 0)
157 return log_error_errno(r, "Failed to watch job for %s: %m", name);
158 }
159
160 if (wu) {
161 r = bus_wait_for_units_add_unit(wu, name, BUS_WAIT_FOR_INACTIVE|BUS_WAIT_NO_JOB, NULL, NULL);
162 if (r < 0)
163 return log_error_errno(r, "Failed to watch unit %s: %m", name);
164 }
165
166 return 0;
167
168 fail:
169 /* There's always a fallback possible for legacy actions. */
170 if (arg_action != ACTION_SYSTEMCTL)
171 return r;
172
173 if (sd_bus_error_has_name(error, BUS_ERROR_UNIT_MASKED) &&
174 STR_IN_SET(method, "TryRestartUnit", "ReloadOrTryRestartUnit")) {
175 /* Ignore masked unit if try-* is requested */
176
177 log_debug_errno(r, "Failed to %s %s, ignoring: %s", job_type, name, bus_error_message(error, r));
178 return 0;
179 }
180
181 log_error_errno(r, "Failed to %s %s: %s", job_type, name, bus_error_message(error, r));
182
183 if (!sd_bus_error_has_names(error, BUS_ERROR_NO_SUCH_UNIT,
184 BUS_ERROR_UNIT_MASKED,
185 BUS_ERROR_JOB_TYPE_NOT_APPLICABLE))
186 log_error("See %s logs and 'systemctl%s status%s %s' for details.",
187 runtime_scope_to_string(arg_runtime_scope),
188 arg_runtime_scope == RUNTIME_SCOPE_SYSTEM ? "" : " --user",
189 name[0] == '-' ? " --" : "",
190 name);
191
192 return r;
193 }
194
195 static int enqueue_marked_jobs(
196 sd_bus *bus,
197 BusWaitForJobs *w) {
198
199 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
200 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
201 int r;
202
203 log_debug("%s dbus call org.freedesktop.systemd1.Manager EnqueueMarkedJobs()",
204 arg_dry_run ? "Would execute" : "Executing");
205
206 if (arg_dry_run)
207 return 0;
208
209 r = bus_call_method(bus, bus_systemd_mgr, "EnqueueMarkedJobs", &error, &reply, NULL);
210 if (r < 0)
211 return log_error_errno(r, "Failed to start jobs: %s", bus_error_message(&error, r));
212
213 _cleanup_strv_free_ char **paths = NULL;
214 r = sd_bus_message_read_strv(reply, &paths);
215 if (r < 0)
216 return bus_log_parse_error(r);
217
218 if (w)
219 STRV_FOREACH(path, paths) {
220 log_debug("Adding %s to the set", *path);
221 r = bus_wait_for_jobs_add(w, *path);
222 if (r < 0)
223 return log_error_errno(r, "Failed to watch job %s: %m", *path);
224 }
225
226 return 0;
227 }
228
229 const struct action_metadata action_table[_ACTION_MAX] = {
230 [ACTION_HALT] = { SPECIAL_HALT_TARGET, "halt", "replace-irreversibly" },
231 [ACTION_POWEROFF] = { SPECIAL_POWEROFF_TARGET, "poweroff", "replace-irreversibly" },
232 [ACTION_REBOOT] = { SPECIAL_REBOOT_TARGET, "reboot", "replace-irreversibly" },
233 [ACTION_KEXEC] = { SPECIAL_KEXEC_TARGET, "kexec", "replace-irreversibly" },
234 [ACTION_SOFT_REBOOT] = { SPECIAL_SOFT_REBOOT_TARGET, "soft-reboot", "replace-irreversibly" },
235 [ACTION_RESCUE] = { SPECIAL_RESCUE_TARGET, "rescue", "isolate" },
236 [ACTION_EMERGENCY] = { SPECIAL_EMERGENCY_TARGET, "emergency", "isolate" },
237 [ACTION_DEFAULT] = { SPECIAL_DEFAULT_TARGET, "default", "isolate" },
238 [ACTION_EXIT] = { SPECIAL_EXIT_TARGET, "exit", "replace-irreversibly" },
239 [ACTION_SUSPEND] = { SPECIAL_SUSPEND_TARGET, "suspend", "replace-irreversibly" },
240 [ACTION_HIBERNATE] = { SPECIAL_HIBERNATE_TARGET, "hibernate", "replace-irreversibly" },
241 [ACTION_HYBRID_SLEEP] = { SPECIAL_HYBRID_SLEEP_TARGET, "hybrid-sleep", "replace-irreversibly" },
242 [ACTION_SUSPEND_THEN_HIBERNATE] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET, "suspend-then-hibernate", "replace-irreversibly" },
243 [ACTION_SLEEP] = { NULL, /* handled only by logind */ "sleep", NULL },
244 };
245
246 enum action verb_to_action(const char *verb) {
247 assert(verb);
248
249 for (enum action i = 0; i < _ACTION_MAX; i++)
250 if (streq_ptr(action_table[i].verb, verb))
251 return i;
252
253 return _ACTION_INVALID;
254 }
255
256 static const char** make_extra_args(const char *extra_args[static 4]) {
257 size_t n = 0;
258
259 assert(extra_args);
260
261 if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
262 extra_args[n++] = "--user";
263
264 switch (arg_transport) {
265
266 case BUS_TRANSPORT_REMOTE:
267 extra_args[n++] = "-H";
268 extra_args[n++] = arg_host;
269 break;
270
271 case BUS_TRANSPORT_MACHINE:
272 extra_args[n++] = "-M";
273 extra_args[n++] = arg_host;
274 break;
275
276 case BUS_TRANSPORT_CAPSULE:
277 extra_args[n++] = "-C";
278 extra_args[n++] = arg_host;
279 break;
280
281 case BUS_TRANSPORT_LOCAL:
282 break;
283
284 default:
285 assert_not_reached();
286 }
287
288 extra_args[n] = NULL;
289 return extra_args;
290 }
291
292 int verb_start(int argc, char *argv[], uintptr_t _data, void *userdata) {
293 _cleanup_(bus_wait_for_units_freep) BusWaitForUnits *wu = NULL;
294 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
295 const char *method, *job_type, *mode, *one_name, *suffix = NULL;
296 _cleanup_free_ char **stopped_units = NULL; /* Do not use _cleanup_strv_free_ */
297 _cleanup_strv_free_ char **names = NULL;
298 bool is_enqueue_marked_jobs = false;
299 int r, ret = EXIT_SUCCESS;
300 sd_bus *bus;
301
302 if (arg_wait && !STR_IN_SET(argv[0], "start", "restart"))
303 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
304 "--wait may only be used with the 'start' or 'restart' commands.");
305
306 /* We cannot do sender tracking on the private bus, so we need the full one for RefUnit to implement
307 * --wait */
308 r = acquire_bus(arg_wait ? BUS_FULL : BUS_MANAGER, &bus);
309 if (r < 0)
310 return r;
311
312 ask_password_agent_open_maybe();
313 polkit_agent_open_maybe();
314
315 if (arg_action == ACTION_SYSTEMCTL) {
316 enum action action;
317
318 action = verb_to_action(argv[0]);
319
320 assert(action != ACTION_SLEEP);
321
322 if (action != _ACTION_INVALID) {
323 /* A command in style "systemctl reboot", "systemctl poweroff", … */
324 method = "StartUnit";
325 job_type = "start";
326 mode = action_table[action].mode;
327 one_name = action_table[action].target;
328 } else {
329 if (streq(argv[0], "isolate")) {
330 /* A "systemctl isolate <unit1> <unit2> …" command */
331 method = "StartUnit";
332 job_type = "start";
333 mode = "isolate";
334 suffix = ".target";
335 } else if (streq(argv[0], "enqueue-marked") || arg_marked) {
336 is_enqueue_marked_jobs = true;
337 method = job_type = mode = NULL;
338
339 if (arg_show_transaction)
340 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
341 "--show-transaction is not supported for enqueue-marked.");
342
343 if (arg_marked)
344 log_warning("--marked is deprecated. Please use 'systemctl enqueue-marked' instead.");
345
346 } else {
347 /* A command in style of "systemctl start <unit1> <unit2> …", "systemctl stop <unit1> <unit2> …" and so on */
348 method = verb_to_method(argv[0]);
349 job_type = verb_to_job_type(argv[0]);
350 mode = arg_job_mode();
351 }
352
353 one_name = NULL;
354 }
355 } else {
356 /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
357 assert(arg_action >= 0 && arg_action < _ACTION_MAX);
358 assert(action_table[arg_action].target);
359 assert(action_table[arg_action].mode);
360
361 method = "StartUnit";
362 job_type = "start";
363 mode = action_table[arg_action].mode;
364 one_name = action_table[arg_action].target;
365 }
366
367 if (one_name) {
368 names = strv_new(one_name);
369 if (!names)
370 return log_oom();
371 } else if (!is_enqueue_marked_jobs) {
372 bool expanded;
373
374 r = expand_unit_names(bus, strv_skip(argv, 1), suffix, &names, &expanded);
375 if (r < 0)
376 return log_error_errno(r, "Failed to expand names: %m");
377
378 if (!arg_all && expanded && streq(job_type, "start") && !arg_quiet) {
379 log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
380 ansi_highlight_red(),
381 ansi_normal());
382 log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
383 " Passing --all will also load units which are pulled in by other units.\n"
384 " See systemctl(1) for more details.");
385 }
386 }
387
388 if (!arg_no_block) {
389 r = bus_wait_for_jobs_new(bus, &w);
390 if (r < 0)
391 return log_error_errno(r, "Could not watch jobs: %m");
392 }
393
394 if (arg_wait) {
395 r = bus_wait_for_units_new(bus, &wu);
396 if (r < 0)
397 return log_error_errno(r, "Failed to allocate unit watch context: %m");
398 }
399
400 _cleanup_(fork_notify_terminate) PidRef journal_pid = PIDREF_NULL;
401 if (is_enqueue_marked_jobs)
402 ret = enqueue_marked_jobs(bus, w);
403 else {
404 if (arg_verbose)
405 (void) journal_fork(arg_runtime_scope, names, arg_output, &journal_pid);
406
407 STRV_FOREACH(name, names) {
408 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
409
410 r = start_unit_one(bus, method, job_type, *name, mode, &error, w, wu);
411 if (ret == EXIT_SUCCESS && r < 0)
412 ret = translate_bus_error_to_exit_status(r, &error);
413
414 if (r >= 0 && streq(method, "StopUnit")) {
415 r = strv_push(&stopped_units, *name);
416 if (r < 0)
417 return log_oom();
418 }
419 }
420 }
421
422 if (!arg_no_block) {
423 const char *extra_args[4];
424 WaitJobsFlags flags = 0;
425
426 SET_FLAG(flags, BUS_WAIT_JOBS_LOG_ERROR, !arg_quiet);
427 SET_FLAG(flags, BUS_WAIT_JOBS_LOG_SUCCESS, arg_show_transaction);
428 r = bus_wait_for_jobs(w, flags, make_extra_args(extra_args));
429 if (r < 0)
430 return r;
431
432 /* When stopping units, warn if they can still be triggered by
433 * another active unit (socket, path, timer) */
434 if (!arg_quiet && !arg_no_warn)
435 STRV_FOREACH(unit, stopped_units)
436 warn_triggering_units(bus, *unit, "Stopping", /* ignore_masked= */ true);
437 }
438
439 if (arg_wait) {
440 r = bus_wait_for_units_run(wu);
441 if (r < 0)
442 return log_error_errno(r, "Failed to wait for units: %m");
443 if (r == BUS_WAIT_FAILURE && ret == EXIT_SUCCESS)
444 ret = EXIT_FAILURE;
445 }
446
447 return ret;
448 }