1 /* SPDX-License-Identifier: LGPL-2.1+ */
6 #include "sd-messages.h"
8 #include "alloc-util.h"
17 #include "parse-util.h"
18 #include "serialize.h"
21 #include "stdio-util.h"
22 #include "string-table.h"
23 #include "string-util.h"
25 #include "terminal-util.h"
29 Job
* job_new_raw(Unit
*unit
) {
32 /* used for deserialization */
41 .manager
= unit
->manager
,
43 .type
= _JOB_TYPE_INVALID
,
49 Job
* job_new(Unit
*unit
, JobType type
) {
52 assert(type
< _JOB_TYPE_MAX
);
54 j
= job_new_raw(unit
);
58 j
->id
= j
->manager
->current_job_id
++;
61 /* We don't link it here, that's what job_dependency() is for */
66 void job_unlink(Job
*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
);
74 if (j
->in_run_queue
) {
75 LIST_REMOVE(run_queue
, j
->manager
->run_queue
, j
);
76 j
->in_run_queue
= false;
79 if (j
->in_dbus_queue
) {
80 LIST_REMOVE(dbus_queue
, j
->manager
->dbus_job_queue
, j
);
81 j
->in_dbus_queue
= false;
85 LIST_REMOVE(gc_queue
, j
->manager
->gc_job_queue
, j
);
86 j
->in_gc_queue
= false;
89 j
->timer_event_source
= sd_event_source_unref(j
->timer_event_source
);
92 void job_free(Job
*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
);
102 sd_bus_track_unref(j
->bus_track
);
103 strv_free(j
->deserialized_clients
);
108 static void job_set_state(Job
*j
, JobState state
) {
111 assert(state
< _JOB_STATE_MAX
);
113 if (j
->state
== state
)
121 if (j
->state
== JOB_RUNNING
)
122 j
->unit
->manager
->n_running_jobs
++;
124 assert(j
->state
== JOB_WAITING
);
125 assert(j
->unit
->manager
->n_running_jobs
> 0);
127 j
->unit
->manager
->n_running_jobs
--;
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
);
134 void job_uninstall(Job
*j
) {
137 assert(j
->installed
);
139 job_set_state(j
, JOB_WAITING
);
141 pj
= (j
->type
== JOB_NOP
) ? &j
->unit
->nop_job
: &j
->unit
->job
;
144 /* Detach from next 'bigger' objects */
146 /* daemon-reload should be transparent to job observers */
147 if (!MANAGER_IS_RELOADING(j
->manager
))
148 bus_job_send_removed_signal(j
);
152 unit_add_to_gc_queue(j
->unit
);
154 hashmap_remove(j
->manager
->jobs
, UINT32_TO_PTR(j
->id
));
155 j
->installed
= false;
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
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
;
175 static void job_merge_into_installed(Job
*j
, Job
*other
) {
176 assert(j
->installed
);
177 assert(j
->unit
== other
->unit
);
179 if (j
->type
!= JOB_NOP
)
180 assert_se(job_type_merge_and_collapse(&j
->type
, other
->type
, j
->unit
) == 0);
182 assert(other
->type
== JOB_NOP
);
184 j
->irreversible
= j
->irreversible
|| other
->irreversible
;
185 j
->ignore_order
= j
->ignore_order
|| other
->ignore_order
;
188 Job
* job_install(Job
*j
) {
192 assert(!j
->installed
);
193 assert(j
->type
< _JOB_TYPE_MAX_IN_TRANSACTION
);
194 assert(j
->state
== JOB_WAITING
);
196 pj
= (j
->type
== JOB_NOP
) ? &j
->unit
->nop_job
: &j
->unit
->job
;
200 if (job_type_is_conflicting(uj
->type
, j
->type
))
201 job_finish_and_invalidate(uj
, JOB_CANCELED
, false, false);
203 /* not conflicting, i.e. mergeable */
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
);
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
);
222 job_set_state(uj
, JOB_WAITING
);
228 /* Install the job */
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
);
237 job_add_to_gc_queue(j
);
242 int job_install_deserialized(Job
*j
) {
245 assert(!j
->installed
);
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
)));
252 pj
= (j
->type
== JOB_NOP
) ? &j
->unit
->nop_job
: &j
->unit
->job
;
254 log_unit_debug(j
->unit
, "Unit already has a job installed. Not installing deserialized job.");
262 if (j
->state
== JOB_RUNNING
)
263 j
->unit
->manager
->n_running_jobs
++;
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
);
271 JobDependency
* job_dependency_new(Job
*subject
, Job
*object
, bool matters
, bool conflicts
) {
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. */
281 l
= new0(JobDependency
, 1);
285 l
->subject
= subject
;
287 l
->matters
= matters
;
288 l
->conflicts
= conflicts
;
291 LIST_PREPEND(subject
, subject
->subject_list
, l
);
293 LIST_PREPEND(object
, object
->object_list
, l
);
298 void job_dependency_free(JobDependency
*l
) {
302 LIST_REMOVE(subject
, l
->subject
->subject_list
, l
);
304 LIST_REMOVE(object
, l
->object
->object_list
, l
);
309 void job_dump(Job
*j
, FILE*f
, const char *prefix
) {
313 prefix
= strempty(prefix
);
317 "%s\tAction: %s -> %s\n"
319 "%s\tIrreversible: %s\n"
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
)));
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.
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:
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.
340 * Mergeability is transitive! If A can be merged with B and B with C then
343 * Also, if A merged with B cannot be merged with C, then either A or B cannot
344 * be merged with C either.
346 static const JobType job_merging_table
[] = {
347 /* What \ With * JOB_START JOB_VERIFY_ACTIVE JOB_STOP JOB_RELOAD */
348 /*********************************************************************************/
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
,
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
);
370 return job_merging_table
[(a
- 1) * a
/ 2 + b
];
373 bool job_type_is_redundant(JobType a
, UnitActiveState b
) {
377 return IN_SET(b
, UNIT_ACTIVE
, UNIT_RELOADING
);
380 return IN_SET(b
, UNIT_INACTIVE
, UNIT_FAILED
);
382 case JOB_VERIFY_ACTIVE
:
383 return IN_SET(b
, UNIT_ACTIVE
, UNIT_RELOADING
);
391 b
== UNIT_ACTIVATING
;
397 assert_not_reached("Invalid job type");
401 JobType
job_type_collapse(JobType t
, Unit
*u
) {
406 case JOB_TRY_RESTART
:
407 s
= unit_active_state(u
);
408 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s
))
414 s
= unit_active_state(u
);
415 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s
))
420 case JOB_RELOAD_OR_START
:
421 s
= unit_active_state(u
);
422 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s
))
432 int job_type_merge_and_collapse(JobType
*a
, JobType b
, Unit
*u
) {
435 t
= job_type_lookup_merge(*a
, b
);
439 *a
= job_type_collapse(t
, u
);
443 static bool job_is_runnable(Job
*j
) {
449 assert(j
->installed
);
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
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
461 /* First check if there is an override */
465 if (j
->type
== JOB_NOP
)
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. */
474 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
)
479 /* Also, if something else is being stopped and we should
480 * change state after it, then let's wait. */
482 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
)
484 IN_SET(other
->job
->type
, JOB_STOP
, JOB_RESTART
))
487 /* This means that for a service a and a service b where b
488 * shall be started after a:
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
495 * This has the side effect that restarts are properly
496 * synchronized too. */
501 static void job_change_type(Job
*j
, JobType newtype
) {
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
));
512 _pure_
static const char* job_get_begin_status_message_format(Unit
*u
, JobType t
) {
513 const UnitStatusMessageFormats
*format_table
;
519 return "Reloading %s.";
521 assert(IN_SET(t
, JOB_START
, JOB_STOP
));
523 format_table
= &UNIT_VTABLE(u
)->status_message_formats
;
525 format
= format_table
->starting_stopping
[t
== JOB_STOP
];
530 /* Return generic strings */
532 return "Starting %s.";
534 assert(t
== JOB_STOP
);
535 return "Stopping %s.";
539 static void job_print_begin_status_message(Unit
*u
, JobType t
) {
544 /* Reload status messages have traditionally not been printed to console. */
545 if (!IN_SET(t
, JOB_START
, JOB_STOP
))
548 format
= job_get_begin_status_message_format(u
, t
);
550 DISABLE_WARNING_FORMAT_NONLITERAL
;
551 unit_status_printf(u
, "", format
);
555 static void job_log_begin_status_message(Unit
*u
, uint32_t job_id
, JobType t
) {
556 const char *format
, *mid
;
561 assert(t
< _JOB_TYPE_MAX
);
563 if (!IN_SET(t
, JOB_START
, JOB_STOP
, JOB_RELOAD
))
566 if (log_on_console()) /* Skip this if it would only go on the console anyway */
569 /* We log status messages for all units and all operations. */
571 format
= job_get_begin_status_message_format(u
, t
);
573 DISABLE_WARNING_FORMAT_NONLITERAL
;
574 (void) snprintf(buf
, sizeof buf
, format
, unit_description(u
));
577 mid
= t
== JOB_START
? "MESSAGE_ID=" SD_MESSAGE_UNIT_STARTING_STR
:
578 t
== JOB_STOP
? "MESSAGE_ID=" SD_MESSAGE_UNIT_STOPPING_STR
:
579 "MESSAGE_ID=" SD_MESSAGE_UNIT_RELOADING_STR
;
581 /* Note that we deliberately use LOG_MESSAGE() instead of
582 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
583 * closely what is written to screen using the status output,
584 * which is supposed the highest level, friendliest output
585 * possible, which means we should avoid the low-level unit
588 LOG_MESSAGE("%s", buf
),
589 "JOB_ID=%" PRIu32
, job_id
,
590 "JOB_TYPE=%s", job_type_to_string(t
),
592 LOG_UNIT_INVOCATION_ID(u
),
596 static void job_emit_begin_status_message(Unit
*u
, uint32_t job_id
, JobType t
) {
599 assert(t
< _JOB_TYPE_MAX
);
601 job_log_begin_status_message(u
, job_id
, t
);
602 job_print_begin_status_message(u
, t
);
605 static int job_perform_on_unit(Job
**j
) {
612 /* While we execute this operation the job might go away (for
613 * example: because it finishes immediately or is replaced by
614 * a new, conflicting job.) To make sure we don't access a
615 * freed job later on we store the id here, so that we can
616 * verify the job is still valid. */
643 assert_not_reached("Invalid job type");
646 /* Log if the job still exists and the start/stop/reload function actually did something. Note that this means
647 * for units for which there's no 'activating' phase (i.e. because we transition directly from 'inactive' to
648 * 'active') we'll possibly skip the "Starting..." message. */
649 *j
= manager_get_job(m
, id
);
651 job_emit_begin_status_message(u
, id
, t
);
656 int job_run_and_invalidate(Job
*j
) {
660 assert(j
->installed
);
661 assert(j
->type
< _JOB_TYPE_MAX_IN_TRANSACTION
);
662 assert(j
->in_run_queue
);
664 LIST_REMOVE(run_queue
, j
->manager
->run_queue
, j
);
665 j
->in_run_queue
= false;
667 if (j
->state
!= JOB_WAITING
)
670 if (!job_is_runnable(j
))
673 job_start_timer(j
, true);
674 job_set_state(j
, JOB_RUNNING
);
675 job_add_to_dbus_queue(j
);
679 case JOB_VERIFY_ACTIVE
: {
682 t
= unit_active_state(j
->unit
);
683 if (UNIT_IS_ACTIVE_OR_RELOADING(t
))
685 else if (t
== UNIT_ACTIVATING
)
695 r
= job_perform_on_unit(&j
);
697 /* If the unit type does not support starting/stopping, then simply wait. */
703 r
= job_perform_on_unit(&j
);
711 assert_not_reached("Unknown job type");
716 job_set_state(j
, JOB_WAITING
); /* Hmm, not ready after all, let's return to JOB_WAITING state */
717 else if (r
== -EALREADY
)
718 r
= job_finish_and_invalidate(j
, JOB_DONE
, true, true);
719 else if (r
== -EBADR
)
720 r
= job_finish_and_invalidate(j
, JOB_SKIPPED
, true, false);
721 else if (r
== -ENOEXEC
)
722 r
= job_finish_and_invalidate(j
, JOB_INVALID
, true, false);
723 else if (r
== -EPROTO
)
724 r
= job_finish_and_invalidate(j
, JOB_ASSERT
, true, false);
725 else if (r
== -EOPNOTSUPP
)
726 r
= job_finish_and_invalidate(j
, JOB_UNSUPPORTED
, true, false);
727 else if (r
== -ENOLINK
)
728 r
= job_finish_and_invalidate(j
, JOB_DEPENDENCY
, true, false);
729 else if (r
== -ESTALE
)
730 r
= job_finish_and_invalidate(j
, JOB_ONCE
, true, false);
732 r
= job_finish_and_invalidate(j
, JOB_FAILED
, true, false);
738 _pure_
static const char *job_get_done_status_message_format(Unit
*u
, JobType t
, JobResult result
) {
740 static const char *const generic_finished_start_job
[_JOB_RESULT_MAX
] = {
741 [JOB_DONE
] = "Started %s.",
742 [JOB_TIMEOUT
] = "Timed out starting %s.",
743 [JOB_FAILED
] = "Failed to start %s.",
744 [JOB_DEPENDENCY
] = "Dependency failed for %s.",
745 [JOB_ASSERT
] = "Assertion failed for %s.",
746 [JOB_UNSUPPORTED
] = "Starting of %s not supported.",
747 [JOB_COLLECTED
] = "Unnecessary job for %s was removed.",
748 [JOB_ONCE
] = "Unit %s has been started before and cannot be started again."
750 static const char *const generic_finished_stop_job
[_JOB_RESULT_MAX
] = {
751 [JOB_DONE
] = "Stopped %s.",
752 [JOB_FAILED
] = "Stopped (with error) %s.",
753 [JOB_TIMEOUT
] = "Timed out stopping %s.",
755 static const char *const generic_finished_reload_job
[_JOB_RESULT_MAX
] = {
756 [JOB_DONE
] = "Reloaded %s.",
757 [JOB_FAILED
] = "Reload failed for %s.",
758 [JOB_TIMEOUT
] = "Timed out reloading %s.",
760 /* When verify-active detects the unit is inactive, report it.
761 * Most likely a DEPEND warning from a requisiting unit will
762 * occur next and it's nice to see what was requisited. */
763 static const char *const generic_finished_verify_active_job
[_JOB_RESULT_MAX
] = {
764 [JOB_SKIPPED
] = "%s is not active.",
767 const UnitStatusMessageFormats
*format_table
;
772 assert(t
< _JOB_TYPE_MAX
);
774 if (IN_SET(t
, JOB_START
, JOB_STOP
, JOB_RESTART
)) {
775 format_table
= &UNIT_VTABLE(u
)->status_message_formats
;
777 format
= t
== JOB_START
? format_table
->finished_start_job
[result
] :
778 format_table
->finished_stop_job
[result
];
784 /* Return generic strings */
786 return generic_finished_start_job
[result
];
787 else if (IN_SET(t
, JOB_STOP
, JOB_RESTART
))
788 return generic_finished_stop_job
[result
];
789 else if (t
== JOB_RELOAD
)
790 return generic_finished_reload_job
[result
];
791 else if (t
== JOB_VERIFY_ACTIVE
)
792 return generic_finished_verify_active_job
[result
];
797 static const struct {
798 const char *color
, *word
;
799 } job_print_done_status_messages
[_JOB_RESULT_MAX
] = {
800 [JOB_DONE
] = { ANSI_OK_COLOR
, " OK " },
801 [JOB_TIMEOUT
] = { ANSI_HIGHLIGHT_RED
, " TIME " },
802 [JOB_FAILED
] = { ANSI_HIGHLIGHT_RED
, "FAILED" },
803 [JOB_DEPENDENCY
] = { ANSI_HIGHLIGHT_YELLOW
, "DEPEND" },
804 [JOB_SKIPPED
] = { ANSI_HIGHLIGHT
, " INFO " },
805 [JOB_ASSERT
] = { ANSI_HIGHLIGHT_YELLOW
, "ASSERT" },
806 [JOB_UNSUPPORTED
] = { ANSI_HIGHLIGHT_YELLOW
, "UNSUPP" },
808 [JOB_ONCE
] = { ANSI_HIGHLIGHT_RED
, " ONCE " },
811 static void job_print_done_status_message(Unit
*u
, JobType t
, JobResult result
) {
817 assert(t
< _JOB_TYPE_MAX
);
819 /* Reload status messages have traditionally not been printed to console. */
823 if (!job_print_done_status_messages
[result
].word
)
826 format
= job_get_done_status_message_format(u
, t
, result
);
830 if (log_get_show_color())
831 status
= strjoina(job_print_done_status_messages
[result
].color
,
832 job_print_done_status_messages
[result
].word
,
835 status
= job_print_done_status_messages
[result
].word
;
837 if (result
!= JOB_DONE
)
838 manager_flip_auto_status(u
->manager
, true);
840 DISABLE_WARNING_FORMAT_NONLITERAL
;
841 unit_status_printf(u
, status
, format
);
844 if (t
== JOB_START
&& result
== JOB_FAILED
) {
845 _cleanup_free_
char *quoted
;
847 quoted
= shell_maybe_quote(u
->id
, ESCAPE_BACKSLASH
);
848 manager_status_printf(u
->manager
, STATUS_TYPE_NORMAL
, NULL
, "See 'systemctl status %s' for details.", strna(quoted
));
852 static void job_log_done_status_message(Unit
*u
, uint32_t job_id
, JobType t
, JobResult result
) {
853 const char *format
, *mid
;
855 static const int job_result_log_level
[_JOB_RESULT_MAX
] = {
856 [JOB_DONE
] = LOG_INFO
,
857 [JOB_CANCELED
] = LOG_INFO
,
858 [JOB_TIMEOUT
] = LOG_ERR
,
859 [JOB_FAILED
] = LOG_ERR
,
860 [JOB_DEPENDENCY
] = LOG_WARNING
,
861 [JOB_SKIPPED
] = LOG_NOTICE
,
862 [JOB_INVALID
] = LOG_INFO
,
863 [JOB_ASSERT
] = LOG_WARNING
,
864 [JOB_UNSUPPORTED
] = LOG_WARNING
,
865 [JOB_COLLECTED
] = LOG_INFO
,
866 [JOB_ONCE
] = LOG_ERR
,
871 assert(t
< _JOB_TYPE_MAX
);
873 /* Skip printing if output goes to the console, and job_print_status_message()
874 will actually print something to the console. */
875 if (log_on_console() && job_print_done_status_messages
[result
].word
)
878 format
= job_get_done_status_message_format(u
, t
, result
);
882 /* The description might be longer than the buffer, but that's OK,
883 * we'll just truncate it here. Note that we use snprintf() rather than
884 * xsprintf() on purpose here: we are fine with truncation and don't
885 * consider that an error. */
886 DISABLE_WARNING_FORMAT_NONLITERAL
;
887 (void) snprintf(buf
, sizeof(buf
), format
, unit_description(u
));
893 if (result
== JOB_DONE
)
894 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_STARTED_STR
;
896 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILED_STR
;
900 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_RELOADED_STR
;
905 mid
= "MESSAGE_ID=" SD_MESSAGE_UNIT_STOPPED_STR
;
909 log_struct(job_result_log_level
[result
],
910 LOG_MESSAGE("%s", buf
),
911 "JOB_ID=%" PRIu32
, job_id
,
912 "JOB_TYPE=%s", job_type_to_string(t
),
913 "JOB_RESULT=%s", job_result_to_string(result
),
915 LOG_UNIT_INVOCATION_ID(u
));
919 log_struct(job_result_log_level
[result
],
920 LOG_MESSAGE("%s", buf
),
921 "JOB_ID=%" PRIu32
, job_id
,
922 "JOB_TYPE=%s", job_type_to_string(t
),
923 "JOB_RESULT=%s", job_result_to_string(result
),
925 LOG_UNIT_INVOCATION_ID(u
),
929 static void job_emit_done_status_message(Unit
*u
, uint32_t job_id
, JobType t
, JobResult result
) {
932 /* No message if the job did not actually do anything due to failed condition. */
933 if (t
== JOB_START
&& result
== JOB_DONE
&& !u
->condition_result
)
936 job_log_done_status_message(u
, job_id
, t
, result
);
937 job_print_done_status_message(u
, t
, result
);
940 static void job_fail_dependencies(Unit
*u
, UnitDependency d
) {
947 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[d
], i
) {
952 if (!IN_SET(j
->type
, JOB_START
, JOB_VERIFY_ACTIVE
))
955 job_finish_and_invalidate(j
, JOB_DEPENDENCY
, true, false);
959 static int job_save_pending_finished_job(Job
*j
) {
964 r
= set_ensure_allocated(&j
->manager
->pending_finished_jobs
, NULL
);
969 return set_put(j
->manager
->pending_finished_jobs
, j
);
972 int job_finish_and_invalidate(Job
*j
, JobResult result
, bool recursive
, bool already
) {
980 assert(j
->installed
);
981 assert(j
->type
< _JOB_TYPE_MAX_IN_TRANSACTION
);
988 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
));
990 /* If this job did nothing to respective unit we don't log the status message */
992 job_emit_done_status_message(u
, j
->id
, t
, result
);
994 /* Patch restart jobs so that they become normal start jobs */
995 if (result
== JOB_DONE
&& t
== JOB_RESTART
) {
997 job_change_type(j
, JOB_START
);
998 job_set_state(j
, JOB_WAITING
);
1000 job_add_to_dbus_queue(j
);
1001 job_add_to_run_queue(j
);
1002 job_add_to_gc_queue(j
);
1007 if (IN_SET(result
, JOB_FAILED
, JOB_INVALID
))
1008 j
->manager
->n_failed_jobs
++;
1011 /* Keep jobs started before the reload to send singal later, free all others */
1012 if (!MANAGER_IS_RELOADING(j
->manager
) ||
1014 job_save_pending_finished_job(j
) < 0)
1017 /* Fail depending jobs on failure */
1018 if (result
!= JOB_DONE
&& recursive
) {
1019 if (IN_SET(t
, JOB_START
, JOB_VERIFY_ACTIVE
)) {
1020 job_fail_dependencies(u
, UNIT_REQUIRED_BY
);
1021 job_fail_dependencies(u
, UNIT_REQUISITE_OF
);
1022 job_fail_dependencies(u
, UNIT_BOUND_BY
);
1023 } else if (t
== JOB_STOP
)
1024 job_fail_dependencies(u
, UNIT_CONFLICTED_BY
);
1027 /* Trigger OnFailure dependencies that are not generated by
1028 * the unit itself. We don't treat JOB_CANCELED as failure in
1029 * this context. And JOB_FAILURE is already handled by the
1031 if (IN_SET(result
, JOB_TIMEOUT
, JOB_DEPENDENCY
)) {
1032 log_struct(LOG_NOTICE
,
1033 "JOB_TYPE=%s", job_type_to_string(t
),
1034 "JOB_RESULT=%s", job_result_to_string(result
),
1036 LOG_UNIT_MESSAGE(u
, "Job %s/%s failed with result '%s'.",
1038 job_type_to_string(t
),
1039 job_result_to_string(result
)));
1041 unit_start_on_failure(u
);
1044 unit_trigger_notify(u
);
1047 /* Try to start the next jobs that can be started */
1048 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_AFTER
], i
)
1050 job_add_to_run_queue(other
->job
);
1051 job_add_to_gc_queue(other
->job
);
1053 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BEFORE
], i
)
1055 job_add_to_run_queue(other
->job
);
1056 job_add_to_gc_queue(other
->job
);
1059 manager_check_finished(u
->manager
);
1064 static int job_dispatch_timer(sd_event_source
*s
, uint64_t monotonic
, void *userdata
) {
1069 assert(s
== j
->timer_event_source
);
1071 log_unit_warning(j
->unit
, "Job %s/%s timed out.", j
->unit
->id
, job_type_to_string(j
->type
));
1074 job_finish_and_invalidate(j
, JOB_TIMEOUT
, true, false);
1076 emergency_action(u
->manager
, u
->job_timeout_action
,
1077 EMERGENCY_ACTION_IS_WATCHDOG
|EMERGENCY_ACTION_WARN
,
1078 u
->job_timeout_reboot_arg
, "job timed out");
1083 int job_start_timer(Job
*j
, bool job_running
) {
1085 usec_t timeout_time
, old_timeout_time
;
1088 j
->begin_running_usec
= now(CLOCK_MONOTONIC
);
1090 if (j
->unit
->job_running_timeout
== USEC_INFINITY
)
1093 timeout_time
= usec_add(j
->begin_running_usec
, j
->unit
->job_running_timeout
);
1095 if (j
->timer_event_source
) {
1096 /* Update only if JobRunningTimeoutSec= results in earlier timeout */
1097 r
= sd_event_source_get_time(j
->timer_event_source
, &old_timeout_time
);
1101 if (old_timeout_time
<= timeout_time
)
1104 return sd_event_source_set_time(j
->timer_event_source
, timeout_time
);
1107 if (j
->timer_event_source
)
1110 j
->begin_usec
= now(CLOCK_MONOTONIC
);
1112 if (j
->unit
->job_timeout
== USEC_INFINITY
)
1115 timeout_time
= usec_add(j
->begin_usec
, j
->unit
->job_timeout
);
1118 r
= sd_event_add_time(
1120 &j
->timer_event_source
,
1123 job_dispatch_timer
, j
);
1127 (void) sd_event_source_set_description(j
->timer_event_source
, "job-start");
1132 void job_add_to_run_queue(Job
*j
) {
1136 assert(j
->installed
);
1138 if (j
->in_run_queue
)
1141 if (!j
->manager
->run_queue
) {
1142 r
= sd_event_source_set_enabled(j
->manager
->run_queue_event_source
, SD_EVENT_ONESHOT
);
1144 log_warning_errno(r
, "Failed to enable job run queue event source, ignoring: %m");
1147 LIST_PREPEND(run_queue
, j
->manager
->run_queue
, j
);
1148 j
->in_run_queue
= true;
1151 void job_add_to_dbus_queue(Job
*j
) {
1153 assert(j
->installed
);
1155 if (j
->in_dbus_queue
)
1158 /* We don't check if anybody is subscribed here, since this
1159 * job might just have been created and not yet assigned to a
1160 * connection/client. */
1162 LIST_PREPEND(dbus_queue
, j
->manager
->dbus_job_queue
, j
);
1163 j
->in_dbus_queue
= true;
1166 char *job_dbus_path(Job
*j
) {
1171 if (asprintf(&p
, "/org/freedesktop/systemd1/job/%"PRIu32
, j
->id
) < 0)
1177 int job_serialize(Job
*j
, FILE *f
) {
1181 (void) serialize_item_format(f
, "job-id", "%u", j
->id
);
1182 (void) serialize_item(f
, "job-type", job_type_to_string(j
->type
));
1183 (void) serialize_item(f
, "job-state", job_state_to_string(j
->state
));
1184 (void) serialize_bool(f
, "job-irreversible", j
->irreversible
);
1185 (void) serialize_bool(f
, "job-sent-dbus-new-signal", j
->sent_dbus_new_signal
);
1186 (void) serialize_bool(f
, "job-ignore-order", j
->ignore_order
);
1188 if (j
->begin_usec
> 0)
1189 (void) serialize_usec(f
, "job-begin", j
->begin_usec
);
1190 if (j
->begin_running_usec
> 0)
1191 (void) serialize_usec(f
, "job-begin-running", j
->begin_running_usec
);
1193 bus_track_serialize(j
->bus_track
, f
, "subscribed");
1200 int job_deserialize(Job
*j
, FILE *f
) {
1207 _cleanup_free_
char *line
= NULL
;
1211 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1213 return log_error_errno(r
, "Failed to read serialization line: %m");
1223 k
= strcspn(l
, "=");
1231 if (streq(l
, "job-id")) {
1233 if (safe_atou32(v
, &j
->id
) < 0)
1234 log_debug("Failed to parse job id value: %s", v
);
1236 } else if (streq(l
, "job-type")) {
1239 t
= job_type_from_string(v
);
1241 log_debug("Failed to parse job type: %s", v
);
1242 else if (t
>= _JOB_TYPE_MAX_IN_TRANSACTION
)
1243 log_debug("Cannot deserialize job of type: %s", v
);
1247 } else if (streq(l
, "job-state")) {
1250 s
= job_state_from_string(v
);
1252 log_debug("Failed to parse job state: %s", v
);
1254 job_set_state(j
, s
);
1256 } else if (streq(l
, "job-irreversible")) {
1259 b
= parse_boolean(v
);
1261 log_debug("Failed to parse job irreversible flag: %s", v
);
1263 j
->irreversible
= j
->irreversible
|| b
;
1265 } else if (streq(l
, "job-sent-dbus-new-signal")) {
1268 b
= parse_boolean(v
);
1270 log_debug("Failed to parse job sent_dbus_new_signal flag: %s", v
);
1272 j
->sent_dbus_new_signal
= j
->sent_dbus_new_signal
|| b
;
1274 } else if (streq(l
, "job-ignore-order")) {
1277 b
= parse_boolean(v
);
1279 log_debug("Failed to parse job ignore_order flag: %s", v
);
1281 j
->ignore_order
= j
->ignore_order
|| b
;
1283 } else if (streq(l
, "job-begin"))
1284 (void) deserialize_usec(v
, &j
->begin_usec
);
1286 else if (streq(l
, "job-begin-running"))
1287 (void) deserialize_usec(v
, &j
->begin_running_usec
);
1289 else if (streq(l
, "subscribed")) {
1290 if (strv_extend(&j
->deserialized_clients
, v
) < 0)
1293 log_debug("Unknown job serialization key: %s", l
);
1297 int job_coldplug(Job
*j
) {
1299 usec_t timeout_time
= USEC_INFINITY
;
1303 /* After deserialization is complete and the bus connection
1304 * set up again, let's start watching our subscribers again */
1305 (void) bus_job_coldplug_bus_track(j
);
1307 if (j
->state
== JOB_WAITING
)
1308 job_add_to_run_queue(j
);
1310 /* Maybe due to new dependencies we don't actually need this job anymore? */
1311 job_add_to_gc_queue(j
);
1313 /* Create timer only when job began or began running and the respective timeout is finite.
1314 * Follow logic of job_start_timer() if both timeouts are finite */
1315 if (j
->begin_usec
== 0)
1318 if (j
->unit
->job_timeout
!= USEC_INFINITY
)
1319 timeout_time
= usec_add(j
->begin_usec
, j
->unit
->job_timeout
);
1321 if (j
->begin_running_usec
> 0 && j
->unit
->job_running_timeout
!= USEC_INFINITY
)
1322 timeout_time
= MIN(timeout_time
, usec_add(j
->begin_running_usec
, j
->unit
->job_running_timeout
));
1324 if (timeout_time
== USEC_INFINITY
)
1327 j
->timer_event_source
= sd_event_source_unref(j
->timer_event_source
);
1329 r
= sd_event_add_time(
1331 &j
->timer_event_source
,
1334 job_dispatch_timer
, j
);
1336 log_debug_errno(r
, "Failed to restart timeout for job: %m");
1338 (void) sd_event_source_set_description(j
->timer_event_source
, "job-timeout");
1343 void job_shutdown_magic(Job
*j
) {
1346 /* The shutdown target gets some special treatment here: we
1347 * tell the kernel to begin with flushing its disk caches, to
1348 * optimize shutdown time a bit. Ideally we wouldn't hardcode
1349 * this magic into PID 1. However all other processes aren't
1350 * options either since they'd exit much sooner than PID 1 and
1351 * asynchronous sync() would cause their exit to be
1354 if (j
->type
!= JOB_START
)
1357 if (!MANAGER_IS_SYSTEM(j
->unit
->manager
))
1360 if (!unit_has_name(j
->unit
, SPECIAL_SHUTDOWN_TARGET
))
1363 /* In case messages on console has been disabled on boot */
1364 j
->unit
->manager
->no_console_output
= false;
1366 if (detect_container() > 0)
1369 (void) asynchronous_sync(NULL
);
1372 int job_get_timeout(Job
*j
, usec_t
*timeout
) {
1373 usec_t x
= USEC_INFINITY
, y
= USEC_INFINITY
;
1379 if (j
->timer_event_source
) {
1380 r
= sd_event_source_get_time(j
->timer_event_source
, &x
);
1385 if (UNIT_VTABLE(u
)->get_timeout
) {
1386 r
= UNIT_VTABLE(u
)->get_timeout(u
, &y
);
1391 if (x
== USEC_INFINITY
&& y
== USEC_INFINITY
)
1394 *timeout
= MIN(x
, y
);
1398 bool job_may_gc(Job
*j
) {
1405 /* Checks whether this job should be GC'ed away. We only do this for jobs of units that have no effect on their
1406 * own and just track external state. For now the only unit type that qualifies for this are .device units.
1407 * Returns true if the job can be collected. */
1409 if (!UNIT_VTABLE(j
->unit
)->gc_jobs
)
1412 if (sd_bus_track_count(j
->bus_track
) > 0)
1415 /* FIXME: So this is a bit ugly: for now we don't properly track references made via private bus connections
1416 * (because it's nasty, as sd_bus_track doesn't apply to it). We simply remember that the job was once
1417 * referenced by one, and reset this whenever we notice that no private bus connections are around. This means
1418 * the GC is a bit too conservative when it comes to jobs created by private bus connections. */
1419 if (j
->ref_by_private_bus
) {
1420 if (set_isempty(j
->unit
->manager
->private_buses
))
1421 j
->ref_by_private_bus
= false;
1426 if (j
->type
== JOB_NOP
)
1429 /* If a job is ordered after ours, and is to be started, then it needs to wait for us, regardless if we stop or
1430 * start, hence let's not GC in that case. */
1431 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
) {
1435 if (other
->job
->ignore_order
)
1438 if (IN_SET(other
->job
->type
, JOB_START
, JOB_VERIFY_ACTIVE
, JOB_RELOAD
))
1442 /* If we are going down, but something else is ordered After= us, then it needs to wait for us */
1443 if (IN_SET(j
->type
, JOB_STOP
, JOB_RESTART
))
1444 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
) {
1448 if (other
->job
->ignore_order
)
1454 /* The logic above is kinda the inverse of the job_is_runnable() logic. Specifically, if the job "we" is
1455 * ordered before the job "other":
1457 * we start + other start → stay
1458 * we start + other stop → gc
1459 * we stop + other start → stay
1460 * we stop + other stop → gc
1462 * "we" are ordered after "other":
1464 * we start + other start → gc
1465 * we start + other stop → gc
1466 * we stop + other start → stay
1467 * we stop + other stop → stay
1473 void job_add_to_gc_queue(Job
*j
) {
1482 LIST_PREPEND(gc_queue
, j
->unit
->manager
->gc_job_queue
, j
);
1483 j
->in_gc_queue
= true;
1486 static int job_compare(Job
* const *a
, Job
* const *b
) {
1487 return CMP((*a
)->id
, (*b
)->id
);
1490 static size_t sort_job_list(Job
**list
, size_t n
) {
1491 Job
*previous
= NULL
;
1494 /* Order by numeric IDs */
1495 typesafe_qsort(list
, n
, job_compare
);
1497 /* Filter out duplicates */
1498 for (a
= 0, b
= 0; a
< n
; a
++) {
1500 if (previous
== list
[a
])
1503 previous
= list
[b
++] = list
[a
];
1509 int job_get_before(Job
*j
, Job
*** ret
) {
1510 _cleanup_free_ Job
** list
= NULL
;
1511 size_t n
= 0, n_allocated
= 0;
1516 /* Returns a list of all pending jobs that need to finish before this job may be started. */
1521 if (j
->ignore_order
) {
1526 if (IN_SET(j
->type
, JOB_START
, JOB_VERIFY_ACTIVE
, JOB_RELOAD
)) {
1528 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
) {
1532 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1534 list
[n
++] = other
->job
;
1538 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
) {
1542 if (!IN_SET(other
->job
->type
, JOB_STOP
, JOB_RESTART
))
1545 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1547 list
[n
++] = other
->job
;
1550 n
= sort_job_list(list
, n
);
1552 *ret
= TAKE_PTR(list
);
1557 int job_get_after(Job
*j
, Job
*** ret
) {
1558 _cleanup_free_ Job
** list
= NULL
;
1559 size_t n
= 0, n_allocated
= 0;
1567 /* Returns a list of all pending jobs that are waiting for this job to finish. */
1569 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_BEFORE
], i
) {
1573 if (other
->job
->ignore_order
)
1576 if (!IN_SET(other
->job
->type
, JOB_START
, JOB_VERIFY_ACTIVE
, JOB_RELOAD
))
1579 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1581 list
[n
++] = other
->job
;
1584 if (IN_SET(j
->type
, JOB_STOP
, JOB_RESTART
)) {
1586 HASHMAP_FOREACH_KEY(v
, other
, j
->unit
->dependencies
[UNIT_AFTER
], i
) {
1590 if (other
->job
->ignore_order
)
1593 if (!GREEDY_REALLOC(list
, n_allocated
, n
+1))
1595 list
[n
++] = other
->job
;
1599 n
= sort_job_list(list
, n
);
1601 *ret
= TAKE_PTR(list
);
1606 static const char* const job_state_table
[_JOB_STATE_MAX
] = {
1607 [JOB_WAITING
] = "waiting",
1608 [JOB_RUNNING
] = "running",
1611 DEFINE_STRING_TABLE_LOOKUP(job_state
, JobState
);
1613 static const char* const job_type_table
[_JOB_TYPE_MAX
] = {
1614 [JOB_START
] = "start",
1615 [JOB_VERIFY_ACTIVE
] = "verify-active",
1616 [JOB_STOP
] = "stop",
1617 [JOB_RELOAD
] = "reload",
1618 [JOB_RELOAD_OR_START
] = "reload-or-start",
1619 [JOB_RESTART
] = "restart",
1620 [JOB_TRY_RESTART
] = "try-restart",
1621 [JOB_TRY_RELOAD
] = "try-reload",
1625 DEFINE_STRING_TABLE_LOOKUP(job_type
, JobType
);
1627 static const char* const job_mode_table
[_JOB_MODE_MAX
] = {
1628 [JOB_FAIL
] = "fail",
1629 [JOB_REPLACE
] = "replace",
1630 [JOB_REPLACE_IRREVERSIBLY
] = "replace-irreversibly",
1631 [JOB_ISOLATE
] = "isolate",
1632 [JOB_FLUSH
] = "flush",
1633 [JOB_IGNORE_DEPENDENCIES
] = "ignore-dependencies",
1634 [JOB_IGNORE_REQUIREMENTS
] = "ignore-requirements",
1637 DEFINE_STRING_TABLE_LOOKUP(job_mode
, JobMode
);
1639 static const char* const job_result_table
[_JOB_RESULT_MAX
] = {
1640 [JOB_DONE
] = "done",
1641 [JOB_CANCELED
] = "canceled",
1642 [JOB_TIMEOUT
] = "timeout",
1643 [JOB_FAILED
] = "failed",
1644 [JOB_DEPENDENCY
] = "dependency",
1645 [JOB_SKIPPED
] = "skipped",
1646 [JOB_INVALID
] = "invalid",
1647 [JOB_ASSERT
] = "assert",
1648 [JOB_UNSUPPORTED
] = "unsupported",
1649 [JOB_COLLECTED
] = "collected",
1650 [JOB_ONCE
] = "once",
1653 DEFINE_STRING_TABLE_LOOKUP(job_result
, JobResult
);
1655 const char* job_type_to_access_method(JobType t
) {
1657 assert(t
< _JOB_TYPE_MAX
);
1659 if (IN_SET(t
, JOB_START
, JOB_RESTART
, JOB_TRY_RESTART
))
1661 else if (t
== JOB_STOP
)