summaryrefslogtreecommitdiff
path: root/src/systemctl/systemctl-start-unit.c
blob: 3dac7da460b417e357c66e36ba9b12321ed0f962 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include "sd-bus.h"

#include "bus-common-errors.h"
#include "bus-error.h"
#include "bus-locator.h"
#include "bus-util.h"
#include "bus-wait-for-jobs.h"
#include "bus-wait-for-units.h"
#include "macro.h"
#include "special.h"
#include "string-util.h"
#include "systemctl-start-unit.h"
#include "systemctl-util.h"
#include "systemctl.h"
#include "terminal-util.h"

static const struct {
        const char *verb;      /* systemctl verb */
        const char *method;    /* Name of the specific D-Bus method */
        const char *job_type;  /* Job type when passing to the generic EnqueueUnitJob() method */
} unit_actions[] = {
        { "start",                 "StartUnit",              "start"                 },
        { "stop",                  "StopUnit",               "stop"                  },
        { "condstop",              "StopUnit",               "stop"                  }, /* legacy alias */
        { "reload",                "ReloadUnit",             "reload"                },
        { "restart",               "RestartUnit",            "restart"               },
        { "try-restart",           "TryRestartUnit",         "try-restart"           },
        { "condrestart",           "TryRestartUnit",         "try-restart"           }, /* legacy alias */
        { "reload-or-restart",     "ReloadOrRestartUnit",    "reload-or-restart"     },
        { "try-reload-or-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" },
        { "reload-or-try-restart", "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
        { "condreload",            "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
        { "force-reload",          "ReloadOrTryRestartUnit", "reload-or-try-restart" }, /* legacy alias */
};

static const char *verb_to_method(const char *verb) {
       for (size_t i = 0; i < ELEMENTSOF(unit_actions); i++)
                if (streq_ptr(unit_actions[i].verb, verb))
                        return unit_actions[i].method;

       return "StartUnit";
}

static const char *verb_to_job_type(const char *verb) {
       for (size_t i = 0; i < ELEMENTSOF(unit_actions); i++)
                if (streq_ptr(unit_actions[i].verb, verb))
                        return unit_actions[i].job_type;

       return "start";
}

static int start_unit_one(
                sd_bus *bus,
                const char *method,    /* When using classic per-job bus methods */
                const char *job_type,  /* When using new-style EnqueueUnitJob() */
                const char *name,
                const char *mode,
                sd_bus_error *error,
                BusWaitForJobs *w,
                BusWaitForUnits *wu) {

        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
        const char *path;
        bool done = false;
        int r;

        assert(method);
        assert(name);
        assert(mode);
        assert(error);

        log_debug("%s dbus call org.freedesktop.systemd1.Manager %s(%s, %s)",
                  arg_dry_run ? "Would execute" : "Executing",
                  method, name, mode);

        if (arg_dry_run)
                return 0;

        if (arg_show_transaction) {
                _cleanup_(sd_bus_error_free) sd_bus_error enqueue_error = SD_BUS_ERROR_NULL;

                /* Use the new, fancy EnqueueUnitJob() API if the user wants us to print the transaction */
                r = bus_call_method(
                                bus,
                                bus_systemd_mgr,
                                "EnqueueUnitJob",
                                &enqueue_error,
                                &reply,
                                "sss",
                                name, job_type, mode);
                if (r < 0) {
                        if (!sd_bus_error_has_name(&enqueue_error, SD_BUS_ERROR_UNKNOWN_METHOD)) {
                                (void) sd_bus_error_move(error, &enqueue_error);
                                goto fail;
                        }

                        /* Hmm, the API is not yet available. Let's use the classic API instead (see below). */
                        log_notice("--show-transaction not supported by this service manager, proceeding without.");
                } else {
                        const char *u, *jt;
                        uint32_t id;

                        r = sd_bus_message_read(reply, "uosos", &id, &path, &u, NULL, &jt);
                        if (r < 0)
                                return bus_log_parse_error(r);

                        log_info("Enqueued anchor job %" PRIu32 " %s/%s.", id, u, jt);

                        r = sd_bus_message_enter_container(reply, 'a', "(uosos)");
                        if (r < 0)
                                return bus_log_parse_error(r);
                        for (;;) {
                                r = sd_bus_message_read(reply, "(uosos)", &id, NULL, &u, NULL, &jt);
                                if (r < 0)
                                        return bus_log_parse_error(r);
                                if (r == 0)
                                        break;

                                log_info("Enqueued auxiliary job %" PRIu32 " %s/%s.", id, u, jt);
                        }

                        r = sd_bus_message_exit_container(reply);
                        if (r < 0)
                                return bus_log_parse_error(r);

                        done = true;
                }
        }

        if (!done) {
                r = bus_call_method(bus, bus_systemd_mgr, method, error, &reply, "ss", name, mode);
                if (r < 0)
                        goto fail;

                r = sd_bus_message_read(reply, "o", &path);
                if (r < 0)
                        return bus_log_parse_error(r);
        }

        if (need_daemon_reload(bus, name) > 0)
                warn_unit_file_changed(name);

        if (w) {
                log_debug("Adding %s to the set", path);
                r = bus_wait_for_jobs_add(w, path);
                if (r < 0)
                        return log_error_errno(r, "Failed to watch job for %s: %m", name);
        }

        if (wu) {
                r = bus_wait_for_units_add_unit(wu, name, BUS_WAIT_FOR_INACTIVE|BUS_WAIT_NO_JOB, NULL, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to watch unit %s: %m", name);
        }

        return 0;

fail:
        /* There's always a fallback possible for legacy actions. */
        if (arg_action != ACTION_SYSTEMCTL)
                return r;

        if (sd_bus_error_has_name(error, BUS_ERROR_UNIT_MASKED) &&
            STR_IN_SET(method, "TryRestartUnit", "ReloadOrTryRestartUnit")) {
                /* Ignore masked unit if try-* is requested */

                log_debug_errno(r, "Failed to %s %s, ignoring: %s", job_type, name, bus_error_message(error, r));
                return 0;
        } else
                log_error_errno(r, "Failed to %s %s: %s", job_type, name, bus_error_message(error, r));

        if (!sd_bus_error_has_names(error, BUS_ERROR_NO_SUCH_UNIT,
                                           BUS_ERROR_UNIT_MASKED,
                                           BUS_ERROR_JOB_TYPE_NOT_APPLICABLE))
                log_error("See %s logs and 'systemctl%s status%s %s' for details.",
                          runtime_scope_to_string(arg_runtime_scope),
                          arg_runtime_scope == RUNTIME_SCOPE_SYSTEM ? "" : " --user",
                          name[0] == '-' ? " --" : "",
                          name);

        return r;
}

static int enqueue_marked_jobs(
                sd_bus *bus,
                BusWaitForJobs *w) {

        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        int r;

        log_debug("%s dbus call org.freedesktop.systemd1.Manager EnqueueMarkedJobs()",
                  arg_dry_run ? "Would execute" : "Executing");

        if (arg_dry_run)
                return 0;

        r = bus_call_method(bus, bus_systemd_mgr, "EnqueueMarkedJobs", &error, &reply, NULL);
        if (r < 0)
                return log_error_errno(r, "Failed to start jobs: %s", bus_error_message(&error, r));

        _cleanup_strv_free_ char **paths = NULL;
        r = sd_bus_message_read_strv(reply, &paths);
        if (r < 0)
                return bus_log_parse_error(r);

        if (w)
                STRV_FOREACH(path, paths) {
                        log_debug("Adding %s to the set", *path);
                        r = bus_wait_for_jobs_add(w, *path);
                        if (r < 0)
                                return log_error_errno(r, "Failed to watch job %s: %m", *path);
                }

        return 0;
}

const struct action_metadata action_table[_ACTION_MAX] = {
        [ACTION_HALT]                   = { SPECIAL_HALT_TARGET,                   "halt",                   "replace-irreversibly" },
        [ACTION_POWEROFF]               = { SPECIAL_POWEROFF_TARGET,               "poweroff",               "replace-irreversibly" },
        [ACTION_REBOOT]                 = { SPECIAL_REBOOT_TARGET,                 "reboot",                 "replace-irreversibly" },
        [ACTION_KEXEC]                  = { SPECIAL_KEXEC_TARGET,                  "kexec",                  "replace-irreversibly" },
        [ACTION_RUNLEVEL2]              = { SPECIAL_MULTI_USER_TARGET,             NULL,                     "isolate"              },
        [ACTION_RUNLEVEL3]              = { SPECIAL_MULTI_USER_TARGET,             NULL,                     "isolate"              },
        [ACTION_RUNLEVEL4]              = { SPECIAL_MULTI_USER_TARGET,             NULL,                     "isolate"              },
        [ACTION_RUNLEVEL5]              = { SPECIAL_GRAPHICAL_TARGET,              NULL,                     "isolate"              },
        [ACTION_RESCUE]                 = { SPECIAL_RESCUE_TARGET,                 "rescue",                 "isolate"              },
        [ACTION_EMERGENCY]              = { SPECIAL_EMERGENCY_TARGET,              "emergency",              "isolate"              },
        [ACTION_DEFAULT]                = { SPECIAL_DEFAULT_TARGET,                "default",                "isolate"              },
        [ACTION_EXIT]                   = { SPECIAL_EXIT_TARGET,                   "exit",                   "replace-irreversibly" },
        [ACTION_SUSPEND]                = { SPECIAL_SUSPEND_TARGET,                "suspend",                "replace-irreversibly" },
        [ACTION_HIBERNATE]              = { SPECIAL_HIBERNATE_TARGET,              "hibernate",              "replace-irreversibly" },
        [ACTION_HYBRID_SLEEP]           = { SPECIAL_HYBRID_SLEEP_TARGET,           "hybrid-sleep",           "replace-irreversibly" },
        [ACTION_SUSPEND_THEN_HIBERNATE] = { SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET, "suspend-then-hibernate", "replace-irreversibly" },
};

enum action verb_to_action(const char *verb) {
        for (enum action i = 0; i < _ACTION_MAX; i++)
                if (streq_ptr(action_table[i].verb, verb))
                        return i;

        return _ACTION_INVALID;
}

static const char** make_extra_args(const char *extra_args[static 4]) {
        size_t n = 0;

        assert(extra_args);

        if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
                extra_args[n++] = "--user";

        if (arg_transport == BUS_TRANSPORT_REMOTE) {
                extra_args[n++] = "-H";
                extra_args[n++] = arg_host;
        } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
                extra_args[n++] = "-M";
                extra_args[n++] = arg_host;
        } else
                assert(arg_transport == BUS_TRANSPORT_LOCAL);

        extra_args[n] = NULL;
        return extra_args;
}

int verb_start(int argc, char *argv[], void *userdata) {
        _cleanup_(bus_wait_for_units_freep) BusWaitForUnits *wu = NULL;
        _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
        const char *method, *job_type, *mode, *one_name, *suffix = NULL;
        _cleanup_free_ char **stopped_units = NULL; /* Do not use _cleanup_strv_free_ */
        _cleanup_strv_free_ char **names = NULL;
        int r, ret = EXIT_SUCCESS;
        sd_bus *bus;

        if (arg_wait && !STR_IN_SET(argv[0], "start", "restart"))
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "--wait may only be used with the 'start' or 'restart' commands.");

        /* We cannot do sender tracking on the private bus, so we need the full one for RefUnit to implement
         * --wait */
        r = acquire_bus(arg_wait ? BUS_FULL : BUS_MANAGER, &bus);
        if (r < 0)
                return r;

        ask_password_agent_open_maybe();
        polkit_agent_open_maybe();

        if (arg_action == ACTION_SYSTEMCTL) {
                enum action action;

                action = verb_to_action(argv[0]);

                if (action != _ACTION_INVALID) {
                        /* A command in style "systemctl reboot", "systemctl poweroff", … */
                        method = "StartUnit";
                        job_type = "start";
                        mode = action_table[action].mode;
                        one_name = action_table[action].target;
                } else {
                        if (streq(argv[0], "isolate")) {
                                /* A "systemctl isolate <unit1> <unit2> …" command */
                                method = "StartUnit";
                                job_type = "start";
                                mode = "isolate";
                                suffix = ".target";
                        } else if (!arg_marked) {
                                /* A command in style of "systemctl start <unit1> <unit2> …", "systemctl stop <unit1> <unit2> …" and so on */
                                method = verb_to_method(argv[0]);
                                job_type = verb_to_job_type(argv[0]);
                                mode = arg_job_mode();
                        } else
                                method = job_type = mode = NULL;

                        one_name = NULL;
                }
        } else {
                /* A SysV legacy command such as "halt", "reboot", "poweroff", … */
                assert(arg_action >= 0 && arg_action < _ACTION_MAX);
                assert(action_table[arg_action].target);
                assert(action_table[arg_action].mode);

                method = "StartUnit";
                job_type = "start";
                mode = action_table[arg_action].mode;
                one_name = action_table[arg_action].target;
        }

        if (one_name) {
                names = strv_new(one_name);
                if (!names)
                        return log_oom();
        } else if (!arg_marked) {
                bool expanded;

                r = expand_unit_names(bus, strv_skip(argv, 1), suffix, &names, &expanded);
                if (r < 0)
                        return log_error_errno(r, "Failed to expand names: %m");

                if (!arg_all && expanded && streq(job_type, "start") && !arg_quiet) {
                        log_warning("Warning: %ssystemctl start called with a glob pattern.%s",
                                    ansi_highlight_red(),
                                    ansi_normal());
                        log_notice("Hint: unit globs expand to loaded units, so start will usually have no effect.\n"
                                   "      Passing --all will also load units which are pulled in by other units.\n"
                                   "      See systemctl(1) for more details.");
                }
        }

        if (!arg_no_block) {
                r = bus_wait_for_jobs_new(bus, &w);
                if (r < 0)
                        return log_error_errno(r, "Could not watch jobs: %m");
        }

        if (arg_wait) {
                r = bus_call_method_async(bus, NULL, bus_systemd_mgr, "Subscribe", NULL, NULL, NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to enable subscription: %m");

                r = bus_wait_for_units_new(bus, &wu);
                if (r < 0)
                        return log_error_errno(r, "Failed to allocate unit watch context: %m");
        }

        if (arg_marked)
                ret = enqueue_marked_jobs(bus, w);
        else
                STRV_FOREACH(name, names) {
                        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;

                        r = start_unit_one(bus, method, job_type, *name, mode, &error, w, wu);
                        if (ret == EXIT_SUCCESS && r < 0)
                                ret = translate_bus_error_to_exit_status(r, &error);

                        if (r >= 0 && streq(method, "StopUnit")) {
                                r = strv_push(&stopped_units, *name);
                                if (r < 0)
                                        return log_oom();
                        }
                }

        if (!arg_no_block) {
                const char* extra_args[4];

                r = bus_wait_for_jobs(w, arg_quiet, make_extra_args(extra_args));
                if (r < 0)
                        return r;

                /* When stopping units, warn if they can still be triggered by
                 * another active unit (socket, path, timer) */
                if (!arg_quiet)
                        STRV_FOREACH(name, stopped_units)
                                (void) check_triggering_units(bus, *name);
        }

        if (arg_wait) {
                r = bus_wait_for_units_run(wu);
                if (r < 0)
                        return log_error_errno(r, "Failed to wait for units: %m");
                if (r == BUS_WAIT_FAILURE && ret == EXIT_SUCCESS)
                        ret = EXIT_FAILURE;
        }

        return ret;
}