chiark / gitweb /
50f3b8fabd5f76266e0c50d66618763c197b17d6
[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
593         assert(u);
594         assert(u->meta.type >= 0);
595
596         if (!prefix)
597                 prefix = "";
598         p2 = strappend(prefix, "\t");
599         prefix2 = p2 ? p2 : prefix;
600
601         fprintf(f,
602                 "%s-> Unit %s:\n"
603                 "%s\tDescription: %s\n"
604                 "%s\tInstance: %s\n"
605                 "%s\tUnit Load State: %s\n"
606                 "%s\tUnit Active State: %s\n"
607                 "%s\tInactive Exit Timestamp: %s\n"
608                 "%s\tActive Enter Timestamp: %s\n"
609                 "%s\tActive Exit Timestamp: %s\n"
610                 "%s\tInactive Enter Timestamp: %s\n"
611                 "%s\tGC Check Good: %s\n"
612                 "%s\tNeed Daemon Reload: %s\n",
613                 prefix, u->meta.id,
614                 prefix, unit_description(u),
615                 prefix, strna(u->meta.instance),
616                 prefix, unit_load_state_to_string(u->meta.load_state),
617                 prefix, unit_active_state_to_string(unit_active_state(u)),
618                 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp.realtime)),
619                 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp.realtime)),
620                 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp.realtime)),
621                 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp.realtime)),
622                 prefix, yes_no(unit_check_gc(u)),
623                 prefix, yes_no(unit_need_daemon_reload(u)));
624
625         SET_FOREACH(t, u->meta.names, i)
626                 fprintf(f, "%s\tName: %s\n", prefix, t);
627
628         if (u->meta.following)
629                 fprintf(f, "%s\tFollowing: %s\n", prefix, u->meta.following->meta.id);
630
631         if (u->meta.fragment_path)
632                 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
633
634         if (u->meta.job_timeout > 0)
635                 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->meta.job_timeout));
636
637         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
638                 Unit *other;
639
640                 SET_FOREACH(other, u->meta.dependencies[d], i)
641                         fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
642         }
643
644         if (u->meta.load_state == UNIT_LOADED) {
645                 fprintf(f,
646                         "%s\tRecursive Stop: %s\n"
647                         "%s\tStopWhenUnneeded: %s\n"
648                         "%s\tOnlyByDependency: %s\n"
649                         "%s\tDefaultDependencies: %s\n"
650                         "%s\tIgnoreDependencyFailure: %s\n",
651                         prefix, yes_no(u->meta.recursive_stop),
652                         prefix, yes_no(u->meta.stop_when_unneeded),
653                         prefix, yes_no(u->meta.only_by_dependency),
654                         prefix, yes_no(u->meta.default_dependencies),
655                         prefix, yes_no(u->meta.ignore_dependency_failure));
656
657                 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
658                         fprintf(f, "%s\tControlGroup: %s:%s\n",
659                                 prefix, b->controller, b->path);
660
661                 if (UNIT_VTABLE(u)->dump)
662                         UNIT_VTABLE(u)->dump(u, f, prefix2);
663
664         } else if (u->meta.load_state == UNIT_MERGED)
665                 fprintf(f,
666                         "%s\tMerged into: %s\n",
667                         prefix, u->meta.merged_into->meta.id);
668
669         if (u->meta.job)
670                 job_dump(u->meta.job, f, prefix2);
671
672         free(p2);
673 }
674
675 /* Common implementation for multiple backends */
676 int unit_load_fragment_and_dropin(Unit *u) {
677         int r;
678
679         assert(u);
680
681         /* Load a .service file */
682         if ((r = unit_load_fragment(u)) < 0)
683                 return r;
684
685         if (u->meta.load_state == UNIT_STUB)
686                 return -ENOENT;
687
688         /* Load drop-in directory data */
689         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
690                 return r;
691
692         return 0;
693 }
694
695 /* Common implementation for multiple backends */
696 int unit_load_fragment_and_dropin_optional(Unit *u) {
697         int r;
698
699         assert(u);
700
701         /* Same as unit_load_fragment_and_dropin(), but whether
702          * something can be loaded or not doesn't matter. */
703
704         /* Load a .service file */
705         if ((r = unit_load_fragment(u)) < 0)
706                 return r;
707
708         if (u->meta.load_state == UNIT_STUB)
709                 u->meta.load_state = UNIT_LOADED;
710
711         /* Load drop-in directory data */
712         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
713                 return r;
714
715         return 0;
716 }
717
718 /* Common implementation for multiple backends */
719 int unit_load_nop(Unit *u) {
720         assert(u);
721
722         if (u->meta.load_state == UNIT_STUB)
723                 u->meta.load_state = UNIT_LOADED;
724
725         return 0;
726 }
727
728 int unit_load(Unit *u) {
729         int r;
730
731         assert(u);
732
733         if (u->meta.in_load_queue) {
734                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
735                 u->meta.in_load_queue = false;
736         }
737
738         if (u->meta.type == _UNIT_TYPE_INVALID)
739                 return -EINVAL;
740
741         if (u->meta.load_state != UNIT_STUB)
742                 return 0;
743
744         if (UNIT_VTABLE(u)->load)
745                 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
746                         goto fail;
747
748         if (u->meta.load_state == UNIT_STUB) {
749                 r = -ENOENT;
750                 goto fail;
751         }
752
753         assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
754
755         unit_add_to_dbus_queue(unit_follow_merge(u));
756         unit_add_to_gc_queue(u);
757
758         return 0;
759
760 fail:
761         u->meta.load_state = UNIT_FAILED;
762         unit_add_to_dbus_queue(u);
763
764         log_notice("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
765
766         return r;
767 }
768
769 /* Errors:
770  *         -EBADR:     This unit type does not support starting.
771  *         -EALREADY:  Unit is already started.
772  *         -EAGAIN:    An operation is already in progress. Retry later.
773  *         -ECANCELED: Too many requests for now.
774  */
775 int unit_start(Unit *u) {
776         UnitActiveState state;
777
778         assert(u);
779
780         if (u->meta.load_state != UNIT_LOADED)
781                 return -EINVAL;
782
783         /* If this is already (being) started, then this will
784          * succeed. Note that this will even succeed if this unit is
785          * not startable by the user. This is relied on to detect when
786          * we need to wait for units and when waiting is finished. */
787         state = unit_active_state(u);
788         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
789                 return -EALREADY;
790
791         /* If it is stopped, but we cannot start it, then fail */
792         if (!UNIT_VTABLE(u)->start)
793                 return -EBADR;
794
795         /* We don't suppress calls to ->start() here when we are
796          * already starting, to allow this request to be used as a
797          * "hurry up" call, for example when the unit is in some "auto
798          * restart" state where it waits for a holdoff timer to elapse
799          * before it will start again. */
800
801         unit_add_to_dbus_queue(u);
802
803         unit_status_printf(u, "Starting %s...\n", unit_description(u));
804
805         return UNIT_VTABLE(u)->start(u);
806 }
807
808 bool unit_can_start(Unit *u) {
809         assert(u);
810
811         return !!UNIT_VTABLE(u)->start;
812 }
813
814 /* Errors:
815  *         -EBADR:    This unit type does not support stopping.
816  *         -EALREADY: Unit is already stopped.
817  *         -EAGAIN:   An operation is already in progress. Retry later.
818  */
819 int unit_stop(Unit *u) {
820         UnitActiveState state;
821
822         assert(u);
823
824         state = unit_active_state(u);
825         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(state))
826                 return -EALREADY;
827
828         if (!UNIT_VTABLE(u)->stop)
829                 return -EBADR;
830
831         unit_add_to_dbus_queue(u);
832
833         unit_status_printf(u, "Stopping %s...\n", unit_description(u));
834
835         return UNIT_VTABLE(u)->stop(u);
836 }
837
838 /* Errors:
839  *         -EBADR:    This unit type does not support reloading.
840  *         -ENOEXEC:  Unit is not started.
841  *         -EAGAIN:   An operation is already in progress. Retry later.
842  */
843 int unit_reload(Unit *u) {
844         UnitActiveState state;
845
846         assert(u);
847
848         if (u->meta.load_state != UNIT_LOADED)
849                 return -EINVAL;
850
851         if (!unit_can_reload(u))
852                 return -EBADR;
853
854         state = unit_active_state(u);
855         if (unit_active_state(u) == UNIT_RELOADING)
856                 return -EALREADY;
857
858         if (unit_active_state(u) != UNIT_ACTIVE)
859                 return -ENOEXEC;
860
861         unit_add_to_dbus_queue(u);
862         return UNIT_VTABLE(u)->reload(u);
863 }
864
865 bool unit_can_reload(Unit *u) {
866         assert(u);
867
868         if (!UNIT_VTABLE(u)->reload)
869                 return false;
870
871         if (!UNIT_VTABLE(u)->can_reload)
872                 return true;
873
874         return UNIT_VTABLE(u)->can_reload(u);
875 }
876
877 static void unit_check_uneeded(Unit *u) {
878         Iterator i;
879         Unit *other;
880
881         assert(u);
882
883         /* If this service shall be shut down when unneeded then do
884          * so. */
885
886         if (!u->meta.stop_when_unneeded)
887                 return;
888
889         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
890                 return;
891
892         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
893                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
894                         return;
895
896         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
897                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
898                         return;
899
900         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
901                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
902                         return;
903
904         log_info("Service %s is not needed anymore. Stopping.", u->meta.id);
905
906         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
907         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
908 }
909
910 static void retroactively_start_dependencies(Unit *u) {
911         Iterator i;
912         Unit *other;
913
914         assert(u);
915         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
916
917         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
918                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
919                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
920
921         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
922                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
923                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
924
925         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
926                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
927                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
928
929         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
930                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
931                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
932
933         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
934                 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
935                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
936 }
937
938 static void retroactively_stop_dependencies(Unit *u) {
939         Iterator i;
940         Unit *other;
941
942         assert(u);
943         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
944
945         if (u->meta.recursive_stop) {
946                 /* Pull down units need us recursively if enabled */
947                 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
948                         if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
949                                 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
950         }
951
952         /* Garbage collect services that might not be needed anymore, if enabled */
953         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
954                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
955                         unit_check_uneeded(other);
956         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
957                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
958                         unit_check_uneeded(other);
959         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
960                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
961                         unit_check_uneeded(other);
962         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
963                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
964                         unit_check_uneeded(other);
965         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
966                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
967                         unit_check_uneeded(other);
968 }
969
970 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
971         dual_timestamp ts;
972         bool unexpected;
973
974         assert(u);
975         assert(os < _UNIT_ACTIVE_STATE_MAX);
976         assert(ns < _UNIT_ACTIVE_STATE_MAX);
977
978         /* Note that this is called for all low-level state changes,
979          * even if they might map to the same high-level
980          * UnitActiveState! That means that ns == os is OK an expected
981          * behaviour here. For example: if a mount point is remounted
982          * this function will be called too and the utmp code below
983          * relies on that! */
984
985         dual_timestamp_get(&ts);
986
987         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(os) && !UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
988                 u->meta.inactive_exit_timestamp = ts;
989         else if (!UNIT_IS_INACTIVE_OR_MAINTENANCE(os) && UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
990                 u->meta.inactive_enter_timestamp = ts;
991
992         if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
993                 u->meta.active_enter_timestamp = ts;
994         else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
995                 u->meta.active_exit_timestamp = ts;
996
997         if (UNIT_IS_INACTIVE_OR_MAINTENANCE(ns))
998                 cgroup_bonding_trim_list(u->meta.cgroup_bondings, true);
999
1000         timer_unit_notify(u, ns);
1001         path_unit_notify(u, ns);
1002
1003         if (u->meta.job) {
1004                 unexpected = false;
1005
1006                 if (u->meta.job->state == JOB_WAITING)
1007
1008                         /* So we reached a different state for this
1009                          * job. Let's see if we can run it now if it
1010                          * failed previously due to EAGAIN. */
1011                         job_add_to_run_queue(u->meta.job);
1012
1013                 /* Let's check whether this state change constitutes a
1014                  * finished job, or maybe cotradicts a running job and
1015                  * hence needs to invalidate jobs. */
1016
1017                 switch (u->meta.job->type) {
1018
1019                 case JOB_START:
1020                 case JOB_VERIFY_ACTIVE:
1021
1022                         if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1023                                 job_finish_and_invalidate(u->meta.job, true);
1024                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1025                                 unexpected = true;
1026                                 job_finish_and_invalidate(u->meta.job, false);
1027                         }
1028
1029                         break;
1030
1031                 case JOB_RELOAD:
1032                 case JOB_RELOAD_OR_START:
1033
1034                         if (u->meta.job->state == JOB_RUNNING) {
1035                                 if (ns == UNIT_ACTIVE)
1036                                         job_finish_and_invalidate(u->meta.job, true);
1037                                 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1038                                         unexpected = true;
1039                                         job_finish_and_invalidate(u->meta.job, false);
1040                                 }
1041                         }
1042
1043                         break;
1044
1045                 case JOB_STOP:
1046                 case JOB_RESTART:
1047                 case JOB_TRY_RESTART:
1048
1049                         if (ns == UNIT_INACTIVE || ns == UNIT_MAINTENANCE)
1050                                 job_finish_and_invalidate(u->meta.job, true);
1051                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1052                                 unexpected = true;
1053                                 job_finish_and_invalidate(u->meta.job, false);
1054                         }
1055
1056                         break;
1057
1058                 default:
1059                         assert_not_reached("Job type unknown");
1060                 }
1061
1062         } else
1063                 unexpected = true;
1064
1065         /* If this state change happened without being requested by a
1066          * job, then let's retroactively start or stop
1067          * dependencies. We skip that step when deserializing, since
1068          * we don't want to create any additional jobs just because
1069          * something is already activated. */
1070
1071         if (unexpected && u->meta.manager->n_deserializing <= 0) {
1072                 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1073                         retroactively_start_dependencies(u);
1074                 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1075                         retroactively_stop_dependencies(u);
1076         }
1077
1078         if (ns != os && ns == UNIT_MAINTENANCE) {
1079                 Iterator i;
1080                 Unit *other;
1081
1082                 SET_FOREACH(other, u->meta.dependencies[UNIT_ON_FAILURE], i)
1083                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1084
1085                 log_notice("Unit %s entered maintenance state.", u->meta.id);
1086         }
1087
1088         /* Some names are special */
1089         if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1090                 if (unit_has_name(u, SPECIAL_DBUS_SERVICE)) {
1091                         /* The bus just might have become available,
1092                          * hence try to connect to it, if we aren't
1093                          * yet connected. */
1094                         bus_init(u->meta.manager);
1095                 }
1096
1097                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1098                         /* The syslog daemon just might have become
1099                          * available, hence try to connect to it, if
1100                          * we aren't yet connected. */
1101                         log_open();
1102
1103                 if (u->meta.type == UNIT_MOUNT)
1104                         /* Another directory became available, let's
1105                          * check if that is enough to write our utmp
1106                          * entry. */
1107                         manager_write_utmp_reboot(u->meta.manager);
1108
1109                 if (u->meta.type == UNIT_TARGET)
1110                         /* A target got activated, maybe this is a runlevel? */
1111                         manager_write_utmp_runlevel(u->meta.manager, u);
1112
1113         } else if (!UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1114
1115                 if (unit_has_name(u, SPECIAL_SYSLOG_SERVICE))
1116                         /* The syslog daemon might just have
1117                          * terminated, hence try to disconnect from
1118                          * it. */
1119                         log_close_syslog();
1120
1121                 /* We don't care about D-Bus here, since we'll get an
1122                  * asynchronous notification for it anyway. */
1123         }
1124
1125         /* Maybe we finished startup and are now ready for being
1126          * stopped because unneeded? */
1127         unit_check_uneeded(u);
1128
1129         unit_add_to_dbus_queue(u);
1130         unit_add_to_gc_queue(u);
1131 }
1132
1133 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1134         struct epoll_event ev;
1135
1136         assert(u);
1137         assert(fd >= 0);
1138         assert(w);
1139         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1140
1141         zero(ev);
1142         ev.data.ptr = w;
1143         ev.events = events;
1144
1145         if (epoll_ctl(u->meta.manager->epoll_fd,
1146                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1147                       fd,
1148                       &ev) < 0)
1149                 return -errno;
1150
1151         w->fd = fd;
1152         w->type = WATCH_FD;
1153         w->data.unit = u;
1154
1155         return 0;
1156 }
1157
1158 void unit_unwatch_fd(Unit *u, Watch *w) {
1159         assert(u);
1160         assert(w);
1161
1162         if (w->type == WATCH_INVALID)
1163                 return;
1164
1165         assert(w->type == WATCH_FD);
1166         assert(w->data.unit == u);
1167         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1168
1169         w->fd = -1;
1170         w->type = WATCH_INVALID;
1171         w->data.unit = NULL;
1172 }
1173
1174 int unit_watch_pid(Unit *u, pid_t pid) {
1175         assert(u);
1176         assert(pid >= 1);
1177
1178         /* Watch a specific PID. We only support one unit watching
1179          * each PID for now. */
1180
1181         return hashmap_put(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1182 }
1183
1184 void unit_unwatch_pid(Unit *u, pid_t pid) {
1185         assert(u);
1186         assert(pid >= 1);
1187
1188         hashmap_remove_value(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1189 }
1190
1191 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1192         struct itimerspec its;
1193         int flags, fd;
1194         bool ours;
1195
1196         assert(u);
1197         assert(w);
1198         assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1199
1200         /* This will try to reuse the old timer if there is one */
1201
1202         if (w->type == WATCH_UNIT_TIMER) {
1203                 assert(w->data.unit == u);
1204                 assert(w->fd >= 0);
1205
1206                 ours = false;
1207                 fd = w->fd;
1208         } else if (w->type == WATCH_INVALID) {
1209
1210                 ours = true;
1211                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1212                         return -errno;
1213         } else
1214                 assert_not_reached("Invalid watch type");
1215
1216         zero(its);
1217
1218         if (delay <= 0) {
1219                 /* Set absolute time in the past, but not 0, since we
1220                  * don't want to disarm the timer */
1221                 its.it_value.tv_sec = 0;
1222                 its.it_value.tv_nsec = 1;
1223
1224                 flags = TFD_TIMER_ABSTIME;
1225         } else {
1226                 timespec_store(&its.it_value, delay);
1227                 flags = 0;
1228         }
1229
1230         /* This will also flush the elapse counter */
1231         if (timerfd_settime(fd, flags, &its, NULL) < 0)
1232                 goto fail;
1233
1234         if (w->type == WATCH_INVALID) {
1235                 struct epoll_event ev;
1236
1237                 zero(ev);
1238                 ev.data.ptr = w;
1239                 ev.events = EPOLLIN;
1240
1241                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1242                         goto fail;
1243         }
1244
1245         w->type = WATCH_UNIT_TIMER;
1246         w->fd = fd;
1247         w->data.unit = u;
1248
1249         return 0;
1250
1251 fail:
1252         if (ours)
1253                 close_nointr_nofail(fd);
1254
1255         return -errno;
1256 }
1257
1258 void unit_unwatch_timer(Unit *u, Watch *w) {
1259         assert(u);
1260         assert(w);
1261
1262         if (w->type == WATCH_INVALID)
1263                 return;
1264
1265         assert(w->type == WATCH_UNIT_TIMER);
1266         assert(w->data.unit == u);
1267         assert(w->fd >= 0);
1268
1269         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1270         close_nointr_nofail(w->fd);
1271
1272         w->fd = -1;
1273         w->type = WATCH_INVALID;
1274         w->data.unit = NULL;
1275 }
1276
1277 bool unit_job_is_applicable(Unit *u, JobType j) {
1278         assert(u);
1279         assert(j >= 0 && j < _JOB_TYPE_MAX);
1280
1281         switch (j) {
1282
1283         case JOB_VERIFY_ACTIVE:
1284         case JOB_START:
1285                 return true;
1286
1287         case JOB_STOP:
1288         case JOB_RESTART:
1289         case JOB_TRY_RESTART:
1290                 return unit_can_start(u);
1291
1292         case JOB_RELOAD:
1293                 return unit_can_reload(u);
1294
1295         case JOB_RELOAD_OR_START:
1296                 return unit_can_reload(u) && unit_can_start(u);
1297
1298         default:
1299                 assert_not_reached("Invalid job type");
1300         }
1301 }
1302
1303 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1304
1305         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1306                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1307                 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1308                 [UNIT_WANTS] = UNIT_WANTED_BY,
1309                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1310                 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1311                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1312                 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1313                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1314                 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
1315                 [UNIT_BEFORE] = UNIT_AFTER,
1316                 [UNIT_AFTER] = UNIT_BEFORE,
1317                 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1318                 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1319                 [UNIT_REFERENCED_BY] = UNIT_REFERENCES
1320         };
1321         int r, q = 0, v = 0, w = 0;
1322
1323         assert(u);
1324         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1325         assert(other);
1326
1327         /* We won't allow dependencies on ourselves. We will not
1328          * consider them an error however. */
1329         if (u == other)
1330                 return 0;
1331
1332         if (UNIT_VTABLE(u)->no_requires &&
1333             (d == UNIT_REQUIRES ||
1334              d == UNIT_REQUIRES_OVERRIDABLE ||
1335              d == UNIT_REQUISITE ||
1336              d == UNIT_REQUISITE_OVERRIDABLE)) {
1337                     return -EINVAL;
1338         }
1339
1340         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1341                 return r;
1342
1343         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1344                 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1345                         return r;
1346
1347         if (add_reference)
1348                 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1349                     (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1350                         return r;
1351
1352         if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1353                 return q;
1354
1355         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1356                 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1357                         r = v;
1358                         goto fail;
1359                 }
1360
1361         if (add_reference) {
1362                 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1363                         r = w;
1364                         goto fail;
1365                 }
1366
1367                 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1368                         goto fail;
1369         }
1370
1371         unit_add_to_dbus_queue(u);
1372         return 0;
1373
1374 fail:
1375         if (q > 0)
1376                 set_remove(u->meta.dependencies[d], other);
1377
1378         if (v > 0)
1379                 set_remove(other->meta.dependencies[inverse_table[d]], u);
1380
1381         if (w > 0)
1382                 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1383
1384         return r;
1385 }
1386
1387 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1388         int r;
1389
1390         assert(u);
1391
1392         if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1393                 return r;
1394
1395         if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1396                 return r;
1397
1398         return 0;
1399 }
1400
1401 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1402         char *s;
1403
1404         assert(u);
1405         assert(name || path);
1406
1407         if (!name)
1408                 name = file_name_from_path(path);
1409
1410         if (!unit_name_is_template(name)) {
1411                 *p = NULL;
1412                 return name;
1413         }
1414
1415         if (u->meta.instance)
1416                 s = unit_name_replace_instance(name, u->meta.instance);
1417         else {
1418                 char *i;
1419
1420                 if (!(i = unit_name_to_prefix(u->meta.id)))
1421                         return NULL;
1422
1423                 s = unit_name_replace_instance(name, i);
1424                 free(i);
1425         }
1426
1427         if (!s)
1428                 return NULL;
1429
1430         *p = s;
1431         return s;
1432 }
1433
1434 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1435         Unit *other;
1436         int r;
1437         char *s;
1438
1439         assert(u);
1440         assert(name || path);
1441
1442         if (!(name = resolve_template(u, name, path, &s)))
1443                 return -ENOMEM;
1444
1445         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1446                 goto finish;
1447
1448         r = unit_add_dependency(u, d, other, add_reference);
1449
1450 finish:
1451         free(s);
1452         return r;
1453 }
1454
1455 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1456         Unit *other;
1457         int r;
1458         char *s;
1459
1460         assert(u);
1461         assert(name || path);
1462
1463         if (!(name = resolve_template(u, name, path, &s)))
1464                 return -ENOMEM;
1465
1466         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1467                 goto finish;
1468
1469         r = unit_add_two_dependencies(u, d, e, other, add_reference);
1470
1471 finish:
1472         free(s);
1473         return r;
1474 }
1475
1476 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1477         Unit *other;
1478         int r;
1479         char *s;
1480
1481         assert(u);
1482         assert(name || path);
1483
1484         if (!(name = resolve_template(u, name, path, &s)))
1485                 return -ENOMEM;
1486
1487         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1488                 goto finish;
1489
1490         r = unit_add_dependency(other, d, u, add_reference);
1491
1492 finish:
1493         free(s);
1494         return r;
1495 }
1496
1497 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1498         Unit *other;
1499         int r;
1500         char *s;
1501
1502         assert(u);
1503         assert(name || path);
1504
1505         if (!(name = resolve_template(u, name, path, &s)))
1506                 return -ENOMEM;
1507
1508         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1509                 goto finish;
1510
1511         if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1512                 goto finish;
1513
1514 finish:
1515         free(s);
1516         return r;
1517 }
1518
1519 int set_unit_path(const char *p) {
1520         char *cwd, *c;
1521         int r;
1522
1523         /* This is mostly for debug purposes */
1524
1525         if (path_is_absolute(p)) {
1526                 if (!(c = strdup(p)))
1527                         return -ENOMEM;
1528         } else {
1529                 if (!(cwd = get_current_dir_name()))
1530                         return -errno;
1531
1532                 r = asprintf(&c, "%s/%s", cwd, p);
1533                 free(cwd);
1534
1535                 if (r < 0)
1536                         return -ENOMEM;
1537         }
1538
1539         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1540                 r = -errno;
1541                 free(c);
1542                 return r;
1543         }
1544
1545         return 0;
1546 }
1547
1548 char *unit_dbus_path(Unit *u) {
1549         char *p, *e;
1550
1551         assert(u);
1552
1553         if (!(e = bus_path_escape(u->meta.id)))
1554                 return NULL;
1555
1556         p = strappend("/org/freedesktop/systemd1/unit/", e);
1557         free(e);
1558
1559         return p;
1560 }
1561
1562 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1563         CGroupBonding *l;
1564         int r;
1565
1566         assert(u);
1567         assert(b);
1568
1569         assert(b->path);
1570
1571         if (!b->controller)
1572                 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1573                         return -ENOMEM;
1574
1575         /* Ensure this hasn't been added yet */
1576         assert(!b->unit);
1577
1578         l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1579         LIST_PREPEND(CGroupBonding, by_path, l, b);
1580
1581         if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1582                 LIST_REMOVE(CGroupBonding, by_path, l, b);
1583                 return r;
1584         }
1585
1586         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1587         b->unit = u;
1588
1589         return 0;
1590 }
1591
1592 static char *default_cgroup_path(Unit *u) {
1593         char *p;
1594         int r;
1595
1596         assert(u);
1597
1598         if (u->meta.instance) {
1599                 char *t;
1600
1601                 if (!(t = unit_name_template(u->meta.id)))
1602                         return NULL;
1603
1604                 r = asprintf(&p, "%s/%s/%s", u->meta.manager->cgroup_hierarchy, t, u->meta.instance);
1605                 free(t);
1606         } else
1607                 r = asprintf(&p, "%s/%s", u->meta.manager->cgroup_hierarchy, u->meta.id);
1608
1609         return r < 0 ? NULL : p;
1610 }
1611
1612 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1613         char *controller = NULL, *path = NULL;
1614         CGroupBonding *b = NULL;
1615         int r;
1616
1617         assert(u);
1618         assert(name);
1619
1620         if ((r = cg_split_spec(name, &controller, &path)) < 0)
1621                 return r;
1622
1623         if (!path)
1624                 path = default_cgroup_path(u);
1625
1626         if (!controller)
1627                 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1628
1629         if (!path || !controller) {
1630                 free(path);
1631                 free(controller);
1632
1633                 return -ENOMEM;
1634         }
1635
1636         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1637                 r = -EEXIST;
1638                 goto fail;
1639         }
1640
1641         if (!(b = new0(CGroupBonding, 1))) {
1642                 r = -ENOMEM;
1643                 goto fail;
1644         }
1645
1646         b->controller = controller;
1647         b->path = path;
1648         b->only_us = false;
1649         b->clean_up = false;
1650
1651         if ((r = unit_add_cgroup(u, b)) < 0)
1652                 goto fail;
1653
1654         return 0;
1655
1656 fail:
1657         free(path);
1658         free(controller);
1659         free(b);
1660
1661         return r;
1662 }
1663
1664 int unit_add_default_cgroup(Unit *u) {
1665         CGroupBonding *b;
1666         int r = -ENOMEM;
1667
1668         assert(u);
1669
1670         /* Adds in the default cgroup data, if it wasn't specified yet */
1671
1672         if (unit_get_default_cgroup(u))
1673                 return 0;
1674
1675         if (!(b = new0(CGroupBonding, 1)))
1676                 return -ENOMEM;
1677
1678         if (!(b->path = default_cgroup_path(u)))
1679                 goto fail;
1680
1681         b->clean_up = true;
1682         b->only_us = true;
1683
1684         if ((r = unit_add_cgroup(u, b)) < 0)
1685                 goto fail;
1686
1687         return 0;
1688
1689 fail:
1690         free(b->path);
1691         free(b->controller);
1692         free(b);
1693
1694         return r;
1695 }
1696
1697 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1698         assert(u);
1699
1700         return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1701 }
1702
1703 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
1704         char *t;
1705         int r;
1706
1707         assert(u);
1708         assert(type);
1709         assert(_found);
1710
1711         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1712                 return -ENOMEM;
1713
1714         assert(!unit_has_name(u, t));
1715
1716         r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
1717         free(t);
1718
1719         assert(r < 0 || *_found != u);
1720
1721         return r;
1722 }
1723
1724 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
1725         Unit *found;
1726         char *t;
1727
1728         assert(u);
1729         assert(type);
1730         assert(_found);
1731
1732         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1733                 return -ENOMEM;
1734
1735         assert(!unit_has_name(u, t));
1736
1737         found = manager_get_unit(u->meta.manager, t);
1738         free(t);
1739
1740         if (!found)
1741                 return -ENOENT;
1742
1743         *_found = found;
1744         return 0;
1745 }
1746
1747 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
1748         Unit *u = userdata;
1749         assert(u);
1750
1751         return unit_name_to_prefix_and_instance(u->meta.id);
1752 }
1753
1754 static char *specifier_prefix(char specifier, void *data, void *userdata) {
1755         Unit *u = userdata;
1756         assert(u);
1757
1758         return unit_name_to_prefix(u->meta.id);
1759 }
1760
1761 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
1762         Unit *u = userdata;
1763         char *p, *r;
1764
1765         assert(u);
1766
1767         if (!(p = unit_name_to_prefix(u->meta.id)))
1768                 return NULL;
1769
1770         r = unit_name_unescape(p);
1771         free(p);
1772
1773         return r;
1774 }
1775
1776 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
1777         Unit *u = userdata;
1778         assert(u);
1779
1780         if (u->meta.instance)
1781                 return unit_name_unescape(u->meta.instance);
1782
1783         return strdup("");
1784 }
1785
1786 char *unit_name_printf(Unit *u, const char* format) {
1787
1788         /*
1789          * This will use the passed string as format string and
1790          * replace the following specifiers:
1791          *
1792          * %n: the full id of the unit                 (foo@bar.waldo)
1793          * %N: the id of the unit without the suffix   (foo@bar)
1794          * %p: the prefix                              (foo)
1795          * %i: the instance                            (bar)
1796          */
1797
1798         const Specifier table[] = {
1799                 { 'n', specifier_string,              u->meta.id },
1800                 { 'N', specifier_prefix_and_instance, NULL },
1801                 { 'p', specifier_prefix,              NULL },
1802                 { 'i', specifier_string,              u->meta.instance },
1803                 { 0, NULL, NULL }
1804         };
1805
1806         assert(u);
1807         assert(format);
1808
1809         return specifier_printf(format, table, u);
1810 }
1811
1812 char *unit_full_printf(Unit *u, const char *format) {
1813
1814         /* This is similar to unit_name_printf() but also supports
1815          * unescaping */
1816
1817         const Specifier table[] = {
1818                 { 'n', specifier_string,              u->meta.id },
1819                 { 'N', specifier_prefix_and_instance, NULL },
1820                 { 'p', specifier_prefix,              NULL },
1821                 { 'P', specifier_prefix_unescaped,    NULL },
1822                 { 'i', specifier_string,              u->meta.instance },
1823                 { 'I', specifier_instance_unescaped,  NULL },
1824                 { 0, NULL, NULL }
1825         };
1826
1827         assert(u);
1828         assert(format);
1829
1830         return specifier_printf(format, table, u);
1831 }
1832
1833 char **unit_full_printf_strv(Unit *u, char **l) {
1834         size_t n;
1835         char **r, **i, **j;
1836
1837         /* Applies unit_full_printf to every entry in l */
1838
1839         assert(u);
1840
1841         n = strv_length(l);
1842         if (!(r = new(char*, n+1)))
1843                 return NULL;
1844
1845         for (i = l, j = r; *i; i++, j++)
1846                 if (!(*j = unit_full_printf(u, *i)))
1847                         goto fail;
1848
1849         *j = NULL;
1850         return r;
1851
1852 fail:
1853         j--;
1854         while (j >= r)
1855                 free(*j);
1856
1857         free(r);
1858
1859         return NULL;
1860 }
1861
1862 int unit_watch_bus_name(Unit *u, const char *name) {
1863         assert(u);
1864         assert(name);
1865
1866         /* Watch a specific name on the bus. We only support one unit
1867          * watching each name for now. */
1868
1869         return hashmap_put(u->meta.manager->watch_bus, name, u);
1870 }
1871
1872 void unit_unwatch_bus_name(Unit *u, const char *name) {
1873         assert(u);
1874         assert(name);
1875
1876         hashmap_remove_value(u->meta.manager->watch_bus, name, u);
1877 }
1878
1879 bool unit_can_serialize(Unit *u) {
1880         assert(u);
1881
1882         return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
1883 }
1884
1885 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
1886         int r;
1887
1888         assert(u);
1889         assert(f);
1890         assert(fds);
1891
1892         if (!unit_can_serialize(u))
1893                 return 0;
1894
1895         if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
1896                 return r;
1897
1898         if (u->meta.job)
1899                 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
1900
1901         /* End marker */
1902         fputc('\n', f);
1903         return 0;
1904 }
1905
1906 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
1907         va_list ap;
1908
1909         assert(u);
1910         assert(f);
1911         assert(key);
1912         assert(format);
1913
1914         fputs(key, f);
1915         fputc('=', f);
1916
1917         va_start(ap, format);
1918         vfprintf(f, format, ap);
1919         va_end(ap);
1920
1921         fputc('\n', f);
1922 }
1923
1924 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
1925         assert(u);
1926         assert(f);
1927         assert(key);
1928         assert(value);
1929
1930         fprintf(f, "%s=%s\n", key, value);
1931 }
1932
1933 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
1934         int r;
1935
1936         assert(u);
1937         assert(f);
1938         assert(fds);
1939
1940         if (!unit_can_serialize(u))
1941                 return 0;
1942
1943         for (;;) {
1944                 char line[1024], *l, *v;
1945                 size_t k;
1946
1947                 if (!fgets(line, sizeof(line), f)) {
1948                         if (feof(f))
1949                                 return 0;
1950                         return -errno;
1951                 }
1952
1953                 l = strstrip(line);
1954
1955                 /* End marker */
1956                 if (l[0] == 0)
1957                         return 0;
1958
1959                 k = strcspn(l, "=");
1960
1961                 if (l[k] == '=') {
1962                         l[k] = 0;
1963                         v = l+k+1;
1964                 } else
1965                         v = l+k;
1966
1967                 if (streq(l, "job")) {
1968                         JobType type;
1969
1970                         if ((type = job_type_from_string(v)) < 0)
1971                                 log_debug("Failed to parse job type value %s", v);
1972                         else
1973                                 u->meta.deserialized_job = type;
1974
1975                         continue;
1976                 }
1977
1978                 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
1979                         return r;
1980         }
1981 }
1982
1983 int unit_add_node_link(Unit *u, const char *what, bool wants) {
1984         Unit *device;
1985         char *e;
1986         int r;
1987
1988         assert(u);
1989
1990         if (!what)
1991                 return 0;
1992
1993         /* Adds in links to the device node that this unit is based on */
1994
1995         if (!is_device_path(what))
1996                 return 0;
1997
1998         if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
1999                 return -ENOMEM;
2000
2001         r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
2002         free(e);
2003
2004         if (r < 0)
2005                 return r;
2006
2007         if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, device, true)) < 0)
2008                 return r;
2009
2010         if (wants)
2011                 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2012                         return r;
2013
2014         return 0;
2015 }
2016
2017 int unit_coldplug(Unit *u) {
2018         int r;
2019
2020         assert(u);
2021
2022         if (UNIT_VTABLE(u)->coldplug)
2023                 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2024                         return r;
2025
2026         if (u->meta.deserialized_job >= 0) {
2027                 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_FAIL, false, NULL, NULL)) < 0)
2028                         return r;
2029
2030                 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2031         }
2032
2033         return 0;
2034 }
2035
2036 void unit_status_printf(Unit *u, const char *format, ...) {
2037         va_list ap;
2038
2039         assert(u);
2040         assert(format);
2041
2042         if (!UNIT_VTABLE(u)->show_status)
2043                 return;
2044
2045         if (u->meta.manager->running_as != MANAGER_SYSTEM)
2046                 return;
2047
2048         if (!u->meta.manager->show_status)
2049                 return;
2050
2051         if (!manager_is_booting_or_shutting_down(u->meta.manager))
2052                 return;
2053
2054         va_start(ap, format);
2055         status_vprintf(format, ap);
2056         va_end(ap);
2057 }
2058
2059 bool unit_need_daemon_reload(Unit *u) {
2060         struct stat st;
2061
2062         assert(u);
2063
2064         if (!u->meta.fragment_path)
2065                 return false;
2066
2067         zero(st);
2068         if (stat(u->meta.fragment_path, &st) < 0)
2069                 /* What, cannot access this anymore? */
2070                 return true;
2071
2072         return
2073                 u->meta.fragment_mtime &&
2074                 timespec_load(&st.st_mtim) != u->meta.fragment_mtime;
2075 }
2076
2077 void unit_reset_maintenance(Unit *u) {
2078         assert(u);
2079
2080         if (UNIT_VTABLE(u)->reset_maintenance)
2081                 UNIT_VTABLE(u)->reset_maintenance(u);
2082 }
2083
2084 static const char* const unit_type_table[_UNIT_TYPE_MAX] = {
2085         [UNIT_SERVICE] = "service",
2086         [UNIT_TIMER] = "timer",
2087         [UNIT_SOCKET] = "socket",
2088         [UNIT_TARGET] = "target",
2089         [UNIT_DEVICE] = "device",
2090         [UNIT_MOUNT] = "mount",
2091         [UNIT_AUTOMOUNT] = "automount",
2092         [UNIT_SNAPSHOT] = "snapshot",
2093         [UNIT_SWAP] = "swap"
2094 };
2095
2096 DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType);
2097
2098 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2099         [UNIT_STUB] = "stub",
2100         [UNIT_LOADED] = "loaded",
2101         [UNIT_FAILED] = "failed",
2102         [UNIT_MERGED] = "merged"
2103 };
2104
2105 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2106
2107 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2108         [UNIT_ACTIVE] = "active",
2109         [UNIT_RELOADING] = "reloading",
2110         [UNIT_INACTIVE] = "inactive",
2111         [UNIT_MAINTENANCE] = "maintenance",
2112         [UNIT_ACTIVATING] = "activating",
2113         [UNIT_DEACTIVATING] = "deactivating"
2114 };
2115
2116 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2117
2118 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2119         [UNIT_REQUIRES] = "Requires",
2120         [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2121         [UNIT_WANTS] = "Wants",
2122         [UNIT_REQUISITE] = "Requisite",
2123         [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2124         [UNIT_REQUIRED_BY] = "RequiredBy",
2125         [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2126         [UNIT_WANTED_BY] = "WantedBy",
2127         [UNIT_CONFLICTS] = "Conflicts",
2128         [UNIT_BEFORE] = "Before",
2129         [UNIT_AFTER] = "After",
2130         [UNIT_REFERENCES] = "References",
2131         [UNIT_REFERENCED_BY] = "ReferencedBy",
2132         [UNIT_ON_FAILURE] = "OnFailure"
2133 };
2134
2135 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);
2136
2137 static const char* const kill_mode_table[_KILL_MODE_MAX] = {
2138         [KILL_CONTROL_GROUP] = "control-group",
2139         [KILL_PROCESS_GROUP] = "process-group",
2140         [KILL_PROCESS] = "process",
2141         [KILL_NONE] = "none"
2142 };
2143
2144 DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);