]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/job.c
Merge pull request #19403 from nmeyerhans/dmi-entries
[thirdparty/systemd.git] / src / core / job.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
1ffba6fe 3#include <errno.h>
60918275 4
718db961
LP
5#include "sd-id128.h"
6#include "sd-messages.h"
4f5dd394 7
b5efdb8a 8#include "alloc-util.h"
f485606b 9#include "async.h"
da8e1782 10#include "cgroup.h"
4f5dd394 11#include "dbus-job.h"
8f8f05a9 12#include "dbus.h"
4f5dd394 13#include "escape.h"
8948b341 14#include "fileio.h"
6bedfcbb 15#include "job.h"
4f5dd394
LP
16#include "log.h"
17#include "macro.h"
6bedfcbb 18#include "parse-util.h"
d68c645b 19#include "serialize.h"
4f5dd394 20#include "set.h"
760877e9 21#include "sort-util.h"
4f5dd394 22#include "special.h"
d054f0a4 23#include "stdio-util.h"
8b43440b 24#include "string-table.h"
07630cea 25#include "string-util.h"
4f5dd394 26#include "strv.h"
288a74cc 27#include "terminal-util.h"
4f5dd394
LP
28#include "unit.h"
29#include "virt.h"
97e6a119 30
39a18c60 31Job* job_new_raw(Unit *unit) {
60918275
LP
32 Job *j;
33
39a18c60
MS
34 /* used for deserialization */
35
87f0e418 36 assert(unit);
60918275 37
08ac00f2 38 j = new(Job, 1);
39a18c60 39 if (!j)
60918275
LP
40 return NULL;
41
08ac00f2
LP
42 *j = (Job) {
43 .manager = unit->manager,
44 .unit = unit,
45 .type = _JOB_TYPE_INVALID,
46 };
faf919f1 47
39a18c60
MS
48 return j;
49}
50
51Job* job_new(Unit *unit, JobType type) {
52 Job *j;
53
54 assert(type < _JOB_TYPE_MAX);
55
56 j = job_new_raw(unit);
57 if (!j)
58 return NULL;
59
60 j->id = j->manager->current_job_id++;
61 j->type = type;
62
e5b5ae50 63 /* We don't link it here, that's what job_dependency() is for */
60918275
LP
64
65 return j;
66}
67
a7a7163d 68void job_unlink(Job *j) {
97e7d748
MS
69 assert(j);
70 assert(!j->installed);
02a3bcc6
MS
71 assert(!j->transaction_prev);
72 assert(!j->transaction_next);
73 assert(!j->subject_list);
74 assert(!j->object_list);
60918275 75
a7a7163d 76 if (j->in_run_queue) {
da8e1782 77 prioq_remove(j->manager->run_queue, j, &j->run_queue_idx);
a7a7163d
DT
78 j->in_run_queue = false;
79 }
c1e1601e 80
a7a7163d 81 if (j->in_dbus_queue) {
71fda00f 82 LIST_REMOVE(dbus_queue, j->manager->dbus_job_queue, j);
a7a7163d
DT
83 j->in_dbus_queue = false;
84 }
c1e1601e 85
a7a7163d 86 if (j->in_gc_queue) {
c5a97ed1 87 LIST_REMOVE(gc_queue, j->manager->gc_job_queue, j);
a7a7163d
DT
88 j->in_gc_queue = false;
89 }
c5a97ed1 90
a7a7163d
DT
91 j->timer_event_source = sd_event_source_unref(j->timer_event_source);
92}
93
728ba51e 94Job* job_free(Job *j) {
a7a7163d
DT
95 assert(j);
96 assert(!j->installed);
97 assert(!j->transaction_prev);
98 assert(!j->transaction_next);
99 assert(!j->subject_list);
100 assert(!j->object_list);
101
102 job_unlink(j);
faf919f1 103
1a465207 104 sd_bus_track_unref(j->bus_track);
b39a2770 105 strv_free(j->deserialized_clients);
faf919f1 106
728ba51e 107 return mfree(j);
60918275 108}
a66d02c3 109
9c3349e2
LP
110static void job_set_state(Job *j, JobState state) {
111 assert(j);
112 assert(state >= 0);
113 assert(state < _JOB_STATE_MAX);
114
115 if (j->state == state)
116 return;
117
118 j->state = state;
119
120 if (!j->installed)
121 return;
122
123 if (j->state == JOB_RUNNING)
124 j->unit->manager->n_running_jobs++;
125 else {
126 assert(j->state == JOB_WAITING);
127 assert(j->unit->manager->n_running_jobs > 0);
128
129 j->unit->manager->n_running_jobs--;
130
131 if (j->unit->manager->n_running_jobs <= 0)
132 j->unit->manager->jobs_in_progress_event_source = sd_event_source_unref(j->unit->manager->jobs_in_progress_event_source);
133 }
134}
135
05d576f1 136void job_uninstall(Job *j) {
e0209d83
MS
137 Job **pj;
138
05d576f1 139 assert(j->installed);
e0209d83 140
9c3349e2
LP
141 job_set_state(j, JOB_WAITING);
142
e0209d83
MS
143 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
144 assert(*pj == j);
145
05d576f1
MS
146 /* Detach from next 'bigger' objects */
147
39a18c60 148 /* daemon-reload should be transparent to job observers */
2c289ea8 149 if (!MANAGER_IS_RELOADING(j->manager))
39a18c60 150 bus_job_send_removed_signal(j);
05d576f1 151
e0209d83
MS
152 *pj = NULL;
153
d6a093d0 154 unit_add_to_gc_queue(j->unit);
05d576f1 155
52c6c9ea
AM
156 unit_add_to_dbus_queue(j->unit); /* The Job property of the unit has changed now */
157
48235ad6 158 hashmap_remove_value(j->manager->jobs, UINT32_TO_PTR(j->id), j);
05d576f1
MS
159 j->installed = false;
160}
161
656bbffc
MS
162static bool job_type_allows_late_merge(JobType t) {
163 /* Tells whether it is OK to merge a job of type 't' with an already
164 * running job.
165 * Reloads cannot be merged this way. Think of the sequence:
166 * 1. Reload of a daemon is in progress; the daemon has already loaded
167 * its config file, but hasn't completed the reload operation yet.
168 * 2. Edit foo's config file.
169 * 3. Trigger another reload to have the daemon use the new config.
170 * Should the second reload job be merged into the first one, the daemon
171 * would not know about the new config.
172 * JOB_RESTART jobs on the other hand can be merged, because they get
173 * patched into JOB_START after stopping the unit. So if we see a
174 * JOB_RESTART running, it means the unit hasn't stopped yet and at
175 * this time the merge is still allowed. */
e0209d83 176 return t != JOB_RELOAD;
656bbffc
MS
177}
178
179static void job_merge_into_installed(Job *j, Job *other) {
180 assert(j->installed);
181 assert(j->unit == other->unit);
182
e0209d83 183 if (j->type != JOB_NOP)
53a2383b 184 assert_se(job_type_merge_and_collapse(&j->type, other->type, j->unit) == 0);
e0209d83
MS
185 else
186 assert(other->type == JOB_NOP);
656bbffc 187
23ade460 188 j->irreversible = j->irreversible || other->irreversible;
e45460d6 189 j->ignore_order = j->ignore_order || other->ignore_order;
656bbffc
MS
190}
191
192Job* job_install(Job *j) {
e0209d83
MS
193 Job **pj;
194 Job *uj;
05d576f1 195
656bbffc 196 assert(!j->installed);
e0209d83 197 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
9c3349e2 198 assert(j->state == JOB_WAITING);
e0209d83
MS
199
200 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
201 uj = *pj;
656bbffc 202
05d576f1 203 if (uj) {
61da906a 204 if (job_type_is_conflicting(uj->type, j->type))
833f92ad 205 job_finish_and_invalidate(uj, JOB_CANCELED, false, false);
656bbffc
MS
206 else {
207 /* not conflicting, i.e. mergeable */
208
61da906a 209 if (uj->state == JOB_WAITING ||
656bbffc
MS
210 (job_type_allows_late_merge(j->type) && job_type_is_superset(uj->type, j->type))) {
211 job_merge_into_installed(uj, j);
f2341e0a 212 log_unit_debug(uj->unit,
28d78d07 213 "Merged %s/%s into installed job %s/%s as %"PRIu32,
92e29d82 214 j->unit->id, job_type_to_string(j->type), uj->unit->id,
28d78d07 215 job_type_to_string(uj->type), uj->id);
656bbffc
MS
216 return uj;
217 } else {
218 /* already running and not safe to merge into */
219 /* Patch uj to become a merged job and re-run it. */
220 /* XXX It should be safer to queue j to run after uj finishes, but it is
221 * not currently possible to have more than one installed job per unit. */
222 job_merge_into_installed(uj, j);
f2341e0a 223 log_unit_debug(uj->unit,
28d78d07
JK
224 "Merged into running job, re-running: %s/%s as %"PRIu32,
225 uj->unit->id, job_type_to_string(uj->type), uj->id);
9c3349e2
LP
226
227 job_set_state(uj, JOB_WAITING);
656bbffc
MS
228 return uj;
229 }
230 }
05d576f1
MS
231 }
232
656bbffc 233 /* Install the job */
e0209d83 234 *pj = j;
05d576f1 235 j->installed = true;
9c3349e2 236
313cefa1 237 j->manager->n_installed_jobs++;
f2341e0a 238 log_unit_debug(j->unit,
66870f90
ZJS
239 "Installed new job %s/%s as %u",
240 j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
c5a97ed1
LP
241
242 job_add_to_gc_queue(j);
243
e6d05912
LP
244 job_add_to_dbus_queue(j); /* announce this job to clients */
245 unit_add_to_dbus_queue(j->unit); /* The Job property of the unit has changed now */
246
656bbffc 247 return j;
05d576f1
MS
248}
249
e0209d83
MS
250int job_install_deserialized(Job *j) {
251 Job **pj;
b17c9620 252 int r;
e0209d83 253
39a18c60
MS
254 assert(!j->installed);
255
baaa35ad 256 if (j->type < 0 || j->type >= _JOB_TYPE_MAX_IN_TRANSACTION)
b17c9620 257 return log_unit_debug_errno(j->unit, SYNTHETIC_ERRNO(EINVAL),
baaa35ad
ZJS
258 "Invalid job type %s in deserialization.",
259 strna(job_type_to_string(j->type)));
e0209d83
MS
260
261 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
b17c9620
LP
262 if (*pj)
263 return log_unit_debug_errno(j->unit, SYNTHETIC_ERRNO(EEXIST),
264 "Unit already has a job installed. Not installing deserialized job.");
265
53dba3ef 266 r = hashmap_ensure_put(&j->manager->jobs, NULL, UINT32_TO_PTR(j->id), j);
b17c9620
LP
267 if (r == -EEXIST)
268 return log_unit_debug_errno(j->unit, r, "Job ID %" PRIu32 " already used, cannot deserialize job.", j->id);
269 if (r < 0)
270 return log_unit_debug_errno(j->unit, r, "Failed to insert job into jobs hash table: %m");
9c3349e2 271
e0209d83 272 *pj = j;
39a18c60 273 j->installed = true;
9c3349e2
LP
274
275 if (j->state == JOB_RUNNING)
276 j->unit->manager->n_running_jobs++;
277
f2341e0a 278 log_unit_debug(j->unit,
66870f90
ZJS
279 "Reinstalled deserialized job %s/%s as %u",
280 j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
e0209d83 281 return 0;
39a18c60
MS
282}
283
1da4264f 284JobDependency* job_dependency_new(Job *subject, Job *object, bool matters, bool conflicts) {
e5b5ae50
LP
285 JobDependency *l;
286
287 assert(object);
288
289 /* Adds a new job link, which encodes that the 'subject' job
290 * needs the 'object' job in some way. If 'subject' is NULL
291 * this means the 'anchor' job (i.e. the one the user
35b8ca3a 292 * explicitly asked for) is the requester. */
e5b5ae50 293
0a23a627
LP
294 l = new0(JobDependency, 1);
295 if (!l)
e5b5ae50
LP
296 return NULL;
297
298 l->subject = subject;
299 l->object = object;
300 l->matters = matters;
69dd2852 301 l->conflicts = conflicts;
e5b5ae50 302
44d8db9e 303 if (subject)
71fda00f 304 LIST_PREPEND(subject, subject->subject_list, l);
e5b5ae50 305
71fda00f 306 LIST_PREPEND(object, object->object_list, l);
e5b5ae50
LP
307
308 return l;
309}
310
1da4264f 311void job_dependency_free(JobDependency *l) {
e5b5ae50
LP
312 assert(l);
313
44d8db9e 314 if (l->subject)
71fda00f 315 LIST_REMOVE(subject, l->subject->subject_list, l);
e5b5ae50 316
71fda00f 317 LIST_REMOVE(object, l->object->object_list, l);
e5b5ae50
LP
318
319 free(l);
320}
321
f2a3de01 322void job_dump(Job *j, FILE *f, const char *prefix) {
a66d02c3
LP
323 assert(j);
324 assert(f);
325
ad5d4b17 326 prefix = strempty(prefix);
9eb63b3c 327
ceed3570 328 fprintf(f,
40d50879
LP
329 "%s-> Job %u:\n"
330 "%s\tAction: %s -> %s\n"
5cb5a6ff 331 "%s\tState: %s\n"
f698d99c
ZJS
332 "%s\tIrreversible: %s\n"
333 "%s\tMay GC: %s\n",
ceed3570 334 prefix, j->id,
ac155bb8 335 prefix, j->unit->id, job_type_to_string(j->type),
94f04347 336 prefix, job_state_to_string(j->state),
f698d99c
ZJS
337 prefix, yes_no(j->irreversible),
338 prefix, yes_no(job_may_gc(j)));
a66d02c3 339}
e5b5ae50 340
348e27fe
MS
341/*
342 * Merging is commutative, so imagine the matrix as symmetric. We store only
343 * its lower triangle to avoid duplication. We don't store the main diagonal,
344 * because A merged with A is simply A.
345 *
e0209d83
MS
346 * If the resulting type is collapsed immediately afterwards (to get rid of
347 * the JOB_RELOAD_OR_START, which lies outside the lookup function's domain),
348 * the following properties hold:
349 *
48b4eab4 350 * Merging is associative! A merged with B, and then merged with C is the same
103635db 351 * as A merged with the result of B merged with C.
348e27fe
MS
352 *
353 * Mergeability is transitive! If A can be merged with B and B with C then
354 * A also with C.
355 *
356 * Also, if A merged with B cannot be merged with C, then either A or B cannot
357 * be merged with C either.
358 */
359static const JobType job_merging_table[] = {
e0209d83
MS
360/* What \ With * JOB_START JOB_VERIFY_ACTIVE JOB_STOP JOB_RELOAD */
361/*********************************************************************************/
348e27fe
MS
362/*JOB_START */
363/*JOB_VERIFY_ACTIVE */ JOB_START,
364/*JOB_STOP */ -1, -1,
365/*JOB_RELOAD */ JOB_RELOAD_OR_START, JOB_RELOAD, -1,
e0209d83 366/*JOB_RESTART */ JOB_RESTART, JOB_RESTART, -1, JOB_RESTART,
348e27fe
MS
367};
368
369JobType job_type_lookup_merge(JobType a, JobType b) {
e0209d83
MS
370 assert_cc(ELEMENTSOF(job_merging_table) == _JOB_TYPE_MAX_MERGING * (_JOB_TYPE_MAX_MERGING - 1) / 2);
371 assert(a >= 0 && a < _JOB_TYPE_MAX_MERGING);
372 assert(b >= 0 && b < _JOB_TYPE_MAX_MERGING);
1ffba6fe
LP
373
374 if (a == b)
348e27fe 375 return a;
1ffba6fe 376
348e27fe
MS
377 if (a < b) {
378 JobType tmp = a;
379 a = b;
380 b = tmp;
1ffba6fe 381 }
e094e853 382
348e27fe 383 return job_merging_table[(a - 1) * a / 2 + b];
e094e853 384}
cd2dbd7d 385
cc479760
DR
386bool job_type_is_redundant(JobType a, UnitActiveState b) {
387 switch (a) {
593fbdd2
LP
388
389 case JOB_START:
cc479760 390 return IN_SET(b, UNIT_ACTIVE, UNIT_RELOADING);
593fbdd2
LP
391
392 case JOB_STOP:
cc479760 393 return IN_SET(b, UNIT_INACTIVE, UNIT_FAILED);
593fbdd2
LP
394
395 case JOB_VERIFY_ACTIVE:
cc479760 396 return IN_SET(b, UNIT_ACTIVE, UNIT_RELOADING);
593fbdd2
LP
397
398 case JOB_RELOAD:
399 return
cc479760 400 b == UNIT_RELOADING;
593fbdd2 401
593fbdd2
LP
402 case JOB_RESTART:
403 return
cc479760 404 b == UNIT_ACTIVATING;
593fbdd2 405
7e803f5e
MS
406 case JOB_NOP:
407 return true;
408
e0209d83
MS
409 default:
410 assert_not_reached("Invalid job type");
411 }
412}
413
c6497ccb 414JobType job_type_collapse(JobType t, Unit *u) {
e0209d83
MS
415 UnitActiveState s;
416
c6497ccb 417 switch (t) {
e0209d83 418
593fbdd2 419 case JOB_TRY_RESTART:
e0209d83 420 s = unit_active_state(u);
d1559793 421 if (!UNIT_IS_ACTIVE_OR_RELOADING(s))
c6497ccb
LP
422 return JOB_NOP;
423
424 return JOB_RESTART;
e0209d83 425
3282591d
LP
426 case JOB_TRY_RELOAD:
427 s = unit_active_state(u);
d1559793 428 if (!UNIT_IS_ACTIVE_OR_RELOADING(s))
3282591d
LP
429 return JOB_NOP;
430
431 return JOB_RELOAD;
432
e0209d83
MS
433 case JOB_RELOAD_OR_START:
434 s = unit_active_state(u);
d1559793 435 if (!UNIT_IS_ACTIVE_OR_RELOADING(s))
c6497ccb
LP
436 return JOB_START;
437
438 return JOB_RELOAD;
593fbdd2
LP
439
440 default:
c6497ccb 441 return t;
593fbdd2
LP
442 }
443}
444
e0209d83 445int job_type_merge_and_collapse(JobType *a, JobType b, Unit *u) {
c6497ccb
LP
446 JobType t;
447
448 t = job_type_lookup_merge(*a, b);
e0209d83
MS
449 if (t < 0)
450 return -EEXIST;
c6497ccb
LP
451
452 *a = job_type_collapse(t, u);
e0209d83
MS
453 return 0;
454}
455
9588bc32 456static bool job_is_runnable(Job *j) {
87f0e418 457 Unit *other;
eef85c4a 458 void *v;
5cb5a6ff
LP
459
460 assert(j);
ac1135be 461 assert(j->installed);
5cb5a6ff 462
87f0e418 463 /* Checks whether there is any job running for the units this
5cb5a6ff 464 * job needs to be running after (in the case of a 'positive'
e67c3609
LP
465 * job type) or before (in the case of a 'negative' job
466 * type. */
467
66ca4ec4
LP
468 /* Note that unit types have a say in what is runnable,
469 * too. For example, if they return -EAGAIN from
470 * unit_start() they can indicate they are not
471 * runnable yet. */
472
e67c3609 473 /* First check if there is an override */
cebe0d41 474 if (j->ignore_order)
e67c3609 475 return true;
5cb5a6ff 476
e0209d83
MS
477 if (j->type == JOB_NOP)
478 return true;
479
90e74a66 480 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER])
c03fbd37
LB
481 if (other->job && job_compare(j, other->job, UNIT_AFTER) > 0) {
482 log_unit_debug(j->unit,
483 "starting held back, waiting for: %s",
484 other->id);
e602f152 485 return false;
c03fbd37 486 }
5cb5a6ff 487
90e74a66 488 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE])
c03fbd37
LB
489 if (other->job && job_compare(j, other->job, UNIT_BEFORE) > 0) {
490 log_unit_debug(j->unit,
491 "stopping held back, waiting for: %s",
492 other->id);
5cb5a6ff 493 return false;
c03fbd37 494 }
5cb5a6ff 495
5cb5a6ff
LP
496 return true;
497}
498
bbd1a837 499static void job_change_type(Job *j, JobType newtype) {
f2341e0a
LP
500 assert(j);
501
502 log_unit_debug(j->unit,
66870f90
ZJS
503 "Converting job %s/%s -> %s/%s",
504 j->unit->id, job_type_to_string(j->type),
505 j->unit->id, job_type_to_string(newtype));
bbd1a837
MS
506
507 j->type = newtype;
508}
509
33a3fdd9 510_pure_ static const char* job_get_begin_status_message_format(Unit *u, JobType t) {
a69b3872 511 const char *format;
33a3fdd9
LP
512
513 assert(u);
a69b3872
LP
514
515 if (t == JOB_RELOAD)
516 return "Reloading %s.";
517
518 assert(IN_SET(t, JOB_START, JOB_STOP));
519
ff30a86b
LP
520 format = UNIT_VTABLE(u)->status_message_formats.starting_stopping[t == JOB_STOP];
521 if (format)
522 return format;
33a3fdd9
LP
523
524 /* Return generic strings */
525 if (t == JOB_START)
526 return "Starting %s.";
a69b3872
LP
527 else {
528 assert(t == JOB_STOP);
33a3fdd9 529 return "Stopping %s.";
a69b3872 530 }
33a3fdd9
LP
531}
532
533static void job_print_begin_status_message(Unit *u, JobType t) {
534 const char *format;
535
536 assert(u);
537
538 /* Reload status messages have traditionally not been printed to console. */
539 if (!IN_SET(t, JOB_START, JOB_STOP))
540 return;
541
542 format = job_get_begin_status_message_format(u, t);
543
544 DISABLE_WARNING_FORMAT_NONLITERAL;
5bcf34eb 545 unit_status_printf(u, STATUS_TYPE_NORMAL, "", format);
33a3fdd9
LP
546 REENABLE_WARNING;
547}
548
b344b363 549static void job_log_begin_status_message(Unit *u, uint32_t job_id, JobType t) {
33a3fdd9
LP
550 const char *format, *mid;
551 char buf[LINE_MAX];
552
553 assert(u);
b344b363
LP
554 assert(t >= 0);
555 assert(t < _JOB_TYPE_MAX);
33a3fdd9
LP
556
557 if (!IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD))
558 return;
559
0e2b4a82 560 if (log_on_console()) /* Skip this if it would only go on the console anyway */
33a3fdd9
LP
561 return;
562
563 /* We log status messages for all units and all operations. */
564
565 format = job_get_begin_status_message_format(u, t);
566
567 DISABLE_WARNING_FORMAT_NONLITERAL;
2a8f53c6 568 (void) snprintf(buf, sizeof buf, format, unit_status_string(u));
33a3fdd9
LP
569 REENABLE_WARNING;
570
571 mid = t == JOB_START ? "MESSAGE_ID=" SD_MESSAGE_UNIT_STARTING_STR :
572 t == JOB_STOP ? "MESSAGE_ID=" SD_MESSAGE_UNIT_STOPPING_STR :
573 "MESSAGE_ID=" SD_MESSAGE_UNIT_RELOADING_STR;
574
575 /* Note that we deliberately use LOG_MESSAGE() instead of
576 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
577 * closely what is written to screen using the status output,
578 * which is supposed the highest level, friendliest output
579 * possible, which means we should avoid the low-level unit
580 * name. */
581 log_struct(LOG_INFO,
582 LOG_MESSAGE("%s", buf),
b344b363
LP
583 "JOB_ID=%" PRIu32, job_id,
584 "JOB_TYPE=%s", job_type_to_string(t),
33a3fdd9
LP
585 LOG_UNIT_ID(u),
586 LOG_UNIT_INVOCATION_ID(u),
587 mid);
588}
589
b344b363 590static void job_emit_begin_status_message(Unit *u, uint32_t job_id, JobType t) {
33a3fdd9
LP
591 assert(u);
592 assert(t >= 0);
593 assert(t < _JOB_TYPE_MAX);
594
b344b363 595 job_log_begin_status_message(u, job_id, t);
33a3fdd9
LP
596 job_print_begin_status_message(u, t);
597}
598
d1a34ae9 599static int job_perform_on_unit(Job **j) {
df446f96
LP
600 uint32_t id;
601 Manager *m;
602 JobType t;
603 Unit *u;
d1a34ae9
MS
604 int r;
605
df446f96
LP
606 /* While we execute this operation the job might go away (for
607 * example: because it finishes immediately or is replaced by
608 * a new, conflicting job.) To make sure we don't access a
609 * freed job later on we store the id here, so that we can
610 * verify the job is still valid. */
611
612 assert(j);
613 assert(*j);
614
615 m = (*j)->manager;
616 u = (*j)->unit;
617 t = (*j)->type;
618 id = (*j)->id;
619
d1a34ae9
MS
620 switch (t) {
621 case JOB_START:
622 r = unit_start(u);
623 break;
624
625 case JOB_RESTART:
626 t = JOB_STOP;
4831981d 627 _fallthrough_;
d1a34ae9
MS
628 case JOB_STOP:
629 r = unit_stop(u);
630 break;
631
632 case JOB_RELOAD:
633 r = unit_reload(u);
634 break;
635
636 default:
637 assert_not_reached("Invalid job type");
638 }
639
0e2b4a82
LP
640 /* Log if the job still exists and the start/stop/reload function actually did something. Note that this means
641 * for units for which there's no 'activating' phase (i.e. because we transition directly from 'inactive' to
642 * 'active') we'll possibly skip the "Starting..." message. */
d1a34ae9
MS
643 *j = manager_get_job(m, id);
644 if (*j && r > 0)
b344b363 645 job_emit_begin_status_message(u, id, t);
d1a34ae9
MS
646
647 return r;
648}
649
5cb5a6ff
LP
650int job_run_and_invalidate(Job *j) {
651 int r;
ac1135be 652
5cb5a6ff 653 assert(j);
ac1135be 654 assert(j->installed);
e0209d83 655 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
66aa6f7f 656 assert(j->in_run_queue);
5cb5a6ff 657
da8e1782 658 prioq_remove(j->manager->run_queue, j, &j->run_queue_idx);
66aa6f7f 659 j->in_run_queue = false;
5cb5a6ff
LP
660
661 if (j->state != JOB_WAITING)
662 return 0;
663
034c6ed7
LP
664 if (!job_is_runnable(j))
665 return -EAGAIN;
666
a2df3ea4 667 job_start_timer(j, true);
9c3349e2 668 job_set_state(j, JOB_RUNNING);
c1e1601e 669 job_add_to_dbus_queue(j);
83c60c9f 670
5cb5a6ff
LP
671 switch (j->type) {
672
5cb5a6ff 673 case JOB_VERIFY_ACTIVE: {
ea2c0e45
LP
674 UnitActiveState t;
675
676 t = unit_active_state(j->unit);
87f0e418 677 if (UNIT_IS_ACTIVE_OR_RELOADING(t))
5cb5a6ff 678 r = -EALREADY;
87f0e418 679 else if (t == UNIT_ACTIVATING)
5cb5a6ff
LP
680 r = -EAGAIN;
681 else
6a371e23 682 r = -EBADR;
5cb5a6ff
LP
683 break;
684 }
685
d1a34ae9 686 case JOB_START:
5cb5a6ff 687 case JOB_STOP:
dd17d388 688 case JOB_RESTART:
d1a34ae9 689 r = job_perform_on_unit(&j);
57339f47 690
ea2c0e45 691 /* If the unit type does not support starting/stopping, then simply wait. */
57339f47
LP
692 if (r == -EBADR)
693 r = 0;
5cb5a6ff
LP
694 break;
695
696 case JOB_RELOAD:
d1a34ae9 697 r = job_perform_on_unit(&j);
5cb5a6ff
LP
698 break;
699
e0209d83
MS
700 case JOB_NOP:
701 r = -EALREADY;
702 break;
703
5cb5a6ff 704 default:
44d8db9e 705 assert_not_reached("Unknown job type");
5cb5a6ff
LP
706 }
707
e0209d83 708 if (j) {
8ebd9175
LP
709 if (r == -EAGAIN)
710 job_set_state(j, JOB_WAITING); /* Hmm, not ready after all, let's return to JOB_WAITING state */
6e64994d 711 else if (r == -EALREADY) /* already being executed */
833f92ad 712 r = job_finish_and_invalidate(j, JOB_DONE, true, true);
6e64994d
LP
713 else if (r == -ECOMM) /* condition failed, but all is good */
714 r = job_finish_and_invalidate(j, JOB_DONE, true, false);
6a371e23 715 else if (r == -EBADR)
833f92ad 716 r = job_finish_and_invalidate(j, JOB_SKIPPED, true, false);
6a371e23 717 else if (r == -ENOEXEC)
833f92ad 718 r = job_finish_and_invalidate(j, JOB_INVALID, true, false);
59fccdc5 719 else if (r == -EPROTO)
833f92ad 720 r = job_finish_and_invalidate(j, JOB_ASSERT, true, false);
15411c0c 721 else if (r == -EOPNOTSUPP)
833f92ad 722 r = job_finish_and_invalidate(j, JOB_UNSUPPORTED, true, false);
631b676b
LP
723 else if (r == -ENOLINK)
724 r = job_finish_and_invalidate(j, JOB_DEPENDENCY, true, false);
d4fd1cf2
LP
725 else if (r == -ESTALE)
726 r = job_finish_and_invalidate(j, JOB_ONCE, true, false);
9c3349e2 727 else if (r < 0)
833f92ad 728 r = job_finish_and_invalidate(j, JOB_FAILED, true, false);
2cf19a7a 729 }
5cb5a6ff
LP
730
731 return r;
732}
733
33a3fdd9 734_pure_ static const char *job_get_done_status_message_format(Unit *u, JobType t, JobResult result) {
df446f96 735
aa49ab5f
MS
736 static const char *const generic_finished_start_job[_JOB_RESULT_MAX] = {
737 [JOB_DONE] = "Started %s.",
738 [JOB_TIMEOUT] = "Timed out starting %s.",
739 [JOB_FAILED] = "Failed to start %s.",
740 [JOB_DEPENDENCY] = "Dependency failed for %s.",
741 [JOB_ASSERT] = "Assertion failed for %s.",
742 [JOB_UNSUPPORTED] = "Starting of %s not supported.",
4332edf6 743 [JOB_COLLECTED] = "Unnecessary job for %s was removed.",
d4fd1cf2 744 [JOB_ONCE] = "Unit %s has been started before and cannot be started again."
aa49ab5f
MS
745 };
746 static const char *const generic_finished_stop_job[_JOB_RESULT_MAX] = {
747 [JOB_DONE] = "Stopped %s.",
748 [JOB_FAILED] = "Stopped (with error) %s.",
b59f0ecd 749 [JOB_TIMEOUT] = "Timed out stopping %s.",
aa49ab5f
MS
750 };
751 static const char *const generic_finished_reload_job[_JOB_RESULT_MAX] = {
752 [JOB_DONE] = "Reloaded %s.",
753 [JOB_FAILED] = "Reload failed for %s.",
754 [JOB_TIMEOUT] = "Timed out reloading %s.",
755 };
756 /* When verify-active detects the unit is inactive, report it.
757 * Most likely a DEPEND warning from a requisiting unit will
758 * occur next and it's nice to see what was requisited. */
759 static const char *const generic_finished_verify_active_job[_JOB_RESULT_MAX] = {
760 [JOB_SKIPPED] = "%s is not active.",
761 };
877d54e9 762
df446f96
LP
763 const char *format;
764
877d54e9
LP
765 assert(u);
766 assert(t >= 0);
767 assert(t < _JOB_TYPE_MAX);
c6918296 768
df446f96 769 if (IN_SET(t, JOB_START, JOB_STOP, JOB_RESTART)) {
eda0cbf0
ZJS
770 const UnitStatusMessageFormats *formats = &UNIT_VTABLE(u)->status_message_formats;
771 if (formats->finished_job) {
772 format = formats->finished_job(u, t, result);
773 if (format)
774 return format;
775 }
ff30a86b 776 format = t == JOB_START ?
eda0cbf0
ZJS
777 formats->finished_start_job[result] :
778 formats->finished_stop_job[result];
ff30a86b
LP
779 if (format)
780 return format;
aa49ab5f 781 }
877d54e9 782
aa49ab5f 783 /* Return generic strings */
877d54e9 784 if (t == JOB_START)
aa49ab5f 785 return generic_finished_start_job[result];
4c701096 786 else if (IN_SET(t, JOB_STOP, JOB_RESTART))
aa49ab5f
MS
787 return generic_finished_stop_job[result];
788 else if (t == JOB_RELOAD)
789 return generic_finished_reload_job[result];
790 else if (t == JOB_VERIFY_ACTIVE)
791 return generic_finished_verify_active_job[result];
877d54e9
LP
792
793 return NULL;
794}
795
047d7219
ZJS
796static const struct {
797 const char *color, *word;
33a3fdd9 798} job_print_done_status_messages[_JOB_RESULT_MAX] = {
96164a39 799 [JOB_DONE] = { ANSI_OK_COLOR, " OK " },
047d7219
ZJS
800 [JOB_TIMEOUT] = { ANSI_HIGHLIGHT_RED, " TIME " },
801 [JOB_FAILED] = { ANSI_HIGHLIGHT_RED, "FAILED" },
802 [JOB_DEPENDENCY] = { ANSI_HIGHLIGHT_YELLOW, "DEPEND" },
803 [JOB_SKIPPED] = { ANSI_HIGHLIGHT, " INFO " },
804 [JOB_ASSERT] = { ANSI_HIGHLIGHT_YELLOW, "ASSERT" },
805 [JOB_UNSUPPORTED] = { ANSI_HIGHLIGHT_YELLOW, "UNSUPP" },
806 /* JOB_COLLECTED */
d4fd1cf2 807 [JOB_ONCE] = { ANSI_HIGHLIGHT_RED, " ONCE " },
047d7219 808};
e02cd6f7 809
33a3fdd9 810static void job_print_done_status_message(Unit *u, JobType t, JobResult result) {
df446f96 811 const char *format;
dc9b5816 812 const char *status;
df446f96 813
877d54e9
LP
814 assert(u);
815 assert(t >= 0);
816 assert(t < _JOB_TYPE_MAX);
817
df446f96
LP
818 /* Reload status messages have traditionally not been printed to console. */
819 if (t == JOB_RELOAD)
820 return;
821
9a80f2f4
LP
822 /* No message if the job did not actually do anything due to failed condition. */
823 if (t == JOB_START && result == JOB_DONE && !u->condition_result)
824 return;
825
33a3fdd9 826 if (!job_print_done_status_messages[result].word)
047d7219
ZJS
827 return;
828
33a3fdd9 829 format = job_get_done_status_message_format(u, t, result);
aa49ab5f
MS
830 if (!format)
831 return;
e02cd6f7 832
dc9b5816 833 if (log_get_show_color())
33a3fdd9
LP
834 status = strjoina(job_print_done_status_messages[result].color,
835 job_print_done_status_messages[result].word,
047d7219 836 ANSI_NORMAL);
dc9b5816 837 else
33a3fdd9 838 status = job_print_done_status_messages[result].word;
dc9b5816 839
aa49ab5f 840 DISABLE_WARNING_FORMAT_NONLITERAL;
5bcf34eb
ZJS
841 unit_status_printf(u,
842 result == JOB_DONE ? STATUS_TYPE_NORMAL : STATUS_TYPE_NOTICE,
843 status, format);
aa49ab5f 844 REENABLE_WARNING;
7cf82e0b 845
aa49ab5f 846 if (t == JOB_START && result == JOB_FAILED) {
c2b2df60 847 _cleanup_free_ char *quoted = NULL;
7cf82e0b 848
804ee07c 849 quoted = shell_maybe_quote(u->id, ESCAPE_BACKSLASH);
df446f96 850 manager_status_printf(u->manager, STATUS_TYPE_NORMAL, NULL, "See 'systemctl status %s' for details.", strna(quoted));
e02cd6f7
LP
851 }
852}
853
33a3fdd9 854static void job_log_done_status_message(Unit *u, uint32_t job_id, JobType t, JobResult result) {
2b044526 855 const char *format, *mid;
877d54e9 856 char buf[LINE_MAX];
64f575d2
MS
857 static const int job_result_log_level[_JOB_RESULT_MAX] = {
858 [JOB_DONE] = LOG_INFO,
859 [JOB_CANCELED] = LOG_INFO,
860 [JOB_TIMEOUT] = LOG_ERR,
861 [JOB_FAILED] = LOG_ERR,
862 [JOB_DEPENDENCY] = LOG_WARNING,
863 [JOB_SKIPPED] = LOG_NOTICE,
864 [JOB_INVALID] = LOG_INFO,
865 [JOB_ASSERT] = LOG_WARNING,
866 [JOB_UNSUPPORTED] = LOG_WARNING,
c5a97ed1 867 [JOB_COLLECTED] = LOG_INFO,
d4fd1cf2 868 [JOB_ONCE] = LOG_ERR,
64f575d2 869 };
877d54e9
LP
870
871 assert(u);
872 assert(t >= 0);
873 assert(t < _JOB_TYPE_MAX);
874
047d7219
ZJS
875 /* Skip printing if output goes to the console, and job_print_status_message()
876 will actually print something to the console. */
33a3fdd9 877 if (log_on_console() && job_print_done_status_messages[result].word)
81270860
LP
878 return;
879
9a80f2f4 880 /* Show condition check message if the job did not actually do anything due to failed condition. */
42e6f549 881 if (t == JOB_START && result == JOB_DONE && !u->condition_result) {
9a80f2f4 882 log_struct(LOG_INFO,
2a8f53c6 883 "MESSAGE=Condition check resulted in %s being skipped.", unit_status_string(u),
9a80f2f4
LP
884 "JOB_ID=%" PRIu32, job_id,
885 "JOB_TYPE=%s", job_type_to_string(t),
886 "JOB_RESULT=%s", job_result_to_string(result),
887 LOG_UNIT_ID(u),
888 LOG_UNIT_INVOCATION_ID(u),
889 "MESSAGE_ID=" SD_MESSAGE_UNIT_STARTED_STR);
890
891 return;
892 }
893
33a3fdd9 894 format = job_get_done_status_message_format(u, t, result);
877d54e9
LP
895 if (!format)
896 return;
897
574432f8
ILG
898 /* The description might be longer than the buffer, but that's OK,
899 * we'll just truncate it here. Note that we use snprintf() rather than
900 * xsprintf() on purpose here: we are fine with truncation and don't
901 * consider that an error. */
bcfce235 902 DISABLE_WARNING_FORMAT_NONLITERAL;
2a8f53c6 903 (void) snprintf(buf, sizeof(buf), format, unit_status_string(u));
bcfce235 904 REENABLE_WARNING;
877d54e9 905
df446f96
LP
906 switch (t) {
907
908 case JOB_START:
2b044526
ZJS
909 if (result == JOB_DONE)
910 mid = "MESSAGE_ID=" SD_MESSAGE_UNIT_STARTED_STR;
911 else
912 mid = "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILED_STR;
df446f96
LP
913 break;
914
915 case JOB_RELOAD:
2b044526 916 mid = "MESSAGE_ID=" SD_MESSAGE_UNIT_RELOADED_STR;
df446f96
LP
917 break;
918
919 case JOB_STOP:
920 case JOB_RESTART:
2b044526 921 mid = "MESSAGE_ID=" SD_MESSAGE_UNIT_STOPPED_STR;
df446f96
LP
922 break;
923
924 default:
64f575d2 925 log_struct(job_result_log_level[result],
4f29c6fe 926 LOG_MESSAGE("%s", buf),
1cd81629 927 "JOB_ID=%" PRIu32, job_id,
646cc98d
LP
928 "JOB_TYPE=%s", job_type_to_string(t),
929 "JOB_RESULT=%s", job_result_to_string(result),
ba360bb0 930 LOG_UNIT_ID(u),
a1230ff9 931 LOG_UNIT_INVOCATION_ID(u));
b81bbe53
MS
932 return;
933 }
934
64f575d2 935 log_struct(job_result_log_level[result],
b81bbe53 936 LOG_MESSAGE("%s", buf),
1cd81629 937 "JOB_ID=%" PRIu32, job_id,
646cc98d
LP
938 "JOB_TYPE=%s", job_type_to_string(t),
939 "JOB_RESULT=%s", job_result_to_string(result),
ba360bb0 940 LOG_UNIT_ID(u),
f1c50bec 941 LOG_UNIT_INVOCATION_ID(u),
a1230ff9 942 mid);
877d54e9 943}
877d54e9 944
33a3fdd9 945static void job_emit_done_status_message(Unit *u, uint32_t job_id, JobType t, JobResult result) {
646cc98d 946 assert(u);
30961fa3 947
33a3fdd9
LP
948 job_log_done_status_message(u, job_id, t, result);
949 job_print_done_status_message(u, t, result);
30961fa3
MS
950}
951
be7d9ff7
LP
952static void job_fail_dependencies(Unit *u, UnitDependency d) {
953 Unit *other;
eef85c4a 954 void *v;
be7d9ff7
LP
955
956 assert(u);
957
90e74a66 958 HASHMAP_FOREACH_KEY(v, other, u->dependencies[d]) {
be7d9ff7
LP
959 Job *j = other->job;
960
961 if (!j)
962 continue;
963 if (!IN_SET(j->type, JOB_START, JOB_VERIFY_ACTIVE))
964 continue;
965
833f92ad 966 job_finish_and_invalidate(j, JOB_DEPENDENCY, true, false);
be7d9ff7
LP
967 }
968}
969
833f92ad 970int job_finish_and_invalidate(Job *j, JobResult result, bool recursive, bool already) {
87f0e418
LP
971 Unit *u;
972 Unit *other;
b866264a 973 JobType t;
eef85c4a 974 void *v;
5cb5a6ff
LP
975
976 assert(j);
ac1135be 977 assert(j->installed);
e0209d83 978 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
5cb5a6ff 979
c6918296
MS
980 u = j->unit;
981 t = j->type;
982
983 j->result = result;
984
771b5242
ZJS
985 log_unit_debug(u, "Job %" PRIu32 " %s/%s finished, result=%s",
986 j->id, u->id, job_type_to_string(t), job_result_to_string(result));
c6918296 987
771b5242 988 /* If this job did nothing to the respective unit we don't log the status message */
833f92ad 989 if (!already)
33a3fdd9 990 job_emit_done_status_message(u, j->id, t, result);
c6918296 991
034c6ed7 992 /* Patch restart jobs so that they become normal start jobs */
c6918296 993 if (result == JOB_DONE && t == JOB_RESTART) {
f50e0a01 994
bbd1a837 995 job_change_type(j, JOB_START);
9c3349e2 996 job_set_state(j, JOB_WAITING);
cc42e081 997
fec7615c 998 job_add_to_dbus_queue(j);
cc42e081 999 job_add_to_run_queue(j);
c5a97ed1 1000 job_add_to_gc_queue(j);
57981b98 1001
57981b98 1002 goto finish;
5cb5a6ff
LP
1003 }
1004
3742095b 1005 if (IN_SET(result, JOB_FAILED, JOB_INVALID))
313cefa1 1006 j->manager->n_failed_jobs++;
76bf48b7 1007
97e7d748 1008 job_uninstall(j);
4a53080b 1009 job_free(j);
5cb5a6ff
LP
1010
1011 /* Fail depending jobs on failure */
5273510e 1012 if (result != JOB_DONE && recursive) {
be7d9ff7
LP
1013 if (IN_SET(t, JOB_START, JOB_VERIFY_ACTIVE)) {
1014 job_fail_dependencies(u, UNIT_REQUIRED_BY);
1015 job_fail_dependencies(u, UNIT_REQUISITE_OF);
1016 job_fail_dependencies(u, UNIT_BOUND_BY);
be7d9ff7
LP
1017 } else if (t == JOB_STOP)
1018 job_fail_dependencies(u, UNIT_CONFLICTED_BY);
5cb5a6ff
LP
1019 }
1020
791cd159
JK
1021 /* A special check to make sure we take down anything RequisiteOf if we
1022 * aren't active. This is when the verify-active job merges with a
1023 * satisfying job type, and then loses it's invalidation effect, as the
1024 * result there is JOB_DONE for the start job we merged into, while we
162392b7 1025 * should be failing the depending job if the said unit isn't in fact
791cd159
JK
1026 * active. Oneshots are an example of this, where going directly from
1027 * activating to inactive is success.
1028 *
1029 * This happens when you use ConditionXYZ= in a unit too, since in that
1030 * case the job completes with the JOB_DONE result, but the unit never
1031 * really becomes active. Note that such a case still involves merging:
1032 *
1033 * A start job waits for something else, and a verify-active comes in
1034 * and merges in the installed job. Then, later, when it becomes
1035 * runnable, it finishes with JOB_DONE result as execution on conditions
1036 * not being met is skipped, breaking our dependency semantics.
1037 *
1038 * Also, depending on if start job waits or not, the merging may or may
1039 * not happen (the verify-active job may trigger after it finishes), so
1040 * you get undeterministic results without this check.
1041 */
1042 if (result == JOB_DONE && recursive && !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1043 if (IN_SET(t, JOB_START, JOB_RELOAD))
1044 job_fail_dependencies(u, UNIT_REQUISITE_OF);
1045 }
c0daa706 1046 /* Trigger OnFailure dependencies that are not generated by
66870f90 1047 * the unit itself. We don't treat JOB_CANCELED as failure in
c0daa706
LP
1048 * this context. And JOB_FAILURE is already handled by the
1049 * unit itself. */
646cc98d 1050 if (IN_SET(result, JOB_TIMEOUT, JOB_DEPENDENCY)) {
f2341e0a
LP
1051 log_struct(LOG_NOTICE,
1052 "JOB_TYPE=%s", job_type_to_string(t),
1053 "JOB_RESULT=%s", job_result_to_string(result),
1054 LOG_UNIT_ID(u),
1055 LOG_UNIT_MESSAGE(u, "Job %s/%s failed with result '%s'.",
e2cc6eca
LP
1056 u->id,
1057 job_type_to_string(t),
a1230ff9 1058 job_result_to_string(result)));
222ae6a8 1059
3ecaa09b 1060 unit_start_on_failure(u);
222ae6a8 1061 }
c0daa706 1062
3ecaa09b
LP
1063 unit_trigger_notify(u);
1064
57981b98 1065finish:
5cb5a6ff 1066 /* Try to start the next jobs that can be started */
90e74a66 1067 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_AFTER])
c5a97ed1 1068 if (other->job) {
ac155bb8 1069 job_add_to_run_queue(other->job);
c5a97ed1
LP
1070 job_add_to_gc_queue(other->job);
1071 }
90e74a66 1072 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BEFORE])
c5a97ed1 1073 if (other->job) {
ac155bb8 1074 job_add_to_run_queue(other->job);
c5a97ed1
LP
1075 job_add_to_gc_queue(other->job);
1076 }
5cb5a6ff 1077
ac155bb8 1078 manager_check_finished(u->manager);
b0c918b9 1079
5273510e 1080 return 0;
5cb5a6ff 1081}
034c6ed7 1082
718db961
LP
1083static int job_dispatch_timer(sd_event_source *s, uint64_t monotonic, void *userdata) {
1084 Job *j = userdata;
f189ab18 1085 Unit *u;
faf919f1 1086
718db961
LP
1087 assert(j);
1088 assert(s == j->timer_event_source);
faf919f1 1089
f2341e0a 1090 log_unit_warning(j->unit, "Job %s/%s timed out.", j->unit->id, job_type_to_string(j->type));
faf919f1 1091
f189ab18 1092 u = j->unit;
833f92ad 1093 job_finish_and_invalidate(j, JOB_TIMEOUT, true, false);
f189ab18 1094
c7adcb1a
ZJS
1095 emergency_action(u->manager, u->job_timeout_action,
1096 EMERGENCY_ACTION_IS_WATCHDOG|EMERGENCY_ACTION_WARN,
7af67e9a 1097 u->job_timeout_reboot_arg, -1, "job timed out");
f189ab18 1098
718db961
LP
1099 return 0;
1100}
faf919f1 1101
a2df3ea4 1102int job_start_timer(Job *j, bool job_running) {
718db961 1103 int r;
171f12ce 1104 usec_t timeout_time, old_timeout_time;
faf919f1 1105
a2df3ea4 1106 if (job_running) {
171f12ce
MK
1107 j->begin_running_usec = now(CLOCK_MONOTONIC);
1108
a2df3ea4
MK
1109 if (j->unit->job_running_timeout == USEC_INFINITY)
1110 return 0;
faf919f1 1111
171f12ce 1112 timeout_time = usec_add(j->begin_running_usec, j->unit->job_running_timeout);
faf919f1 1113
a2df3ea4
MK
1114 if (j->timer_event_source) {
1115 /* Update only if JobRunningTimeoutSec= results in earlier timeout */
1116 r = sd_event_source_get_time(j->timer_event_source, &old_timeout_time);
1117 if (r < 0)
1118 return r;
1119
1120 if (old_timeout_time <= timeout_time)
1121 return 0;
1122
1123 return sd_event_source_set_time(j->timer_event_source, timeout_time);
1124 }
1125 } else {
1126 if (j->timer_event_source)
1127 return 0;
1128
1129 j->begin_usec = now(CLOCK_MONOTONIC);
1130
1131 if (j->unit->job_timeout == USEC_INFINITY)
1132 return 0;
1133
1134 timeout_time = usec_add(j->begin_usec, j->unit->job_timeout);
1135 }
8bb310c3 1136
6a0f1f6d
LP
1137 r = sd_event_add_time(
1138 j->manager->event,
1139 &j->timer_event_source,
1140 CLOCK_MONOTONIC,
a2df3ea4 1141 timeout_time, 0,
6a0f1f6d 1142 job_dispatch_timer, j);
718db961
LP
1143 if (r < 0)
1144 return r;
faf919f1 1145
7dfbe2e3
TG
1146 (void) sd_event_source_set_description(j->timer_event_source, "job-start");
1147
718db961 1148 return 0;
faf919f1
LP
1149}
1150
c1e1601e 1151void job_add_to_run_queue(Job *j) {
f8c34706
LP
1152 int r;
1153
034c6ed7 1154 assert(j);
ac1135be 1155 assert(j->installed);
034c6ed7
LP
1156
1157 if (j->in_run_queue)
1158 return;
1159
da8e1782 1160 if (prioq_isempty(j->manager->run_queue)) {
f8c34706
LP
1161 r = sd_event_source_set_enabled(j->manager->run_queue_event_source, SD_EVENT_ONESHOT);
1162 if (r < 0)
1163 log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
1164 }
752b5905 1165
735a8b6d
LP
1166 r = prioq_put(j->manager->run_queue, j, &j->run_queue_idx);
1167 if (r < 0)
1168 log_warning_errno(r, "Failed put job in run queue, ignoring: %m");
1169 else
1170 j->in_run_queue = true;
034c6ed7 1171}
94f04347 1172
c1e1601e
LP
1173void job_add_to_dbus_queue(Job *j) {
1174 assert(j);
1175 assert(j->installed);
1176
1177 if (j->in_dbus_queue)
1178 return;
1179
a567261a
LP
1180 /* We don't check if anybody is subscribed here, since this
1181 * job might just have been created and not yet assigned to a
1182 * connection/client. */
94b6dfa2 1183
71fda00f 1184 LIST_PREPEND(dbus_queue, j->manager->dbus_job_queue, j);
c1e1601e
LP
1185 j->in_dbus_queue = true;
1186}
1187
ea430986
LP
1188char *job_dbus_path(Job *j) {
1189 char *p;
1190
1191 assert(j);
1192
ccd06097 1193 if (asprintf(&p, "/org/freedesktop/systemd1/job/%"PRIu32, j->id) < 0)
ea430986
LP
1194 return NULL;
1195
1196 return p;
1197}
1198
05a98afd
LP
1199int job_serialize(Job *j, FILE *f) {
1200 assert(j);
1201 assert(f);
1202
d68c645b
LP
1203 (void) serialize_item_format(f, "job-id", "%u", j->id);
1204 (void) serialize_item(f, "job-type", job_type_to_string(j->type));
1205 (void) serialize_item(f, "job-state", job_state_to_string(j->state));
1206 (void) serialize_bool(f, "job-irreversible", j->irreversible);
1207 (void) serialize_bool(f, "job-sent-dbus-new-signal", j->sent_dbus_new_signal);
1208 (void) serialize_bool(f, "job-ignore-order", j->ignore_order);
718db961
LP
1209
1210 if (j->begin_usec > 0)
d68c645b 1211 (void) serialize_usec(f, "job-begin", j->begin_usec);
171f12ce 1212 if (j->begin_running_usec > 0)
d68c645b 1213 (void) serialize_usec(f, "job-begin-running", j->begin_running_usec);
718db961 1214
1a465207 1215 bus_track_serialize(j->bus_track, f, "subscribed");
39a18c60
MS
1216
1217 /* End marker */
1218 fputc('\n', f);
1219 return 0;
1220}
1221
05a98afd 1222int job_deserialize(Job *j, FILE *f) {
8948b341
LP
1223 int r;
1224
718db961 1225 assert(j);
05a98afd 1226 assert(f);
718db961 1227
39a18c60 1228 for (;;) {
8948b341
LP
1229 _cleanup_free_ char *line = NULL;
1230 char *l, *v;
39a18c60
MS
1231 size_t k;
1232
8948b341
LP
1233 r = read_line(f, LONG_LINE_MAX, &line);
1234 if (r < 0)
1235 return log_error_errno(r, "Failed to read serialization line: %m");
1236 if (r == 0)
1237 return 0;
39a18c60 1238
39a18c60
MS
1239 l = strstrip(line);
1240
1241 /* End marker */
8948b341 1242 if (isempty(l))
39a18c60
MS
1243 return 0;
1244
1245 k = strcspn(l, "=");
1246
1247 if (l[k] == '=') {
1248 l[k] = 0;
1249 v = l+k+1;
1250 } else
1251 v = l+k;
1252
1253 if (streq(l, "job-id")) {
718db961 1254
39a18c60 1255 if (safe_atou32(v, &j->id) < 0)
15ec1021 1256 log_debug("Failed to parse job id value: %s", v);
718db961 1257
39a18c60 1258 } else if (streq(l, "job-type")) {
718db961
LP
1259 JobType t;
1260
1261 t = job_type_from_string(v);
39a18c60 1262 if (t < 0)
15ec1021 1263 log_debug("Failed to parse job type: %s", v);
e0209d83 1264 else if (t >= _JOB_TYPE_MAX_IN_TRANSACTION)
15ec1021 1265 log_debug("Cannot deserialize job of type: %s", v);
39a18c60
MS
1266 else
1267 j->type = t;
718db961 1268
39a18c60 1269 } else if (streq(l, "job-state")) {
718db961
LP
1270 JobState s;
1271
1272 s = job_state_from_string(v);
39a18c60 1273 if (s < 0)
15ec1021 1274 log_debug("Failed to parse job state: %s", v);
39a18c60 1275 else
9c3349e2 1276 job_set_state(j, s);
718db961 1277
23ade460 1278 } else if (streq(l, "job-irreversible")) {
718db961
LP
1279 int b;
1280
1281 b = parse_boolean(v);
23ade460 1282 if (b < 0)
15ec1021 1283 log_debug("Failed to parse job irreversible flag: %s", v);
23ade460
MS
1284 else
1285 j->irreversible = j->irreversible || b;
718db961 1286
39a18c60 1287 } else if (streq(l, "job-sent-dbus-new-signal")) {
718db961
LP
1288 int b;
1289
1290 b = parse_boolean(v);
39a18c60 1291 if (b < 0)
15ec1021 1292 log_debug("Failed to parse job sent_dbus_new_signal flag: %s", v);
39a18c60
MS
1293 else
1294 j->sent_dbus_new_signal = j->sent_dbus_new_signal || b;
718db961 1295
39a18c60 1296 } else if (streq(l, "job-ignore-order")) {
718db961
LP
1297 int b;
1298
1299 b = parse_boolean(v);
39a18c60 1300 if (b < 0)
15ec1021 1301 log_debug("Failed to parse job ignore_order flag: %s", v);
39a18c60
MS
1302 else
1303 j->ignore_order = j->ignore_order || b;
718db961 1304
d68c645b
LP
1305 } else if (streq(l, "job-begin"))
1306 (void) deserialize_usec(v, &j->begin_usec);
718db961 1307
d68c645b
LP
1308 else if (streq(l, "job-begin-running"))
1309 (void) deserialize_usec(v, &j->begin_running_usec);
718db961 1310
d68c645b 1311 else if (streq(l, "subscribed")) {
b39a2770 1312 if (strv_extend(&j->deserialized_clients, v) < 0)
d68c645b
LP
1313 return log_oom();
1314 } else
1315 log_debug("Unknown job serialization key: %s", l);
39a18c60
MS
1316 }
1317}
1318
1319int job_coldplug(Job *j) {
718db961 1320 int r;
171f12ce 1321 usec_t timeout_time = USEC_INFINITY;
718db961
LP
1322
1323 assert(j);
39a18c60 1324
8f8f05a9
LP
1325 /* After deserialization is complete and the bus connection
1326 * set up again, let's start watching our subscribers again */
c5a97ed1 1327 (void) bus_job_coldplug_bus_track(j);
8f8f05a9 1328
1727a595
MM
1329 if (j->state == JOB_WAITING)
1330 job_add_to_run_queue(j);
1331
c5a97ed1
LP
1332 /* Maybe due to new dependencies we don't actually need this job anymore? */
1333 job_add_to_gc_queue(j);
1334
171f12ce
MK
1335 /* Create timer only when job began or began running and the respective timeout is finite.
1336 * Follow logic of job_start_timer() if both timeouts are finite */
1337 if (j->begin_usec == 0)
1338 return 0;
1339
1340 if (j->unit->job_timeout != USEC_INFINITY)
1341 timeout_time = usec_add(j->begin_usec, j->unit->job_timeout);
1342
1f65fd49 1343 if (timestamp_is_set(j->begin_running_usec))
171f12ce
MK
1344 timeout_time = MIN(timeout_time, usec_add(j->begin_running_usec, j->unit->job_running_timeout));
1345
1346 if (timeout_time == USEC_INFINITY)
39a18c60
MS
1347 return 0;
1348
36c16a7c 1349 j->timer_event_source = sd_event_source_unref(j->timer_event_source);
39a18c60 1350
6a0f1f6d
LP
1351 r = sd_event_add_time(
1352 j->manager->event,
1353 &j->timer_event_source,
1354 CLOCK_MONOTONIC,
171f12ce 1355 timeout_time, 0,
6a0f1f6d 1356 job_dispatch_timer, j);
718db961 1357 if (r < 0)
da927ba9 1358 log_debug_errno(r, "Failed to restart timeout for job: %m");
718db961 1359
7dfbe2e3
TG
1360 (void) sd_event_source_set_description(j->timer_event_source, "job-timeout");
1361
718db961 1362 return r;
39a18c60
MS
1363}
1364
c65eb836
LP
1365void job_shutdown_magic(Job *j) {
1366 assert(j);
1367
1368 /* The shutdown target gets some special treatment here: we
1369 * tell the kernel to begin with flushing its disk caches, to
1370 * optimize shutdown time a bit. Ideally we wouldn't hardcode
1371 * this magic into PID 1. However all other processes aren't
1372 * options either since they'd exit much sooner than PID 1 and
1373 * asynchronous sync() would cause their exit to be
1374 * delayed. */
1375
c2756a68 1376 if (j->type != JOB_START)
c65eb836
LP
1377 return;
1378
463d0d15 1379 if (!MANAGER_IS_SYSTEM(j->unit->manager))
c2756a68
LP
1380 return;
1381
1382 if (!unit_has_name(j->unit, SPECIAL_SHUTDOWN_TARGET))
c65eb836
LP
1383 return;
1384
5b1869ea
OB
1385 /* In case messages on console has been disabled on boot */
1386 j->unit->manager->no_console_output = false;
1387
75f86906 1388 if (detect_container() > 0)
c65eb836
LP
1389 return;
1390
d00c2631 1391 (void) asynchronous_sync(NULL);
c65eb836
LP
1392}
1393
7a7821c8
LP
1394int job_get_timeout(Job *j, usec_t *timeout) {
1395 usec_t x = USEC_INFINITY, y = USEC_INFINITY;
68db7a3b 1396 Unit *u = j->unit;
7a7821c8 1397 int r;
68db7a3b
ZJS
1398
1399 assert(u);
1400
1401 if (j->timer_event_source) {
1402 r = sd_event_source_get_time(j->timer_event_source, &x);
1403 if (r < 0)
1404 return r;
68db7a3b
ZJS
1405 }
1406
1407 if (UNIT_VTABLE(u)->get_timeout) {
7a7821c8
LP
1408 r = UNIT_VTABLE(u)->get_timeout(u, &y);
1409 if (r < 0)
1410 return r;
68db7a3b
ZJS
1411 }
1412
7a7821c8 1413 if (x == USEC_INFINITY && y == USEC_INFINITY)
68db7a3b
ZJS
1414 return 0;
1415
1416 *timeout = MIN(x, y);
68db7a3b
ZJS
1417 return 1;
1418}
1419
2ab3050f 1420bool job_may_gc(Job *j) {
c5a97ed1 1421 Unit *other;
eef85c4a 1422 void *v;
c5a97ed1
LP
1423
1424 assert(j);
1425
1426 /* Checks whether this job should be GC'ed away. We only do this for jobs of units that have no effect on their
2ab3050f
ZJS
1427 * own and just track external state. For now the only unit type that qualifies for this are .device units.
1428 * Returns true if the job can be collected. */
c5a97ed1
LP
1429
1430 if (!UNIT_VTABLE(j->unit)->gc_jobs)
2ab3050f 1431 return false;
c5a97ed1
LP
1432
1433 if (sd_bus_track_count(j->bus_track) > 0)
2ab3050f 1434 return false;
c5a97ed1
LP
1435
1436 /* FIXME: So this is a bit ugly: for now we don't properly track references made via private bus connections
1437 * (because it's nasty, as sd_bus_track doesn't apply to it). We simply remember that the job was once
1438 * referenced by one, and reset this whenever we notice that no private bus connections are around. This means
1439 * the GC is a bit too conservative when it comes to jobs created by private bus connections. */
1440 if (j->ref_by_private_bus) {
1441 if (set_isempty(j->unit->manager->private_buses))
1442 j->ref_by_private_bus = false;
1443 else
2ab3050f 1444 return false;
c5a97ed1
LP
1445 }
1446
1447 if (j->type == JOB_NOP)
2ab3050f 1448 return false;
c5a97ed1 1449
e602f152 1450 /* The logic is inverse to job_is_runnable, we cannot GC as long as we block any job. */
90e74a66 1451 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE])
e602f152 1452 if (other->job && job_compare(j, other->job, UNIT_BEFORE) < 0)
2ab3050f 1453 return false;
c5a97ed1 1454
90e74a66 1455 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER])
e602f152 1456 if (other->job && job_compare(j, other->job, UNIT_AFTER) < 0)
2ab3050f 1457 return false;
c5a97ed1 1458
2ab3050f 1459 return true;
c5a97ed1
LP
1460}
1461
1462void job_add_to_gc_queue(Job *j) {
1463 assert(j);
1464
1465 if (j->in_gc_queue)
1466 return;
1467
2ab3050f 1468 if (!job_may_gc(j))
c5a97ed1
LP
1469 return;
1470
1471 LIST_PREPEND(gc_queue, j->unit->manager->gc_job_queue, j);
1472 j->in_gc_queue = true;
1473}
1474
e602f152 1475static int job_compare_id(Job * const *a, Job * const *b) {
93bab288 1476 return CMP((*a)->id, (*b)->id);
15ea79f8
LP
1477}
1478
1479static size_t sort_job_list(Job **list, size_t n) {
1480 Job *previous = NULL;
1481 size_t a, b;
1482
1483 /* Order by numeric IDs */
e602f152 1484 typesafe_qsort(list, n, job_compare_id);
15ea79f8
LP
1485
1486 /* Filter out duplicates */
1487 for (a = 0, b = 0; a < n; a++) {
1488
1489 if (previous == list[a])
1490 continue;
1491
1492 previous = list[b++] = list[a];
1493 }
1494
1495 return b;
1496}
1497
1498int job_get_before(Job *j, Job*** ret) {
1499 _cleanup_free_ Job** list = NULL;
1500 size_t n = 0, n_allocated = 0;
1501 Unit *other = NULL;
eef85c4a 1502 void *v;
15ea79f8
LP
1503
1504 /* Returns a list of all pending jobs that need to finish before this job may be started. */
1505
1506 assert(j);
1507 assert(ret);
1508
1509 if (j->ignore_order) {
1510 *ret = NULL;
1511 return 0;
1512 }
1513
90e74a66 1514 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER]) {
e602f152
MK
1515 if (!other->job)
1516 continue;
1517 if (job_compare(j, other->job, UNIT_AFTER) <= 0)
1518 continue;
15ea79f8 1519
e602f152
MK
1520 if (!GREEDY_REALLOC(list, n_allocated, n+1))
1521 return -ENOMEM;
1522 list[n++] = other->job;
15ea79f8
LP
1523 }
1524
90e74a66 1525 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE]) {
15ea79f8
LP
1526 if (!other->job)
1527 continue;
e602f152 1528 if (job_compare(j, other->job, UNIT_BEFORE) <= 0)
15ea79f8
LP
1529 continue;
1530
1531 if (!GREEDY_REALLOC(list, n_allocated, n+1))
1532 return -ENOMEM;
1533 list[n++] = other->job;
1534 }
1535
1536 n = sort_job_list(list, n);
1537
1cc6c93a 1538 *ret = TAKE_PTR(list);
15ea79f8
LP
1539
1540 return (int) n;
1541}
1542
1543int job_get_after(Job *j, Job*** ret) {
1544 _cleanup_free_ Job** list = NULL;
1545 size_t n = 0, n_allocated = 0;
1546 Unit *other = NULL;
eef85c4a 1547 void *v;
15ea79f8
LP
1548
1549 assert(j);
1550 assert(ret);
1551
1552 /* Returns a list of all pending jobs that are waiting for this job to finish. */
1553
90e74a66 1554 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE]) {
15ea79f8
LP
1555 if (!other->job)
1556 continue;
1557
1558 if (other->job->ignore_order)
1559 continue;
1560
e602f152 1561 if (job_compare(j, other->job, UNIT_BEFORE) >= 0)
15ea79f8
LP
1562 continue;
1563
1564 if (!GREEDY_REALLOC(list, n_allocated, n+1))
1565 return -ENOMEM;
1566 list[n++] = other->job;
1567 }
1568
90e74a66 1569 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER]) {
e602f152
MK
1570 if (!other->job)
1571 continue;
1572
1573 if (other->job->ignore_order)
1574 continue;
15ea79f8 1575
e602f152
MK
1576 if (job_compare(j, other->job, UNIT_AFTER) >= 0)
1577 continue;
15ea79f8 1578
e602f152
MK
1579 if (!GREEDY_REALLOC(list, n_allocated, n+1))
1580 return -ENOMEM;
1581 list[n++] = other->job;
15ea79f8
LP
1582 }
1583
1584 n = sort_job_list(list, n);
1585
1cc6c93a 1586 *ret = TAKE_PTR(list);
15ea79f8
LP
1587
1588 return (int) n;
1589}
1590
94f04347
LP
1591static const char* const job_state_table[_JOB_STATE_MAX] = {
1592 [JOB_WAITING] = "waiting",
0a23a627 1593 [JOB_RUNNING] = "running",
94f04347
LP
1594};
1595
1596DEFINE_STRING_TABLE_LOOKUP(job_state, JobState);
1597
1598static const char* const job_type_table[_JOB_TYPE_MAX] = {
1599 [JOB_START] = "start",
1600 [JOB_VERIFY_ACTIVE] = "verify-active",
1601 [JOB_STOP] = "stop",
1602 [JOB_RELOAD] = "reload",
1603 [JOB_RELOAD_OR_START] = "reload-or-start",
1604 [JOB_RESTART] = "restart",
1605 [JOB_TRY_RESTART] = "try-restart",
3282591d 1606 [JOB_TRY_RELOAD] = "try-reload",
e0209d83 1607 [JOB_NOP] = "nop",
94f04347
LP
1608};
1609
1610DEFINE_STRING_TABLE_LOOKUP(job_type, JobType);
b548631a
LP
1611
1612static const char* const job_mode_table[_JOB_MODE_MAX] = {
1613 [JOB_FAIL] = "fail",
c497c7a9 1614 [JOB_REPLACE] = "replace",
23ade460 1615 [JOB_REPLACE_IRREVERSIBLY] = "replace-irreversibly",
e67c3609 1616 [JOB_ISOLATE] = "isolate",
2c5859af 1617 [JOB_FLUSH] = "flush",
cebe0d41 1618 [JOB_IGNORE_DEPENDENCIES] = "ignore-dependencies",
255baef6 1619 [JOB_IGNORE_REQUIREMENTS] = "ignore-requirements",
1f0f9f21 1620 [JOB_TRIGGERING] = "triggering",
b548631a
LP
1621};
1622
1623DEFINE_STRING_TABLE_LOOKUP(job_mode, JobMode);
5d44db4a
LP
1624
1625static const char* const job_result_table[_JOB_RESULT_MAX] = {
1626 [JOB_DONE] = "done",
1627 [JOB_CANCELED] = "canceled",
1628 [JOB_TIMEOUT] = "timeout",
1629 [JOB_FAILED] = "failed",
d68201e9 1630 [JOB_DEPENDENCY] = "dependency",
6a371e23
ZJS
1631 [JOB_SKIPPED] = "skipped",
1632 [JOB_INVALID] = "invalid",
59fccdc5 1633 [JOB_ASSERT] = "assert",
0faacd47 1634 [JOB_UNSUPPORTED] = "unsupported",
c5a97ed1 1635 [JOB_COLLECTED] = "collected",
d4fd1cf2 1636 [JOB_ONCE] = "once",
5d44db4a
LP
1637};
1638
1639DEFINE_STRING_TABLE_LOOKUP(job_result, JobResult);
94bd7323
EV
1640
1641const char* job_type_to_access_method(JobType t) {
1642 assert(t >= 0);
1643 assert(t < _JOB_TYPE_MAX);
1644
1645 if (IN_SET(t, JOB_START, JOB_RESTART, JOB_TRY_RESTART))
1646 return "start";
1647 else if (t == JOB_STOP)
1648 return "stop";
1649 else
1650 return "reload";
1651}
e602f152
MK
1652
1653/*
1654 * assume_dep assumed dependency between units (a is before/after b)
1655 *
1656 * Returns
1657 * 0 jobs are independent,
1658 * >0 a should run after b,
1659 * <0 a should run before b,
1660 *
1661 * The logic means that for a service a and a service b where b.After=a:
1662 *
1663 * start a + start b → 1st step start a, 2nd step start b
1664 * start a + stop b → 1st step stop b, 2nd step start a
1665 * stop a + start b → 1st step stop a, 2nd step start b
1666 * stop a + stop b → 1st step stop b, 2nd step stop a
1667 *
1668 * This has the side effect that restarts are properly
1669 * synchronized too.
1670 */
1671int job_compare(Job *a, Job *b, UnitDependency assume_dep) {
1672 assert(a->type < _JOB_TYPE_MAX_IN_TRANSACTION);
1673 assert(b->type < _JOB_TYPE_MAX_IN_TRANSACTION);
1674 assert(IN_SET(assume_dep, UNIT_AFTER, UNIT_BEFORE));
1675
1676 /* Trivial cases first */
1677 if (a->type == JOB_NOP || b->type == JOB_NOP)
1678 return 0;
1679
1680 if (a->ignore_order || b->ignore_order)
1681 return 0;
1682
1683 if (assume_dep == UNIT_AFTER)
1684 return -job_compare(b, a, UNIT_BEFORE);
1685
1686 /* Let's make it simple, JOB_STOP goes always first (in case both ua and ub stop,
1687 * then ub's stop goes first anyway).
1688 * JOB_RESTART is JOB_STOP in disguise (before it is patched to JOB_START). */
1689 if (IN_SET(b->type, JOB_STOP, JOB_RESTART))
1690 return 1;
1691 else
1692 return -1;
1693}