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