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