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