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