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