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