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