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