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