]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/job.c
util-lib: split string parsing related calls from util.[ch] into parse-util.[ch]
[thirdparty/systemd.git] / src / core / job.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <errno.h>
23
24 #include "sd-id128.h"
25 #include "sd-messages.h"
26
27 #include "async.h"
28 #include "dbus-job.h"
29 #include "dbus.h"
30 #include "escape.h"
31 #include "job.h"
32 #include "log.h"
33 #include "macro.h"
34 #include "parse-util.h"
35 #include "set.h"
36 #include "special.h"
37 #include "string-util.h"
38 #include "strv.h"
39 #include "terminal-util.h"
40 #include "unit.h"
41 #include "virt.h"
42
43 Job* job_new_raw(Unit *unit) {
44 Job *j;
45
46 /* used for deserialization */
47
48 assert(unit);
49
50 j = new0(Job, 1);
51 if (!j)
52 return NULL;
53
54 j->manager = unit->manager;
55 j->unit = unit;
56 j->type = _JOB_TYPE_INVALID;
57
58 return j;
59 }
60
61 Job* job_new(Unit *unit, JobType type) {
62 Job *j;
63
64 assert(type < _JOB_TYPE_MAX);
65
66 j = job_new_raw(unit);
67 if (!j)
68 return NULL;
69
70 j->id = j->manager->current_job_id++;
71 j->type = type;
72
73 /* We don't link it here, that's what job_dependency() is for */
74
75 return j;
76 }
77
78 void job_free(Job *j) {
79 assert(j);
80 assert(!j->installed);
81 assert(!j->transaction_prev);
82 assert(!j->transaction_next);
83 assert(!j->subject_list);
84 assert(!j->object_list);
85
86 if (j->in_run_queue)
87 LIST_REMOVE(run_queue, j->manager->run_queue, j);
88
89 if (j->in_dbus_queue)
90 LIST_REMOVE(dbus_queue, j->manager->dbus_job_queue, j);
91
92 sd_event_source_unref(j->timer_event_source);
93
94 sd_bus_track_unref(j->clients);
95 strv_free(j->deserialized_clients);
96
97 free(j);
98 }
99
100 static void job_set_state(Job *j, JobState state) {
101 assert(j);
102 assert(state >= 0);
103 assert(state < _JOB_STATE_MAX);
104
105 if (j->state == state)
106 return;
107
108 j->state = state;
109
110 if (!j->installed)
111 return;
112
113 if (j->state == JOB_RUNNING)
114 j->unit->manager->n_running_jobs++;
115 else {
116 assert(j->state == JOB_WAITING);
117 assert(j->unit->manager->n_running_jobs > 0);
118
119 j->unit->manager->n_running_jobs--;
120
121 if (j->unit->manager->n_running_jobs <= 0)
122 j->unit->manager->jobs_in_progress_event_source = sd_event_source_unref(j->unit->manager->jobs_in_progress_event_source);
123 }
124 }
125
126 void job_uninstall(Job *j) {
127 Job **pj;
128
129 assert(j->installed);
130
131 job_set_state(j, JOB_WAITING);
132
133 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
134 assert(*pj == j);
135
136 /* Detach from next 'bigger' objects */
137
138 /* daemon-reload should be transparent to job observers */
139 if (j->manager->n_reloading <= 0)
140 bus_job_send_removed_signal(j);
141
142 *pj = NULL;
143
144 unit_add_to_gc_queue(j->unit);
145
146 hashmap_remove(j->manager->jobs, UINT32_TO_PTR(j->id));
147 j->installed = false;
148 }
149
150 static bool job_type_allows_late_merge(JobType t) {
151 /* Tells whether it is OK to merge a job of type 't' with an already
152 * running job.
153 * Reloads cannot be merged this way. Think of the sequence:
154 * 1. Reload of a daemon is in progress; the daemon has already loaded
155 * its config file, but hasn't completed the reload operation yet.
156 * 2. Edit foo's config file.
157 * 3. Trigger another reload to have the daemon use the new config.
158 * Should the second reload job be merged into the first one, the daemon
159 * would not know about the new config.
160 * JOB_RESTART jobs on the other hand can be merged, because they get
161 * patched into JOB_START after stopping the unit. So if we see a
162 * JOB_RESTART running, it means the unit hasn't stopped yet and at
163 * this time the merge is still allowed. */
164 return t != JOB_RELOAD;
165 }
166
167 static void job_merge_into_installed(Job *j, Job *other) {
168 assert(j->installed);
169 assert(j->unit == other->unit);
170
171 if (j->type != JOB_NOP)
172 job_type_merge_and_collapse(&j->type, other->type, j->unit);
173 else
174 assert(other->type == JOB_NOP);
175
176 j->override = j->override || other->override;
177 j->irreversible = j->irreversible || other->irreversible;
178 j->ignore_order = j->ignore_order || other->ignore_order;
179 }
180
181 Job* job_install(Job *j) {
182 Job **pj;
183 Job *uj;
184
185 assert(!j->installed);
186 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
187 assert(j->state == JOB_WAITING);
188
189 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
190 uj = *pj;
191
192 if (uj) {
193 if (job_type_is_conflicting(uj->type, j->type))
194 job_finish_and_invalidate(uj, JOB_CANCELED, false);
195 else {
196 /* not conflicting, i.e. mergeable */
197
198 if (uj->state == JOB_WAITING ||
199 (job_type_allows_late_merge(j->type) && job_type_is_superset(uj->type, j->type))) {
200 job_merge_into_installed(uj, j);
201 log_unit_debug(uj->unit,
202 "Merged into installed job %s/%s as %u",
203 uj->unit->id, job_type_to_string(uj->type), (unsigned) uj->id);
204 return uj;
205 } else {
206 /* already running and not safe to merge into */
207 /* Patch uj to become a merged job and re-run it. */
208 /* XXX It should be safer to queue j to run after uj finishes, but it is
209 * not currently possible to have more than one installed job per unit. */
210 job_merge_into_installed(uj, j);
211 log_unit_debug(uj->unit,
212 "Merged into running job, re-running: %s/%s as %u",
213 uj->unit->id, job_type_to_string(uj->type), (unsigned) uj->id);
214
215 job_set_state(uj, JOB_WAITING);
216 return uj;
217 }
218 }
219 }
220
221 /* Install the job */
222 *pj = j;
223 j->installed = true;
224
225 j->manager->n_installed_jobs ++;
226 log_unit_debug(j->unit,
227 "Installed new job %s/%s as %u",
228 j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
229 return j;
230 }
231
232 int job_install_deserialized(Job *j) {
233 Job **pj;
234
235 assert(!j->installed);
236
237 if (j->type < 0 || j->type >= _JOB_TYPE_MAX_IN_TRANSACTION) {
238 log_debug("Invalid job type %s in deserialization.", strna(job_type_to_string(j->type)));
239 return -EINVAL;
240 }
241
242 pj = (j->type == JOB_NOP) ? &j->unit->nop_job : &j->unit->job;
243 if (*pj) {
244 log_unit_debug(j->unit, "Unit already has a job installed. Not installing deserialized job.");
245 return -EEXIST;
246 }
247
248 *pj = j;
249 j->installed = true;
250
251 if (j->state == JOB_RUNNING)
252 j->unit->manager->n_running_jobs++;
253
254 log_unit_debug(j->unit,
255 "Reinstalled deserialized job %s/%s as %u",
256 j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
257 return 0;
258 }
259
260 JobDependency* job_dependency_new(Job *subject, Job *object, bool matters, bool conflicts) {
261 JobDependency *l;
262
263 assert(object);
264
265 /* Adds a new job link, which encodes that the 'subject' job
266 * needs the 'object' job in some way. If 'subject' is NULL
267 * this means the 'anchor' job (i.e. the one the user
268 * explicitly asked for) is the requester. */
269
270 if (!(l = new0(JobDependency, 1)))
271 return NULL;
272
273 l->subject = subject;
274 l->object = object;
275 l->matters = matters;
276 l->conflicts = conflicts;
277
278 if (subject)
279 LIST_PREPEND(subject, subject->subject_list, l);
280
281 LIST_PREPEND(object, object->object_list, l);
282
283 return l;
284 }
285
286 void job_dependency_free(JobDependency *l) {
287 assert(l);
288
289 if (l->subject)
290 LIST_REMOVE(subject, l->subject->subject_list, l);
291
292 LIST_REMOVE(object, l->object->object_list, l);
293
294 free(l);
295 }
296
297 void job_dump(Job *j, FILE*f, const char *prefix) {
298 assert(j);
299 assert(f);
300
301 if (!prefix)
302 prefix = "";
303
304 fprintf(f,
305 "%s-> Job %u:\n"
306 "%s\tAction: %s -> %s\n"
307 "%s\tState: %s\n"
308 "%s\tForced: %s\n"
309 "%s\tIrreversible: %s\n",
310 prefix, j->id,
311 prefix, j->unit->id, job_type_to_string(j->type),
312 prefix, job_state_to_string(j->state),
313 prefix, yes_no(j->override),
314 prefix, yes_no(j->irreversible));
315 }
316
317 /*
318 * Merging is commutative, so imagine the matrix as symmetric. We store only
319 * its lower triangle to avoid duplication. We don't store the main diagonal,
320 * because A merged with A is simply A.
321 *
322 * If the resulting type is collapsed immediately afterwards (to get rid of
323 * the JOB_RELOAD_OR_START, which lies outside the lookup function's domain),
324 * the following properties hold:
325 *
326 * Merging is associative! A merged with B, and then merged with C is the same
327 * as A merged with the result of B merged with C.
328 *
329 * Mergeability is transitive! If A can be merged with B and B with C then
330 * A also with C.
331 *
332 * Also, if A merged with B cannot be merged with C, then either A or B cannot
333 * be merged with C either.
334 */
335 static const JobType job_merging_table[] = {
336 /* What \ With * JOB_START JOB_VERIFY_ACTIVE JOB_STOP JOB_RELOAD */
337 /*********************************************************************************/
338 /*JOB_START */
339 /*JOB_VERIFY_ACTIVE */ JOB_START,
340 /*JOB_STOP */ -1, -1,
341 /*JOB_RELOAD */ JOB_RELOAD_OR_START, JOB_RELOAD, -1,
342 /*JOB_RESTART */ JOB_RESTART, JOB_RESTART, -1, JOB_RESTART,
343 };
344
345 JobType job_type_lookup_merge(JobType a, JobType b) {
346 assert_cc(ELEMENTSOF(job_merging_table) == _JOB_TYPE_MAX_MERGING * (_JOB_TYPE_MAX_MERGING - 1) / 2);
347 assert(a >= 0 && a < _JOB_TYPE_MAX_MERGING);
348 assert(b >= 0 && b < _JOB_TYPE_MAX_MERGING);
349
350 if (a == b)
351 return a;
352
353 if (a < b) {
354 JobType tmp = a;
355 a = b;
356 b = tmp;
357 }
358
359 return job_merging_table[(a - 1) * a / 2 + b];
360 }
361
362 bool job_type_is_redundant(JobType a, UnitActiveState b) {
363 switch (a) {
364
365 case JOB_START:
366 return
367 b == UNIT_ACTIVE ||
368 b == UNIT_RELOADING;
369
370 case JOB_STOP:
371 return
372 b == UNIT_INACTIVE ||
373 b == UNIT_FAILED;
374
375 case JOB_VERIFY_ACTIVE:
376 return
377 b == UNIT_ACTIVE ||
378 b == UNIT_RELOADING;
379
380 case JOB_RELOAD:
381 return
382 b == UNIT_RELOADING;
383
384 case JOB_RESTART:
385 return
386 b == UNIT_ACTIVATING;
387
388 case JOB_NOP:
389 return true;
390
391 default:
392 assert_not_reached("Invalid job type");
393 }
394 }
395
396 JobType job_type_collapse(JobType t, Unit *u) {
397 UnitActiveState s;
398
399 switch (t) {
400
401 case JOB_TRY_RESTART:
402 s = unit_active_state(u);
403 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s))
404 return JOB_NOP;
405
406 return JOB_RESTART;
407
408 case JOB_RELOAD_OR_START:
409 s = unit_active_state(u);
410 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(s))
411 return JOB_START;
412
413 return JOB_RELOAD;
414
415 default:
416 return t;
417 }
418 }
419
420 int job_type_merge_and_collapse(JobType *a, JobType b, Unit *u) {
421 JobType t;
422
423 t = job_type_lookup_merge(*a, b);
424 if (t < 0)
425 return -EEXIST;
426
427 *a = job_type_collapse(t, u);
428 return 0;
429 }
430
431 static bool job_is_runnable(Job *j) {
432 Iterator i;
433 Unit *other;
434
435 assert(j);
436 assert(j->installed);
437
438 /* Checks whether there is any job running for the units this
439 * job needs to be running after (in the case of a 'positive'
440 * job type) or before (in the case of a 'negative' job
441 * type. */
442
443 /* Note that unit types have a say in what is runnable,
444 * too. For example, if they return -EAGAIN from
445 * unit_start() they can indicate they are not
446 * runnable yet. */
447
448 /* First check if there is an override */
449 if (j->ignore_order)
450 return true;
451
452 if (j->type == JOB_NOP)
453 return true;
454
455 if (j->type == JOB_START ||
456 j->type == JOB_VERIFY_ACTIVE ||
457 j->type == JOB_RELOAD) {
458
459 /* Immediate result is that the job is or might be
460 * started. In this case let's wait for the
461 * dependencies, regardless whether they are
462 * starting or stopping something. */
463
464 SET_FOREACH(other, j->unit->dependencies[UNIT_AFTER], i)
465 if (other->job)
466 return false;
467 }
468
469 /* Also, if something else is being stopped and we should
470 * change state after it, then let's wait. */
471
472 SET_FOREACH(other, j->unit->dependencies[UNIT_BEFORE], i)
473 if (other->job &&
474 (other->job->type == JOB_STOP ||
475 other->job->type == JOB_RESTART))
476 return false;
477
478 /* This means that for a service a and a service b where b
479 * shall be started after a:
480 *
481 * start a + start b → 1st step start a, 2nd step start b
482 * start a + stop b → 1st step stop b, 2nd step start a
483 * stop a + start b → 1st step stop a, 2nd step start b
484 * stop a + stop b → 1st step stop b, 2nd step stop a
485 *
486 * This has the side effect that restarts are properly
487 * synchronized too. */
488
489 return true;
490 }
491
492 static void job_change_type(Job *j, JobType newtype) {
493 assert(j);
494
495 log_unit_debug(j->unit,
496 "Converting job %s/%s -> %s/%s",
497 j->unit->id, job_type_to_string(j->type),
498 j->unit->id, job_type_to_string(newtype));
499
500 j->type = newtype;
501 }
502
503 static int job_perform_on_unit(Job **j) {
504 /* While we execute this operation the job might go away (for
505 * example: because it finishes immediately or is replaced by a new,
506 * conflicting job.) To make sure we don't access a freed job later on
507 * we store the id here, so that we can verify the job is still
508 * valid. */
509 Manager *m = (*j)->manager;
510 Unit *u = (*j)->unit;
511 JobType t = (*j)->type;
512 uint32_t id = (*j)->id;
513 int r;
514
515 switch (t) {
516 case JOB_START:
517 r = unit_start(u);
518 break;
519
520 case JOB_RESTART:
521 t = JOB_STOP;
522 case JOB_STOP:
523 r = unit_stop(u);
524 break;
525
526 case JOB_RELOAD:
527 r = unit_reload(u);
528 break;
529
530 default:
531 assert_not_reached("Invalid job type");
532 }
533
534 /* Log if the job still exists and the start/stop/reload function
535 * actually did something. */
536 *j = manager_get_job(m, id);
537 if (*j && r > 0)
538 unit_status_emit_starting_stopping_reloading(u, t);
539
540 return r;
541 }
542
543 int job_run_and_invalidate(Job *j) {
544 int r;
545
546 assert(j);
547 assert(j->installed);
548 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
549 assert(j->in_run_queue);
550
551 LIST_REMOVE(run_queue, j->manager->run_queue, j);
552 j->in_run_queue = false;
553
554 if (j->state != JOB_WAITING)
555 return 0;
556
557 if (!job_is_runnable(j))
558 return -EAGAIN;
559
560 job_set_state(j, JOB_RUNNING);
561 job_add_to_dbus_queue(j);
562
563
564 switch (j->type) {
565
566 case JOB_VERIFY_ACTIVE: {
567 UnitActiveState t = unit_active_state(j->unit);
568 if (UNIT_IS_ACTIVE_OR_RELOADING(t))
569 r = -EALREADY;
570 else if (t == UNIT_ACTIVATING)
571 r = -EAGAIN;
572 else
573 r = -EBADR;
574 break;
575 }
576
577 case JOB_START:
578 case JOB_STOP:
579 case JOB_RESTART:
580 r = job_perform_on_unit(&j);
581
582 /* If the unit type does not support starting/stopping,
583 * then simply wait. */
584 if (r == -EBADR)
585 r = 0;
586 break;
587
588 case JOB_RELOAD:
589 r = job_perform_on_unit(&j);
590 break;
591
592 case JOB_NOP:
593 r = -EALREADY;
594 break;
595
596 default:
597 assert_not_reached("Unknown job type");
598 }
599
600 if (j) {
601 if (r == -EALREADY)
602 r = job_finish_and_invalidate(j, JOB_DONE, true);
603 else if (r == -EBADR)
604 r = job_finish_and_invalidate(j, JOB_SKIPPED, true);
605 else if (r == -ENOEXEC)
606 r = job_finish_and_invalidate(j, JOB_INVALID, true);
607 else if (r == -EPROTO)
608 r = job_finish_and_invalidate(j, JOB_ASSERT, true);
609 else if (r == -EOPNOTSUPP)
610 r = job_finish_and_invalidate(j, JOB_UNSUPPORTED, true);
611 else if (r == -EAGAIN)
612 job_set_state(j, JOB_WAITING);
613 else if (r < 0)
614 r = job_finish_and_invalidate(j, JOB_FAILED, true);
615 }
616
617 return r;
618 }
619
620 _pure_ static const char *job_get_status_message_format(Unit *u, JobType t, JobResult result) {
621 const char *format;
622 const UnitStatusMessageFormats *format_table;
623 static const char *const generic_finished_start_job[_JOB_RESULT_MAX] = {
624 [JOB_DONE] = "Started %s.",
625 [JOB_TIMEOUT] = "Timed out starting %s.",
626 [JOB_FAILED] = "Failed to start %s.",
627 [JOB_DEPENDENCY] = "Dependency failed for %s.",
628 [JOB_ASSERT] = "Assertion failed for %s.",
629 [JOB_UNSUPPORTED] = "Starting of %s not supported.",
630 };
631 static const char *const generic_finished_stop_job[_JOB_RESULT_MAX] = {
632 [JOB_DONE] = "Stopped %s.",
633 [JOB_FAILED] = "Stopped (with error) %s.",
634 [JOB_TIMEOUT] = "Timed out stoppping %s.",
635 };
636 static const char *const generic_finished_reload_job[_JOB_RESULT_MAX] = {
637 [JOB_DONE] = "Reloaded %s.",
638 [JOB_FAILED] = "Reload failed for %s.",
639 [JOB_TIMEOUT] = "Timed out reloading %s.",
640 };
641 /* When verify-active detects the unit is inactive, report it.
642 * Most likely a DEPEND warning from a requisiting unit will
643 * occur next and it's nice to see what was requisited. */
644 static const char *const generic_finished_verify_active_job[_JOB_RESULT_MAX] = {
645 [JOB_SKIPPED] = "%s is not active.",
646 };
647
648 assert(u);
649 assert(t >= 0);
650 assert(t < _JOB_TYPE_MAX);
651
652 if (t == JOB_START || t == JOB_STOP || t == JOB_RESTART) {
653 format_table = &UNIT_VTABLE(u)->status_message_formats;
654 if (format_table) {
655 format = t == JOB_START ? format_table->finished_start_job[result] :
656 format_table->finished_stop_job[result];
657 if (format)
658 return format;
659 }
660 }
661
662 /* Return generic strings */
663 if (t == JOB_START)
664 return generic_finished_start_job[result];
665 else if (t == JOB_STOP || t == JOB_RESTART)
666 return generic_finished_stop_job[result];
667 else if (t == JOB_RELOAD)
668 return generic_finished_reload_job[result];
669 else if (t == JOB_VERIFY_ACTIVE)
670 return generic_finished_verify_active_job[result];
671
672 return NULL;
673 }
674
675 static void job_print_status_message(Unit *u, JobType t, JobResult result) {
676 const char *format;
677 static const char* const job_result_status_table[_JOB_RESULT_MAX] = {
678 [JOB_DONE] = ANSI_GREEN " OK " ANSI_NORMAL,
679 [JOB_TIMEOUT] = ANSI_HIGHLIGHT_RED " TIME " ANSI_NORMAL,
680 [JOB_FAILED] = ANSI_HIGHLIGHT_RED "FAILED" ANSI_NORMAL,
681 [JOB_DEPENDENCY] = ANSI_HIGHLIGHT_YELLOW "DEPEND" ANSI_NORMAL,
682 [JOB_SKIPPED] = ANSI_HIGHLIGHT " INFO " ANSI_NORMAL,
683 [JOB_ASSERT] = ANSI_HIGHLIGHT_YELLOW "ASSERT" ANSI_NORMAL,
684 [JOB_UNSUPPORTED] = ANSI_HIGHLIGHT_YELLOW "UNSUPP" ANSI_NORMAL,
685 };
686
687 assert(u);
688 assert(t >= 0);
689 assert(t < _JOB_TYPE_MAX);
690
691 format = job_get_status_message_format(u, t, result);
692 if (!format)
693 return;
694
695 if (result != JOB_DONE)
696 manager_flip_auto_status(u->manager, true);
697
698 DISABLE_WARNING_FORMAT_NONLITERAL;
699 unit_status_printf(u, job_result_status_table[result], format);
700 REENABLE_WARNING;
701
702 if (t == JOB_START && result == JOB_FAILED) {
703 _cleanup_free_ char *quoted = shell_maybe_quote(u->id);
704
705 manager_status_printf(u->manager, STATUS_TYPE_NORMAL, NULL,
706 "See 'systemctl status %s' for details.", strna(quoted));
707 }
708 }
709
710 static void job_log_status_message(Unit *u, JobType t, JobResult result) {
711 const char *format;
712 char buf[LINE_MAX];
713 sd_id128_t mid;
714 static const int job_result_log_level[_JOB_RESULT_MAX] = {
715 [JOB_DONE] = LOG_INFO,
716 [JOB_CANCELED] = LOG_INFO,
717 [JOB_TIMEOUT] = LOG_ERR,
718 [JOB_FAILED] = LOG_ERR,
719 [JOB_DEPENDENCY] = LOG_WARNING,
720 [JOB_SKIPPED] = LOG_NOTICE,
721 [JOB_INVALID] = LOG_INFO,
722 [JOB_ASSERT] = LOG_WARNING,
723 [JOB_UNSUPPORTED] = LOG_WARNING,
724 };
725
726 assert(u);
727 assert(t >= 0);
728 assert(t < _JOB_TYPE_MAX);
729
730 /* Skip this if it goes to the console. since we already print
731 * to the console anyway... */
732
733 if (log_on_console())
734 return;
735
736 format = job_get_status_message_format(u, t, result);
737 if (!format)
738 return;
739
740 DISABLE_WARNING_FORMAT_NONLITERAL;
741 snprintf(buf, sizeof(buf), format, unit_description(u));
742 REENABLE_WARNING;
743
744 if (t == JOB_START)
745 mid = result == JOB_DONE ? SD_MESSAGE_UNIT_STARTED : SD_MESSAGE_UNIT_FAILED;
746 else if (t == JOB_STOP || t == JOB_RESTART)
747 mid = SD_MESSAGE_UNIT_STOPPED;
748 else if (t == JOB_RELOAD)
749 mid = SD_MESSAGE_UNIT_RELOADED;
750 else {
751 log_struct(job_result_log_level[result],
752 LOG_UNIT_ID(u),
753 LOG_MESSAGE("%s", buf),
754 "RESULT=%s", job_result_to_string(result),
755 NULL);
756 return;
757 }
758
759 log_struct(job_result_log_level[result],
760 LOG_MESSAGE_ID(mid),
761 LOG_UNIT_ID(u),
762 LOG_MESSAGE("%s", buf),
763 "RESULT=%s", job_result_to_string(result),
764 NULL);
765 }
766
767 static void job_emit_status_message(Unit *u, JobType t, JobResult result) {
768
769 /* No message if the job did not actually do anything due to failed condition. */
770 if (t == JOB_START && result == JOB_DONE && !u->condition_result)
771 return;
772
773 job_log_status_message(u, t, result);
774
775 /* Reload status messages have traditionally not been printed to console. */
776 if (t != JOB_RELOAD)
777 job_print_status_message(u, t, result);
778 }
779
780 static void job_fail_dependencies(Unit *u, UnitDependency d) {
781 Unit *other;
782 Iterator i;
783
784 assert(u);
785
786 SET_FOREACH(other, u->dependencies[d], i) {
787 Job *j = other->job;
788
789 if (!j)
790 continue;
791 if (!IN_SET(j->type, JOB_START, JOB_VERIFY_ACTIVE))
792 continue;
793
794 job_finish_and_invalidate(j, JOB_DEPENDENCY, true);
795 }
796 }
797
798 int job_finish_and_invalidate(Job *j, JobResult result, bool recursive) {
799 Unit *u;
800 Unit *other;
801 JobType t;
802 Iterator i;
803
804 assert(j);
805 assert(j->installed);
806 assert(j->type < _JOB_TYPE_MAX_IN_TRANSACTION);
807
808 u = j->unit;
809 t = j->type;
810
811 j->result = result;
812
813 log_unit_debug(u, "Job %s/%s finished, result=%s", u->id, job_type_to_string(t), job_result_to_string(result));
814
815 job_emit_status_message(u, t, result);
816
817 job_add_to_dbus_queue(j);
818
819 /* Patch restart jobs so that they become normal start jobs */
820 if (result == JOB_DONE && t == JOB_RESTART) {
821
822 job_change_type(j, JOB_START);
823 job_set_state(j, JOB_WAITING);
824
825 job_add_to_run_queue(j);
826
827 goto finish;
828 }
829
830 if (result == JOB_FAILED || result == JOB_INVALID)
831 j->manager->n_failed_jobs ++;
832
833 job_uninstall(j);
834 job_free(j);
835
836 /* Fail depending jobs on failure */
837 if (result != JOB_DONE && recursive) {
838 if (IN_SET(t, JOB_START, JOB_VERIFY_ACTIVE)) {
839 job_fail_dependencies(u, UNIT_REQUIRED_BY);
840 job_fail_dependencies(u, UNIT_REQUISITE_OF);
841 job_fail_dependencies(u, UNIT_BOUND_BY);
842 job_fail_dependencies(u, UNIT_REQUIRED_BY_OVERRIDABLE);
843 job_fail_dependencies(u, UNIT_REQUISITE_OF_OVERRIDABLE);
844 } else if (t == JOB_STOP)
845 job_fail_dependencies(u, UNIT_CONFLICTED_BY);
846 }
847
848 /* Trigger OnFailure dependencies that are not generated by
849 * the unit itself. We don't treat JOB_CANCELED as failure in
850 * this context. And JOB_FAILURE is already handled by the
851 * unit itself. */
852 if (result == JOB_TIMEOUT || result == JOB_DEPENDENCY) {
853 log_struct(LOG_NOTICE,
854 "JOB_TYPE=%s", job_type_to_string(t),
855 "JOB_RESULT=%s", job_result_to_string(result),
856 LOG_UNIT_ID(u),
857 LOG_UNIT_MESSAGE(u, "Job %s/%s failed with result '%s'.",
858 u->id,
859 job_type_to_string(t),
860 job_result_to_string(result)),
861 NULL);
862
863 unit_start_on_failure(u);
864 }
865
866 unit_trigger_notify(u);
867
868 finish:
869 /* Try to start the next jobs that can be started */
870 SET_FOREACH(other, u->dependencies[UNIT_AFTER], i)
871 if (other->job)
872 job_add_to_run_queue(other->job);
873 SET_FOREACH(other, u->dependencies[UNIT_BEFORE], i)
874 if (other->job)
875 job_add_to_run_queue(other->job);
876
877 manager_check_finished(u->manager);
878
879 return 0;
880 }
881
882 static int job_dispatch_timer(sd_event_source *s, uint64_t monotonic, void *userdata) {
883 Job *j = userdata;
884 Unit *u;
885
886 assert(j);
887 assert(s == j->timer_event_source);
888
889 log_unit_warning(j->unit, "Job %s/%s timed out.", j->unit->id, job_type_to_string(j->type));
890
891 u = j->unit;
892 job_finish_and_invalidate(j, JOB_TIMEOUT, true);
893
894 failure_action(u->manager, u->job_timeout_action, u->job_timeout_reboot_arg);
895
896 return 0;
897 }
898
899 int job_start_timer(Job *j) {
900 int r;
901
902 if (j->timer_event_source)
903 return 0;
904
905 j->begin_usec = now(CLOCK_MONOTONIC);
906
907 if (j->unit->job_timeout <= 0)
908 return 0;
909
910 r = sd_event_add_time(
911 j->manager->event,
912 &j->timer_event_source,
913 CLOCK_MONOTONIC,
914 j->begin_usec + j->unit->job_timeout, 0,
915 job_dispatch_timer, j);
916 if (r < 0)
917 return r;
918
919 (void) sd_event_source_set_description(j->timer_event_source, "job-start");
920
921 return 0;
922 }
923
924 void job_add_to_run_queue(Job *j) {
925 assert(j);
926 assert(j->installed);
927
928 if (j->in_run_queue)
929 return;
930
931 if (!j->manager->run_queue)
932 sd_event_source_set_enabled(j->manager->run_queue_event_source, SD_EVENT_ONESHOT);
933
934 LIST_PREPEND(run_queue, j->manager->run_queue, j);
935 j->in_run_queue = true;
936 }
937
938 void job_add_to_dbus_queue(Job *j) {
939 assert(j);
940 assert(j->installed);
941
942 if (j->in_dbus_queue)
943 return;
944
945 /* We don't check if anybody is subscribed here, since this
946 * job might just have been created and not yet assigned to a
947 * connection/client. */
948
949 LIST_PREPEND(dbus_queue, j->manager->dbus_job_queue, j);
950 j->in_dbus_queue = true;
951 }
952
953 char *job_dbus_path(Job *j) {
954 char *p;
955
956 assert(j);
957
958 if (asprintf(&p, "/org/freedesktop/systemd1/job/%"PRIu32, j->id) < 0)
959 return NULL;
960
961 return p;
962 }
963
964 int job_serialize(Job *j, FILE *f, FDSet *fds) {
965 fprintf(f, "job-id=%u\n", j->id);
966 fprintf(f, "job-type=%s\n", job_type_to_string(j->type));
967 fprintf(f, "job-state=%s\n", job_state_to_string(j->state));
968 fprintf(f, "job-override=%s\n", yes_no(j->override));
969 fprintf(f, "job-irreversible=%s\n", yes_no(j->irreversible));
970 fprintf(f, "job-sent-dbus-new-signal=%s\n", yes_no(j->sent_dbus_new_signal));
971 fprintf(f, "job-ignore-order=%s\n", yes_no(j->ignore_order));
972
973 if (j->begin_usec > 0)
974 fprintf(f, "job-begin="USEC_FMT"\n", j->begin_usec);
975
976 bus_track_serialize(j->clients, f);
977
978 /* End marker */
979 fputc('\n', f);
980 return 0;
981 }
982
983 int job_deserialize(Job *j, FILE *f, FDSet *fds) {
984 assert(j);
985
986 for (;;) {
987 char line[LINE_MAX], *l, *v;
988 size_t k;
989
990 if (!fgets(line, sizeof(line), f)) {
991 if (feof(f))
992 return 0;
993 return -errno;
994 }
995
996 char_array_0(line);
997 l = strstrip(line);
998
999 /* End marker */
1000 if (l[0] == 0)
1001 return 0;
1002
1003 k = strcspn(l, "=");
1004
1005 if (l[k] == '=') {
1006 l[k] = 0;
1007 v = l+k+1;
1008 } else
1009 v = l+k;
1010
1011 if (streq(l, "job-id")) {
1012
1013 if (safe_atou32(v, &j->id) < 0)
1014 log_debug("Failed to parse job id value %s", v);
1015
1016 } else if (streq(l, "job-type")) {
1017 JobType t;
1018
1019 t = job_type_from_string(v);
1020 if (t < 0)
1021 log_debug("Failed to parse job type %s", v);
1022 else if (t >= _JOB_TYPE_MAX_IN_TRANSACTION)
1023 log_debug("Cannot deserialize job of type %s", v);
1024 else
1025 j->type = t;
1026
1027 } else if (streq(l, "job-state")) {
1028 JobState s;
1029
1030 s = job_state_from_string(v);
1031 if (s < 0)
1032 log_debug("Failed to parse job state %s", v);
1033 else
1034 job_set_state(j, s);
1035
1036 } else if (streq(l, "job-override")) {
1037 int b;
1038
1039 b = parse_boolean(v);
1040 if (b < 0)
1041 log_debug("Failed to parse job override flag %s", v);
1042 else
1043 j->override = j->override || b;
1044
1045 } else if (streq(l, "job-irreversible")) {
1046 int b;
1047
1048 b = parse_boolean(v);
1049 if (b < 0)
1050 log_debug("Failed to parse job irreversible flag %s", v);
1051 else
1052 j->irreversible = j->irreversible || b;
1053
1054 } else if (streq(l, "job-sent-dbus-new-signal")) {
1055 int b;
1056
1057 b = parse_boolean(v);
1058 if (b < 0)
1059 log_debug("Failed to parse job sent_dbus_new_signal flag %s", v);
1060 else
1061 j->sent_dbus_new_signal = j->sent_dbus_new_signal || b;
1062
1063 } else if (streq(l, "job-ignore-order")) {
1064 int b;
1065
1066 b = parse_boolean(v);
1067 if (b < 0)
1068 log_debug("Failed to parse job ignore_order flag %s", v);
1069 else
1070 j->ignore_order = j->ignore_order || b;
1071
1072 } else if (streq(l, "job-begin")) {
1073 unsigned long long ull;
1074
1075 if (sscanf(v, "%llu", &ull) != 1)
1076 log_debug("Failed to parse job-begin value %s", v);
1077 else
1078 j->begin_usec = ull;
1079
1080 } else if (streq(l, "subscribed")) {
1081
1082 if (strv_extend(&j->deserialized_clients, v) < 0)
1083 return log_oom();
1084 }
1085 }
1086 }
1087
1088 int job_coldplug(Job *j) {
1089 int r;
1090
1091 assert(j);
1092
1093 /* After deserialization is complete and the bus connection
1094 * set up again, let's start watching our subscribers again */
1095 r = bus_track_coldplug(j->manager, &j->clients, &j->deserialized_clients);
1096 if (r < 0)
1097 return r;
1098
1099 if (j->state == JOB_WAITING)
1100 job_add_to_run_queue(j);
1101
1102 if (j->begin_usec == 0 || j->unit->job_timeout == 0)
1103 return 0;
1104
1105 if (j->timer_event_source)
1106 j->timer_event_source = sd_event_source_unref(j->timer_event_source);
1107
1108 r = sd_event_add_time(
1109 j->manager->event,
1110 &j->timer_event_source,
1111 CLOCK_MONOTONIC,
1112 j->begin_usec + j->unit->job_timeout, 0,
1113 job_dispatch_timer, j);
1114 if (r < 0)
1115 log_debug_errno(r, "Failed to restart timeout for job: %m");
1116
1117 (void) sd_event_source_set_description(j->timer_event_source, "job-timeout");
1118
1119 return r;
1120 }
1121
1122 void job_shutdown_magic(Job *j) {
1123 assert(j);
1124
1125 /* The shutdown target gets some special treatment here: we
1126 * tell the kernel to begin with flushing its disk caches, to
1127 * optimize shutdown time a bit. Ideally we wouldn't hardcode
1128 * this magic into PID 1. However all other processes aren't
1129 * options either since they'd exit much sooner than PID 1 and
1130 * asynchronous sync() would cause their exit to be
1131 * delayed. */
1132
1133 if (j->type != JOB_START)
1134 return;
1135
1136 if (j->unit->manager->running_as != MANAGER_SYSTEM)
1137 return;
1138
1139 if (!unit_has_name(j->unit, SPECIAL_SHUTDOWN_TARGET))
1140 return;
1141
1142 /* In case messages on console has been disabled on boot */
1143 j->unit->manager->no_console_output = false;
1144
1145 if (detect_container() > 0)
1146 return;
1147
1148 asynchronous_sync();
1149 }
1150
1151 int job_get_timeout(Job *j, uint64_t *timeout) {
1152 Unit *u = j->unit;
1153 uint64_t x = -1, y = -1;
1154 int r = 0, q = 0;
1155
1156 assert(u);
1157
1158 if (j->timer_event_source) {
1159 r = sd_event_source_get_time(j->timer_event_source, &x);
1160 if (r < 0)
1161 return r;
1162 r = 1;
1163 }
1164
1165 if (UNIT_VTABLE(u)->get_timeout) {
1166 q = UNIT_VTABLE(u)->get_timeout(u, &y);
1167 if (q < 0)
1168 return q;
1169 }
1170
1171 if (r == 0 && q == 0)
1172 return 0;
1173
1174 *timeout = MIN(x, y);
1175
1176 return 1;
1177 }
1178
1179 static const char* const job_state_table[_JOB_STATE_MAX] = {
1180 [JOB_WAITING] = "waiting",
1181 [JOB_RUNNING] = "running"
1182 };
1183
1184 DEFINE_STRING_TABLE_LOOKUP(job_state, JobState);
1185
1186 static const char* const job_type_table[_JOB_TYPE_MAX] = {
1187 [JOB_START] = "start",
1188 [JOB_VERIFY_ACTIVE] = "verify-active",
1189 [JOB_STOP] = "stop",
1190 [JOB_RELOAD] = "reload",
1191 [JOB_RELOAD_OR_START] = "reload-or-start",
1192 [JOB_RESTART] = "restart",
1193 [JOB_TRY_RESTART] = "try-restart",
1194 [JOB_NOP] = "nop",
1195 };
1196
1197 DEFINE_STRING_TABLE_LOOKUP(job_type, JobType);
1198
1199 static const char* const job_mode_table[_JOB_MODE_MAX] = {
1200 [JOB_FAIL] = "fail",
1201 [JOB_REPLACE] = "replace",
1202 [JOB_REPLACE_IRREVERSIBLY] = "replace-irreversibly",
1203 [JOB_ISOLATE] = "isolate",
1204 [JOB_FLUSH] = "flush",
1205 [JOB_IGNORE_DEPENDENCIES] = "ignore-dependencies",
1206 [JOB_IGNORE_REQUIREMENTS] = "ignore-requirements",
1207 };
1208
1209 DEFINE_STRING_TABLE_LOOKUP(job_mode, JobMode);
1210
1211 static const char* const job_result_table[_JOB_RESULT_MAX] = {
1212 [JOB_DONE] = "done",
1213 [JOB_CANCELED] = "canceled",
1214 [JOB_TIMEOUT] = "timeout",
1215 [JOB_FAILED] = "failed",
1216 [JOB_DEPENDENCY] = "dependency",
1217 [JOB_SKIPPED] = "skipped",
1218 [JOB_INVALID] = "invalid",
1219 [JOB_ASSERT] = "assert",
1220 [JOB_UNSUPPORTED] = "unsupported",
1221 };
1222
1223 DEFINE_STRING_TABLE_LOOKUP(job_result, JobResult);