1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
7 #include <sys/timerfd.h>
16 #include "load-fragment.h"
17 #include "load-dropin.h"
20 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
21 [UNIT_SERVICE] = &service_vtable,
22 [UNIT_TIMER] = &timer_vtable,
23 [UNIT_SOCKET] = &socket_vtable,
24 [UNIT_TARGET] = &target_vtable,
25 [UNIT_DEVICE] = &device_vtable,
26 [UNIT_MOUNT] = &mount_vtable,
27 [UNIT_AUTOMOUNT] = &automount_vtable,
28 [UNIT_SNAPSHOT] = &snapshot_vtable
31 UnitType unit_name_to_type(const char *n) {
36 for (t = 0; t < _UNIT_TYPE_MAX; t++)
37 if (endswith(n, unit_vtable[t]->suffix))
40 return _UNIT_TYPE_INVALID;
45 "abcdefghijklmnopqrstuvwxyz" \
46 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
49 bool unit_name_is_valid(const char *n) {
55 if (strlen(n) >= UNIT_NAME_MAX)
58 t = unit_name_to_type(n);
59 if (t < 0 || t >= _UNIT_TYPE_MAX)
62 if (!(e = strrchr(n, '.')))
68 for (i = n; i < e; i++)
69 if (!strchr(VALID_CHARS, *i))
75 char *unit_name_change_suffix(const char *n, const char *suffix) {
80 assert(unit_name_is_valid(n));
83 assert_se(e = strrchr(n, '.'));
87 if (!(r = new(char, a + b + 1)))
91 memcpy(r+a, suffix, b+1);
96 Unit *unit_new(Manager *m) {
101 if (!(u = new0(Unit, 1)))
104 if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
110 u->meta.type = _UNIT_TYPE_INVALID;
115 int unit_add_name(Unit *u, const char *text) {
123 if (!unit_name_is_valid(text))
126 if ((t = unit_name_to_type(text)) == _UNIT_TYPE_INVALID)
129 if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type)
132 if (!(s = strdup(text)))
135 if ((r = set_put(u->meta.names, s)) < 0) {
144 if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
145 set_remove(u->meta.names, s);
158 int unit_choose_id(Unit *u, const char *name) {
164 /* Selects one of the names of this unit as the id */
166 if (!(s = set_get(u->meta.names, (char*) name)))
173 void unit_add_to_load_queue(Unit *u) {
176 if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
179 LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
180 u->meta.in_load_queue = true;
183 static void bidi_set_free(Unit *u, Set *s) {
189 /* Frees the set and makes sure we are dropped from the
190 * inverse pointers */
192 SET_FOREACH(other, s, i) {
195 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
196 set_remove(other->meta.dependencies[d], u);
202 void unit_free(Unit *u) {
209 /* Detach from next 'bigger' objects */
211 SET_FOREACH(t, u->meta.names, i)
212 hashmap_remove_value(u->meta.manager->units, t, u);
214 if (u->meta.in_load_queue)
215 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
217 if (u->meta.load_state == UNIT_LOADED)
218 if (UNIT_VTABLE(u)->done)
219 UNIT_VTABLE(u)->done(u);
221 /* Free data and next 'smaller' objects */
223 job_free(u->meta.job);
225 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
226 bidi_set_free(u, u->meta.dependencies[d]);
228 free(u->meta.description);
229 free(u->meta.load_path);
231 while ((t = set_steal_first(u->meta.names)))
233 set_free(u->meta.names);
238 UnitActiveState unit_active_state(Unit *u) {
241 if (u->meta.load_state != UNIT_LOADED)
242 return UNIT_INACTIVE;
244 return UNIT_VTABLE(u)->active_state(u);
247 static int ensure_merge(Set **s, Set *other) {
253 return set_merge(*s, other);
255 if (!(*s = set_copy(other)))
261 /* FIXME: Does not rollback on failure! Needs to fix special unit
262 * pointers. Needs to merge names and dependencies properly.*/
263 int unit_merge(Unit *u, Unit *other) {
269 assert(u->meta.manager == other->meta.manager);
271 /* This merges 'other' into 'unit'. FIXME: This does not
272 * rollback on failure. */
274 if (u->meta.type != u->meta.type)
277 if (u->meta.load_state != UNIT_STUB)
281 if ((r = ensure_merge(&u->meta.names, other->meta.names)) < 0)
284 /* Merge dependencies */
285 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
286 /* fixme, the inverse mapping is missing */
287 if ((r = ensure_merge(&u->meta.dependencies[d], other->meta.dependencies[d])) < 0)
293 const char* unit_id(Unit *u) {
299 return set_first(u->meta.names);
302 const char *unit_description(Unit *u) {
305 if (u->meta.description)
306 return u->meta.description;
311 void unit_dump(Unit *u, FILE *f, const char *prefix) {
313 static const char* const load_state_table[_UNIT_LOAD_STATE_MAX] = {
314 [UNIT_STUB] = "stub",
315 [UNIT_LOADED] = "loaded",
316 [UNIT_FAILED] = "failed"
319 static const char* const active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
320 [UNIT_ACTIVE] = "active",
321 [UNIT_INACTIVE] = "inactive",
322 [UNIT_ACTIVATING] = "activating",
323 [UNIT_DEACTIVATING] = "deactivating"
326 static const char* const dependency_table[_UNIT_DEPENDENCY_MAX] = {
327 [UNIT_REQUIRES] = "Requires",
328 [UNIT_SOFT_REQUIRES] = "SoftRequires",
329 [UNIT_WANTS] = "Wants",
330 [UNIT_REQUISITE] = "Requisite",
331 [UNIT_SOFT_REQUISITE] = "SoftRequisite",
332 [UNIT_REQUIRED_BY] = "RequiredBy",
333 [UNIT_SOFT_REQUIRED_BY] = "SoftRequiredBy",
334 [UNIT_WANTED_BY] = "WantedBy",
335 [UNIT_CONFLICTS] = "Conflicts",
336 [UNIT_BEFORE] = "Before",
337 [UNIT_AFTER] = "After",
349 prefix2 = strappend(prefix, "\t");
355 "%s\tDescription: %s\n"
356 "%s\tUnit Load State: %s\n"
357 "%s\tUnit Active State: %s\n",
359 prefix, unit_description(u),
360 prefix, load_state_table[u->meta.load_state],
361 prefix, active_state_table[unit_active_state(u)]);
363 if (u->meta.load_path)
364 fprintf(f, "%s\tLoad Path: %s\n", prefix, u->meta.load_path);
366 SET_FOREACH(t, u->meta.names, i)
367 fprintf(f, "%s\tName: %s\n", prefix, t);
369 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
372 if (set_isempty(u->meta.dependencies[d]))
375 SET_FOREACH(other, u->meta.dependencies[d], i)
376 fprintf(f, "%s\t%s: %s\n", prefix, dependency_table[d], unit_id(other));
379 if (UNIT_VTABLE(u)->dump)
380 UNIT_VTABLE(u)->dump(u, f, prefix2);
383 job_dump(u->meta.job, f, prefix2);
388 /* Common implementation for multiple backends */
389 int unit_load_fragment_and_dropin(Unit *u) {
394 /* Load a .socket file */
395 if ((r = unit_load_fragment(u)) < 0)
400 /* Load drop-in directory data */
401 if ((r = unit_load_dropin(u)) < 0)
407 int unit_load(Unit *u) {
412 if (u->meta.in_load_queue) {
413 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
414 u->meta.in_load_queue = false;
417 if (u->meta.load_state != UNIT_STUB)
420 if (UNIT_VTABLE(u)->init)
421 if ((r = UNIT_VTABLE(u)->init(u)) < 0)
424 u->meta.load_state = UNIT_LOADED;
428 u->meta.load_state = UNIT_FAILED;
433 * -EBADR: This unit type does not support starting.
434 * -EALREADY: Unit is already started.
435 * -EAGAIN: An operation is already in progress. Retry later.
437 int unit_start(Unit *u) {
438 UnitActiveState state;
442 if (!UNIT_VTABLE(u)->start)
445 state = unit_active_state(u);
446 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
449 /* We don't suppress calls to ->start() here when we are
450 * already starting, to allow this request to be used as a
451 * "hurry up" call, for example when the unit is in some "auto
452 * restart" state where it waits for a holdoff timer to elapse
453 * before it will start again. */
455 return UNIT_VTABLE(u)->start(u);
458 bool unit_can_start(Unit *u) {
461 return !!UNIT_VTABLE(u)->start;
465 * -EBADR: This unit type does not support stopping.
466 * -EALREADY: Unit is already stopped.
467 * -EAGAIN: An operation is already in progress. Retry later.
469 int unit_stop(Unit *u) {
470 UnitActiveState state;
474 if (!UNIT_VTABLE(u)->stop)
477 state = unit_active_state(u);
478 if (state == UNIT_INACTIVE)
481 if (state == UNIT_DEACTIVATING)
484 return UNIT_VTABLE(u)->stop(u);
488 * -EBADR: This unit type does not support reloading.
489 * -ENOEXEC: Unit is not started.
490 * -EAGAIN: An operation is already in progress. Retry later.
492 int unit_reload(Unit *u) {
493 UnitActiveState state;
497 if (!unit_can_reload(u))
500 state = unit_active_state(u);
501 if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
504 if (unit_active_state(u) != UNIT_ACTIVE)
507 return UNIT_VTABLE(u)->reload(u);
510 bool unit_can_reload(Unit *u) {
513 if (!UNIT_VTABLE(u)->reload)
516 if (!UNIT_VTABLE(u)->can_reload)
519 return UNIT_VTABLE(u)->can_reload(u);
522 static void retroactively_start_dependencies(Unit *u) {
527 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
529 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
530 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
531 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
533 SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
534 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
535 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
537 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
538 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
539 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
541 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
542 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
543 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
545 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
546 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
547 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
550 static void retroactively_stop_dependencies(Unit *u) {
555 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
557 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
558 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
559 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
562 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
564 assert(os < _UNIT_ACTIVE_STATE_MAX);
565 assert(ns < _UNIT_ACTIVE_STATE_MAX);
566 assert(!(os == UNIT_ACTIVE && ns == UNIT_ACTIVATING));
567 assert(!(os == UNIT_INACTIVE && ns == UNIT_DEACTIVATING));
572 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
573 u->meta.active_enter_timestamp = now(CLOCK_REALTIME);
574 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
575 u->meta.active_exit_timestamp = now(CLOCK_REALTIME);
579 if (u->meta.job->state == JOB_WAITING)
581 /* So we reached a different state for this
582 * job. Let's see if we can run it now if it
583 * failed previously due to EAGAIN. */
584 job_schedule_run(u->meta.job);
587 assert(u->meta.job->state == JOB_RUNNING);
589 /* Let's check of this state change
590 * constitutes a finished job, or maybe
591 * cotradicts a running job and hence needs to
592 * invalidate jobs. */
594 switch (u->meta.job->type) {
597 case JOB_VERIFY_ACTIVE:
599 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
600 job_finish_and_invalidate(u->meta.job, true);
602 } else if (ns == UNIT_ACTIVATING)
605 job_finish_and_invalidate(u->meta.job, false);
610 case JOB_RELOAD_OR_START:
612 if (ns == UNIT_ACTIVE) {
613 job_finish_and_invalidate(u->meta.job, true);
615 } else if (ns == UNIT_ACTIVATING || ns == UNIT_ACTIVE_RELOADING)
618 job_finish_and_invalidate(u->meta.job, false);
624 case JOB_TRY_RESTART:
626 if (ns == UNIT_INACTIVE) {
627 job_finish_and_invalidate(u->meta.job, true);
629 } else if (ns == UNIT_DEACTIVATING)
632 job_finish_and_invalidate(u->meta.job, false);
637 assert_not_reached("Job type unknown");
642 /* If this state change happened without being requested by a
643 * job, then let's retroactively start or stop dependencies */
645 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
646 retroactively_start_dependencies(u);
647 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
648 retroactively_stop_dependencies(u);
651 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
652 struct epoll_event ev;
657 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->unit == u));
663 if (epoll_ctl(u->meta.manager->epoll_fd,
664 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
676 void unit_unwatch_fd(Unit *u, Watch *w) {
680 if (w->type == WATCH_INVALID)
683 assert(w->type == WATCH_FD && w->unit == u);
684 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
687 w->type = WATCH_INVALID;
691 int unit_watch_pid(Unit *u, pid_t pid) {
695 return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
698 void unit_unwatch_pid(Unit *u, pid_t pid) {
702 hashmap_remove(u->meta.manager->watch_pids, UINT32_TO_PTR(pid));
705 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
706 struct itimerspec its;
712 assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->unit == u));
714 /* This will try to reuse the old timer if there is one */
716 if (w->type == WATCH_TIMER) {
721 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
728 /* Set absolute time in the past, but not 0, since we
729 * don't want to disarm the timer */
730 its.it_value.tv_sec = 0;
731 its.it_value.tv_nsec = 1;
733 flags = TFD_TIMER_ABSTIME;
735 timespec_store(&its.it_value, delay);
739 /* This will also flush the elapse counter */
740 if (timerfd_settime(fd, flags, &its, NULL) < 0)
743 if (w->type == WATCH_INVALID) {
744 struct epoll_event ev;
750 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
755 w->type = WATCH_TIMER;
762 assert_se(close_nointr(fd) == 0);
767 void unit_unwatch_timer(Unit *u, Watch *w) {
771 if (w->type == WATCH_INVALID)
774 assert(w->type == WATCH_TIMER && w->unit == u);
776 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
777 assert_se(close_nointr(w->fd) == 0);
780 w->type = WATCH_INVALID;
784 bool unit_job_is_applicable(Unit *u, JobType j) {
786 assert(j >= 0 && j < _JOB_TYPE_MAX);
790 case JOB_VERIFY_ACTIVE:
796 case JOB_TRY_RESTART:
797 return unit_can_start(u);
800 return unit_can_reload(u);
802 case JOB_RELOAD_OR_START:
803 return unit_can_reload(u) && unit_can_start(u);
806 assert_not_reached("Invalid job type");
810 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other) {
812 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
813 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
814 [UNIT_SOFT_REQUIRES] = UNIT_SOFT_REQUIRED_BY,
815 [UNIT_WANTS] = UNIT_WANTED_BY,
816 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
817 [UNIT_SOFT_REQUISITE] = UNIT_SOFT_REQUIRED_BY,
818 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
819 [UNIT_SOFT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
820 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
821 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
822 [UNIT_BEFORE] = UNIT_AFTER,
823 [UNIT_AFTER] = UNIT_BEFORE
828 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
829 assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
832 /* We won't allow dependencies on ourselves. We will not
833 * consider them an error however. */
837 if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
840 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
843 if ((r = set_put(u->meta.dependencies[d], other)) < 0)
846 if ((r = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
847 set_remove(u->meta.dependencies[d], other);
854 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name) {
858 if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
861 if ((r = unit_add_dependency(u, d, other)) < 0)
867 const char *unit_path(void) {
870 if ((e = getenv("UNIT_PATH")))
871 if (path_is_absolute(e))
877 int set_unit_path(const char *p) {
881 /* This is mostly for debug purposes */
883 if (path_is_absolute(p)) {
884 if (!(c = strdup(p)))
887 if (!(cwd = get_current_dir_name()))
890 r = asprintf(&c, "%s/%s", cwd, p);
897 if (setenv("UNIT_PATH", c, 0) < 0) {
906 char *unit_name_escape_path(const char *prefix, const char *path, const char *suffix) {
913 /* Takes a path and a suffix and prefix and makes a nice
914 * string suitable as unit name of it, escaping all weird
917 * / becomes ., and all chars not alloweed in a unit name get
918 * escaped as \xFF, including \ and ., of course. This
919 * escaping is hence reversible.
932 if (!(r = new(char, a+b*4+c+1)))
935 memcpy(r, prefix, a);
937 for (f = path, t = r+a; *f; f++) {
940 else if (*f == '.' || *f == '\\' || !strchr(VALID_CHARS, *f)) {
943 *(t++) = hexchar(*f > 4);
944 *(t++) = hexchar(*f);
949 memcpy(t, suffix, c+1);