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