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