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