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