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