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 int unit_set_description(Unit *u, const char *description) {
178 if (!(s = strdup(description)))
181 free(u->meta.description);
182 u->meta.description = s;
186 void unit_add_to_load_queue(Unit *u) {
189 if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
192 LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
193 u->meta.in_load_queue = true;
196 static void bidi_set_free(Unit *u, Set *s) {
202 /* Frees the set and makes sure we are dropped from the
203 * inverse pointers */
205 SET_FOREACH(other, s, i) {
208 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
209 set_remove(other->meta.dependencies[d], u);
215 void unit_free(Unit *u) {
222 /* Detach from next 'bigger' objects */
224 SET_FOREACH(t, u->meta.names, i)
225 hashmap_remove_value(u->meta.manager->units, t, u);
227 if (u->meta.in_load_queue)
228 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
230 if (u->meta.load_state == UNIT_LOADED)
231 if (UNIT_VTABLE(u)->done)
232 UNIT_VTABLE(u)->done(u);
234 /* Free data and next 'smaller' objects */
236 job_free(u->meta.job);
238 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
239 bidi_set_free(u, u->meta.dependencies[d]);
241 free(u->meta.description);
242 free(u->meta.load_path);
244 while ((t = set_steal_first(u->meta.names)))
246 set_free(u->meta.names);
251 UnitActiveState unit_active_state(Unit *u) {
254 if (u->meta.load_state != UNIT_LOADED)
255 return UNIT_INACTIVE;
257 return UNIT_VTABLE(u)->active_state(u);
260 static int ensure_merge(Set **s, Set *other) {
266 return set_merge(*s, other);
268 if (!(*s = set_copy(other)))
274 /* FIXME: Does not rollback on failure! Needs to fix special unit
275 * pointers. Needs to merge names and dependencies properly.*/
276 int unit_merge(Unit *u, Unit *other) {
282 assert(u->meta.manager == other->meta.manager);
284 /* This merges 'other' into 'unit'. FIXME: This does not
285 * rollback on failure. */
287 if (u->meta.type != u->meta.type)
290 if (u->meta.load_state != UNIT_STUB)
294 if ((r = ensure_merge(&u->meta.names, other->meta.names)) < 0)
297 /* Merge dependencies */
298 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
299 /* fixme, the inverse mapping is missing */
300 if ((r = ensure_merge(&u->meta.dependencies[d], other->meta.dependencies[d])) < 0)
306 const char* unit_id(Unit *u) {
312 return set_first(u->meta.names);
315 const char *unit_description(Unit *u) {
318 if (u->meta.description)
319 return u->meta.description;
324 void unit_dump(Unit *u, FILE *f, const char *prefix) {
326 static const char* const load_state_table[_UNIT_LOAD_STATE_MAX] = {
327 [UNIT_STUB] = "stub",
328 [UNIT_LOADED] = "loaded",
329 [UNIT_FAILED] = "failed"
332 static const char* const active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
333 [UNIT_ACTIVE] = "active",
334 [UNIT_INACTIVE] = "inactive",
335 [UNIT_ACTIVATING] = "activating",
336 [UNIT_DEACTIVATING] = "deactivating"
339 static const char* const dependency_table[_UNIT_DEPENDENCY_MAX] = {
340 [UNIT_REQUIRES] = "Requires",
341 [UNIT_SOFT_REQUIRES] = "SoftRequires",
342 [UNIT_WANTS] = "Wants",
343 [UNIT_REQUISITE] = "Requisite",
344 [UNIT_SOFT_REQUISITE] = "SoftRequisite",
345 [UNIT_REQUIRED_BY] = "RequiredBy",
346 [UNIT_SOFT_REQUIRED_BY] = "SoftRequiredBy",
347 [UNIT_WANTED_BY] = "WantedBy",
348 [UNIT_CONFLICTS] = "Conflicts",
349 [UNIT_BEFORE] = "Before",
350 [UNIT_AFTER] = "After",
362 prefix2 = strappend(prefix, "\t");
368 "%s\tDescription: %s\n"
369 "%s\tUnit Load State: %s\n"
370 "%s\tUnit Active State: %s\n",
372 prefix, unit_description(u),
373 prefix, load_state_table[u->meta.load_state],
374 prefix, active_state_table[unit_active_state(u)]);
376 if (u->meta.load_path)
377 fprintf(f, "%s\tLoad Path: %s\n", prefix, u->meta.load_path);
379 SET_FOREACH(t, u->meta.names, i)
380 fprintf(f, "%s\tName: %s\n", prefix, t);
382 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
385 if (set_isempty(u->meta.dependencies[d]))
388 SET_FOREACH(other, u->meta.dependencies[d], i)
389 fprintf(f, "%s\t%s: %s\n", prefix, dependency_table[d], unit_id(other));
392 if (UNIT_VTABLE(u)->dump)
393 UNIT_VTABLE(u)->dump(u, f, prefix2);
396 job_dump(u->meta.job, f, prefix2);
401 /* Common implementation for multiple backends */
402 int unit_load_fragment_and_dropin(Unit *u) {
407 /* Load a .socket file */
408 if ((r = unit_load_fragment(u)) < 0)
413 /* Load drop-in directory data */
414 if ((r = unit_load_dropin(u)) < 0)
420 int unit_load(Unit *u) {
425 if (u->meta.in_load_queue) {
426 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
427 u->meta.in_load_queue = false;
430 if (u->meta.load_state != UNIT_STUB)
433 if (UNIT_VTABLE(u)->init)
434 if ((r = UNIT_VTABLE(u)->init(u)) < 0)
437 u->meta.load_state = UNIT_LOADED;
441 u->meta.load_state = UNIT_FAILED;
446 * -EBADR: This unit type does not support starting.
447 * -EALREADY: Unit is already started.
448 * -EAGAIN: An operation is already in progress. Retry later.
450 int unit_start(Unit *u) {
451 UnitActiveState state;
455 if (!UNIT_VTABLE(u)->start)
458 state = unit_active_state(u);
459 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
462 /* We don't suppress calls to ->start() here when we are
463 * already starting, to allow this request to be used as a
464 * "hurry up" call, for example when the unit is in some "auto
465 * restart" state where it waits for a holdoff timer to elapse
466 * before it will start again. */
468 return UNIT_VTABLE(u)->start(u);
471 bool unit_can_start(Unit *u) {
474 return !!UNIT_VTABLE(u)->start;
478 * -EBADR: This unit type does not support stopping.
479 * -EALREADY: Unit is already stopped.
480 * -EAGAIN: An operation is already in progress. Retry later.
482 int unit_stop(Unit *u) {
483 UnitActiveState state;
487 if (!UNIT_VTABLE(u)->stop)
490 state = unit_active_state(u);
491 if (state == UNIT_INACTIVE)
494 if (state == UNIT_DEACTIVATING)
497 return UNIT_VTABLE(u)->stop(u);
501 * -EBADR: This unit type does not support reloading.
502 * -ENOEXEC: Unit is not started.
503 * -EAGAIN: An operation is already in progress. Retry later.
505 int unit_reload(Unit *u) {
506 UnitActiveState state;
510 if (!unit_can_reload(u))
513 state = unit_active_state(u);
514 if (unit_active_state(u) == UNIT_ACTIVE_RELOADING)
517 if (unit_active_state(u) != UNIT_ACTIVE)
520 return UNIT_VTABLE(u)->reload(u);
523 bool unit_can_reload(Unit *u) {
526 if (!UNIT_VTABLE(u)->reload)
529 if (!UNIT_VTABLE(u)->can_reload)
532 return UNIT_VTABLE(u)->can_reload(u);
535 static void retroactively_start_dependencies(Unit *u) {
540 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
542 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
543 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
544 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
546 SET_FOREACH(other, u->meta.dependencies[UNIT_SOFT_REQUIRES], i)
547 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
548 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
550 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
551 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
552 manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL);
554 SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
555 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
556 manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL);
558 SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
559 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
560 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
563 static void retroactively_stop_dependencies(Unit *u) {
568 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
570 SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
571 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
572 manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL);
575 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns) {
577 assert(os < _UNIT_ACTIVE_STATE_MAX);
578 assert(ns < _UNIT_ACTIVE_STATE_MAX);
579 assert(!(os == UNIT_ACTIVE && ns == UNIT_ACTIVATING));
580 assert(!(os == UNIT_INACTIVE && ns == UNIT_DEACTIVATING));
585 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
586 u->meta.active_enter_timestamp = now(CLOCK_REALTIME);
587 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
588 u->meta.active_exit_timestamp = now(CLOCK_REALTIME);
592 if (u->meta.job->state == JOB_WAITING)
594 /* So we reached a different state for this
595 * job. Let's see if we can run it now if it
596 * failed previously due to EAGAIN. */
597 job_schedule_run(u->meta.job);
600 assert(u->meta.job->state == JOB_RUNNING);
602 /* Let's check whether this state change
603 * constitutes a finished job, or maybe
604 * cotradicts a running job and hence needs to
605 * invalidate jobs. */
607 switch (u->meta.job->type) {
610 case JOB_VERIFY_ACTIVE:
612 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
613 job_finish_and_invalidate(u->meta.job, true);
615 } else if (ns == UNIT_ACTIVATING)
618 job_finish_and_invalidate(u->meta.job, false);
623 case JOB_RELOAD_OR_START:
625 if (ns == UNIT_ACTIVE) {
626 job_finish_and_invalidate(u->meta.job, true);
628 } else if (ns == UNIT_ACTIVATING || ns == UNIT_ACTIVE_RELOADING)
631 job_finish_and_invalidate(u->meta.job, false);
637 case JOB_TRY_RESTART:
639 if (ns == UNIT_INACTIVE) {
640 job_finish_and_invalidate(u->meta.job, true);
642 } else if (ns == UNIT_DEACTIVATING)
645 job_finish_and_invalidate(u->meta.job, false);
650 assert_not_reached("Job type unknown");
655 /* If this state change happened without being requested by a
656 * job, then let's retroactively start or stop dependencies */
658 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
659 retroactively_start_dependencies(u);
660 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
661 retroactively_stop_dependencies(u);
664 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
665 struct epoll_event ev;
670 assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->unit == u));
676 if (epoll_ctl(u->meta.manager->epoll_fd,
677 w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
689 void unit_unwatch_fd(Unit *u, Watch *w) {
693 if (w->type == WATCH_INVALID)
696 assert(w->type == WATCH_FD && w->unit == u);
697 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
700 w->type = WATCH_INVALID;
704 int unit_watch_pid(Unit *u, pid_t pid) {
708 return hashmap_put(u->meta.manager->watch_pids, UINT32_TO_PTR(pid), u);
711 void unit_unwatch_pid(Unit *u, pid_t pid) {
715 hashmap_remove(u->meta.manager->watch_pids, UINT32_TO_PTR(pid));
718 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
719 struct itimerspec its;
725 assert(w->type == WATCH_INVALID || (w->type == WATCH_TIMER && w->unit == u));
727 /* This will try to reuse the old timer if there is one */
729 if (w->type == WATCH_TIMER) {
734 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
741 /* Set absolute time in the past, but not 0, since we
742 * don't want to disarm the timer */
743 its.it_value.tv_sec = 0;
744 its.it_value.tv_nsec = 1;
746 flags = TFD_TIMER_ABSTIME;
748 timespec_store(&its.it_value, delay);
752 /* This will also flush the elapse counter */
753 if (timerfd_settime(fd, flags, &its, NULL) < 0)
756 if (w->type == WATCH_INVALID) {
757 struct epoll_event ev;
763 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
768 w->type = WATCH_TIMER;
775 assert_se(close_nointr(fd) == 0);
780 void unit_unwatch_timer(Unit *u, Watch *w) {
784 if (w->type == WATCH_INVALID)
787 assert(w->type == WATCH_TIMER && w->unit == u);
789 assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
790 assert_se(close_nointr(w->fd) == 0);
793 w->type = WATCH_INVALID;
797 bool unit_job_is_applicable(Unit *u, JobType j) {
799 assert(j >= 0 && j < _JOB_TYPE_MAX);
803 case JOB_VERIFY_ACTIVE:
809 case JOB_TRY_RESTART:
810 return unit_can_start(u);
813 return unit_can_reload(u);
815 case JOB_RELOAD_OR_START:
816 return unit_can_reload(u) && unit_can_start(u);
819 assert_not_reached("Invalid job type");
823 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other) {
825 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
826 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
827 [UNIT_SOFT_REQUIRES] = UNIT_SOFT_REQUIRED_BY,
828 [UNIT_WANTS] = UNIT_WANTED_BY,
829 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
830 [UNIT_SOFT_REQUISITE] = UNIT_SOFT_REQUIRED_BY,
831 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
832 [UNIT_SOFT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
833 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
834 [UNIT_CONFLICTS] = UNIT_CONFLICTS,
835 [UNIT_BEFORE] = UNIT_AFTER,
836 [UNIT_AFTER] = UNIT_BEFORE
841 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
842 assert(inverse_table[d] != _UNIT_DEPENDENCY_INVALID);
845 /* We won't allow dependencies on ourselves. We will not
846 * consider them an error however. */
850 if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
853 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
856 if ((r = set_put(u->meta.dependencies[d], other)) < 0)
859 if ((r = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
860 set_remove(u->meta.dependencies[d], other);
867 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name) {
871 if ((r = manager_load_unit(u->meta.manager, name, &other)) < 0)
874 if ((r = unit_add_dependency(u, d, other)) < 0)
880 const char *unit_path(void) {
883 if ((e = getenv("UNIT_PATH")))
884 if (path_is_absolute(e))
890 int set_unit_path(const char *p) {
894 /* This is mostly for debug purposes */
896 if (path_is_absolute(p)) {
897 if (!(c = strdup(p)))
900 if (!(cwd = get_current_dir_name()))
903 r = asprintf(&c, "%s/%s", cwd, p);
910 if (setenv("UNIT_PATH", c, 0) < 0) {
919 char *unit_name_escape_path(const char *prefix, const char *path, const char *suffix) {
926 /* Takes a path and a suffix and prefix and makes a nice
927 * string suitable as unit name of it, escaping all weird
930 * / becomes ., and all chars not alloweed in a unit name get
931 * escaped as \xFF, including \ and ., of course. This
932 * escaping is hence reversible.
945 if (!(r = new(char, a+b*4+c+1)))
948 memcpy(r, prefix, a);
950 for (f = path, t = r+a; *f; f++) {
953 else if (*f == '.' || *f == '\\' || !strchr(VALID_CHARS, *f)) {
956 *(t++) = hexchar(*f > 4);
957 *(t++) = hexchar(*f);
962 memcpy(t, suffix, c+1);