1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
11 #include "sd-messages.h"
13 #include "alloc-util.h"
21 #include "parse-util.h"
24 #include "stdio-util.h"
25 #include "string-table.h"
26 #include "string-util.h"
28 #include "terminal-util.h"
32 Job
* job_new_raw(Unit
*unit
) {
35 /* used for deserialization */
43 j
->manager
= unit
->manager
;
45 j
->type
= _JOB_TYPE_INVALID
;
51 Job
* job_new(Unit
*unit
, JobType type
) {
54 assert(type
< _JOB_TYPE_MAX
);
56 j
= job_new_raw(unit
);
60 j
->id
= j
->manager
->current_job_id
++;
63 /* We don't link it here, that's what job_dependency() is for */
68 void job_unlink(Job
*j
) {
70 assert(!j
->installed
);
71 assert(!j
->transaction_prev
);
72 assert(!j
->transaction_next
);
73 assert(!j
->subject_list
);
74 assert(!j
->object_list
);
76 if (j
->in_run_queue
) {
77 LIST_REMOVE(run_queue
, j
->manager
->run_queue
, j
);
78 j
->in_run_queue
= false;
81 if (j
->in_dbus_queue
) {
82 LIST_REMOVE(dbus_queue
, j
->manager
->dbus_job_queue
, j
);
83 j
->in_dbus_queue
= false;
87 LIST_REMOVE(gc_queue
, j
->manager
->gc_job_queue
, j
);
88 j
->in_gc_queue
= false;
91 j
->timer_event_source
= sd_event_source_unref(j
->timer_event_source
);
94 void job_free(Job
*j
) {
96 assert(!j
->installed
);
97 assert(!j
->transaction_prev
);
98 assert(!j
->transaction_next
);
99 assert(!j
->subject_list
);
100 assert(!j
->object_list
);
104 sd_bus_track_unref(j
->bus_track
);
105 strv_free(j
->deserialized_clients
);
110 static void job_set_state(Job
*j
, JobState state
) {
113 assert(state
< _JOB_STATE_MAX
);
115 if (j
->state
== state
)
123 if (j
->state
== JOB_RUNNING
)
124 j
->unit
->manager
->n_running_jobs
++;
126 assert(j
->state
== JOB_WAITING
);
127 assert(j
->unit
->manager
->n_running_jobs
> 0);
129 j
->unit
->manager
->n_running_jobs
--;
131 if (j
->unit
->manager
->n_running_jobs
<= 0)
132 j
->unit
->manager
->jobs_in_progress_event_source
= sd_event_source_unref(j
->unit
->manager
->jobs_in_progress_event_source
);
136 void job_uninstall(Job
*j
) {
139 assert(j
->installed
);
141 job_set_state(j
, JOB_WAITING
);
143 pj
= (j
->type
== JOB_NOP
) ? &j
->unit
->nop_job
: &j
->unit
->job
;
146 /* Detach from next 'bigger' objects */
148 /* daemon-reload should be transparent to job observers */
149 if (!MANAGER_IS_RELOADING(j
->manager
))
150 bus_job_send_removed_signal(j
);
154 unit_add_to_gc_queue(j
->unit
);
156 hashmap_remove(j
->manager
->jobs
, UINT32_TO_PTR(j
->id
));
157 j
->installed
= false;
160 static bool job_type_allows_late_merge(JobType t
) {
161 /* Tells whether it is OK to merge a job of type 't' with an already
163 * Reloads cannot be merged this way. Think of the sequence:
164 * 1. Reload of a daemon is in progress; the daemon has already loaded
165 * its config file, but hasn't completed the reload operation yet.
166 * 2. Edit foo's config file.
167 * 3. Trigger another reload to have the daemon use the new config.
168 * Should the second reload job be merged into the first one, the daemon
169 * would not know about the new config.
170 * JOB_RESTART jobs on the other hand can be merged, because they get
171 * patched into JOB_START after stopping the unit. So if we see a
172 * JOB_RESTART running, it means the unit hasn't stopped yet and at
173 * this time the merge is still allowed. */
174 return t
!= JOB_RELOAD
;
177 static void job_merge_into_installed(Job
*j
, Job
*other
) {
178 assert(j
->installed
);
179 assert(j
->unit
== other
->unit
);
181 if (j
->type
!= JOB_NOP
)
182 job_type_merge_and_collapse(&j
->type
, other
->type
, j
->unit
);
184 assert(other
->type
== JOB_NOP
);
186 j
->irreversible
= j
->irreversible
|| other
->irreversible
;
187 j
->ignore_order
= j
->ignore_order
|| other
->ignore_order
;
190 Job
* job_install(Job
*j
) {
194 assert(!j
->installed
);
195 assert(j
->type
< _JOB_TYPE_MAX_IN_TRANSACTION
);
196 assert(j
->state
== JOB_WAITING
);
198 pj
= (j
->type
== JOB_NOP
) ? &j
->unit
->nop_job
: &j
->unit
->job
;
202 if (job_type_is_conflicting(uj
->type
, j
->type
))
203 job_finish_and_invalidate(uj
, JOB_CANCELED
, false, false);
205 /* not conflicting, i.e. mergeable */
207 if (uj
->state
== JOB_WAITING
||
208 (job_type_allows_late_merge(j
->type
) && job_type_is_superset(uj
->type
, j
->type
))) {
209 job_merge_into_installed(uj
, j
);
210 log_unit_debug(uj
->unit
,
211 "Merged into installed job %s/%s as %u",
212 uj
->unit
->id
, job_type_to_string(uj
->type
), (unsigned) uj
->id
);
215 /* already running and not safe to merge into */
216 /* Patch uj to become a merged job and re-run it. */
217 /* XXX It should be safer to queue j to run after uj finishes, but it is
218 * not currently possible to have more than one installed job per unit. */
219 job_merge_into_installed(uj
, j
);
220 log_unit_debug(uj
->unit
,
221 "Merged into running job, re-running: %s/%s as %u",
222 uj
->unit
->id
, job_type_to_string(uj
->type
), (unsigned) uj
->id
);
224 job_set_state(uj
, JOB_WAITING
);
230 /* Install the job */
234 j
->manager
->n_installed_jobs
++;
235 log_unit_debug(j
->unit
,
236 "Installed new job %s/%s as %u",
237 j
->unit
->id
, job_type_to_string(j
->type
), (unsigned) j
->id
);
239 job_add_to_gc_queue(j
);
244 int job_install_deserialized(Job
*j
) {
247 assert(!j
->installed
);
249 if (j
->type
< 0 || j
->type
>= _JOB_TYPE_MAX_IN_TRANSACTION
) {
250 log_debug("Invalid job type %s in deserialization.", strna(job_type_to_string(j
->type
)));
254 pj
= (j
->type
== JOB_NOP
) ? &j
->unit
->nop_job
: &j
->unit
->job
;
256 log_unit_debug(j
->unit
, "Unit already has a job installed. Not installing deserialized job.");
264 if (j
->state
== JOB_RUNNING
)
265 j
->unit
->manager
->n_running_jobs
++;
267 log_unit_debug(j
->unit
,
268 "Reinstalled deserialized job %s/%s as %u",
269 j
->unit
->id
, job_type_to_string(j
->type
), (unsigned) j
->id
);
273 JobDependency
* job_dependency_new(Job
*subject
, Job
*object
, bool matters
, bool conflicts
) {
278 /* Adds a new job link, which encodes that the 'subject' job
279 * needs the 'object' job in some way. If 'subject' is NULL
280 * this means the 'anchor' job (i.e. the one the user
281 * explicitly asked for) is the requester. */
283 l
= new0(JobDependency
, 1);
287 l
->subject
= subject
;
289 l
->matters
= matters
;
290 l
->conflicts
= conflicts
;
293 LIST_PREPEND(subject
, subject
->subject_list
, l
);
295 LIST_PREPEND(object
, object
->object_list
, l
);
300 void job_dependency_free(JobDependency
*l
) {
304 LIST_REMOVE(subject
, l
->subject
->subject_list
, l
);
306 LIST_REMOVE(object
, l
->object
->object_list
, l
);
311 void job_dump(Job
*j
, FILE*f
, const char *prefix
) {
315 prefix
= strempty(prefix
);
319 "%s\tAction: %s -> %s\n"
321 "%s\tIrreversible: %s\n"
324 prefix
, j
->unit
->id
, job_type_to_string(j
->type
),
325 prefix
, job_state_to_string(j
->state
),
326 prefix
, yes_no(j
->irreversible
),
327 prefix
, yes_no(job_may_gc(j
)));
331 * Merging is commutative, so imagine the matrix as symmetric. We store only
332 * its lower triangle to avoid duplication. We don't store the main diagonal,
333 * because A merged with A is simply A.
335 * If the resulting type is collapsed immediately afterwards (to get rid of
336 * the JOB_RELOAD_OR_START, which lies outside the lookup function's domain),
337 * the following properties hold:
339 * Merging is associative! A merged with B, and then merged with C is the same
340 * as A merged with the result of B merged with C.
342 * Mergeability is transitive! If A can be merged with B and B with C then
345 * Also, if A merged with B cannot be merged with C, then either A or B cannot
346 * be merged with C either.
348 static const JobType job_merging_table
[] = {
349 /* What \ With * JOB_START JOB_VERIFY_ACTIVE JOB_STOP JOB_RELOAD */
350 /*********************************************************************************/
352 /*JOB_VERIFY_ACTIVE */ JOB_START
,
353 /*JOB_STOP */ -1, -1,
354 /*JOB_RELOAD */ JOB_RELOAD_OR_START
, JOB_RELOAD
, -1,
355 /*JOB_RESTART */ JOB_RESTART
, JOB_RESTART
, -1, JOB_RESTART
,
358 JobType
job_type_lookup_merge(JobType a
, JobType b
) {
359 assert_cc(ELEMENTSOF(job_merging_table
) == _JOB_TYPE_MAX_MERGING
* (_JOB_TYPE_MAX_MERGING
- 1) / 2);
360 assert(a
>= 0 && a
< _JOB_TYPE_MAX_MERGING
);
361 assert(b
>= 0 && b
< _JOB_TYPE_MAX_MERGING
);
372 return job_merging_table
[(a
- 1) * a
/ 2 + b
];
375 bool job_type_is_redundant(JobType a
, UnitActiveState b
) {
379 return IN_SET(b
, UNIT_ACTIVE
, UNIT_RELOADING
);
382 return IN_SET(b
, UNIT_INACTIVE
, UNIT_FAILED
);
384 case JOB_VERIFY_ACTIVE
:
385 return IN_SET(b
, UNIT_ACTIVE
, UNIT_RELOADING
);
393 b
== UNIT_ACTIVATING
;
399 assert_not_reached("Invalid job type");
403 JobType
job_type_collapse(JobType t
, Unit
*u
) {
408 case JOB_TRY_RESTART
:
409 s
= unit_active_state(u
);
410 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s
))
416 s
= unit_active_state(u
);
417 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s
))
422 case JOB_RELOAD_OR_START
:
423 s
= unit_active_state(u
);
424 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s
))
434 int job_type_merge_and_collapse(JobType
*a
, JobType b
, Unit
*u
) {
437 t
= job_type_lookup_merge(*a
, b
);
441 *a
= job_type_collapse(t
, u
);
445 static bool job_is_runnable(Job
*j
) {
451 assert(j
->installed
);
453 /* Checks whether there is any job running for the units this
454 * job needs to be running after (in the case of a 'positive'
455 * job type) or before (in the case of a 'negative' job
458 /* Note that unit types have a say in what is runnable,
459 * too. For example, if they return -EAGAIN from
460 * unit_start() they can indicate they are not
463 /* First check if there is an override */
467 if (j
->type
== JOB_NOP
)
470 if (IN_SET(j
->type
, JOB_START
, JOB_VERIFY_ACTIVE
, JOB_RELOAD
)) {
471 /* Immediate result is that the job is or might be
472 * started. In this case let's wait for the
473 * dependencies, regardless whether they are
474 * starting or stopping something. */
476 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
)
481 /* Also, if something else is being stopped and we should
482 * change state after it, then let's wait. */
484 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
)
486 IN_SET(other
->job
->type
, JOB_STOP
, JOB_RESTART
))
489 /* This means that for a service a and a service b where b
490 * shall be started after a:
492 * start a + start b → 1st step start a, 2nd step start b
493 * start a + stop b → 1st step stop b, 2nd step start a
494 * stop a + start b → 1st step stop a, 2nd step start b
495 * stop a + stop b → 1st step stop b, 2nd step stop a
497 * This has the side effect that restarts are properly
498 * synchronized too. */
503 static void job_change_type(Job
*j
, JobType newtype
) {
506 log_unit_debug(j
->unit
,
507 "Converting job %s/%s -> %s/%s",
508 j
->unit
->id
, job_type_to_string(j
->type
),
509 j
->unit
->id
, job_type_to_string(newtype
));
514 static int job_perform_on_unit(Job
**j
) {
521 /* While we execute this operation the job might go away (for
522 * example: because it finishes immediately or is replaced by
523 * a new, conflicting job.) To make sure we don't access a
524 * freed job later on we store the id here, so that we can
525 * verify the job is still valid. */
552 assert_not_reached("Invalid job type");
555 /* Log if the job still exists and the start/stop/reload function
556 * actually did something. */
557 *j
= manager_get_job(m
, id
);
559 unit_status_emit_starting_stopping_reloading(u
, t
);
564 int job_run_and_invalidate(Job
*j
) {
568 assert(j
->installed
);
569 assert(j
->type
< _JOB_TYPE_MAX_IN_TRANSACTION
);
570 assert(j
->in_run_queue
);
572 LIST_REMOVE(run_queue
, j
->manager
->run_queue
, j
);
573 j
->in_run_queue
= false;
575 if (j
->state
!= JOB_WAITING
)
578 if (!job_is_runnable(j
))
581 job_start_timer(j
, true);
582 job_set_state(j
, JOB_RUNNING
);
583 job_add_to_dbus_queue(j
);
587 case JOB_VERIFY_ACTIVE
: {
588 UnitActiveState t
= unit_active_state(j
->unit
);
589 if (UNIT_IS_ACTIVE_OR_RELOADING(t
))
591 else if (t
== UNIT_ACTIVATING
)
601 r
= job_perform_on_unit(&j
);
603 /* If the unit type does not support starting/stopping,
604 * then simply wait. */
610 r
= job_perform_on_unit(&j
);
618 assert_not_reached("Unknown job type");
623 r
= job_finish_and_invalidate(j
, JOB_DONE
, true, true);
624 else if (r
== -EBADR
)
625 r
= job_finish_and_invalidate(j
, JOB_SKIPPED
, true, false);
626 else if (r
== -ENOEXEC
)
627 r
= job_finish_and_invalidate(j
, JOB_INVALID
, true, false);
628 else if (r
== -EPROTO
)
629 r
= job_finish_and_invalidate(j
, JOB_ASSERT
, true, false);
630 else if (r
== -EOPNOTSUPP
)
631 r
= job_finish_and_invalidate(j
, JOB_UNSUPPORTED
, true, false);
632 else if (r
== -ENOLINK
)
633 r
= job_finish_and_invalidate(j
, JOB_DEPENDENCY
, true, false);
634 else if (r
== -ESTALE
)
635 r
= job_finish_and_invalidate(j
, JOB_ONCE
, true, false);
636 else if (r
== -EAGAIN
)
637 job_set_state(j
, JOB_WAITING
);
639 r
= job_finish_and_invalidate(j
, JOB_FAILED
, true, false);
645 _pure_
static const char *job_get_status_message_format(Unit
*u
, JobType t
, JobResult result
) {
647 static const char *const generic_finished_start_job
[_JOB_RESULT_MAX
] = {
648 [JOB_DONE
] = "Started %s.",
649 [JOB_TIMEOUT
] = "Timed out starting %s.",
650 [JOB_FAILED
] = "Failed to start %s.",
651 [JOB_DEPENDENCY
] = "Dependency failed for %s.",
652 [JOB_ASSERT
] = "Assertion failed for %s.",
653 [JOB_UNSUPPORTED
] = "Starting of %s not supported.",
654 [JOB_COLLECTED
] = "Unnecessary job for %s was removed.",
655 [JOB_ONCE
] = "Unit %s has been started before and cannot be started again."
657 static const char *const generic_finished_stop_job
[_JOB_RESULT_MAX
] = {
658 [JOB_DONE
] = "Stopped %s.",
659 [JOB_FAILED
] = "Stopped (with error) %s.",
660 [JOB_TIMEOUT
] = "Timed out stopping %s.",
662 static const char *const generic_finished_reload_job
[_JOB_RESULT_MAX
] = {
663 [JOB_DONE
] = "Reloaded %s.",
664 [JOB_FAILED
] = "Reload failed for %s.",
665 [JOB_TIMEOUT
] = "Timed out reloading %s.",
667 /* When verify-active detects the unit is inactive, report it.
668 * Most likely a DEPEND warning from a requisiting unit will
669 * occur next and it's nice to see what was requisited. */
670 static const char *const generic_finished_verify_active_job
[_JOB_RESULT_MAX
] = {
671 [JOB_SKIPPED
] = "%s is not active.",
674 const UnitStatusMessageFormats
*format_table
;
679 assert(t
< _JOB_TYPE_MAX
);
681 if (IN_SET(t
, JOB_START
, JOB_STOP
, JOB_RESTART
)) {
682 format_table
= &UNIT_VTABLE(u
)->status_message_formats
;
684 format
= t
== JOB_START
? format_table
->finished_start_job
[result
] :
685 format_table
->finished_stop_job
[result
];
691 /* Return generic strings */
693 return generic_finished_start_job
[result
];
694 else if (IN_SET(t
, JOB_STOP
, JOB_RESTART
))
695 return generic_finished_stop_job
[result
];
696 else if (t
== JOB_RELOAD
)
697 return generic_finished_reload_job
[result
];
698 else if (t
== JOB_VERIFY_ACTIVE
)
699 return generic_finished_verify_active_job
[result
];
704 static const struct {
705 const char *color
, *word
;
706 } job_print_status_messages
[_JOB_RESULT_MAX
] = {
707 [JOB_DONE
] = { ANSI_OK_COLOR
, " OK " },
708 [JOB_TIMEOUT
] = { ANSI_HIGHLIGHT_RED
, " TIME " },
709 [JOB_FAILED
] = { ANSI_HIGHLIGHT_RED
, "FAILED" },
710 [JOB_DEPENDENCY
] = { ANSI_HIGHLIGHT_YELLOW
, "DEPEND" },
711 [JOB_SKIPPED
] = { ANSI_HIGHLIGHT
, " INFO " },
712 [JOB_ASSERT
] = { ANSI_HIGHLIGHT_YELLOW
, "ASSERT" },
713 [JOB_UNSUPPORTED
] = { ANSI_HIGHLIGHT_YELLOW
, "UNSUPP" },
715 [JOB_ONCE
] = { ANSI_HIGHLIGHT_RED
, " ONCE " },
718 static void job_print_status_message(Unit
*u
, JobType t
, JobResult result
) {
724 assert(t
< _JOB_TYPE_MAX
);
726 /* Reload status messages have traditionally not been printed to console. */
730 if (!job_print_status_messages
[result
].word
)
733 format
= job_get_status_message_format(u
, t
, result
);
737 if (log_get_show_color())
738 status
= strjoina(job_print_status_messages
[result
].color
,
739 job_print_status_messages
[result
].word
,
742 status
= job_print_status_messages
[result
].word
;
744 if (result
!= JOB_DONE
)
745 manager_flip_auto_status(u
->manager
, true);
747 DISABLE_WARNING_FORMAT_NONLITERAL
;
748 unit_status_printf(u
, status
, format
);
751 if (t
== JOB_START
&& result
== JOB_FAILED
) {
752 _cleanup_free_
char *quoted
;
754 quoted
= shell_maybe_quote(u
->id
, ESCAPE_BACKSLASH
);
755 manager_status_printf(u
->manager
, STATUS_TYPE_NORMAL
, NULL
, "See 'systemctl status %s' for details.", strna(quoted
));
759 static void job_log_status_message(Unit
*u
, JobType t
, JobResult result
) {
760 const char *format
, *mid
;
762 static const int job_result_log_level
[_JOB_RESULT_MAX
] = {
763 [JOB_DONE
] = LOG_INFO
,
764 [JOB_CANCELED
] = LOG_INFO
,
765 [JOB_TIMEOUT
] = LOG_ERR
,
766 [JOB_FAILED
] = LOG_ERR
,
767 [JOB_DEPENDENCY
] = LOG_WARNING
,
768 [JOB_SKIPPED
] = LOG_NOTICE
,
769 [JOB_INVALID
] = LOG_INFO
,
770 [JOB_ASSERT
] = LOG_WARNING
,
771 [JOB_UNSUPPORTED
] = LOG_WARNING
,
772 [JOB_COLLECTED
] = LOG_INFO
,
773 [JOB_ONCE
] = LOG_ERR
,
778 assert(t
< _JOB_TYPE_MAX
);
780 /* Skip printing if output goes to the console, and job_print_status_message()
781 will actually print something to the console. */
782 if (log_on_console() && job_print_status_messages
[result
].word
)
785 format
= job_get_status_message_format(u
, t
, result
);
789 /* The description might be longer than the buffer, but that's OK,
790 * we'll just truncate it here. Note that we use snprintf() rather than
791 * xsprintf() on purpose here: we are fine with truncation and don't
792 * consider that an error. */
793 DISABLE_WARNING_FORMAT_NONLITERAL
;
794 (void) snprintf(buf
, sizeof(buf
), format
, unit_description(u
));
800 if (result
== JOB_DONE
)
801 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_STARTED_STR
;
803 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILED_STR
;
807 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_RELOADED_STR
;
812 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_STOPPED_STR
;
816 log_struct(job_result_log_level
[result
],
817 LOG_MESSAGE("%s", buf
),
818 "JOB_TYPE=%s", job_type_to_string(t
),
819 "JOB_RESULT=%s", job_result_to_string(result
),
821 LOG_UNIT_INVOCATION_ID(u
),
826 log_struct(job_result_log_level
[result
],
827 LOG_MESSAGE("%s", buf
),
828 "JOB_TYPE=%s", job_type_to_string(t
),
829 "JOB_RESULT=%s", job_result_to_string(result
),
831 LOG_UNIT_INVOCATION_ID(u
),
836 static void job_emit_status_message(Unit
*u
, JobType t
, JobResult result
) {
839 /* No message if the job did not actually do anything due to failed condition. */
840 if (t
== JOB_START
&& result
== JOB_DONE
&& !u
->condition_result
)
843 job_log_status_message(u
, t
, result
);
844 job_print_status_message(u
, t
, result
);
847 static void job_fail_dependencies(Unit
*u
, UnitDependency d
) {
854 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[d
], i
) {
859 if (!IN_SET(j
->type
, JOB_START
, JOB_VERIFY_ACTIVE
))
862 job_finish_and_invalidate(j
, JOB_DEPENDENCY
, true, false);
866 static int job_save_pending_finished_job(Job
*j
) {
871 r
= set_ensure_allocated(&j
->manager
->pending_finished_jobs
, NULL
);
876 return set_put(j
->manager
->pending_finished_jobs
, j
);
879 int job_finish_and_invalidate(Job
*j
, JobResult result
, bool recursive
, bool already
) {
887 assert(j
->installed
);
888 assert(j
->type
< _JOB_TYPE_MAX_IN_TRANSACTION
);
895 log_unit_debug(u
, "Job %s/%s finished, result=%s", u
->id
, job_type_to_string(t
), job_result_to_string(result
));
897 /* If this job did nothing to respective unit we don't log the status message */
899 job_emit_status_message(u
, t
, result
);
901 /* Patch restart jobs so that they become normal start jobs */
902 if (result
== JOB_DONE
&& t
== JOB_RESTART
) {
904 job_change_type(j
, JOB_START
);
905 job_set_state(j
, JOB_WAITING
);
907 job_add_to_dbus_queue(j
);
908 job_add_to_run_queue(j
);
909 job_add_to_gc_queue(j
);
914 if (IN_SET(result
, JOB_FAILED
, JOB_INVALID
))
915 j
->manager
->n_failed_jobs
++;
918 /* Keep jobs started before the reload to send singal later, free all others */
919 if (!MANAGER_IS_RELOADING(j
->manager
) ||
921 job_save_pending_finished_job(j
) < 0)
924 /* Fail depending jobs on failure */
925 if (result
!= JOB_DONE
&& recursive
) {
926 if (IN_SET(t
, JOB_START
, JOB_VERIFY_ACTIVE
)) {
927 job_fail_dependencies(u
, UNIT_REQUIRED_BY
);
928 job_fail_dependencies(u
, UNIT_REQUISITE_OF
);
929 job_fail_dependencies(u
, UNIT_BOUND_BY
);
930 } else if (t
== JOB_STOP
)
931 job_fail_dependencies(u
, UNIT_CONFLICTED_BY
);
934 /* Trigger OnFailure dependencies that are not generated by
935 * the unit itself. We don't treat JOB_CANCELED as failure in
936 * this context. And JOB_FAILURE is already handled by the
938 if (IN_SET(result
, JOB_TIMEOUT
, JOB_DEPENDENCY
)) {
939 log_struct(LOG_NOTICE
,
940 "JOB_TYPE=%s", job_type_to_string(t
),
941 "JOB_RESULT=%s", job_result_to_string(result
),
943 LOG_UNIT_MESSAGE(u
, "Job %s/%s failed with result '%s'.",
945 job_type_to_string(t
),
946 job_result_to_string(result
)),
949 unit_start_on_failure(u
);
952 unit_trigger_notify(u
);
955 /* Try to start the next jobs that can be started */
956 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_AFTER
], i
)
958 job_add_to_run_queue(other
->job
);
959 job_add_to_gc_queue(other
->job
);
961 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BEFORE
], i
)
963 job_add_to_run_queue(other
->job
);
964 job_add_to_gc_queue(other
->job
);
967 manager_check_finished(u
->manager
);
972 static int job_dispatch_timer(sd_event_source
*s
, uint64_t monotonic
, void *userdata
) {
977 assert(s
== j
->timer_event_source
);
979 log_unit_warning(j
->unit
, "Job %s/%s timed out.", j
->unit
->id
, job_type_to_string(j
->type
));
982 job_finish_and_invalidate(j
, JOB_TIMEOUT
, true, false);
984 emergency_action(u
->manager
, u
->job_timeout_action
, u
->job_timeout_reboot_arg
, "job timed out");
989 int job_start_timer(Job
*j
, bool job_running
) {
991 usec_t timeout_time
, old_timeout_time
;
994 j
->begin_running_usec
= now(CLOCK_MONOTONIC
);
996 if (j
->unit
->job_running_timeout
== USEC_INFINITY
)
999 timeout_time
= usec_add(j
->begin_running_usec
, j
->unit
->job_running_timeout
);
1001 if (j
->timer_event_source
) {
1002 /* Update only if JobRunningTimeoutSec= results in earlier timeout */
1003 r
= sd_event_source_get_time(j
->timer_event_source
, &old_timeout_time
);
1007 if (old_timeout_time
<= timeout_time
)
1010 return sd_event_source_set_time(j
->timer_event_source
, timeout_time
);
1013 if (j
->timer_event_source
)
1016 j
->begin_usec
= now(CLOCK_MONOTONIC
);
1018 if (j
->unit
->job_timeout
== USEC_INFINITY
)
1021 timeout_time
= usec_add(j
->begin_usec
, j
->unit
->job_timeout
);
1024 r
= sd_event_add_time(
1026 &j
->timer_event_source
,
1029 job_dispatch_timer
, j
);
1033 (void) sd_event_source_set_description(j
->timer_event_source
, "job-start");
1038 void job_add_to_run_queue(Job
*j
) {
1040 assert(j
->installed
);
1042 if (j
->in_run_queue
)
1045 if (!j
->manager
->run_queue
)
1046 sd_event_source_set_enabled(j
->manager
->run_queue_event_source
, SD_EVENT_ONESHOT
);
1048 LIST_PREPEND(run_queue
, j
->manager
->run_queue
, j
);
1049 j
->in_run_queue
= true;
1052 void job_add_to_dbus_queue(Job
*j
) {
1054 assert(j
->installed
);
1056 if (j
->in_dbus_queue
)
1059 /* We don't check if anybody is subscribed here, since this
1060 * job might just have been created and not yet assigned to a
1061 * connection/client. */
1063 LIST_PREPEND(dbus_queue
, j
->manager
->dbus_job_queue
, j
);
1064 j
->in_dbus_queue
= true;
1067 char *job_dbus_path(Job
*j
) {
1072 if (asprintf(&p
, "/org/freedesktop/systemd1/job/%"PRIu32
, j
->id
) < 0)
1078 int job_serialize(Job
*j
, FILE *f
) {
1082 fprintf(f
, "job-id=%u\n", j
->id
);
1083 fprintf(f
, "job-type=%s\n", job_type_to_string(j
->type
));
1084 fprintf(f
, "job-state=%s\n", job_state_to_string(j
->state
));
1085 fprintf(f
, "job-irreversible=%s\n", yes_no(j
->irreversible
));
1086 fprintf(f
, "job-sent-dbus-new-signal=%s\n", yes_no(j
->sent_dbus_new_signal
));
1087 fprintf(f
, "job-ignore-order=%s\n", yes_no(j
->ignore_order
));
1089 if (j
->begin_usec
> 0)
1090 fprintf(f
, "job-begin="USEC_FMT
"\n", j
->begin_usec
);
1091 if (j
->begin_running_usec
> 0)
1092 fprintf(f
, "job-begin-running="USEC_FMT
"\n", j
->begin_running_usec
);
1094 bus_track_serialize(j
->bus_track
, f
, "subscribed");
1101 int job_deserialize(Job
*j
, FILE *f
) {
1106 char line
[LINE_MAX
], *l
, *v
;
1109 if (!fgets(line
, sizeof(line
), f
)) {
1122 k
= strcspn(l
, "=");
1130 if (streq(l
, "job-id")) {
1132 if (safe_atou32(v
, &j
->id
) < 0)
1133 log_debug("Failed to parse job id value %s", v
);
1135 } else if (streq(l
, "job-type")) {
1138 t
= job_type_from_string(v
);
1140 log_debug("Failed to parse job type %s", v
);
1141 else if (t
>= _JOB_TYPE_MAX_IN_TRANSACTION
)
1142 log_debug("Cannot deserialize job of type %s", v
);
1146 } else if (streq(l
, "job-state")) {
1149 s
= job_state_from_string(v
);
1151 log_debug("Failed to parse job state %s", v
);
1153 job_set_state(j
, s
);
1155 } else if (streq(l
, "job-irreversible")) {
1158 b
= parse_boolean(v
);
1160 log_debug("Failed to parse job irreversible flag %s", v
);
1162 j
->irreversible
= j
->irreversible
|| b
;
1164 } else if (streq(l
, "job-sent-dbus-new-signal")) {
1167 b
= parse_boolean(v
);
1169 log_debug("Failed to parse job sent_dbus_new_signal flag %s", v
);
1171 j
->sent_dbus_new_signal
= j
->sent_dbus_new_signal
|| b
;
1173 } else if (streq(l
, "job-ignore-order")) {
1176 b
= parse_boolean(v
);
1178 log_debug("Failed to parse job ignore_order flag %s", v
);
1180 j
->ignore_order
= j
->ignore_order
|| b
;
1182 } else if (streq(l
, "job-begin")) {
1183 unsigned long long ull
;
1185 if (sscanf(v
, "%llu", &ull
) != 1)
1186 log_debug("Failed to parse job-begin value %s", v
);
1188 j
->begin_usec
= ull
;
1190 } else if (streq(l
, "job-begin-running")) {
1191 unsigned long long ull
;
1193 if (sscanf(v
, "%llu", &ull
) != 1)
1194 log_debug("Failed to parse job-begin-running value %s", v
);
1196 j
->begin_running_usec
= ull
;
1198 } else if (streq(l
, "subscribed")) {
1200 if (strv_extend(&j
->deserialized_clients
, v
) < 0)
1206 int job_coldplug(Job
*j
) {
1208 usec_t timeout_time
= USEC_INFINITY
;
1212 /* After deserialization is complete and the bus connection
1213 * set up again, let's start watching our subscribers again */
1214 (void) bus_job_coldplug_bus_track(j
);
1216 if (j
->state
== JOB_WAITING
)
1217 job_add_to_run_queue(j
);
1219 /* Maybe due to new dependencies we don't actually need this job anymore? */
1220 job_add_to_gc_queue(j
);
1222 /* Create timer only when job began or began running and the respective timeout is finite.
1223 * Follow logic of job_start_timer() if both timeouts are finite */
1224 if (j
->begin_usec
== 0)
1227 if (j
->unit
->job_timeout
!= USEC_INFINITY
)
1228 timeout_time
= usec_add(j
->begin_usec
, j
->unit
->job_timeout
);
1230 if (j
->begin_running_usec
> 0 && j
->unit
->job_running_timeout
!= USEC_INFINITY
)
1231 timeout_time
= MIN(timeout_time
, usec_add(j
->begin_running_usec
, j
->unit
->job_running_timeout
));
1233 if (timeout_time
== USEC_INFINITY
)
1236 j
->timer_event_source
= sd_event_source_unref(j
->timer_event_source
);
1238 r
= sd_event_add_time(
1240 &j
->timer_event_source
,
1243 job_dispatch_timer
, j
);
1245 log_debug_errno(r
, "Failed to restart timeout for job: %m");
1247 (void) sd_event_source_set_description(j
->timer_event_source
, "job-timeout");
1252 void job_shutdown_magic(Job
*j
) {
1255 /* The shutdown target gets some special treatment here: we
1256 * tell the kernel to begin with flushing its disk caches, to
1257 * optimize shutdown time a bit. Ideally we wouldn't hardcode
1258 * this magic into PID 1. However all other processes aren't
1259 * options either since they'd exit much sooner than PID 1 and
1260 * asynchronous sync() would cause their exit to be
1263 if (j
->type
!= JOB_START
)
1266 if (!MANAGER_IS_SYSTEM(j
->unit
->manager
))
1269 if (!unit_has_name(j
->unit
, SPECIAL_SHUTDOWN_TARGET
))
1272 /* In case messages on console has been disabled on boot */
1273 j
->unit
->manager
->no_console_output
= false;
1275 if (detect_container() > 0)
1278 (void) asynchronous_sync(NULL
);
1281 int job_get_timeout(Job
*j
, usec_t
*timeout
) {
1282 usec_t x
= USEC_INFINITY
, y
= USEC_INFINITY
;
1288 if (j
->timer_event_source
) {
1289 r
= sd_event_source_get_time(j
->timer_event_source
, &x
);
1294 if (UNIT_VTABLE(u
)->get_timeout
) {
1295 r
= UNIT_VTABLE(u
)->get_timeout(u
, &y
);
1300 if (x
== USEC_INFINITY
&& y
== USEC_INFINITY
)
1303 *timeout
= MIN(x
, y
);
1307 bool job_may_gc(Job
*j
) {
1314 /* Checks whether this job should be GC'ed away. We only do this for jobs of units that have no effect on their
1315 * own and just track external state. For now the only unit type that qualifies for this are .device units.
1316 * Returns true if the job can be collected. */
1318 if (!UNIT_VTABLE(j
->unit
)->gc_jobs
)
1321 if (sd_bus_track_count(j
->bus_track
) > 0)
1324 /* FIXME: So this is a bit ugly: for now we don't properly track references made via private bus connections
1325 * (because it's nasty, as sd_bus_track doesn't apply to it). We simply remember that the job was once
1326 * referenced by one, and reset this whenever we notice that no private bus connections are around. This means
1327 * the GC is a bit too conservative when it comes to jobs created by private bus connections. */
1328 if (j
->ref_by_private_bus
) {
1329 if (set_isempty(j
->unit
->manager
->private_buses
))
1330 j
->ref_by_private_bus
= false;
1335 if (j
->type
== JOB_NOP
)
1338 /* If a job is ordered after ours, and is to be started, then it needs to wait for us, regardless if we stop or
1339 * start, hence let's not GC in that case. */
1340 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
) {
1344 if (other
->job
->ignore_order
)
1347 if (IN_SET(other
->job
->type
, JOB_START
, JOB_VERIFY_ACTIVE
, JOB_RELOAD
))
1351 /* If we are going down, but something else is ordered After= us, then it needs to wait for us */
1352 if (IN_SET(j
->type
, JOB_STOP
, JOB_RESTART
))
1353 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
) {
1357 if (other
->job
->ignore_order
)
1363 /* The logic above is kinda the inverse of the job_is_runnable() logic. Specifically, if the job "we" is
1364 * ordered before the job "other":
1366 * we start + other start → stay
1367 * we start + other stop → gc
1368 * we stop + other start → stay
1369 * we stop + other stop → gc
1371 * "we" are ordered after "other":
1373 * we start + other start → gc
1374 * we start + other stop → gc
1375 * we stop + other start → stay
1376 * we stop + other stop → stay
1383 void job_add_to_gc_queue(Job
*j
) {
1392 LIST_PREPEND(gc_queue
, j
->unit
->manager
->gc_job_queue
, j
);
1393 j
->in_gc_queue
= true;
1396 static int job_compare(const void *a
, const void *b
) {
1397 Job
*x
= *(Job
**) a
, *y
= *(Job
**) b
;
1407 static size_t sort_job_list(Job
**list
, size_t n
) {
1408 Job
*previous
= NULL
;
1411 /* Order by numeric IDs */
1412 qsort_safe(list
, n
, sizeof(Job
*), job_compare
);
1414 /* Filter out duplicates */
1415 for (a
= 0, b
= 0; a
< n
; a
++) {
1417 if (previous
== list
[a
])
1420 previous
= list
[b
++] = list
[a
];
1426 int job_get_before(Job
*j
, Job
*** ret
) {
1427 _cleanup_free_ Job
** list
= NULL
;
1428 size_t n
= 0, n_allocated
= 0;
1433 /* Returns a list of all pending jobs that need to finish before this job may be started. */
1438 if (j
->ignore_order
) {
1443 if (IN_SET(j
->type
, JOB_START
, JOB_VERIFY_ACTIVE
, JOB_RELOAD
)) {
1445 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
) {
1449 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1451 list
[n
++] = other
->job
;
1455 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
) {
1459 if (!IN_SET(other
->job
->type
, JOB_STOP
, JOB_RESTART
))
1462 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1464 list
[n
++] = other
->job
;
1467 n
= sort_job_list(list
, n
);
1469 *ret
= TAKE_PTR(list
);
1474 int job_get_after(Job
*j
, Job
*** ret
) {
1475 _cleanup_free_ Job
** list
= NULL
;
1476 size_t n
= 0, n_allocated
= 0;
1484 /* Returns a list of all pending jobs that are waiting for this job to finish. */
1486 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
) {
1490 if (other
->job
->ignore_order
)
1493 if (!IN_SET(other
->job
->type
, JOB_START
, JOB_VERIFY_ACTIVE
, JOB_RELOAD
))
1496 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1498 list
[n
++] = other
->job
;
1501 if (IN_SET(j
->type
, JOB_STOP
, JOB_RESTART
)) {
1503 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
) {
1507 if (other
->job
->ignore_order
)
1510 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1512 list
[n
++] = other
->job
;
1516 n
= sort_job_list(list
, n
);
1518 *ret
= TAKE_PTR(list
);
1523 static const char* const job_state_table
[_JOB_STATE_MAX
] = {
1524 [JOB_WAITING
] = "waiting",
1525 [JOB_RUNNING
] = "running",
1528 DEFINE_STRING_TABLE_LOOKUP(job_state
, JobState
);
1530 static const char* const job_type_table
[_JOB_TYPE_MAX
] = {
1531 [JOB_START
] = "start",
1532 [JOB_VERIFY_ACTIVE
] = "verify-active",
1533 [JOB_STOP
] = "stop",
1534 [JOB_RELOAD
] = "reload",
1535 [JOB_RELOAD_OR_START
] = "reload-or-start",
1536 [JOB_RESTART
] = "restart",
1537 [JOB_TRY_RESTART
] = "try-restart",
1538 [JOB_TRY_RELOAD
] = "try-reload",
1542 DEFINE_STRING_TABLE_LOOKUP(job_type
, JobType
);
1544 static const char* const job_mode_table
[_JOB_MODE_MAX
] = {
1545 [JOB_FAIL
] = "fail",
1546 [JOB_REPLACE
] = "replace",
1547 [JOB_REPLACE_IRREVERSIBLY
] = "replace-irreversibly",
1548 [JOB_ISOLATE
] = "isolate",
1549 [JOB_FLUSH
] = "flush",
1550 [JOB_IGNORE_DEPENDENCIES
] = "ignore-dependencies",
1551 [JOB_IGNORE_REQUIREMENTS
] = "ignore-requirements",
1554 DEFINE_STRING_TABLE_LOOKUP(job_mode
, JobMode
);
1556 static const char* const job_result_table
[_JOB_RESULT_MAX
] = {
1557 [JOB_DONE
] = "done",
1558 [JOB_CANCELED
] = "canceled",
1559 [JOB_TIMEOUT
] = "timeout",
1560 [JOB_FAILED
] = "failed",
1561 [JOB_DEPENDENCY
] = "dependency",
1562 [JOB_SKIPPED
] = "skipped",
1563 [JOB_INVALID
] = "invalid",
1564 [JOB_ASSERT
] = "assert",
1565 [JOB_UNSUPPORTED
] = "unsupported",
1566 [JOB_COLLECTED
] = "collected",
1567 [JOB_ONCE
] = "once",
1570 DEFINE_STRING_TABLE_LOOKUP(job_result
, JobResult
);
1572 const char* job_type_to_access_method(JobType t
) {
1574 assert(t
< _JOB_TYPE_MAX
);
1576 if (IN_SET(t
, JOB_START
, JOB_RESTART
, JOB_TRY_RESTART
))
1578 else if (t
== JOB_STOP
)