]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/job.c
df7eacfbc04b6102cd50ba2920651d3117097274
[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 "dbus-job.h"
11 #include "dbus.h"
12 #include "escape.h"
13 #include "fileio.h"
14 #include "job.h"
15 #include "log.h"
16 #include "macro.h"
17 #include "parse-util.h"
18 #include "serialize.h"
19 #include "set.h"
20 #include "sort-util.h"
21 #include "special.h"
22 #include "stdio-util.h"
23 #include "string-table.h"
24 #include "string-util.h"
25 #include "strv.h"
26 #include "terminal-util.h"
27 #include "unit.h"
28 #include "virt.h"
29
30 Job* job_new_raw(Unit *unit) {
31 Job *j;
32
33 /* used for deserialization */
34
35 assert(unit);
36
37 j = new(Job, 1);
38 if (!j)
39 return NULL;
40
41 *j = (Job) {
42 .manager = unit->manager,
43 .unit = unit,
44 .type = _JOB_TYPE_INVALID,
45 };
46
47 return j;
48 }
49
50 Job* 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
62 /* We don't link it here, that's what job_dependency() is for */
63
64 return j;
65 }
66
67 void job_unlink(Job *j) {
68 assert(j);
69 assert(!j->installed);
70 assert(!j->transaction_prev);
71 assert(!j->transaction_next);
72 assert(!j->subject_list);
73 assert(!j->object_list);
74
75 if (j->in_run_queue) {
76 LIST_REMOVE(run_queue, j->manager->run_queue, j);
77 j->in_run_queue = false;
78 }
79
80 if (j->in_dbus_queue) {
81 LIST_REMOVE(dbus_queue, j->manager->dbus_job_queue, j);
82 j->in_dbus_queue = false;
83 }
84
85 if (j->in_gc_queue) {
86 LIST_REMOVE(gc_queue, j->manager->gc_job_queue, j);
87 j->in_gc_queue = false;
88 }
89
90 j->timer_event_source = sd_event_source_unref(j->timer_event_source);
91 }
92
93 Job* job_free(Job *j) {
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);
102
103 sd_bus_track_unref(j->bus_track);
104 strv_free(j->deserialized_clients);
105
106 return mfree(j);
107 }
108
109 static 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
135 void job_uninstall(Job *j) {
136 Job **pj;
137
138 assert(j->installed);
139
140 job_set_state(j, JOB_WAITING);
141
142 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
143 assert(*pj == j);
144
145 /* Detach from next 'bigger' objects */
146
147 /* daemon-reload should be transparent to job observers */
148 if (!MANAGER_IS_RELOADING(j->manager))
149 bus_job_send_removed_signal(j);
150
151 *pj = NULL;
152
153 unit_add_to_gc_queue(j->unit);
154
155 unit_add_to_dbus_queue(j->unit); /* The Job property of the unit has changed now */
156
157 hashmap_remove_value(j->manager->jobs, UINT32_TO_PTR(j->id), j);
158 j->installed = false;
159 }
160
161 static 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. */
175 return t != JOB_RELOAD;
176 }
177
178 static void job_merge_into_installed(Job *j, Job *other) {
179 assert(j->installed);
180 assert(j->unit == other->unit);
181
182 if (j->type != JOB_NOP)
183 assert_se(job_type_merge_and_collapse(&j->type, other->type, j->unit) == 0);
184 else
185 assert(other->type == JOB_NOP);
186
187 j->irreversible = j->irreversible || other->irreversible;
188 j->ignore_order = j->ignore_order || other->ignore_order;
189 }
190
191 Job* job_install(Job *j) {
192 Job **pj;
193 Job *uj;
194
195 assert(!j->installed);
196 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
197 assert(j->state == JOB_WAITING);
198
199 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
200 uj = *pj;
201
202 if (uj) {
203 if (job_type_is_conflicting(uj->type, j->type))
204 job_finish_and_invalidate(uj, JOB_CANCELED, false, false);
205 else {
206 /* not conflicting, i.e. mergeable */
207
208 if (uj->state == JOB_WAITING ||
209 (job_type_allows_late_merge(j->type) && job_type_is_superset(uj->type, j->type))) {
210 job_merge_into_installed(uj, j);
211 log_unit_debug(uj->unit,
212 "Merged %s/%s into installed job %s/%s as %"PRIu32,
213 j->unit->id, job_type_to_string(j->type), uj->unit->id,
214 job_type_to_string(uj->type), uj->id);
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);
222 log_unit_debug(uj->unit,
223 "Merged into running job, re-running: %s/%s as %"PRIu32,
224 uj->unit->id, job_type_to_string(uj->type), uj->id);
225
226 job_set_state(uj, JOB_WAITING);
227 return uj;
228 }
229 }
230 }
231
232 /* Install the job */
233 *pj = j;
234 j->installed = true;
235
236 j->manager->n_installed_jobs++;
237 log_unit_debug(j->unit,
238 "Installed new job %s/%s as %u",
239 j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
240
241 job_add_to_gc_queue(j);
242
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
246 return j;
247 }
248
249 int job_install_deserialized(Job *j) {
250 Job **pj;
251 int r;
252
253 assert(!j->installed);
254
255 if (j->type < 0 || j->type >= _JOB_TYPE_MAX_IN_TRANSACTION)
256 return log_unit_debug_errno(j->unit, SYNTHETIC_ERRNO(EINVAL),
257 "Invalid job type %s in deserialization.",
258 strna(job_type_to_string(j->type)));
259
260 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
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");
270
271 *pj = j;
272 j->installed = true;
273
274 if (j->state == JOB_RUNNING)
275 j->unit->manager->n_running_jobs++;
276
277 log_unit_debug(j->unit,
278 "Reinstalled deserialized job %s/%s as %u",
279 j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
280 return 0;
281 }
282
283 JobDependency* job_dependency_new(Job *subject, Job *object, bool matters, bool conflicts) {
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
291 * explicitly asked for) is the requester. */
292
293 l = new0(JobDependency, 1);
294 if (!l)
295 return NULL;
296
297 l->subject = subject;
298 l->object = object;
299 l->matters = matters;
300 l->conflicts = conflicts;
301
302 if (subject)
303 LIST_PREPEND(subject, subject->subject_list, l);
304
305 LIST_PREPEND(object, object->object_list, l);
306
307 return l;
308 }
309
310 void job_dependency_free(JobDependency *l) {
311 assert(l);
312
313 if (l->subject)
314 LIST_REMOVE(subject, l->subject->subject_list, l);
315
316 LIST_REMOVE(object, l->object->object_list, l);
317
318 free(l);
319 }
320
321 void job_dump(Job *j, FILE *f, const char *prefix) {
322 assert(j);
323 assert(f);
324
325 prefix = strempty(prefix);
326
327 fprintf(f,
328 "%s-> Job %u:\n"
329 "%s\tAction: %s -> %s\n"
330 "%s\tState: %s\n"
331 "%s\tIrreversible: %s\n"
332 "%s\tMay GC: %s\n",
333 prefix, j->id,
334 prefix, j->unit->id, job_type_to_string(j->type),
335 prefix, job_state_to_string(j->state),
336 prefix, yes_no(j->irreversible),
337 prefix, yes_no(job_may_gc(j)));
338 }
339
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 *
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 *
349 * Merging is associative! A merged with B, and then merged with C is the same
350 * as A merged with the result of B merged with C.
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 */
358 static const JobType job_merging_table[] = {
359 /* What \ With * JOB_START JOB_VERIFY_ACTIVE JOB_STOP JOB_RELOAD */
360 /*********************************************************************************/
361 /*JOB_START */
362 /*JOB_VERIFY_ACTIVE */ JOB_START,
363 /*JOB_STOP */ -1, -1,
364 /*JOB_RELOAD */ JOB_RELOAD_OR_START, JOB_RELOAD, -1,
365 /*JOB_RESTART */ JOB_RESTART, JOB_RESTART, -1, JOB_RESTART,
366 };
367
368 JobType job_type_lookup_merge(JobType a, JobType b) {
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);
372
373 if (a == b)
374 return a;
375
376 if (a < b) {
377 JobType tmp = a;
378 a = b;
379 b = tmp;
380 }
381
382 return job_merging_table[(a - 1) * a / 2 + b];
383 }
384
385 bool job_type_is_redundant(JobType a, UnitActiveState b) {
386 switch (a) {
387
388 case JOB_START:
389 return IN_SET(b, UNIT_ACTIVE, UNIT_RELOADING);
390
391 case JOB_STOP:
392 return IN_SET(b, UNIT_INACTIVE, UNIT_FAILED);
393
394 case JOB_VERIFY_ACTIVE:
395 return IN_SET(b, UNIT_ACTIVE, UNIT_RELOADING);
396
397 case JOB_RELOAD:
398 return
399 b == UNIT_RELOADING;
400
401 case JOB_RESTART:
402 return
403 b == UNIT_ACTIVATING;
404
405 case JOB_NOP:
406 return true;
407
408 default:
409 assert_not_reached("Invalid job type");
410 }
411 }
412
413 JobType job_type_collapse(JobType t, Unit *u) {
414 UnitActiveState s;
415
416 switch (t) {
417
418 case JOB_TRY_RESTART:
419 s = unit_active_state(u);
420 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s))
421 return JOB_NOP;
422
423 return JOB_RESTART;
424
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
432 case JOB_RELOAD_OR_START:
433 s = unit_active_state(u);
434 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s))
435 return JOB_START;
436
437 return JOB_RELOAD;
438
439 default:
440 return t;
441 }
442 }
443
444 int job_type_merge_and_collapse(JobType *a, JobType b, Unit *u) {
445 JobType t;
446
447 t = job_type_lookup_merge(*a, b);
448 if (t < 0)
449 return -EEXIST;
450
451 *a = job_type_collapse(t, u);
452 return 0;
453 }
454
455 static bool job_is_runnable(Job *j) {
456 Iterator i;
457 Unit *other;
458 void *v;
459
460 assert(j);
461 assert(j->installed);
462
463 /* Checks whether there is any job running for the units this
464 * job needs to be running after (in the case of a 'positive'
465 * job type) or before (in the case of a 'negative' job
466 * type. */
467
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
473 /* First check if there is an override */
474 if (j->ignore_order)
475 return true;
476
477 if (j->type == JOB_NOP)
478 return true;
479
480 if (IN_SET(j->type, JOB_START, JOB_VERIFY_ACTIVE, JOB_RELOAD)) {
481 /* Immediate result is that the job is or might be
482 * started. In this case let's wait for the
483 * dependencies, regardless whether they are
484 * starting or stopping something. */
485
486 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER], i)
487 if (other->job)
488 return false;
489 }
490
491 /* Also, if something else is being stopped and we should
492 * change state after it, then let's wait. */
493
494 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE], i)
495 if (other->job &&
496 IN_SET(other->job->type, JOB_STOP, JOB_RESTART))
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
513 static void job_change_type(Job *j, JobType newtype) {
514 assert(j);
515
516 log_unit_debug(j->unit,
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));
520
521 j->type = newtype;
522 }
523
524 _pure_ static const char* job_get_begin_status_message_format(Unit *u, JobType t) {
525 const char *format;
526
527 assert(u);
528
529 if (t == JOB_RELOAD)
530 return "Reloading %s.";
531
532 assert(IN_SET(t, JOB_START, JOB_STOP));
533
534 format = UNIT_VTABLE(u)->status_message_formats.starting_stopping[t == JOB_STOP];
535 if (format)
536 return format;
537
538 /* Return generic strings */
539 if (t == JOB_START)
540 return "Starting %s.";
541 else {
542 assert(t == JOB_STOP);
543 return "Stopping %s.";
544 }
545 }
546
547 static 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
563 static void job_log_begin_status_message(Unit *u, uint32_t job_id, JobType t) {
564 const char *format, *mid;
565 char buf[LINE_MAX];
566
567 assert(u);
568 assert(t >= 0);
569 assert(t < _JOB_TYPE_MAX);
570
571 if (!IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD))
572 return;
573
574 if (log_on_console()) /* Skip this if it would only go on the console anyway */
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),
597 "JOB_ID=%" PRIu32, job_id,
598 "JOB_TYPE=%s", job_type_to_string(t),
599 LOG_UNIT_ID(u),
600 LOG_UNIT_INVOCATION_ID(u),
601 mid);
602 }
603
604 static void job_emit_begin_status_message(Unit *u, uint32_t job_id, JobType t) {
605 assert(u);
606 assert(t >= 0);
607 assert(t < _JOB_TYPE_MAX);
608
609 job_log_begin_status_message(u, job_id, t);
610 job_print_begin_status_message(u, t);
611 }
612
613 static int job_perform_on_unit(Job **j) {
614 uint32_t id;
615 Manager *m;
616 JobType t;
617 Unit *u;
618 int r;
619
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
634 switch (t) {
635 case JOB_START:
636 r = unit_start(u);
637 break;
638
639 case JOB_RESTART:
640 t = JOB_STOP;
641 _fallthrough_;
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
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. */
657 *j = manager_get_job(m, id);
658 if (*j && r > 0)
659 job_emit_begin_status_message(u, id, t);
660
661 return r;
662 }
663
664 int job_run_and_invalidate(Job *j) {
665 int r;
666
667 assert(j);
668 assert(j->installed);
669 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
670 assert(j->in_run_queue);
671
672 LIST_REMOVE(run_queue, j->manager->run_queue, j);
673 j->in_run_queue = false;
674
675 if (j->state != JOB_WAITING)
676 return 0;
677
678 if (!job_is_runnable(j))
679 return -EAGAIN;
680
681 job_start_timer(j, true);
682 job_set_state(j, JOB_RUNNING);
683 job_add_to_dbus_queue(j);
684
685 switch (j->type) {
686
687 case JOB_VERIFY_ACTIVE: {
688 UnitActiveState t;
689
690 t = unit_active_state(j->unit);
691 if (UNIT_IS_ACTIVE_OR_RELOADING(t))
692 r = -EALREADY;
693 else if (t == UNIT_ACTIVATING)
694 r = -EAGAIN;
695 else
696 r = -EBADR;
697 break;
698 }
699
700 case JOB_START:
701 case JOB_STOP:
702 case JOB_RESTART:
703 r = job_perform_on_unit(&j);
704
705 /* If the unit type does not support starting/stopping, then simply wait. */
706 if (r == -EBADR)
707 r = 0;
708 break;
709
710 case JOB_RELOAD:
711 r = job_perform_on_unit(&j);
712 break;
713
714 case JOB_NOP:
715 r = -EALREADY;
716 break;
717
718 default:
719 assert_not_reached("Unknown job type");
720 }
721
722 if (j) {
723 if (r == -EAGAIN)
724 job_set_state(j, JOB_WAITING); /* Hmm, not ready after all, let's return to JOB_WAITING state */
725 else if (r == -EALREADY) /* already being executed */
726 r = job_finish_and_invalidate(j, JOB_DONE, true, true);
727 else if (r == -ECOMM) /* condition failed, but all is good */
728 r = job_finish_and_invalidate(j, JOB_DONE, true, false);
729 else if (r == -EBADR)
730 r = job_finish_and_invalidate(j, JOB_SKIPPED, true, false);
731 else if (r == -ENOEXEC)
732 r = job_finish_and_invalidate(j, JOB_INVALID, true, false);
733 else if (r == -EPROTO)
734 r = job_finish_and_invalidate(j, JOB_ASSERT, true, false);
735 else if (r == -EOPNOTSUPP)
736 r = job_finish_and_invalidate(j, JOB_UNSUPPORTED, true, false);
737 else if (r == -ENOLINK)
738 r = job_finish_and_invalidate(j, JOB_DEPENDENCY, true, false);
739 else if (r == -ESTALE)
740 r = job_finish_and_invalidate(j, JOB_ONCE, true, false);
741 else if (r < 0)
742 r = job_finish_and_invalidate(j, JOB_FAILED, true, false);
743 }
744
745 return r;
746 }
747
748 _pure_ static const char *job_get_done_status_message_format(Unit *u, JobType t, JobResult result) {
749
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.",
757 [JOB_COLLECTED] = "Unnecessary job for %s was removed.",
758 [JOB_ONCE] = "Unit %s has been started before and cannot be started again."
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.",
763 [JOB_TIMEOUT] = "Timed out stopping %s.",
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 };
776
777 const char *format;
778
779 assert(u);
780 assert(t >= 0);
781 assert(t < _JOB_TYPE_MAX);
782
783 if (IN_SET(t, JOB_START, JOB_STOP, JOB_RESTART)) {
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;
789 }
790
791 /* Return generic strings */
792 if (t == JOB_START)
793 return generic_finished_start_job[result];
794 else if (IN_SET(t, JOB_STOP, JOB_RESTART))
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];
800
801 return NULL;
802 }
803
804 static const struct {
805 const char *color, *word;
806 } job_print_done_status_messages[_JOB_RESULT_MAX] = {
807 [JOB_DONE] = { ANSI_OK_COLOR, " OK " },
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 */
815 [JOB_ONCE] = { ANSI_HIGHLIGHT_RED, " ONCE " },
816 };
817
818 static void job_print_done_status_message(Unit *u, JobType t, JobResult result) {
819 const char *format;
820 const char *status;
821
822 assert(u);
823 assert(t >= 0);
824 assert(t < _JOB_TYPE_MAX);
825
826 /* Reload status messages have traditionally not been printed to console. */
827 if (t == JOB_RELOAD)
828 return;
829
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
834 if (!job_print_done_status_messages[result].word)
835 return;
836
837 format = job_get_done_status_message_format(u, t, result);
838 if (!format)
839 return;
840
841 if (log_get_show_color())
842 status = strjoina(job_print_done_status_messages[result].color,
843 job_print_done_status_messages[result].word,
844 ANSI_NORMAL);
845 else
846 status = job_print_done_status_messages[result].word;
847
848 if (result != JOB_DONE)
849 manager_flip_auto_status(u->manager, true);
850
851 DISABLE_WARNING_FORMAT_NONLITERAL;
852 unit_status_printf(u, status, format);
853 REENABLE_WARNING;
854
855 if (t == JOB_START && result == JOB_FAILED) {
856 _cleanup_free_ char *quoted;
857
858 quoted = shell_maybe_quote(u->id, ESCAPE_BACKSLASH);
859 manager_status_printf(u->manager, STATUS_TYPE_NORMAL, NULL, "See 'systemctl status %s' for details.", strna(quoted));
860 }
861 }
862
863 static void job_log_done_status_message(Unit *u, uint32_t job_id, JobType t, JobResult result) {
864 const char *format, *mid;
865 char buf[LINE_MAX];
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,
876 [JOB_COLLECTED] = LOG_INFO,
877 [JOB_ONCE] = LOG_ERR,
878 };
879
880 assert(u);
881 assert(t >= 0);
882 assert(t < _JOB_TYPE_MAX);
883
884 /* Skip printing if output goes to the console, and job_print_status_message()
885 will actually print something to the console. */
886 if (log_on_console() && job_print_done_status_messages[result].word)
887 return;
888
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
903 format = job_get_done_status_message_format(u, t, result);
904 if (!format)
905 return;
906
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. */
911 DISABLE_WARNING_FORMAT_NONLITERAL;
912 (void) snprintf(buf, sizeof(buf), format, unit_description(u));
913 REENABLE_WARNING;
914
915 switch (t) {
916
917 case JOB_START:
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;
922 break;
923
924 case JOB_RELOAD:
925 mid = "MESSAGE_ID=" SD_MESSAGE_UNIT_RELOADED_STR;
926 break;
927
928 case JOB_STOP:
929 case JOB_RESTART:
930 mid = "MESSAGE_ID=" SD_MESSAGE_UNIT_STOPPED_STR;
931 break;
932
933 default:
934 log_struct(job_result_log_level[result],
935 LOG_MESSAGE("%s", buf),
936 "JOB_ID=%" PRIu32, job_id,
937 "JOB_TYPE=%s", job_type_to_string(t),
938 "JOB_RESULT=%s", job_result_to_string(result),
939 LOG_UNIT_ID(u),
940 LOG_UNIT_INVOCATION_ID(u));
941 return;
942 }
943
944 log_struct(job_result_log_level[result],
945 LOG_MESSAGE("%s", buf),
946 "JOB_ID=%" PRIu32, job_id,
947 "JOB_TYPE=%s", job_type_to_string(t),
948 "JOB_RESULT=%s", job_result_to_string(result),
949 LOG_UNIT_ID(u),
950 LOG_UNIT_INVOCATION_ID(u),
951 mid);
952 }
953
954 static void job_emit_done_status_message(Unit *u, uint32_t job_id, JobType t, JobResult result) {
955 assert(u);
956
957 job_log_done_status_message(u, job_id, t, result);
958 job_print_done_status_message(u, t, result);
959 }
960
961 static void job_fail_dependencies(Unit *u, UnitDependency d) {
962 Unit *other;
963 Iterator i;
964 void *v;
965
966 assert(u);
967
968 HASHMAP_FOREACH_KEY(v, other, u->dependencies[d], i) {
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
976 job_finish_and_invalidate(j, JOB_DEPENDENCY, true, false);
977 }
978 }
979
980 int job_finish_and_invalidate(Job *j, JobResult result, bool recursive, bool already) {
981 Unit *u;
982 Unit *other;
983 JobType t;
984 Iterator i;
985 void *v;
986
987 assert(j);
988 assert(j->installed);
989 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
990
991 u = j->unit;
992 t = j->type;
993
994 j->result = result;
995
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));
997
998 /* If this job did nothing to respective unit we don't log the status message */
999 if (!already)
1000 job_emit_done_status_message(u, j->id, t, result);
1001
1002 /* Patch restart jobs so that they become normal start jobs */
1003 if (result == JOB_DONE && t == JOB_RESTART) {
1004
1005 job_change_type(j, JOB_START);
1006 job_set_state(j, JOB_WAITING);
1007
1008 job_add_to_dbus_queue(j);
1009 job_add_to_run_queue(j);
1010 job_add_to_gc_queue(j);
1011
1012 goto finish;
1013 }
1014
1015 if (IN_SET(result, JOB_FAILED, JOB_INVALID))
1016 j->manager->n_failed_jobs++;
1017
1018 job_uninstall(j);
1019 job_free(j);
1020
1021 /* Fail depending jobs on failure */
1022 if (result != JOB_DONE && recursive) {
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);
1027 } else if (t == JOB_STOP)
1028 job_fail_dependencies(u, UNIT_CONFLICTED_BY);
1029 }
1030
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 }
1056 /* Trigger OnFailure dependencies that are not generated by
1057 * the unit itself. We don't treat JOB_CANCELED as failure in
1058 * this context. And JOB_FAILURE is already handled by the
1059 * unit itself. */
1060 if (IN_SET(result, JOB_TIMEOUT, JOB_DEPENDENCY)) {
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'.",
1066 u->id,
1067 job_type_to_string(t),
1068 job_result_to_string(result)));
1069
1070 unit_start_on_failure(u);
1071 }
1072
1073 unit_trigger_notify(u);
1074
1075 finish:
1076 /* Try to start the next jobs that can be started */
1077 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_AFTER], i)
1078 if (other->job) {
1079 job_add_to_run_queue(other->job);
1080 job_add_to_gc_queue(other->job);
1081 }
1082 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BEFORE], i)
1083 if (other->job) {
1084 job_add_to_run_queue(other->job);
1085 job_add_to_gc_queue(other->job);
1086 }
1087
1088 manager_check_finished(u->manager);
1089
1090 return 0;
1091 }
1092
1093 static int job_dispatch_timer(sd_event_source *s, uint64_t monotonic, void *userdata) {
1094 Job *j = userdata;
1095 Unit *u;
1096
1097 assert(j);
1098 assert(s == j->timer_event_source);
1099
1100 log_unit_warning(j->unit, "Job %s/%s timed out.", j->unit->id, job_type_to_string(j->type));
1101
1102 u = j->unit;
1103 job_finish_and_invalidate(j, JOB_TIMEOUT, true, false);
1104
1105 emergency_action(u->manager, u->job_timeout_action,
1106 EMERGENCY_ACTION_IS_WATCHDOG|EMERGENCY_ACTION_WARN,
1107 u->job_timeout_reboot_arg, -1, "job timed out");
1108
1109 return 0;
1110 }
1111
1112 int job_start_timer(Job *j, bool job_running) {
1113 int r;
1114 usec_t timeout_time, old_timeout_time;
1115
1116 if (job_running) {
1117 j->begin_running_usec = now(CLOCK_MONOTONIC);
1118
1119 if (j->unit->job_running_timeout == USEC_INFINITY)
1120 return 0;
1121
1122 timeout_time = usec_add(j->begin_running_usec, j->unit->job_running_timeout);
1123
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 }
1146
1147 r = sd_event_add_time(
1148 j->manager->event,
1149 &j->timer_event_source,
1150 CLOCK_MONOTONIC,
1151 timeout_time, 0,
1152 job_dispatch_timer, j);
1153 if (r < 0)
1154 return r;
1155
1156 (void) sd_event_source_set_description(j->timer_event_source, "job-start");
1157
1158 return 0;
1159 }
1160
1161 void job_add_to_run_queue(Job *j) {
1162 int r;
1163
1164 assert(j);
1165 assert(j->installed);
1166
1167 if (j->in_run_queue)
1168 return;
1169
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 }
1175
1176 LIST_PREPEND(run_queue, j->manager->run_queue, j);
1177 j->in_run_queue = true;
1178 }
1179
1180 void job_add_to_dbus_queue(Job *j) {
1181 assert(j);
1182 assert(j->installed);
1183
1184 if (j->in_dbus_queue)
1185 return;
1186
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. */
1190
1191 LIST_PREPEND(dbus_queue, j->manager->dbus_job_queue, j);
1192 j->in_dbus_queue = true;
1193 }
1194
1195 char *job_dbus_path(Job *j) {
1196 char *p;
1197
1198 assert(j);
1199
1200 if (asprintf(&p, "/org/freedesktop/systemd1/job/%"PRIu32, j->id) < 0)
1201 return NULL;
1202
1203 return p;
1204 }
1205
1206 int job_serialize(Job *j, FILE *f) {
1207 assert(j);
1208 assert(f);
1209
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);
1216
1217 if (j->begin_usec > 0)
1218 (void) serialize_usec(f, "job-begin", j->begin_usec);
1219 if (j->begin_running_usec > 0)
1220 (void) serialize_usec(f, "job-begin-running", j->begin_running_usec);
1221
1222 bus_track_serialize(j->bus_track, f, "subscribed");
1223
1224 /* End marker */
1225 fputc('\n', f);
1226 return 0;
1227 }
1228
1229 int job_deserialize(Job *j, FILE *f) {
1230 int r;
1231
1232 assert(j);
1233 assert(f);
1234
1235 for (;;) {
1236 _cleanup_free_ char *line = NULL;
1237 char *l, *v;
1238 size_t k;
1239
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;
1245
1246 l = strstrip(line);
1247
1248 /* End marker */
1249 if (isempty(l))
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")) {
1261
1262 if (safe_atou32(v, &j->id) < 0)
1263 log_debug("Failed to parse job id value: %s", v);
1264
1265 } else if (streq(l, "job-type")) {
1266 JobType t;
1267
1268 t = job_type_from_string(v);
1269 if (t < 0)
1270 log_debug("Failed to parse job type: %s", v);
1271 else if (t >= _JOB_TYPE_MAX_IN_TRANSACTION)
1272 log_debug("Cannot deserialize job of type: %s", v);
1273 else
1274 j->type = t;
1275
1276 } else if (streq(l, "job-state")) {
1277 JobState s;
1278
1279 s = job_state_from_string(v);
1280 if (s < 0)
1281 log_debug("Failed to parse job state: %s", v);
1282 else
1283 job_set_state(j, s);
1284
1285 } else if (streq(l, "job-irreversible")) {
1286 int b;
1287
1288 b = parse_boolean(v);
1289 if (b < 0)
1290 log_debug("Failed to parse job irreversible flag: %s", v);
1291 else
1292 j->irreversible = j->irreversible || b;
1293
1294 } else if (streq(l, "job-sent-dbus-new-signal")) {
1295 int b;
1296
1297 b = parse_boolean(v);
1298 if (b < 0)
1299 log_debug("Failed to parse job sent_dbus_new_signal flag: %s", v);
1300 else
1301 j->sent_dbus_new_signal = j->sent_dbus_new_signal || b;
1302
1303 } else if (streq(l, "job-ignore-order")) {
1304 int b;
1305
1306 b = parse_boolean(v);
1307 if (b < 0)
1308 log_debug("Failed to parse job ignore_order flag: %s", v);
1309 else
1310 j->ignore_order = j->ignore_order || b;
1311
1312 } else if (streq(l, "job-begin"))
1313 (void) deserialize_usec(v, &j->begin_usec);
1314
1315 else if (streq(l, "job-begin-running"))
1316 (void) deserialize_usec(v, &j->begin_running_usec);
1317
1318 else if (streq(l, "subscribed")) {
1319 if (strv_extend(&j->deserialized_clients, v) < 0)
1320 return log_oom();
1321 } else
1322 log_debug("Unknown job serialization key: %s", l);
1323 }
1324 }
1325
1326 int job_coldplug(Job *j) {
1327 int r;
1328 usec_t timeout_time = USEC_INFINITY;
1329
1330 assert(j);
1331
1332 /* After deserialization is complete and the bus connection
1333 * set up again, let's start watching our subscribers again */
1334 (void) bus_job_coldplug_bus_track(j);
1335
1336 if (j->state == JOB_WAITING)
1337 job_add_to_run_queue(j);
1338
1339 /* Maybe due to new dependencies we don't actually need this job anymore? */
1340 job_add_to_gc_queue(j);
1341
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 (timestamp_is_set(j->begin_running_usec))
1351 timeout_time = MIN(timeout_time, usec_add(j->begin_running_usec, j->unit->job_running_timeout));
1352
1353 if (timeout_time == USEC_INFINITY)
1354 return 0;
1355
1356 j->timer_event_source = sd_event_source_unref(j->timer_event_source);
1357
1358 r = sd_event_add_time(
1359 j->manager->event,
1360 &j->timer_event_source,
1361 CLOCK_MONOTONIC,
1362 timeout_time, 0,
1363 job_dispatch_timer, j);
1364 if (r < 0)
1365 log_debug_errno(r, "Failed to restart timeout for job: %m");
1366
1367 (void) sd_event_source_set_description(j->timer_event_source, "job-timeout");
1368
1369 return r;
1370 }
1371
1372 void 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
1383 if (j->type != JOB_START)
1384 return;
1385
1386 if (!MANAGER_IS_SYSTEM(j->unit->manager))
1387 return;
1388
1389 if (!unit_has_name(j->unit, SPECIAL_SHUTDOWN_TARGET))
1390 return;
1391
1392 /* In case messages on console has been disabled on boot */
1393 j->unit->manager->no_console_output = false;
1394
1395 if (detect_container() > 0)
1396 return;
1397
1398 (void) asynchronous_sync(NULL);
1399 }
1400
1401 int job_get_timeout(Job *j, usec_t *timeout) {
1402 usec_t x = USEC_INFINITY, y = USEC_INFINITY;
1403 Unit *u = j->unit;
1404 int r;
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;
1412 }
1413
1414 if (UNIT_VTABLE(u)->get_timeout) {
1415 r = UNIT_VTABLE(u)->get_timeout(u, &y);
1416 if (r < 0)
1417 return r;
1418 }
1419
1420 if (x == USEC_INFINITY && y == USEC_INFINITY)
1421 return 0;
1422
1423 *timeout = MIN(x, y);
1424 return 1;
1425 }
1426
1427 bool job_may_gc(Job *j) {
1428 Unit *other;
1429 Iterator i;
1430 void *v;
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
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. */
1437
1438 if (!UNIT_VTABLE(j->unit)->gc_jobs)
1439 return false;
1440
1441 if (sd_bus_track_count(j->bus_track) > 0)
1442 return false;
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
1452 return false;
1453 }
1454
1455 if (j->type == JOB_NOP)
1456 return false;
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. */
1460 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE], i) {
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))
1468 return false;
1469 }
1470
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))
1473 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER], i) {
1474 if (!other->job)
1475 continue;
1476
1477 if (other->job->ignore_order)
1478 continue;
1479
1480 return false;
1481 }
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
1497 */
1498
1499 return true;
1500 }
1501
1502 void job_add_to_gc_queue(Job *j) {
1503 assert(j);
1504
1505 if (j->in_gc_queue)
1506 return;
1507
1508 if (!job_may_gc(j))
1509 return;
1510
1511 LIST_PREPEND(gc_queue, j->unit->manager->gc_job_queue, j);
1512 j->in_gc_queue = true;
1513 }
1514
1515 static int job_compare(Job * const *a, Job * const *b) {
1516 return CMP((*a)->id, (*b)->id);
1517 }
1518
1519 static 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 */
1524 typesafe_qsort(list, n, job_compare);
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
1538 int 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;
1543 void *v;
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
1557 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER], i) {
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
1567 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE], i) {
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
1581 *ret = TAKE_PTR(list);
1582
1583 return (int) n;
1584 }
1585
1586 int 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;
1590 void *v;
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
1598 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_BEFORE], i) {
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
1615 HASHMAP_FOREACH_KEY(v, other, j->unit->dependencies[UNIT_AFTER], i) {
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
1630 *ret = TAKE_PTR(list);
1631
1632 return (int) n;
1633 }
1634
1635 static const char* const job_state_table[_JOB_STATE_MAX] = {
1636 [JOB_WAITING] = "waiting",
1637 [JOB_RUNNING] = "running",
1638 };
1639
1640 DEFINE_STRING_TABLE_LOOKUP(job_state, JobState);
1641
1642 static 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",
1650 [JOB_TRY_RELOAD] = "try-reload",
1651 [JOB_NOP] = "nop",
1652 };
1653
1654 DEFINE_STRING_TABLE_LOOKUP(job_type, JobType);
1655
1656 static const char* const job_mode_table[_JOB_MODE_MAX] = {
1657 [JOB_FAIL] = "fail",
1658 [JOB_REPLACE] = "replace",
1659 [JOB_REPLACE_IRREVERSIBLY] = "replace-irreversibly",
1660 [JOB_ISOLATE] = "isolate",
1661 [JOB_FLUSH] = "flush",
1662 [JOB_IGNORE_DEPENDENCIES] = "ignore-dependencies",
1663 [JOB_IGNORE_REQUIREMENTS] = "ignore-requirements",
1664 };
1665
1666 DEFINE_STRING_TABLE_LOOKUP(job_mode, JobMode);
1667
1668 static 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",
1673 [JOB_DEPENDENCY] = "dependency",
1674 [JOB_SKIPPED] = "skipped",
1675 [JOB_INVALID] = "invalid",
1676 [JOB_ASSERT] = "assert",
1677 [JOB_UNSUPPORTED] = "unsupported",
1678 [JOB_COLLECTED] = "collected",
1679 [JOB_ONCE] = "once",
1680 };
1681
1682 DEFINE_STRING_TABLE_LOOKUP(job_result, JobResult);
1683
1684 const 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 }