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