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