chiark / gitweb /
manager: when two pending jobs conflict, keep the one that "conflicts", remove the...
[elogind.git] / src / unit.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 General Public License as published by
10   the Free Software Foundation; either version 2 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   General Public License for more details.
17
18   You should have received a copy of the GNU 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 <string.h>
25 #include <sys/epoll.h>
26 #include <sys/timerfd.h>
27 #include <sys/poll.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <sys/stat.h>
31
32 #include "set.h"
33 #include "unit.h"
34 #include "macro.h"
35 #include "strv.h"
36 #include "load-fragment.h"
37 #include "load-dropin.h"
38 #include "log.h"
39 #include "unit-name.h"
40 #include "specifier.h"
41 #include "dbus-unit.h"
42 #include "special.h"
43 #include "cgroup-util.h"
44
45 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
46         [UNIT_SERVICE] = &service_vtable,
47         [UNIT_TIMER] = &timer_vtable,
48         [UNIT_SOCKET] = &socket_vtable,
49         [UNIT_TARGET] = &target_vtable,
50         [UNIT_DEVICE] = &device_vtable,
51         [UNIT_MOUNT] = &mount_vtable,
52         [UNIT_AUTOMOUNT] = &automount_vtable,
53         [UNIT_SNAPSHOT] = &snapshot_vtable,
54         [UNIT_SWAP] = &swap_vtable,
55         [UNIT_PATH] = &path_vtable
56 };
57
58 Unit *unit_new(Manager *m) {
59         Unit *u;
60
61         assert(m);
62
63         if (!(u = new0(Unit, 1)))
64                 return NULL;
65
66         if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
67                 free(u);
68                 return NULL;
69         }
70
71         u->meta.manager = m;
72         u->meta.type = _UNIT_TYPE_INVALID;
73         u->meta.deserialized_job = _JOB_TYPE_INVALID;
74         u->meta.default_dependencies = true;
75
76         return u;
77 }
78
79 bool unit_has_name(Unit *u, const char *name) {
80         assert(u);
81         assert(name);
82
83         return !!set_get(u->meta.names, (char*) name);
84 }
85
86 int unit_add_name(Unit *u, const char *text) {
87         UnitType t;
88         char *s, *i = NULL;
89         int r;
90
91         assert(u);
92         assert(text);
93
94         if (unit_name_is_template(text)) {
95                 if (!u->meta.instance)
96                         return -EINVAL;
97
98                 s = unit_name_replace_instance(text, u->meta.instance);
99         } else
100                 s = strdup(text);
101
102         if (!s)
103                 return -ENOMEM;
104
105         if (!unit_name_is_valid(s)) {
106                 r = -EINVAL;
107                 goto fail;
108         }
109
110         assert_se((t = unit_name_to_type(s)) >= 0);
111
112         if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type) {
113                 r = -EINVAL;
114                 goto fail;
115         }
116
117         if ((r = unit_name_to_instance(s, &i)) < 0)
118                 goto fail;
119
120         if (i && unit_vtable[t]->no_instances)
121                 goto fail;
122
123         /* Ensure that this unit is either instanced or not instanced,
124          * but not both. */
125         if (u->meta.type != _UNIT_TYPE_INVALID && !u->meta.instance != !i) {
126                 r = -EINVAL;
127                 goto fail;
128         }
129
130         if (unit_vtable[t]->no_alias &&
131             !set_isempty(u->meta.names) &&
132             !set_get(u->meta.names, s)) {
133                 r = -EEXIST;
134                 goto fail;
135         }
136
137         if (hashmap_size(u->meta.manager->units) >= MANAGER_MAX_NAMES) {
138                 r = -E2BIG;
139                 goto fail;
140         }
141
142         if ((r = set_put(u->meta.names, s)) < 0) {
143                 if (r == -EEXIST)
144                         r = 0;
145                 goto fail;
146         }
147
148         if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
149                 set_remove(u->meta.names, s);
150                 goto fail;
151         }
152
153         if (u->meta.type == _UNIT_TYPE_INVALID) {
154
155                 u->meta.type = t;
156                 u->meta.id = s;
157                 u->meta.instance = i;
158
159                 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
160
161                 if (UNIT_VTABLE(u)->init)
162                         UNIT_VTABLE(u)->init(u);
163         } else
164                 free(i);
165
166         unit_add_to_dbus_queue(u);
167         return 0;
168
169 fail:
170         free(s);
171         free(i);
172
173         return r;
174 }
175
176 int unit_choose_id(Unit *u, const char *name) {
177         char *s, *t = NULL, *i;
178         int r;
179
180         assert(u);
181         assert(name);
182
183         if (unit_name_is_template(name)) {
184
185                 if (!u->meta.instance)
186                         return -EINVAL;
187
188                 if (!(t = unit_name_replace_instance(name, u->meta.instance)))
189                         return -ENOMEM;
190
191                 name = t;
192         }
193
194         /* Selects one of the names of this unit as the id */
195         s = set_get(u->meta.names, (char*) name);
196         free(t);
197
198         if (!s)
199                 return -ENOENT;
200
201         if ((r = unit_name_to_instance(s, &i)) < 0)
202                 return r;
203
204         u->meta.id = s;
205
206         free(u->meta.instance);
207         u->meta.instance = i;
208
209         unit_add_to_dbus_queue(u);
210
211         return 0;
212 }
213
214 int unit_set_description(Unit *u, const char *description) {
215         char *s;
216
217         assert(u);
218
219         if (!(s = strdup(description)))
220                 return -ENOMEM;
221
222         free(u->meta.description);
223         u->meta.description = s;
224
225         unit_add_to_dbus_queue(u);
226         return 0;
227 }
228
229 bool unit_check_gc(Unit *u) {
230         assert(u);
231
232         if (u->meta.load_state == UNIT_STUB)
233                 return true;
234
235         if (UNIT_VTABLE(u)->no_gc)
236                 return true;
237
238         if (u->meta.job)
239                 return true;
240
241         if (unit_active_state(u) != UNIT_INACTIVE)
242                 return true;
243
244         if (UNIT_VTABLE(u)->check_gc)
245                 if (UNIT_VTABLE(u)->check_gc(u))
246                         return true;
247
248         return false;
249 }
250
251 void unit_add_to_load_queue(Unit *u) {
252         assert(u);
253         assert(u->meta.type != _UNIT_TYPE_INVALID);
254
255         if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
256                 return;
257
258         LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
259         u->meta.in_load_queue = true;
260 }
261
262 void unit_add_to_cleanup_queue(Unit *u) {
263         assert(u);
264
265         if (u->meta.in_cleanup_queue)
266                 return;
267
268         LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
269         u->meta.in_cleanup_queue = true;
270 }
271
272 void unit_add_to_gc_queue(Unit *u) {
273         assert(u);
274
275         if (u->meta.in_gc_queue || u->meta.in_cleanup_queue)
276                 return;
277
278         if (unit_check_gc(u))
279                 return;
280
281         LIST_PREPEND(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
282         u->meta.in_gc_queue = true;
283
284         u->meta.manager->n_in_gc_queue ++;
285
286         if (u->meta.manager->gc_queue_timestamp <= 0)
287                 u->meta.manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
288 }
289
290 void unit_add_to_dbus_queue(Unit *u) {
291         assert(u);
292         assert(u->meta.type != _UNIT_TYPE_INVALID);
293
294         if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue)
295                 return;
296
297         /* Shortcut things if nobody cares */
298         if (!bus_has_subscriber(u->meta.manager)) {
299                 u->meta.sent_dbus_new_signal = true;
300                 return;
301         }
302
303         LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
304         u->meta.in_dbus_queue = true;
305 }
306
307 static void bidi_set_free(Unit *u, Set *s) {
308         Iterator i;
309         Unit *other;
310
311         assert(u);
312
313         /* Frees the set and makes sure we are dropped from the
314          * inverse pointers */
315
316         SET_FOREACH(other, s, i) {
317                 UnitDependency d;
318
319                 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
320                         set_remove(other->meta.dependencies[d], u);
321
322                 unit_add_to_gc_queue(other);
323         }
324
325         set_free(s);
326 }
327
328 void unit_free(Unit *u) {
329         UnitDependency d;
330         Iterator i;
331         char *t;
332
333         assert(u);
334
335         bus_unit_send_removed_signal(u);
336
337         if (u->meta.load_state != UNIT_STUB)
338                 if (UNIT_VTABLE(u)->done)
339                         UNIT_VTABLE(u)->done(u);
340
341         SET_FOREACH(t, u->meta.names, i)
342                 hashmap_remove_value(u->meta.manager->units, t, u);
343
344         if (u->meta.job)
345                 job_free(u->meta.job);
346
347         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
348                 bidi_set_free(u, u->meta.dependencies[d]);
349
350         if (u->meta.type != _UNIT_TYPE_INVALID)
351                 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
352
353         if (u->meta.in_load_queue)
354                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
355
356         if (u->meta.in_dbus_queue)
357                 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
358
359         if (u->meta.in_cleanup_queue)
360                 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
361
362         if (u->meta.in_gc_queue) {
363                 LIST_REMOVE(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
364                 u->meta.manager->n_in_gc_queue--;
365         }
366
367         cgroup_bonding_free_list(u->meta.cgroup_bondings);
368
369         free(u->meta.description);
370         free(u->meta.fragment_path);
371
372         set_free_free(u->meta.names);
373
374         free(u->meta.instance);
375
376         free(u);
377 }
378
379 UnitActiveState unit_active_state(Unit *u) {
380         assert(u);
381
382         if (u->meta.load_state == UNIT_MERGED)
383                 return unit_active_state(unit_follow_merge(u));
384
385         /* After a reload it might happen that a unit is not correctly
386          * loaded but still has a process around. That's why we won't
387          * shortcut failed loading to UNIT_INACTIVE_MAINTENANCE. */
388
389         return UNIT_VTABLE(u)->active_state(u);
390 }
391
392 const char* unit_sub_state_to_string(Unit *u) {
393         assert(u);
394
395         return UNIT_VTABLE(u)->sub_state_to_string(u);
396 }
397
398 static void complete_move(Set **s, Set **other) {
399         assert(s);
400         assert(other);
401
402         if (!*other)
403                 return;
404
405         if (*s)
406                 set_move(*s, *other);
407         else {
408                 *s = *other;
409                 *other = NULL;
410         }
411 }
412
413 static void merge_names(Unit *u, Unit *other) {
414         char *t;
415         Iterator i;
416
417         assert(u);
418         assert(other);
419
420         complete_move(&u->meta.names, &other->meta.names);
421
422         set_free_free(other->meta.names);
423         other->meta.names = NULL;
424         other->meta.id = NULL;
425
426         SET_FOREACH(t, u->meta.names, i)
427                 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
428 }
429
430 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
431         Iterator i;
432         Unit *back;
433         int r;
434
435         assert(u);
436         assert(other);
437         assert(d < _UNIT_DEPENDENCY_MAX);
438
439         SET_FOREACH(back, other->meta.dependencies[d], i) {
440                 UnitDependency k;
441
442                 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
443                         if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
444
445                                 if (r == -EEXIST)
446                                         set_remove(back->meta.dependencies[k], other);
447                                 else
448                                         assert(r == -ENOENT);
449                         }
450         }
451
452         complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
453
454         set_free(other->meta.dependencies[d]);
455         other->meta.dependencies[d] = NULL;
456 }
457
458 int unit_merge(Unit *u, Unit *other) {
459         UnitDependency d;
460
461         assert(u);
462         assert(other);
463         assert(u->meta.manager == other->meta.manager);
464         assert(u->meta.type != _UNIT_TYPE_INVALID);
465
466         other = unit_follow_merge(other);
467
468         if (other == u)
469                 return 0;
470
471         if (u->meta.type != other->meta.type)
472                 return -EINVAL;
473
474         if (!u->meta.instance != !other->meta.instance)
475                 return -EINVAL;
476
477         if (other->meta.load_state != UNIT_STUB &&
478             other->meta.load_state != UNIT_FAILED)
479                 return -EEXIST;
480
481         if (other->meta.job)
482                 return -EEXIST;
483
484         if (!UNIT_IS_INACTIVE_OR_MAINTENANCE(unit_active_state(other)))
485                 return -EEXIST;
486
487         /* Merge names */
488         merge_names(u, other);
489
490         /* Merge dependencies */
491         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
492                 merge_dependencies(u, other, d);
493
494         other->meta.load_state = UNIT_MERGED;
495         other->meta.merged_into = u;
496
497         /* If there is still some data attached to the other node, we
498          * don't need it anymore, and can free it. */
499         if (other->meta.load_state != UNIT_STUB)
500                 if (UNIT_VTABLE(other)->done)
501                         UNIT_VTABLE(other)->done(other);
502
503         unit_add_to_dbus_queue(u);
504         unit_add_to_cleanup_queue(other);
505
506         return 0;
507 }
508
509 int unit_merge_by_name(Unit *u, const char *name) {
510         Unit *other;
511         int r;
512         char *s = NULL;
513
514         assert(u);
515         assert(name);
516
517         if (unit_name_is_template(name)) {
518                 if (!u->meta.instance)
519                         return -EINVAL;
520
521                 if (!(s = unit_name_replace_instance(name, u->meta.instance)))
522                         return -ENOMEM;
523
524                 name = s;
525         }
526
527         if (!(other = manager_get_unit(u->meta.manager, name)))
528                 r = unit_add_name(u, name);
529         else
530                 r = unit_merge(u, other);
531
532         free(s);
533         return r;
534 }
535
536 Unit* unit_follow_merge(Unit *u) {
537         assert(u);
538
539         while (u->meta.load_state == UNIT_MERGED)
540                 assert_se(u = u->meta.merged_into);
541
542         return u;
543 }
544
545 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
546         int r;
547
548         assert(u);
549         assert(c);
550
551         if (c->std_output != EXEC_OUTPUT_KMSG &&
552             c->std_output != EXEC_OUTPUT_SYSLOG &&
553             c->std_error != EXEC_OUTPUT_KMSG &&
554             c->std_error != EXEC_OUTPUT_SYSLOG)
555                 return 0;
556
557         /* If syslog or kernel logging is requested, make sure our own
558          * logging daemon is run first. */
559
560         if ((r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
561                 return r;
562
563         if (u->meta.manager->running_as == MANAGER_SYSTEM)
564                 if ((r = unit_add_dependency_by_name(u, UNIT_REQUIRES, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
565                         return r;
566
567         return 0;
568 }
569
570 const char *unit_description(Unit *u) {
571         assert(u);
572
573         if (u->meta.description)
574                 return u->meta.description;
575
576         return u->meta.id;
577 }
578
579 void unit_dump(Unit *u, FILE *f, const char *prefix) {
580         char *t;
581         UnitDependency d;
582         Iterator i;
583         char *p2;
584         const char *prefix2;
585         CGroupBonding *b;
586         char
587                 timestamp1[FORMAT_TIMESTAMP_MAX],
588                 timestamp2[FORMAT_TIMESTAMP_MAX],
589                 timestamp3[FORMAT_TIMESTAMP_MAX],
590                 timestamp4[FORMAT_TIMESTAMP_MAX],
591                 timespan[FORMAT_TIMESPAN_MAX];
592         Unit *following;
593
594         assert(u);
595         assert(u->meta.type >= 0);
596
597         if (!prefix)
598                 prefix = "";
599         p2 = strappend(prefix, "\t");
600         prefix2 = p2 ? p2 : prefix;
601
602         fprintf(f,
603                 "%s-> Unit %s:\n"
604                 "%s\tDescription: %s\n"
605                 "%s\tInstance: %s\n"
606                 "%s\tUnit Load State: %s\n"
607                 "%s\tUnit Active State: %s\n"
608                 "%s\tInactive Exit Timestamp: %s\n"
609                 "%s\tActive Enter Timestamp: %s\n"
610                 "%s\tActive Exit Timestamp: %s\n"
611                 "%s\tInactive Enter Timestamp: %s\n"
612                 "%s\tGC Check Good: %s\n"
613                 "%s\tNeed Daemon Reload: %s\n",
614                 prefix, u->meta.id,
615                 prefix, unit_description(u),
616                 prefix, strna(u->meta.instance),
617                 prefix, unit_load_state_to_string(u->meta.load_state),
618                 prefix, unit_active_state_to_string(unit_active_state(u)),
619                 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp.realtime)),
620                 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp.realtime)),
621                 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp.realtime)),
622                 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp.realtime)),
623                 prefix, yes_no(unit_check_gc(u)),
624                 prefix, yes_no(unit_need_daemon_reload(u)));
625
626         SET_FOREACH(t, u->meta.names, i)
627                 fprintf(f, "%s\tName: %s\n", prefix, t);
628
629         if ((following = unit_following(u)))
630                 fprintf(f, "%s\tFollowing: %s\n", prefix, following->meta.id);
631
632         if (u->meta.fragment_path)
633                 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
634
635         if (u->meta.job_timeout > 0)
636                 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->meta.job_timeout));
637
638         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
639                 Unit *other;
640
641                 SET_FOREACH(other, u->meta.dependencies[d], i)
642                         fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
643         }
644
645         if (u->meta.load_state == UNIT_LOADED) {
646                 fprintf(f,
647                         "%s\tRecursive Stop: %s\n"
648                         "%s\tStopWhenUnneeded: %s\n"
649                         "%s\tOnlyByDependency: %s\n"
650                         "%s\tDefaultDependencies: %s\n"
651                         "%s\tIgnoreDependencyFailure: %s\n",
652                         prefix, yes_no(u->meta.recursive_stop),
653                         prefix, yes_no(u->meta.stop_when_unneeded),
654                         prefix, yes_no(u->meta.only_by_dependency),
655                         prefix, yes_no(u->meta.default_dependencies),
656                         prefix, yes_no(u->meta.ignore_dependency_failure));
657
658                 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
659                         fprintf(f, "%s\tControlGroup: %s:%s\n",
660                                 prefix, b->controller, b->path);
661
662                 if (UNIT_VTABLE(u)->dump)
663                         UNIT_VTABLE(u)->dump(u, f, prefix2);
664
665         } else if (u->meta.load_state == UNIT_MERGED)
666                 fprintf(f,
667                         "%s\tMerged into: %s\n",
668                         prefix, u->meta.merged_into->meta.id);
669
670         if (u->meta.job)
671                 job_dump(u->meta.job, f, prefix2);
672
673         free(p2);
674 }
675
676 /* Common implementation for multiple backends */
677 int unit_load_fragment_and_dropin(Unit *u) {
678         int r;
679
680         assert(u);
681
682         /* Load a .service file */
683         if ((r = unit_load_fragment(u)) < 0)
684                 return r;
685
686         if (u->meta.load_state == UNIT_STUB)
687                 return -ENOENT;
688
689         /* Load drop-in directory data */
690         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
691                 return r;
692
693         return 0;
694 }
695
696 /* Common implementation for multiple backends */
697 int unit_load_fragment_and_dropin_optional(Unit *u) {
698         int r;
699
700         assert(u);
701
702         /* Same as unit_load_fragment_and_dropin(), but whether
703          * something can be loaded or not doesn't matter. */
704
705         /* Load a .service file */
706         if ((r = unit_load_fragment(u)) < 0)
707                 return r;
708
709         if (u->meta.load_state == UNIT_STUB)
710                 u->meta.load_state = UNIT_LOADED;
711
712         /* Load drop-in directory data */
713         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
714                 return r;
715
716         return 0;
717 }
718
719 /* Common implementation for multiple backends */
720 int unit_load_nop(Unit *u) {
721         assert(u);
722
723         if (u->meta.load_state == UNIT_STUB)
724                 u->meta.load_state = UNIT_LOADED;
725
726         return 0;
727 }
728
729 int unit_load(Unit *u) {
730         int r;
731
732         assert(u);
733
734         if (u->meta.in_load_queue) {
735                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
736                 u->meta.in_load_queue = false;
737         }
738
739         if (u->meta.type == _UNIT_TYPE_INVALID)
740                 return -EINVAL;
741
742         if (u->meta.load_state != UNIT_STUB)
743                 return 0;
744
745         if (UNIT_VTABLE(u)->load)
746                 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
747                         goto fail;
748
749         if (u->meta.load_state == UNIT_STUB) {
750                 r = -ENOENT;
751                 goto fail;
752         }
753
754         assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
755
756         unit_add_to_dbus_queue(unit_follow_merge(u));
757         unit_add_to_gc_queue(u);
758
759         return 0;
760
761 fail:
762         u->meta.load_state = UNIT_FAILED;
763         unit_add_to_dbus_queue(u);
764
765         log_notice("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
766
767         return r;
768 }
769
770 /* Errors:
771  *         -EBADR:     This unit type does not support starting.
772  *         -EALREADY:  Unit is already started.
773  *         -EAGAIN:    An operation is already in progress. Retry later.
774  *         -ECANCELED: Too many requests for now.
775  */
776 int unit_start(Unit *u) {
777         UnitActiveState state;
778
779         assert(u);
780
781         if (u->meta.load_state != UNIT_LOADED)
782                 return -EINVAL;
783
784         /* If this is already (being) started, then this will
785          * succeed. Note that this will even succeed if this unit is
786          * not startable by the user. This is relied on to detect when
787          * we need to wait for units and when waiting is finished. */
788         state = unit_active_state(u);
789         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
790                 return -EALREADY;
791
792         /* If it is stopped, but we cannot start it, then fail */
793         if (!UNIT_VTABLE(u)->start)
794                 return -EBADR;
795
796         /* We don't suppress calls to ->start() here when we are
797          * already starting, to allow this request to be used as a
798          * "hurry up" call, for example when the unit is in some "auto
799          * restart" state where it waits for a holdoff timer to elapse
800          * before it will start again. */
801
802         unit_add_to_dbus_queue(u);
803
804         unit_status_printf(u, "Starting %s...\n", unit_description(u));
805
806         return UNIT_VTABLE(u)->start(u);
807 }
808
809 bool unit_can_start(Unit *u) {
810         assert(u);
811
812         return !!UNIT_VTABLE(u)->start;
813 }
814
815 /* Errors:
816  *         -EBADR:    This unit type does not support stopping.
817  *         -EALREADY: Unit is already stopped.
818  *         -EAGAIN:   An operation is already in progress. Retry later.
819  */
820 int unit_stop(Unit *u) {
821         UnitActiveState state;
822
823         assert(u);
824
825         state = unit_active_state(u);
826         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(state))
827                 return -EALREADY;
828
829         if (!UNIT_VTABLE(u)->stop)
830                 return -EBADR;
831
832         unit_add_to_dbus_queue(u);
833
834         unit_status_printf(u, "Stopping %s...\n", unit_description(u));
835
836         return UNIT_VTABLE(u)->stop(u);
837 }
838
839 /* Errors:
840  *         -EBADR:    This unit type does not support reloading.
841  *         -ENOEXEC:  Unit is not started.
842  *         -EAGAIN:   An operation is already in progress. Retry later.
843  */
844 int unit_reload(Unit *u) {
845         UnitActiveState state;
846
847         assert(u);
848
849         if (u->meta.load_state != UNIT_LOADED)
850                 return -EINVAL;
851
852         if (!unit_can_reload(u))
853                 return -EBADR;
854
855         state = unit_active_state(u);
856         if (unit_active_state(u) == UNIT_RELOADING)
857                 return -EALREADY;
858
859         if (unit_active_state(u) != UNIT_ACTIVE)
860                 return -ENOEXEC;
861
862         unit_add_to_dbus_queue(u);
863         return UNIT_VTABLE(u)->reload(u);
864 }
865
866 bool unit_can_reload(Unit *u) {
867         assert(u);
868
869         if (!UNIT_VTABLE(u)->reload)
870                 return false;
871
872         if (!UNIT_VTABLE(u)->can_reload)
873                 return true;
874
875         return UNIT_VTABLE(u)->can_reload(u);
876 }
877
878 static void unit_check_uneeded(Unit *u) {
879         Iterator i;
880         Unit *other;
881
882         assert(u);
883
884         /* If this service shall be shut down when unneeded then do
885          * so. */
886
887         if (!u->meta.stop_when_unneeded)
888                 return;
889
890         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
891                 return;
892
893         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
894                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
895                         return;
896
897         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
898                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
899                         return;
900
901         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
902                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
903                         return;
904
905         log_info("Service %s is not needed anymore. Stopping.", u->meta.id);
906
907         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
908         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
909 }
910
911 static void retroactively_start_dependencies(Unit *u) {
912         Iterator i;
913         Unit *other;
914
915         assert(u);
916         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
917
918         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
919                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
920                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
921
922         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
923                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
924                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
925
926         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
927                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
928                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
929
930         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
931                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
932                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
933
934         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
935                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
936                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
937
938         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTED_BY], i)
939                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
940                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
941 }
942
943 static void retroactively_stop_dependencies(Unit *u) {
944         Iterator i;
945         Unit *other;
946
947         assert(u);
948         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
949
950         if (u->meta.recursive_stop) {
951                 /* Pull down units need us recursively if enabled */
952                 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
953                         if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
954                                 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
955         }
956
957         /* Garbage collect services that might not be needed anymore, if enabled */
958         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
959                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
960                         unit_check_uneeded(other);
961         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
962                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
963                         unit_check_uneeded(other);
964         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
965                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
966                         unit_check_uneeded(other);
967         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
968                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
969                         unit_check_uneeded(other);
970         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
971                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
972                         unit_check_uneeded(other);
973 }
974
975 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
976         dual_timestamp ts;
977         bool unexpected;
978
979         assert(u);
980         assert(os < _UNIT_ACTIVE_STATE_MAX);
981         assert(ns < _UNIT_ACTIVE_STATE_MAX);
982
983         /* Note that this is called for all low-level state changes,
984          * even if they might map to the same high-level
985          * UnitActiveState! That means that ns == os is OK an expected
986          * behaviour here. For example: if a mount point is remounted
987          * this function will be called too and the utmp code below
988          * relies on that! */
989
990         dual_timestamp_get(&ts);
991
992         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(os) && !UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
993                 u->meta.inactive_exit_timestamp = ts;
994         else if (!UNIT_IS_INACTIVE_OR_MAINTENANCE(os) && UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
995                 u->meta.inactive_enter_timestamp = ts;
996
997         if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
998                 u->meta.active_enter_timestamp = ts;
999         else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1000                 u->meta.active_exit_timestamp = ts;
1001
1002         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
1003                 cgroup_bonding_trim_list(u->meta.cgroup_bondings, true);
1004
1005         timer_unit_notify(u, ns);
1006         path_unit_notify(u, ns);
1007
1008         if (u->meta.job) {
1009                 unexpected = false;
1010
1011                 if (u->meta.job->state == JOB_WAITING)
1012
1013                         /* So we reached a different state for this
1014                          * job. Let's see if we can run it now if it
1015                          * failed previously due to EAGAIN. */
1016                         job_add_to_run_queue(u->meta.job);
1017
1018                 /* Let's check whether this state change constitutes a
1019                  * finished job, or maybe cotradicts a running job and
1020                  * hence needs to invalidate jobs. */
1021
1022                 switch (u->meta.job->type) {
1023
1024                 case JOB_START:
1025                 case JOB_VERIFY_ACTIVE:
1026
1027                         if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1028                                 job_finish_and_invalidate(u->meta.job, true);
1029                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1030                                 unexpected = true;
1031                                 job_finish_and_invalidate(u->meta.job, false);
1032                         }
1033
1034                         break;
1035
1036                 case JOB_RELOAD:
1037                 case JOB_RELOAD_OR_START:
1038
1039                         if (u->meta.job->state == JOB_RUNNING) {
1040                                 if (ns == UNIT_ACTIVE)
1041                                         job_finish_and_invalidate(u->meta.job, true);
1042                                 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1043                                         unexpected = true;
1044                                         job_finish_and_invalidate(u->meta.job, false);
1045                                 }
1046                         }
1047
1048                         break;
1049
1050                 case JOB_STOP:
1051                 case JOB_RESTART:
1052                 case JOB_TRY_RESTART:
1053
1054                         if (ns == UNIT_INACTIVE || ns == UNIT_MAINTENANCE)
1055                                 job_finish_and_invalidate(u->meta.job, true);
1056                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1057                                 unexpected = true;
1058                                 job_finish_and_invalidate(u->meta.job, false);
1059                         }
1060
1061                         break;
1062
1063                 default:
1064                         assert_not_reached("Job type unknown");
1065                 }
1066
1067         } else
1068                 unexpected = true;
1069
1070         /* If this state change happened without being requested by a
1071          * job, then let's retroactively start or stop
1072          * dependencies. We skip that step when deserializing, since
1073          * we don't want to create any additional jobs just because
1074          * something is already activated. */
1075
1076         if (unexpected && u->meta.manager->n_deserializing <= 0) {
1077                 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1078                         retroactively_start_dependencies(u);
1079                 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1080                         retroactively_stop_dependencies(u);
1081         }
1082
1083         if (ns != os && ns == UNIT_MAINTENANCE) {
1084                 Iterator i;
1085                 Unit *other;
1086
1087                 SET_FOREACH(other, u->meta.dependencies[UNIT_ON_FAILURE], i)
1088                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1089
1090                 log_notice("Unit %s entered maintenance state.", u->meta.id);
1091         }
1092
1093         /* Some names are special */
1094         if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1095                 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
1096                         /* The bus just might have become available,
1097                          * hence try to connect to it, if we aren't
1098                          * yet connected. */
1099                         bus_init(u->meta.manager);
1100                 }
1101
1102                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1103                         /* The syslog daemon just might have become
1104                          * available, hence try to connect to it, if
1105                          * we aren't yet connected. */
1106                         log_open();
1107
1108                 if (u->meta.type == UNIT_MOUNT)
1109                         /* Another directory became available, let's
1110                          * check if that is enough to write our utmp
1111                          * entry. */
1112                         manager_write_utmp_reboot(u->meta.manager);
1113
1114                 if (u->meta.type == UNIT_TARGET)
1115                         /* A target got activated, maybe this is a runlevel? */
1116                         manager_write_utmp_runlevel(u->meta.manager, u);
1117
1118         } else if (!UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1119
1120                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1121                         /* The syslog daemon might just have
1122                          * terminated, hence try to disconnect from
1123                          * it. */
1124                         log_close_syslog();
1125
1126                 /* We don't care about D-Bus here, since we'll get an
1127                  * asynchronous notification for it anyway. */
1128         }
1129
1130         /* Maybe we finished startup and are now ready for being
1131          * stopped because unneeded? */
1132         unit_check_uneeded(u);
1133
1134         unit_add_to_dbus_queue(u);
1135         unit_add_to_gc_queue(u);
1136 }
1137
1138 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1139         struct epoll_event ev;
1140
1141         assert(u);
1142         assert(fd >= 0);
1143         assert(w);
1144         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1145
1146         zero(ev);
1147         ev.data.ptr = w;
1148         ev.events = events;
1149
1150         if (epoll_ctl(u->meta.manager->epoll_fd,
1151                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1152                       fd,
1153                       &ev) < 0)
1154                 return -errno;
1155
1156         w->fd = fd;
1157         w->type = WATCH_FD;
1158         w->data.unit = u;
1159
1160         return 0;
1161 }
1162
1163 void unit_unwatch_fd(Unit *u, Watch *w) {
1164         assert(u);
1165         assert(w);
1166
1167         if (w->type == WATCH_INVALID)
1168                 return;
1169
1170         assert(w->type == WATCH_FD);
1171         assert(w->data.unit == u);
1172         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1173
1174         w->fd = -1;
1175         w->type = WATCH_INVALID;
1176         w->data.unit = NULL;
1177 }
1178
1179 int unit_watch_pid(Unit *u, pid_t pid) {
1180         assert(u);
1181         assert(pid >= 1);
1182
1183         /* Watch a specific PID. We only support one unit watching
1184          * each PID for now. */
1185
1186         return hashmap_put(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1187 }
1188
1189 void unit_unwatch_pid(Unit *u, pid_t pid) {
1190         assert(u);
1191         assert(pid >= 1);
1192
1193         hashmap_remove_value(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1194 }
1195
1196 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1197         struct itimerspec its;
1198         int flags, fd;
1199         bool ours;
1200
1201         assert(u);
1202         assert(w);
1203         assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1204
1205         /* This will try to reuse the old timer if there is one */
1206
1207         if (w->type == WATCH_UNIT_TIMER) {
1208                 assert(w->data.unit == u);
1209                 assert(w->fd >= 0);
1210
1211                 ours = false;
1212                 fd = w->fd;
1213         } else if (w->type == WATCH_INVALID) {
1214
1215                 ours = true;
1216                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1217                         return -errno;
1218         } else
1219                 assert_not_reached("Invalid watch type");
1220
1221         zero(its);
1222
1223         if (delay <= 0) {
1224                 /* Set absolute time in the past, but not 0, since we
1225                  * don't want to disarm the timer */
1226                 its.it_value.tv_sec = 0;
1227                 its.it_value.tv_nsec = 1;
1228
1229                 flags = TFD_TIMER_ABSTIME;
1230         } else {
1231                 timespec_store(&its.it_value, delay);
1232                 flags = 0;
1233         }
1234
1235         /* This will also flush the elapse counter */
1236         if (timerfd_settime(fd, flags, &its, NULL) < 0)
1237                 goto fail;
1238
1239         if (w->type == WATCH_INVALID) {
1240                 struct epoll_event ev;
1241
1242                 zero(ev);
1243                 ev.data.ptr = w;
1244                 ev.events = EPOLLIN;
1245
1246                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1247                         goto fail;
1248         }
1249
1250         w->type = WATCH_UNIT_TIMER;
1251         w->fd = fd;
1252         w->data.unit = u;
1253
1254         return 0;
1255
1256 fail:
1257         if (ours)
1258                 close_nointr_nofail(fd);
1259
1260         return -errno;
1261 }
1262
1263 void unit_unwatch_timer(Unit *u, Watch *w) {
1264         assert(u);
1265         assert(w);
1266
1267         if (w->type == WATCH_INVALID)
1268                 return;
1269
1270         assert(w->type == WATCH_UNIT_TIMER);
1271         assert(w->data.unit == u);
1272         assert(w->fd >= 0);
1273
1274         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1275         close_nointr_nofail(w->fd);
1276
1277         w->fd = -1;
1278         w->type = WATCH_INVALID;
1279         w->data.unit = NULL;
1280 }
1281
1282 bool unit_job_is_applicable(Unit *u, JobType j) {
1283         assert(u);
1284         assert(j >= 0 && j < _JOB_TYPE_MAX);
1285
1286         switch (j) {
1287
1288         case JOB_VERIFY_ACTIVE:
1289         case JOB_START:
1290                 return true;
1291
1292         case JOB_STOP:
1293         case JOB_RESTART:
1294         case JOB_TRY_RESTART:
1295                 return unit_can_start(u);
1296
1297         case JOB_RELOAD:
1298                 return unit_can_reload(u);
1299
1300         case JOB_RELOAD_OR_START:
1301                 return unit_can_reload(u) && unit_can_start(u);
1302
1303         default:
1304                 assert_not_reached("Invalid job type");
1305         }
1306 }
1307
1308 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1309
1310         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1311                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1312                 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1313                 [UNIT_WANTS] = UNIT_WANTED_BY,
1314                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1315                 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1316                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1317                 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1318                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1319                 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
1320                 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
1321                 [UNIT_BEFORE] = UNIT_AFTER,
1322                 [UNIT_AFTER] = UNIT_BEFORE,
1323                 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1324                 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1325                 [UNIT_REFERENCED_BY] = UNIT_REFERENCES
1326         };
1327         int r, q = 0, v = 0, w = 0;
1328
1329         assert(u);
1330         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1331         assert(other);
1332
1333         /* We won't allow dependencies on ourselves. We will not
1334          * consider them an error however. */
1335         if (u == other)
1336                 return 0;
1337
1338         if (UNIT_VTABLE(u)->no_requires &&
1339             (d == UNIT_REQUIRES ||
1340              d == UNIT_REQUIRES_OVERRIDABLE ||
1341              d == UNIT_REQUISITE ||
1342              d == UNIT_REQUISITE_OVERRIDABLE)) {
1343                     return -EINVAL;
1344         }
1345
1346         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1347                 return r;
1348
1349         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1350                 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1351                         return r;
1352
1353         if (add_reference)
1354                 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1355                     (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1356                         return r;
1357
1358         if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1359                 return q;
1360
1361         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1362                 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1363                         r = v;
1364                         goto fail;
1365                 }
1366
1367         if (add_reference) {
1368                 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1369                         r = w;
1370                         goto fail;
1371                 }
1372
1373                 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1374                         goto fail;
1375         }
1376
1377         unit_add_to_dbus_queue(u);
1378         return 0;
1379
1380 fail:
1381         if (q > 0)
1382                 set_remove(u->meta.dependencies[d], other);
1383
1384         if (v > 0)
1385                 set_remove(other->meta.dependencies[inverse_table[d]], u);
1386
1387         if (w > 0)
1388                 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1389
1390         return r;
1391 }
1392
1393 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1394         int r;
1395
1396         assert(u);
1397
1398         if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1399                 return r;
1400
1401         if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1402                 return r;
1403
1404         return 0;
1405 }
1406
1407 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1408         char *s;
1409
1410         assert(u);
1411         assert(name || path);
1412
1413         if (!name)
1414                 name = file_name_from_path(path);
1415
1416         if (!unit_name_is_template(name)) {
1417                 *p = NULL;
1418                 return name;
1419         }
1420
1421         if (u->meta.instance)
1422                 s = unit_name_replace_instance(name, u->meta.instance);
1423         else {
1424                 char *i;
1425
1426                 if (!(i = unit_name_to_prefix(u->meta.id)))
1427                         return NULL;
1428
1429                 s = unit_name_replace_instance(name, i);
1430                 free(i);
1431         }
1432
1433         if (!s)
1434                 return NULL;
1435
1436         *p = s;
1437         return s;
1438 }
1439
1440 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1441         Unit *other;
1442         int r;
1443         char *s;
1444
1445         assert(u);
1446         assert(name || path);
1447
1448         if (!(name = resolve_template(u, name, path, &s)))
1449                 return -ENOMEM;
1450
1451         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1452                 goto finish;
1453
1454         r = unit_add_dependency(u, d, other, add_reference);
1455
1456 finish:
1457         free(s);
1458         return r;
1459 }
1460
1461 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1462         Unit *other;
1463         int r;
1464         char *s;
1465
1466         assert(u);
1467         assert(name || path);
1468
1469         if (!(name = resolve_template(u, name, path, &s)))
1470                 return -ENOMEM;
1471
1472         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1473                 goto finish;
1474
1475         r = unit_add_two_dependencies(u, d, e, other, add_reference);
1476
1477 finish:
1478         free(s);
1479         return r;
1480 }
1481
1482 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1483         Unit *other;
1484         int r;
1485         char *s;
1486
1487         assert(u);
1488         assert(name || path);
1489
1490         if (!(name = resolve_template(u, name, path, &s)))
1491                 return -ENOMEM;
1492
1493         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1494                 goto finish;
1495
1496         r = unit_add_dependency(other, d, u, add_reference);
1497
1498 finish:
1499         free(s);
1500         return r;
1501 }
1502
1503 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1504         Unit *other;
1505         int r;
1506         char *s;
1507
1508         assert(u);
1509         assert(name || path);
1510
1511         if (!(name = resolve_template(u, name, path, &s)))
1512                 return -ENOMEM;
1513
1514         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1515                 goto finish;
1516
1517         if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1518                 goto finish;
1519
1520 finish:
1521         free(s);
1522         return r;
1523 }
1524
1525 int set_unit_path(const char *p) {
1526         char *cwd, *c;
1527         int r;
1528
1529         /* This is mostly for debug purposes */
1530
1531         if (path_is_absolute(p)) {
1532                 if (!(c = strdup(p)))
1533                         return -ENOMEM;
1534         } else {
1535                 if (!(cwd = get_current_dir_name()))
1536                         return -errno;
1537
1538                 r = asprintf(&c, "%s/%s", cwd, p);
1539                 free(cwd);
1540
1541                 if (r < 0)
1542                         return -ENOMEM;
1543         }
1544
1545         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1546                 r = -errno;
1547                 free(c);
1548                 return r;
1549         }
1550
1551         return 0;
1552 }
1553
1554 char *unit_dbus_path(Unit *u) {
1555         char *p, *e;
1556
1557         assert(u);
1558
1559         if (!u->meta.id)
1560                 return NULL;
1561
1562         if (!(e = bus_path_escape(u->meta.id)))
1563                 return NULL;
1564
1565         p = strappend("/org/freedesktop/systemd1/unit/", e);
1566         free(e);
1567
1568         return p;
1569 }
1570
1571 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1572         CGroupBonding *l;
1573         int r;
1574
1575         assert(u);
1576         assert(b);
1577
1578         assert(b->path);
1579
1580         if (!b->controller)
1581                 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1582                         return -ENOMEM;
1583
1584         /* Ensure this hasn't been added yet */
1585         assert(!b->unit);
1586
1587         l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1588         LIST_PREPEND(CGroupBonding, by_path, l, b);
1589
1590         if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1591                 LIST_REMOVE(CGroupBonding, by_path, l, b);
1592                 return r;
1593         }
1594
1595         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1596         b->unit = u;
1597
1598         return 0;
1599 }
1600
1601 static char *default_cgroup_path(Unit *u) {
1602         char *p;
1603         int r;
1604
1605         assert(u);
1606
1607         if (u->meta.instance) {
1608                 char *t;
1609
1610                 if (!(t = unit_name_template(u->meta.id)))
1611                         return NULL;
1612
1613                 r = asprintf(&p, "%s/%s/%s", u->meta.manager->cgroup_hierarchy, t, u->meta.instance);
1614                 free(t);
1615         } else
1616                 r = asprintf(&p, "%s/%s", u->meta.manager->cgroup_hierarchy, u->meta.id);
1617
1618         return r < 0 ? NULL : p;
1619 }
1620
1621 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1622         char *controller = NULL, *path = NULL;
1623         CGroupBonding *b = NULL;
1624         int r;
1625
1626         assert(u);
1627         assert(name);
1628
1629         if ((r = cg_split_spec(name, &controller, &path)) < 0)
1630                 return r;
1631
1632         if (!path)
1633                 path = default_cgroup_path(u);
1634
1635         if (!controller)
1636                 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1637
1638         if (!path || !controller) {
1639                 free(path);
1640                 free(controller);
1641
1642                 return -ENOMEM;
1643         }
1644
1645         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1646                 r = -EEXIST;
1647                 goto fail;
1648         }
1649
1650         if (!(b = new0(CGroupBonding, 1))) {
1651                 r = -ENOMEM;
1652                 goto fail;
1653         }
1654
1655         b->controller = controller;
1656         b->path = path;
1657         b->only_us = false;
1658         b->clean_up = false;
1659
1660         if ((r = unit_add_cgroup(u, b)) < 0)
1661                 goto fail;
1662
1663         return 0;
1664
1665 fail:
1666         free(path);
1667         free(controller);
1668         free(b);
1669
1670         return r;
1671 }
1672
1673 int unit_add_default_cgroup(Unit *u) {
1674         CGroupBonding *b;
1675         int r = -ENOMEM;
1676
1677         assert(u);
1678
1679         /* Adds in the default cgroup data, if it wasn't specified yet */
1680
1681         if (unit_get_default_cgroup(u))
1682                 return 0;
1683
1684         if (!(b = new0(CGroupBonding, 1)))
1685                 return -ENOMEM;
1686
1687         if (!(b->path = default_cgroup_path(u)))
1688                 goto fail;
1689
1690         b->clean_up = true;
1691         b->only_us = true;
1692
1693         if ((r = unit_add_cgroup(u, b)) < 0)
1694                 goto fail;
1695
1696         return 0;
1697
1698 fail:
1699         free(b->path);
1700         free(b->controller);
1701         free(b);
1702
1703         return r;
1704 }
1705
1706 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1707         assert(u);
1708
1709         return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1710 }
1711
1712 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
1713         char *t;
1714         int r;
1715
1716         assert(u);
1717         assert(type);
1718         assert(_found);
1719
1720         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1721                 return -ENOMEM;
1722
1723         assert(!unit_has_name(u, t));
1724
1725         r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
1726         free(t);
1727
1728         assert(r < 0 || *_found != u);
1729
1730         return r;
1731 }
1732
1733 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
1734         Unit *found;
1735         char *t;
1736
1737         assert(u);
1738         assert(type);
1739         assert(_found);
1740
1741         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1742                 return -ENOMEM;
1743
1744         assert(!unit_has_name(u, t));
1745
1746         found = manager_get_unit(u->meta.manager, t);
1747         free(t);
1748
1749         if (!found)
1750                 return -ENOENT;
1751
1752         *_found = found;
1753         return 0;
1754 }
1755
1756 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
1757         Unit *u = userdata;
1758         assert(u);
1759
1760         return unit_name_to_prefix_and_instance(u->meta.id);
1761 }
1762
1763 static char *specifier_prefix(char specifier, void *data, void *userdata) {
1764         Unit *u = userdata;
1765         assert(u);
1766
1767         return unit_name_to_prefix(u->meta.id);
1768 }
1769
1770 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
1771         Unit *u = userdata;
1772         char *p, *r;
1773
1774         assert(u);
1775
1776         if (!(p = unit_name_to_prefix(u->meta.id)))
1777                 return NULL;
1778
1779         r = unit_name_unescape(p);
1780         free(p);
1781
1782         return r;
1783 }
1784
1785 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
1786         Unit *u = userdata;
1787         assert(u);
1788
1789         if (u->meta.instance)
1790                 return unit_name_unescape(u->meta.instance);
1791
1792         return strdup("");
1793 }
1794
1795 char *unit_name_printf(Unit *u, const char* format) {
1796
1797         /*
1798          * This will use the passed string as format string and
1799          * replace the following specifiers:
1800          *
1801          * %n: the full id of the unit                 (foo@bar.waldo)
1802          * %N: the id of the unit without the suffix   (foo@bar)
1803          * %p: the prefix                              (foo)
1804          * %i: the instance                            (bar)
1805          */
1806
1807         const Specifier table[] = {
1808                 { 'n', specifier_string,              u->meta.id },
1809                 { 'N', specifier_prefix_and_instance, NULL },
1810                 { 'p', specifier_prefix,              NULL },
1811                 { 'i', specifier_string,              u->meta.instance },
1812                 { 0, NULL, NULL }
1813         };
1814
1815         assert(u);
1816         assert(format);
1817
1818         return specifier_printf(format, table, u);
1819 }
1820
1821 char *unit_full_printf(Unit *u, const char *format) {
1822
1823         /* This is similar to unit_name_printf() but also supports
1824          * unescaping */
1825
1826         const Specifier table[] = {
1827                 { 'n', specifier_string,              u->meta.id },
1828                 { 'N', specifier_prefix_and_instance, NULL },
1829                 { 'p', specifier_prefix,              NULL },
1830                 { 'P', specifier_prefix_unescaped,    NULL },
1831                 { 'i', specifier_string,              u->meta.instance },
1832                 { 'I', specifier_instance_unescaped,  NULL },
1833                 { 0, NULL, NULL }
1834         };
1835
1836         assert(u);
1837         assert(format);
1838
1839         return specifier_printf(format, table, u);
1840 }
1841
1842 char **unit_full_printf_strv(Unit *u, char **l) {
1843         size_t n;
1844         char **r, **i, **j;
1845
1846         /* Applies unit_full_printf to every entry in l */
1847
1848         assert(u);
1849
1850         n = strv_length(l);
1851         if (!(r = new(char*, n+1)))
1852                 return NULL;
1853
1854         for (i = l, j = r; *i; i++, j++)
1855                 if (!(*j = unit_full_printf(u, *i)))
1856                         goto fail;
1857
1858         *j = NULL;
1859         return r;
1860
1861 fail:
1862         j--;
1863         while (j >= r)
1864                 free(*j);
1865
1866         free(r);
1867
1868         return NULL;
1869 }
1870
1871 int unit_watch_bus_name(Unit *u, const char *name) {
1872         assert(u);
1873         assert(name);
1874
1875         /* Watch a specific name on the bus. We only support one unit
1876          * watching each name for now. */
1877
1878         return hashmap_put(u->meta.manager->watch_bus, name, u);
1879 }
1880
1881 void unit_unwatch_bus_name(Unit *u, const char *name) {
1882         assert(u);
1883         assert(name);
1884
1885         hashmap_remove_value(u->meta.manager->watch_bus, name, u);
1886 }
1887
1888 bool unit_can_serialize(Unit *u) {
1889         assert(u);
1890
1891         return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
1892 }
1893
1894 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
1895         int r;
1896
1897         assert(u);
1898         assert(f);
1899         assert(fds);
1900
1901         if (!unit_can_serialize(u))
1902                 return 0;
1903
1904         if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
1905                 return r;
1906
1907         if (u->meta.job)
1908                 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
1909
1910         /* End marker */
1911         fputc('\n', f);
1912         return 0;
1913 }
1914
1915 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
1916         va_list ap;
1917
1918         assert(u);
1919         assert(f);
1920         assert(key);
1921         assert(format);
1922
1923         fputs(key, f);
1924         fputc('=', f);
1925
1926         va_start(ap, format);
1927         vfprintf(f, format, ap);
1928         va_end(ap);
1929
1930         fputc('\n', f);
1931 }
1932
1933 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
1934         assert(u);
1935         assert(f);
1936         assert(key);
1937         assert(value);
1938
1939         fprintf(f, "%s=%s\n", key, value);
1940 }
1941
1942 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
1943         int r;
1944
1945         assert(u);
1946         assert(f);
1947         assert(fds);
1948
1949         if (!unit_can_serialize(u))
1950                 return 0;
1951
1952         for (;;) {
1953                 char line[1024], *l, *v;
1954                 size_t k;
1955
1956                 if (!fgets(line, sizeof(line), f)) {
1957                         if (feof(f))
1958                                 return 0;
1959                         return -errno;
1960                 }
1961
1962                 l = strstrip(line);
1963
1964                 /* End marker */
1965                 if (l[0] == 0)
1966                         return 0;
1967
1968                 k = strcspn(l, "=");
1969
1970                 if (l[k] == '=') {
1971                         l[k] = 0;
1972                         v = l+k+1;
1973                 } else
1974                         v = l+k;
1975
1976                 if (streq(l, "job")) {
1977                         JobType type;
1978
1979                         if ((type = job_type_from_string(v)) < 0)
1980                                 log_debug("Failed to parse job type value %s", v);
1981                         else
1982                                 u->meta.deserialized_job = type;
1983
1984                         continue;
1985                 }
1986
1987                 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
1988                         return r;
1989         }
1990 }
1991
1992 int unit_add_node_link(Unit *u, const char *what, bool wants) {
1993         Unit *device;
1994         char *e;
1995         int r;
1996
1997         assert(u);
1998
1999         if (!what)
2000                 return 0;
2001
2002         /* Adds in links to the device node that this unit is based on */
2003
2004         if (!is_device_path(what))
2005                 return 0;
2006
2007         if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
2008                 return -ENOMEM;
2009
2010         r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
2011         free(e);
2012
2013         if (r < 0)
2014                 return r;
2015
2016         if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, device, true)) < 0)
2017                 return r;
2018
2019         if (wants)
2020                 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2021                         return r;
2022
2023         return 0;
2024 }
2025
2026 int unit_coldplug(Unit *u) {
2027         int r;
2028
2029         assert(u);
2030
2031         if (UNIT_VTABLE(u)->coldplug)
2032                 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2033                         return r;
2034
2035         if (u->meta.deserialized_job >= 0) {
2036                 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_FAIL, false, NULL, NULL)) < 0)
2037                         return r;
2038
2039                 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2040         }
2041
2042         return 0;
2043 }
2044
2045 void unit_status_printf(Unit *u, const char *format, ...) {
2046         va_list ap;
2047
2048         assert(u);
2049         assert(format);
2050
2051         if (!UNIT_VTABLE(u)->show_status)
2052                 return;
2053
2054         if (u->meta.manager->running_as != MANAGER_SYSTEM)
2055                 return;
2056
2057         if (!u->meta.manager->show_status)
2058                 return;
2059
2060         if (!manager_is_booting_or_shutting_down(u->meta.manager))
2061                 return;
2062
2063         va_start(ap, format);
2064         status_vprintf(format, ap);
2065         va_end(ap);
2066 }
2067
2068 bool unit_need_daemon_reload(Unit *u) {
2069         struct stat st;
2070
2071         assert(u);
2072
2073         if (!u->meta.fragment_path)
2074                 return false;
2075
2076         zero(st);
2077         if (stat(u->meta.fragment_path, &st) < 0)
2078                 /* What, cannot access this anymore? */
2079                 return true;
2080
2081         return
2082                 u->meta.fragment_mtime &&
2083                 timespec_load(&st.st_mtim) != u->meta.fragment_mtime;
2084 }
2085
2086 void unit_reset_maintenance(Unit *u) {
2087         assert(u);
2088
2089         if (UNIT_VTABLE(u)->reset_maintenance)
2090                 UNIT_VTABLE(u)->reset_maintenance(u);
2091 }
2092
2093 Unit *unit_following(Unit *u) {
2094         assert(u);
2095
2096         if (UNIT_VTABLE(u)->following)
2097                 return UNIT_VTABLE(u)->following(u);
2098
2099         return NULL;
2100 }
2101
2102 static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
2103         [UNIT_SERVICE] = "service",
2104         [UNIT_TIMER] = "timer",
2105         [UNIT_SOCKET] = "socket",
2106         [UNIT_TARGET] = "target",
2107         [UNIT_DEVICE] = "device",
2108         [UNIT_MOUNT] = "mount",
2109         [UNIT_AUTOMOUNT] = "automount",
2110         [UNIT_SNAPSHOT] = "snapshot",
2111         [UNIT_SWAP] = "swap"
2112 };
2113
2114 DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
2115
2116 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2117         [UNIT_STUB] = "stub",
2118         [UNIT_LOADED] = "loaded",
2119         [UNIT_FAILED] = "failed",
2120         [UNIT_MERGED] = "merged"
2121 };
2122
2123 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2124
2125 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2126         [UNIT_ACTIVE] = "active",
2127         [UNIT_RELOADING] = "reloading",
2128         [UNIT_INACTIVE] = "inactive",
2129         [UNIT_MAINTENANCE] = "maintenance",
2130         [UNIT_ACTIVATING] = "activating",
2131         [UNIT_DEACTIVATING] = "deactivating"
2132 };
2133
2134 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2135
2136 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2137         [UNIT_REQUIRES] = "Requires",
2138         [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2139         [UNIT_WANTS] = "Wants",
2140         [UNIT_REQUISITE] = "Requisite",
2141         [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2142         [UNIT_REQUIRED_BY] = "RequiredBy",
2143         [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2144         [UNIT_WANTED_BY] = "WantedBy",
2145         [UNIT_CONFLICTS] = "Conflicts",
2146         [UNIT_CONFLICTED_BY] = "ConflictedBy",
2147         [UNIT_BEFORE] = "Before",
2148         [UNIT_AFTER] = "After",
2149         [UNIT_REFERENCES] = "References",
2150         [UNIT_REFERENCED_BY] = "ReferencedBy",
2151         [UNIT_ON_FAILURE] = "OnFailure"
2152 };
2153
2154 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);
2155
2156 static const char* const kill_mode_table[_KILL_MODE_MAX] = {
2157         [KILL_CONTROL_GROUP] = "control-group",
2158         [KILL_PROCESS_GROUP] = "process-group",
2159         [KILL_PROCESS] = "process",
2160         [KILL_NONE] = "none"
2161 };
2162
2163 DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);