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);
150 if (u->meta.type == _UNIT_TYPE_INVALID)
151 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
161 int unit_choose_id(Unit *u, const char *name) {
167 /* Selects one of the names of this unit as the id */
169 if (!(s = set_get(u->meta.names, (char*) name)))
176 int unit_set_description(Unit *u, const char *description) {
181 if (!(s = strdup(description)))
184 free(u->meta.description);
185 u->meta.description = s;
189 void unit_add_to_load_queue(Unit *u) {
192 if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
195 LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
196 u->meta.in_load_queue = true;
199 static void bidi_set_free(Unit *u, Set *s) {
205 /* Frees the set and makes sure we are dropped from the
206 * inverse pointers */
208 SET_FOREACH(other, s, i) {
211 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
212 set_remove(other->meta.dependencies[d], u);
218 void unit_free(Unit *u) {
225 /* Detach from next 'bigger' objects */
227 SET_FOREACH(t, u->meta.names, i)
228 hashmap_remove_value(u->meta.manager->units, t, u);
230 if (u->meta.type != _UNIT_TYPE_INVALID)
231 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
233 if (u->meta.in_load_queue)
234 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
236 if (u->meta.load_state == UNIT_LOADED)
237 if (UNIT_VTABLE(u)->done)
238 UNIT_VTABLE(u)->done(u);
240 /* Free data and next 'smaller' objects */
242 job_free(u->meta.job);
244 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
245 bidi_set_free(u, u->meta.dependencies[d]);
247 free(u->meta.description);
248 free(u->meta.load_path);
250 while ((t = set_steal_first(u->meta.names)))
252 set_free(u->meta.names);
257 UnitActiveState unit_active_state(Unit *u) {
260 if (u->meta.load_state != UNIT_LOADED)
261 return UNIT_INACTIVE;
263 return UNIT_VTABLE(u)->active_state(u);
266 static int ensure_merge(Set **s, Set *other) {
272 return set_merge(*s, other);
274 if (!(*s = set_copy(other)))
280 /* FIXME: Does not rollback on failure! Needs to fix special unit
281 * pointers. Needs to merge names and dependencies properly.*/
282 int unit_merge(Unit *u, Unit *other) {
288 assert(u->meta.manager == other->meta.manager);
290 /* This merges 'other' into 'unit'. FIXME: This does not
291 * rollback on failure. */
293 if (u->meta.type != u->meta.type)
296 if (u->meta.load_state != UNIT_STUB)
300 if ((r = ensure_merge(&u->meta.names, other->meta.names)) < 0)
303 /* Merge dependencies */
304 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
305 /* fixme, the inverse mapping is missing */
306 if ((r = ensure_merge(&u->meta.dependencies[d], other->meta.dependencies[d])) < 0)
312 const char* unit_id(Unit *u) {
318 return set_first(u->meta.names);
321 const char *unit_description(Unit *u) {
324 if (u->meta.description)
325 return u->meta.description;
330 void unit_dump(Unit *u, FILE *f, const char *prefix) {
332 static const char* const load_state_table[_UNIT_LOAD_STATE_MAX] = {
333 [UNIT_STUB] = "stub",
334 [UNIT_LOADED] = "loaded",
335 [UNIT_FAILED] = "failed"
338 static const char* const active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
339 [UNIT_ACTIVE] = "active",
340 [UNIT_INACTIVE] = "inactive",
341 [UNIT_ACTIVATING] = "activating",
342 [UNIT_DEACTIVATING] = "deactivating"
345 static const char* const dependency_table[_UNIT_DEPENDENCY_MAX] = {
346 [UNIT_REQUIRES] = "Requires",
347 [UNIT_SOFT_REQUIRES] = "SoftRequires",
348 [UNIT_WANTS] = "Wants",
349 [UNIT_REQUISITE] = "Requisite",
350 [UNIT_SOFT_REQUISITE] = "SoftRequisite",
351 [UNIT_REQUIRED_BY] = "RequiredBy",
352 [UNIT_SOFT_REQUIRED_BY] = "SoftRequiredBy",
353 [UNIT_WANTED_BY] = "WantedBy",
354 [UNIT_CONFLICTS] = "Conflicts",
355 [UNIT_BEFORE] = "Before",
356 [UNIT_AFTER] = "After",
368 prefix2 = strappend(prefix, "\t");
374 "%s\tDescription: %s\n"
375 "%s\tUnit Load State: %s\n"
376 "%s\tUnit Active State: %s\n",
378 prefix, unit_description(u),
379 prefix, load_state_table[u->meta.load_state],
380 prefix, active_state_table[unit_active_state(u)]);
382 if (u->meta.load_path)
383 fprintf(f, "%s\tLoad Path: %s\n", prefix, u->meta.load_path);
385 SET_FOREACH(t, u->meta.names, i)
386 fprintf(f, "%s\tName: %s\n", prefix, t);
388 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
391 if (set_isempty(u->meta.dependencies[d]))
394 SET_FOREACH(other, u->meta.dependencies[d], i)
395 fprintf(f, "%s\t%s: %s\n", prefix, dependency_table[d], unit_id(other));
398 if (UNIT_VTABLE(u)->dump)
399 UNIT_VTABLE(u)->dump(u, f, prefix2);
402 job_dump(u->meta.job, f, prefix2);
407 /* Common implementation for multiple backends */
408 int unit_load_fragment_and_dropin(Unit *u) {
413 /* Load a .socket file */
414 if ((r = unit_load_fragment(u)) < 0)
419 /* Load drop-in directory data */
420 if ((r = unit_load_dropin(u)) < 0)
426 int unit_load(Unit *u) {
431 if (u->meta.in_load_queue) {
432 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
433 u->meta.in_load_queue = false;
436 if (u->meta.load_state != UNIT_STUB)
439 if (UNIT_VTABLE(u)->init)
440 if ((r = UNIT_VTABLE(u)->init(u)) < 0)
443 u->meta.load_state = UNIT_LOADED;
447 u->meta.load_state = UNIT_FAILED;
452 * -EBADR: This unit type does not support starting.
453 * -EALREADY: Unit is already started.
454 * -EAGAIN: An operation is already in progress. Retry later.
456 int unit_start(Unit *u) {
457 UnitActiveState state;
461 if (!UNIT_VTABLE(u)->start)
464 state = unit_active_state(u);
465 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
468 /* We don't suppress calls to ->start() here when we are
469 * already starting, to allow this request to be used as a
470 * "hurry up" call, for example when the unit is in some "auto
471 * restart" state where it waits for a holdoff timer to elapse
472 * before it will start again. */
474 return UNIT_VTABLE(u)->start(u);
477 bool unit_can_start(Unit *u) {
480 return !!UNIT_VTABLE(u)->start;
484 * -EBADR: This unit type does not support stopping.
485 * -EALREADY: Unit is already stopped.
486 * -EAGAIN: An operation is already in progress. Retry later.
488 int unit_stop(Unit *u) {
489 UnitActiveState state;
493 if (!UNIT_VTABLE(u)->stop)
496 state = unit_active_state(u);
497 if (state == UNIT_INACTIVE)
500 if (state == UNIT_DEACTIVATING)
503 return UNIT_VTABLE(u)->stop(u);
507 * -EBADR: This unit type does not support reloading.
508 * -ENOEXEC: Unit is not started.
509 * -EAGAIN: An operation is already in progress. Retry later.
511 int unit_reload(Unit *u) {
512 UnitActiveState state;
516 if (!unit_can_reload(u))
519 state = unit_active_state(u);
520 if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
523 if (unit_active_state(u) != UNIT_ACTIVE)
526 return UNIT_VTABLE(u)->reload(u);
529 bool unit_can_reload(Unit *u) {
532 if (!UNIT_VTABLE(u)->reload)
535 if (!UNIT_VTABLE(u)->can_reload)
538 return UNIT_VTABLE(u)->can_reload(u);
541 static void retroactively_start_dependencies(Unit *u) {
546 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
548 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
549 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
550 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
552 SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
553 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
554 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
556 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
557 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
558 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
560 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
561 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
562 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
564 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
565 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
566 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
569 static void retroactively_stop_dependencies(Unit *u) {
574 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
576 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
577 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
578 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
581 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
583 assert(os < _UNIT_ACTIVE_STATE_MAX);
584 assert(ns < _UNIT_ACTIVE_STATE_MAX);
585 assert(!(os == UNIT_ACTIVE && ns == UNIT_ACTIVATING));
586 assert(!(os == UNIT_INACTIVE && ns == UNIT_DEACTIVATING));
591 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
592 u->meta.active_enter_timestamp = now(CLOCK_REALTIME);
593 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
594 u->meta.active_exit_timestamp = now(CLOCK_REALTIME);
598 if (u->meta.job->state == JOB_WAITING)
600 /* So we reached a different state for this
601 * job. Let's see if we can run it now if it
602 * failed previously due to EAGAIN. */
603 job_schedule_run(u->meta.job);
606 assert(u->meta.job->state == JOB_RUNNING);
608 /* Let's check whether this state change
609 * constitutes a finished job, or maybe
610 * cotradicts a running job and hence needs to
611 * invalidate jobs. */
613 switch (u->meta.job->type) {
616 case JOB_VERIFY_ACTIVE:
618 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
619 job_finish_and_invalidate(u->meta.job, true);
621 } else if (ns == UNIT_ACTIVATING)
624 job_finish_and_invalidate(u->meta.job, false);
629 case JOB_RELOAD_OR_START:
631 if (ns == UNIT_ACTIVE) {
632 job_finish_and_invalidate(u->meta.job, true);
634 } else if (ns == UNIT_ACTIVATING || ns == UNIT_ACTIVE_RELOADING)
637 job_finish_and_invalidate(u->meta.job, false);
643 case JOB_TRY_RESTART:
645 if (ns == UNIT_INACTIVE) {
646 job_finish_and_invalidate(u->meta.job, true);
648 } else if (ns == UNIT_DEACTIVATING)
651 job_finish_and_invalidate(u->meta.job, false);
656 assert_not_reached("Job type unknown");
661 /* If this state change happened without being requested by a
662 * job, then let's retroactively start or stop dependencies */
664 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
665 retroactively_start_dependencies(u);
666 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
667 retroactively_stop_dependencies(u);
670 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
671 struct epoll_event ev;
676 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->unit == u));
682 if (epoll_ctl(u->meta.manager->epoll_fd,
683 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
695 void unit_unwatch_fd(Unit *u, Watch *w) {
699 if (w->type == WATCH_INVALID)
702 assert(w->type == WATCH_FD && w->unit == u);
703 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
706 w->type = WATCH_INVALID;
710 int unit_watch_pid(Unit *u, pid_t pid) {
714 return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
717 void unit_unwatch_pid(Unit *u, pid_t pid) {
721 hashmap_remove(u->meta.manager->watch_pids, UINT32_TO_PTR(pid));
724 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
725 struct itimerspec its;
731 assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->unit == u));
733 /* This will try to reuse the old timer if there is one */
735 if (w->type == WATCH_TIMER) {
740 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
747 /* Set absolute time in the past, but not 0, since we
748 * don't want to disarm the timer */
749 its.it_value.tv_sec = 0;
750 its.it_value.tv_nsec = 1;
752 flags = TFD_TIMER_ABSTIME;
754 timespec_store(&its.it_value, delay);
758 /* This will also flush the elapse counter */
759 if (timerfd_settime(fd, flags, &its, NULL) < 0)
762 if (w->type == WATCH_INVALID) {
763 struct epoll_event ev;
769 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
774 w->type = WATCH_TIMER;
781 assert_se(close_nointr(fd) == 0);
786 void unit_unwatch_timer(Unit *u, Watch *w) {
790 if (w->type == WATCH_INVALID)
793 assert(w->type == WATCH_TIMER && w->unit == u);
795 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
796 assert_se(close_nointr(w->fd) == 0);
799 w->type = WATCH_INVALID;
803 bool unit_job_is_applicable(Unit *u, JobType j) {
805 assert(j >= 0 && j < _JOB_TYPE_MAX);
809 case JOB_VERIFY_ACTIVE:
815 case JOB_TRY_RESTART:
816 return unit_can_start(u);
819 return unit_can_reload(u);
821 case JOB_RELOAD_OR_START:
822 return unit_can_reload(u) && unit_can_start(u);
825 assert_not_reached("Invalid job type");
829 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other) {
831 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
832 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
833 [UNIT_SOFT_REQUIRES] = UNIT_SOFT_REQUIRED_BY,
834 [UNIT_WANTS] = UNIT_WANTED_BY,
835 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
836 [UNIT_SOFT_REQUISITE] = UNIT_SOFT_REQUIRED_BY,
837 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
838 [UNIT_SOFT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
839 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
840 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
841 [UNIT_BEFORE] = UNIT_AFTER,
842 [UNIT_AFTER] = UNIT_BEFORE
847 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
848 assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
851 /* We won't allow dependencies on ourselves. We will not
852 * consider them an error however. */
856 if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
859 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
862 if ((r = set_put(u->meta.dependencies[d], other)) < 0)
865 if ((r = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
866 set_remove(u->meta.dependencies[d], other);
873 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name) {
877 if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
880 if ((r = unit_add_dependency(u, d, other)) < 0)
886 const char *unit_path(void) {
889 if ((e = getenv("UNIT_PATH")))
890 if (path_is_absolute(e))
896 int set_unit_path(const char *p) {
900 /* This is mostly for debug purposes */
902 if (path_is_absolute(p)) {
903 if (!(c = strdup(p)))
906 if (!(cwd = get_current_dir_name()))
909 r = asprintf(&c, "%s/%s", cwd, p);
916 if (setenv("UNIT_PATH", c, 0) < 0) {
925 char *unit_name_escape_path(const char *prefix, const char *path, const char *suffix) {
932 /* Takes a path and a suffix and prefix and makes a nice
933 * string suitable as unit name of it, escaping all weird
936 * / becomes ., and all chars not alloweed in a unit name get
937 * escaped as \xFF, including \ and ., of course. This
938 * escaping is hence reversible.
951 if (!(r = new(char, a+b*4+c+1)))
954 memcpy(r, prefix, a);
956 for (f = path, t = r+a; *f; f++) {
959 else if (*f == '.' || *f == '\\' || !strchr(VALID_CHARS, *f)) {
962 *(t++) = hexchar(*f > 4);
963 *(t++) = hexchar(*f);
968 memcpy(t, suffix, c+1);