1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "sd-messages.h"
11 #include "all-units.h"
12 #include "alloc-util.h"
13 #include "bpf-firewall.h"
14 #include "bus-common-errors.h"
16 #include "cgroup-setup.h"
17 #include "cgroup-util.h"
18 #include "core-varlink.h"
19 #include "dbus-unit.h"
25 #include "fileio-label.h"
27 #include "format-util.h"
28 #include "id128-util.h"
32 #include "load-dropin.h"
33 #include "load-fragment.h"
36 #include "missing_audit.h"
38 #include "path-util.h"
39 #include "process-util.h"
42 #include "signal-util.h"
43 #include "sparse-endian.h"
45 #include "specifier.h"
46 #include "stat-util.h"
47 #include "stdio-util.h"
48 #include "string-table.h"
49 #include "string-util.h"
51 #include "terminal-util.h"
52 #include "tmpfile-util.h"
53 #include "umask-util.h"
54 #include "unit-name.h"
56 #include "user-util.h"
59 /* Thresholds for logging at INFO level about resource consumption */
60 #define MENTIONWORTHY_CPU_NSEC (1 * NSEC_PER_SEC)
61 #define MENTIONWORTHY_IO_BYTES (1024 * 1024ULL)
62 #define MENTIONWORTHY_IP_BYTES (0ULL)
64 /* Thresholds for logging at INFO level about resource consumption */
65 #define NOTICEWORTHY_CPU_NSEC (10*60 * NSEC_PER_SEC) /* 10 minutes */
66 #define NOTICEWORTHY_IO_BYTES (10 * 1024 * 1024ULL) /* 10 MB */
67 #define NOTICEWORTHY_IP_BYTES (128 * 1024 * 1024ULL) /* 128 MB */
69 const UnitVTable
* const unit_vtable
[_UNIT_TYPE_MAX
] = {
70 [UNIT_SERVICE
] = &service_vtable
,
71 [UNIT_SOCKET
] = &socket_vtable
,
72 [UNIT_TARGET
] = &target_vtable
,
73 [UNIT_DEVICE
] = &device_vtable
,
74 [UNIT_MOUNT
] = &mount_vtable
,
75 [UNIT_AUTOMOUNT
] = &automount_vtable
,
76 [UNIT_SWAP
] = &swap_vtable
,
77 [UNIT_TIMER
] = &timer_vtable
,
78 [UNIT_PATH
] = &path_vtable
,
79 [UNIT_SLICE
] = &slice_vtable
,
80 [UNIT_SCOPE
] = &scope_vtable
,
83 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
);
85 Unit
* unit_new(Manager
*m
, size_t size
) {
89 assert(size
>= sizeof(Unit
));
96 u
->type
= _UNIT_TYPE_INVALID
;
97 u
->default_dependencies
= true;
98 u
->unit_file_state
= _UNIT_FILE_STATE_INVALID
;
99 u
->unit_file_preset
= -1;
100 u
->on_failure_job_mode
= JOB_REPLACE
;
101 u
->cgroup_control_inotify_wd
= -1;
102 u
->cgroup_memory_inotify_wd
= -1;
103 u
->job_timeout
= USEC_INFINITY
;
104 u
->job_running_timeout
= USEC_INFINITY
;
105 u
->ref_uid
= UID_INVALID
;
106 u
->ref_gid
= GID_INVALID
;
107 u
->cpu_usage_last
= NSEC_INFINITY
;
108 u
->cgroup_invalidated_mask
|= CGROUP_MASK_BPF_FIREWALL
;
109 u
->failure_action_exit_status
= u
->success_action_exit_status
= -1;
111 u
->ip_accounting_ingress_map_fd
= -1;
112 u
->ip_accounting_egress_map_fd
= -1;
113 u
->ipv4_allow_map_fd
= -1;
114 u
->ipv6_allow_map_fd
= -1;
115 u
->ipv4_deny_map_fd
= -1;
116 u
->ipv6_deny_map_fd
= -1;
118 u
->last_section_private
= -1;
120 u
->start_ratelimit
= (RateLimit
) { m
->default_start_limit_interval
, m
->default_start_limit_burst
};
121 u
->auto_stop_ratelimit
= (RateLimit
) { 10 * USEC_PER_SEC
, 16 };
123 for (CGroupIOAccountingMetric i
= 0; i
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; i
++)
124 u
->io_accounting_last
[i
] = UINT64_MAX
;
129 int unit_new_for_name(Manager
*m
, size_t size
, const char *name
, Unit
**ret
) {
130 _cleanup_(unit_freep
) Unit
*u
= NULL
;
133 u
= unit_new(m
, size
);
137 r
= unit_add_name(u
, name
);
146 bool unit_has_name(const Unit
*u
, const char *name
) {
150 return streq_ptr(name
, u
->id
) ||
151 set_contains(u
->aliases
, name
);
154 static void unit_init(Unit
*u
) {
161 assert(u
->type
>= 0);
163 cc
= unit_get_cgroup_context(u
);
165 cgroup_context_init(cc
);
167 /* Copy in the manager defaults into the cgroup
168 * context, _before_ the rest of the settings have
169 * been initialized */
171 cc
->cpu_accounting
= u
->manager
->default_cpu_accounting
;
172 cc
->io_accounting
= u
->manager
->default_io_accounting
;
173 cc
->blockio_accounting
= u
->manager
->default_blockio_accounting
;
174 cc
->memory_accounting
= u
->manager
->default_memory_accounting
;
175 cc
->tasks_accounting
= u
->manager
->default_tasks_accounting
;
176 cc
->ip_accounting
= u
->manager
->default_ip_accounting
;
178 if (u
->type
!= UNIT_SLICE
)
179 cc
->tasks_max
= u
->manager
->default_tasks_max
;
182 ec
= unit_get_exec_context(u
);
184 exec_context_init(ec
);
186 if (MANAGER_IS_SYSTEM(u
->manager
))
187 ec
->keyring_mode
= EXEC_KEYRING_SHARED
;
189 ec
->keyring_mode
= EXEC_KEYRING_INHERIT
;
191 /* User manager might have its umask redefined by PAM or UMask=. In this
192 * case let the units it manages inherit this value by default. They can
193 * still tune this value through their own unit file */
194 (void) get_process_umask(getpid_cached(), &ec
->umask
);
198 kc
= unit_get_kill_context(u
);
200 kill_context_init(kc
);
202 if (UNIT_VTABLE(u
)->init
)
203 UNIT_VTABLE(u
)->init(u
);
206 static int unit_add_alias(Unit
*u
, char *donated_name
) {
209 /* Make sure that u->names is allocated. We may leave u->names
210 * empty if we fail later, but this is not a problem. */
211 r
= set_ensure_put(&u
->aliases
, &string_hash_ops
, donated_name
);
219 int unit_add_name(Unit
*u
, const char *text
) {
220 _cleanup_free_
char *name
= NULL
, *instance
= NULL
;
227 if (unit_name_is_valid(text
, UNIT_NAME_TEMPLATE
)) {
229 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
230 "instance is not set when adding name '%s': %m", text
);
232 r
= unit_name_replace_instance(text
, u
->instance
, &name
);
234 return log_unit_debug_errno(u
, r
,
235 "failed to build instance name from '%s': %m", text
);
242 if (unit_has_name(u
, name
))
245 if (hashmap_contains(u
->manager
->units
, name
))
246 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EEXIST
),
247 "unit already exist when adding name '%s': %m", name
);
249 if (!unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
250 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
251 "name '%s' is invalid: %m", name
);
253 t
= unit_name_to_type(name
);
255 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
256 "failed to derive unit type from name '%s': %m", name
);
258 if (u
->type
!= _UNIT_TYPE_INVALID
&& t
!= u
->type
)
259 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
260 "unit type is illegal: u->type(%d) and t(%d) for name '%s': %m",
263 r
= unit_name_to_instance(name
, &instance
);
265 return log_unit_debug_errno(u
, r
, "failed to extract instance from name '%s': %m", name
);
267 if (instance
&& !unit_type_may_template(t
))
268 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
), "templates are not allowed for name '%s': %m", name
);
270 /* Ensure that this unit either has no instance, or that the instance matches. */
271 if (u
->type
!= _UNIT_TYPE_INVALID
&& !streq_ptr(u
->instance
, instance
))
272 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
273 "cannot add name %s, the instances don't match (\"%s\" != \"%s\").",
274 name
, instance
, u
->instance
);
276 if (u
->id
&& !unit_type_may_alias(t
))
277 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EEXIST
),
278 "cannot add name %s, aliases are not allowed for %s units.",
279 name
, unit_type_to_string(t
));
281 if (hashmap_size(u
->manager
->units
) >= MANAGER_MAX_NAMES
)
282 return log_unit_warning_errno(u
, SYNTHETIC_ERRNO(E2BIG
), "cannot add name, manager has too many units: %m");
284 /* Add name to the global hashmap first, because that's easier to undo */
285 r
= hashmap_put(u
->manager
->units
, name
, u
);
287 return log_unit_debug_errno(u
, r
, "add unit to hashmap failed for name '%s': %m", text
);
290 r
= unit_add_alias(u
, name
); /* unit_add_alias() takes ownership of the name on success */
292 hashmap_remove(u
->manager
->units
, name
);
298 /* A new name, we don't need the set yet. */
299 assert(u
->type
== _UNIT_TYPE_INVALID
);
300 assert(!u
->instance
);
303 u
->id
= TAKE_PTR(name
);
304 u
->instance
= TAKE_PTR(instance
);
306 LIST_PREPEND(units_by_type
, u
->manager
->units_by_type
[t
], u
);
310 unit_add_to_dbus_queue(u
);
314 int unit_choose_id(Unit
*u
, const char *name
) {
315 _cleanup_free_
char *t
= NULL
;
322 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
326 r
= unit_name_replace_instance(name
, u
->instance
, &t
);
333 if (streq_ptr(u
->id
, name
))
334 return 0; /* Nothing to do. */
336 /* Selects one of the aliases of this unit as the id */
337 s
= set_get(u
->aliases
, (char*) name
);
342 r
= set_remove_and_put(u
->aliases
, name
, u
->id
);
346 assert_se(set_remove(u
->aliases
, name
)); /* see set_get() above… */
348 u
->id
= s
; /* Old u->id is now stored in the set, and s is not stored anywhere */
349 unit_add_to_dbus_queue(u
);
354 int unit_set_description(Unit
*u
, const char *description
) {
359 r
= free_and_strdup(&u
->description
, empty_to_null(description
));
363 unit_add_to_dbus_queue(u
);
368 bool unit_may_gc(Unit
*u
) {
369 UnitActiveState state
;
374 /* Checks whether the unit is ready to be unloaded for garbage collection.
375 * Returns true when the unit may be collected, and false if there's some
376 * reason to keep it loaded.
378 * References from other units are *not* checked here. Instead, this is done
379 * in unit_gc_sweep(), but using markers to properly collect dependency loops.
388 state
= unit_active_state(u
);
390 /* If the unit is inactive and failed and no job is queued for it, then release its runtime resources */
391 if (UNIT_IS_INACTIVE_OR_FAILED(state
) &&
392 UNIT_VTABLE(u
)->release_resources
)
393 UNIT_VTABLE(u
)->release_resources(u
);
398 if (sd_bus_track_count(u
->bus_track
) > 0)
401 /* But we keep the unit object around for longer when it is referenced or configured to not be gc'ed */
402 switch (u
->collect_mode
) {
404 case COLLECT_INACTIVE
:
405 if (state
!= UNIT_INACTIVE
)
410 case COLLECT_INACTIVE_OR_FAILED
:
411 if (!IN_SET(state
, UNIT_INACTIVE
, UNIT_FAILED
))
417 assert_not_reached("Unknown garbage collection mode");
420 if (u
->cgroup_path
) {
421 /* If the unit has a cgroup, then check whether there's anything in it. If so, we should stay
422 * around. Units with active processes should never be collected. */
424 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
426 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
431 if (UNIT_VTABLE(u
)->may_gc
&& !UNIT_VTABLE(u
)->may_gc(u
))
437 void unit_add_to_load_queue(Unit
*u
) {
439 assert(u
->type
!= _UNIT_TYPE_INVALID
);
441 if (u
->load_state
!= UNIT_STUB
|| u
->in_load_queue
)
444 LIST_PREPEND(load_queue
, u
->manager
->load_queue
, u
);
445 u
->in_load_queue
= true;
448 void unit_add_to_cleanup_queue(Unit
*u
) {
451 if (u
->in_cleanup_queue
)
454 LIST_PREPEND(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
455 u
->in_cleanup_queue
= true;
458 void unit_add_to_gc_queue(Unit
*u
) {
461 if (u
->in_gc_queue
|| u
->in_cleanup_queue
)
467 LIST_PREPEND(gc_queue
, u
->manager
->gc_unit_queue
, u
);
468 u
->in_gc_queue
= true;
471 void unit_add_to_dbus_queue(Unit
*u
) {
473 assert(u
->type
!= _UNIT_TYPE_INVALID
);
475 if (u
->load_state
== UNIT_STUB
|| u
->in_dbus_queue
)
478 /* Shortcut things if nobody cares */
479 if (sd_bus_track_count(u
->manager
->subscribed
) <= 0 &&
480 sd_bus_track_count(u
->bus_track
) <= 0 &&
481 set_isempty(u
->manager
->private_buses
)) {
482 u
->sent_dbus_new_signal
= true;
486 LIST_PREPEND(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
487 u
->in_dbus_queue
= true;
490 void unit_submit_to_stop_when_unneeded_queue(Unit
*u
) {
493 if (u
->in_stop_when_unneeded_queue
)
496 if (!u
->stop_when_unneeded
)
499 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
)))
502 LIST_PREPEND(stop_when_unneeded_queue
, u
->manager
->stop_when_unneeded_queue
, u
);
503 u
->in_stop_when_unneeded_queue
= true;
506 static void bidi_set_free(Unit
*u
, Hashmap
*h
) {
512 /* Frees the hashmap and makes sure we are dropped from the inverse pointers */
514 HASHMAP_FOREACH_KEY(v
, other
, h
) {
515 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
516 hashmap_remove(other
->dependencies
[d
], u
);
518 unit_add_to_gc_queue(other
);
524 static void unit_remove_transient(Unit
*u
) {
532 if (u
->fragment_path
)
533 (void) unlink(u
->fragment_path
);
535 STRV_FOREACH(i
, u
->dropin_paths
) {
536 _cleanup_free_
char *p
= NULL
, *pp
= NULL
;
538 p
= dirname_malloc(*i
); /* Get the drop-in directory from the drop-in file */
542 pp
= dirname_malloc(p
); /* Get the config directory from the drop-in directory */
546 /* Only drop transient drop-ins */
547 if (!path_equal(u
->manager
->lookup_paths
.transient
, pp
))
555 static void unit_free_requires_mounts_for(Unit
*u
) {
559 _cleanup_free_
char *path
;
561 path
= hashmap_steal_first_key(u
->requires_mounts_for
);
565 char s
[strlen(path
) + 1];
567 PATH_FOREACH_PREFIX_MORE(s
, path
) {
571 x
= hashmap_get2(u
->manager
->units_requiring_mounts_for
, s
, (void**) &y
);
575 (void) set_remove(x
, u
);
577 if (set_isempty(x
)) {
578 (void) hashmap_remove(u
->manager
->units_requiring_mounts_for
, y
);
586 u
->requires_mounts_for
= hashmap_free(u
->requires_mounts_for
);
589 static void unit_done(Unit
*u
) {
598 if (UNIT_VTABLE(u
)->done
)
599 UNIT_VTABLE(u
)->done(u
);
601 ec
= unit_get_exec_context(u
);
603 exec_context_done(ec
);
605 cc
= unit_get_cgroup_context(u
);
607 cgroup_context_done(cc
);
610 Unit
* unit_free(Unit
*u
) {
616 u
->transient_file
= safe_fclose(u
->transient_file
);
618 if (!MANAGER_IS_RELOADING(u
->manager
))
619 unit_remove_transient(u
);
621 bus_unit_send_removed_signal(u
);
625 unit_dequeue_rewatch_pids(u
);
627 sd_bus_slot_unref(u
->match_bus_slot
);
628 sd_bus_track_unref(u
->bus_track
);
629 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
630 u
->pending_freezer_message
= sd_bus_message_unref(u
->pending_freezer_message
);
632 unit_free_requires_mounts_for(u
);
634 SET_FOREACH(t
, u
->aliases
)
635 hashmap_remove_value(u
->manager
->units
, t
, u
);
637 hashmap_remove_value(u
->manager
->units
, u
->id
, u
);
639 if (!sd_id128_is_null(u
->invocation_id
))
640 hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
654 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
655 bidi_set_free(u
, u
->dependencies
[d
]);
657 /* A unit is being dropped from the tree, make sure our family is realized properly. Do this after we
658 * detach the unit from slice tree in order to eliminate its effect on controller masks. */
659 if (UNIT_ISSET(u
->slice
))
660 unit_add_family_to_cgroup_realize_queue(UNIT_DEREF(u
->slice
));
663 manager_unref_console(u
->manager
);
665 unit_release_cgroup(u
);
667 if (!MANAGER_IS_RELOADING(u
->manager
))
668 unit_unlink_state_files(u
);
670 unit_unref_uid_gid(u
, false);
672 (void) manager_update_failed_units(u
->manager
, u
, false);
673 set_remove(u
->manager
->startup_units
, u
);
675 unit_unwatch_all_pids(u
);
677 unit_ref_unset(&u
->slice
);
678 while (u
->refs_by_target
)
679 unit_ref_unset(u
->refs_by_target
);
681 if (u
->type
!= _UNIT_TYPE_INVALID
)
682 LIST_REMOVE(units_by_type
, u
->manager
->units_by_type
[u
->type
], u
);
684 if (u
->in_load_queue
)
685 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
687 if (u
->in_dbus_queue
)
688 LIST_REMOVE(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
691 LIST_REMOVE(gc_queue
, u
->manager
->gc_unit_queue
, u
);
693 if (u
->in_cgroup_realize_queue
)
694 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
696 if (u
->in_cgroup_empty_queue
)
697 LIST_REMOVE(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
699 if (u
->in_cleanup_queue
)
700 LIST_REMOVE(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
702 if (u
->in_target_deps_queue
)
703 LIST_REMOVE(target_deps_queue
, u
->manager
->target_deps_queue
, u
);
705 if (u
->in_stop_when_unneeded_queue
)
706 LIST_REMOVE(stop_when_unneeded_queue
, u
->manager
->stop_when_unneeded_queue
, u
);
708 safe_close(u
->ip_accounting_ingress_map_fd
);
709 safe_close(u
->ip_accounting_egress_map_fd
);
711 safe_close(u
->ipv4_allow_map_fd
);
712 safe_close(u
->ipv6_allow_map_fd
);
713 safe_close(u
->ipv4_deny_map_fd
);
714 safe_close(u
->ipv6_deny_map_fd
);
716 bpf_program_unref(u
->ip_bpf_ingress
);
717 bpf_program_unref(u
->ip_bpf_ingress_installed
);
718 bpf_program_unref(u
->ip_bpf_egress
);
719 bpf_program_unref(u
->ip_bpf_egress_installed
);
721 set_free(u
->ip_bpf_custom_ingress
);
722 set_free(u
->ip_bpf_custom_egress
);
723 set_free(u
->ip_bpf_custom_ingress_installed
);
724 set_free(u
->ip_bpf_custom_egress_installed
);
726 bpf_program_unref(u
->bpf_device_control_installed
);
728 condition_free_list(u
->conditions
);
729 condition_free_list(u
->asserts
);
731 free(u
->description
);
732 strv_free(u
->documentation
);
733 free(u
->fragment_path
);
734 free(u
->source_path
);
735 strv_free(u
->dropin_paths
);
738 free(u
->job_timeout_reboot_arg
);
741 set_free_free(u
->aliases
);
747 FreezerState
unit_freezer_state(Unit
*u
) {
750 return u
->freezer_state
;
753 int unit_freezer_state_kernel(Unit
*u
, FreezerState
*ret
) {
754 char *values
[1] = {};
759 r
= cg_get_keyed_attribute(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events",
760 STRV_MAKE("frozen"), values
);
764 r
= _FREEZER_STATE_INVALID
;
767 if (streq(values
[0], "0"))
769 else if (streq(values
[0], "1"))
779 UnitActiveState
unit_active_state(Unit
*u
) {
782 if (u
->load_state
== UNIT_MERGED
)
783 return unit_active_state(unit_follow_merge(u
));
785 /* After a reload it might happen that a unit is not correctly
786 * loaded but still has a process around. That's why we won't
787 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
789 return UNIT_VTABLE(u
)->active_state(u
);
792 const char* unit_sub_state_to_string(Unit
*u
) {
795 return UNIT_VTABLE(u
)->sub_state_to_string(u
);
798 static int hashmap_complete_move(Hashmap
**s
, Hashmap
**other
) {
806 return hashmap_move(*s
, *other
);
808 *s
= TAKE_PTR(*other
);
813 static int merge_names(Unit
*u
, Unit
*other
) {
820 r
= unit_add_alias(u
, other
->id
);
824 r
= set_move(u
->aliases
, other
->aliases
);
826 set_remove(u
->aliases
, other
->id
);
831 other
->aliases
= set_free_free(other
->aliases
);
833 SET_FOREACH(name
, u
->aliases
)
834 assert_se(hashmap_replace(u
->manager
->units
, name
, u
) == 0);
839 static int reserve_dependencies(Unit
*u
, Unit
*other
, UnitDependency d
) {
844 assert(d
< _UNIT_DEPENDENCY_MAX
);
847 * If u does not have this dependency set allocated, there is no need
848 * to reserve anything. In that case other's set will be transferred
849 * as a whole to u by complete_move().
851 if (!u
->dependencies
[d
])
854 /* merge_dependencies() will skip a u-on-u dependency */
855 n_reserve
= hashmap_size(other
->dependencies
[d
]) - !!hashmap_get(other
->dependencies
[d
], u
);
857 return hashmap_reserve(u
->dependencies
[d
], n_reserve
);
860 static void merge_dependencies(Unit
*u
, Unit
*other
, const char *other_id
, UnitDependency d
) {
865 /* Merges all dependencies of type 'd' of the unit 'other' into the deps of the unit 'u' */
869 assert(d
< _UNIT_DEPENDENCY_MAX
);
871 /* Fix backwards pointers. Let's iterate through all dependent units of the other unit. */
872 HASHMAP_FOREACH_KEY(v
, back
, other
->dependencies
[d
])
874 /* Let's now iterate through the dependencies of that dependencies of the other units,
875 * looking for pointers back, and let's fix them up, to instead point to 'u'. */
876 for (UnitDependency k
= 0; k
< _UNIT_DEPENDENCY_MAX
; k
++)
878 /* Do not add dependencies between u and itself. */
879 if (hashmap_remove(back
->dependencies
[k
], other
))
880 maybe_warn_about_dependency(u
, other_id
, k
);
882 UnitDependencyInfo di_u
, di_other
;
884 /* Let's drop this dependency between "back" and "other", and let's create it between
885 * "back" and "u" instead. Let's merge the bit masks of the dependency we are moving,
886 * and any such dependency which might already exist */
888 di_other
.data
= hashmap_get(back
->dependencies
[k
], other
);
890 continue; /* dependency isn't set, let's try the next one */
892 di_u
.data
= hashmap_get(back
->dependencies
[k
], u
);
894 UnitDependencyInfo di_merged
= {
895 .origin_mask
= di_u
.origin_mask
| di_other
.origin_mask
,
896 .destination_mask
= di_u
.destination_mask
| di_other
.destination_mask
,
899 r
= hashmap_remove_and_replace(back
->dependencies
[k
], other
, u
, di_merged
.data
);
901 log_warning_errno(r
, "Failed to remove/replace: back=%s other=%s u=%s: %m", back
->id
, other_id
, u
->id
);
904 /* assert_se(hashmap_remove_and_replace(back->dependencies[k], other, u, di_merged.data) >= 0); */
907 /* Also do not move dependencies on u to itself */
908 back
= hashmap_remove(other
->dependencies
[d
], u
);
910 maybe_warn_about_dependency(u
, other_id
, d
);
912 /* The move cannot fail. The caller must have performed a reservation. */
913 assert_se(hashmap_complete_move(&u
->dependencies
[d
], &other
->dependencies
[d
]) == 0);
915 other
->dependencies
[d
] = hashmap_free(other
->dependencies
[d
]);
918 int unit_merge(Unit
*u
, Unit
*other
) {
919 const char *other_id
= NULL
;
924 assert(u
->manager
== other
->manager
);
925 assert(u
->type
!= _UNIT_TYPE_INVALID
);
927 other
= unit_follow_merge(other
);
932 if (u
->type
!= other
->type
)
935 if (!unit_type_may_alias(u
->type
)) /* Merging only applies to unit names that support aliases */
938 if (!IN_SET(other
->load_state
, UNIT_STUB
, UNIT_NOT_FOUND
))
941 if (!streq_ptr(u
->instance
, other
->instance
))
950 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
954 other_id
= strdupa(other
->id
);
956 /* Make reservations to ensure merge_dependencies() won't fail */
957 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
958 r
= reserve_dependencies(u
, other
, d
);
960 * We don't rollback reservations if we fail. We don't have
961 * a way to undo reservations. A reservation is not a leak.
968 r
= merge_names(u
, other
);
972 /* Redirect all references */
973 while (other
->refs_by_target
)
974 unit_ref_set(other
->refs_by_target
, other
->refs_by_target
->source
, u
);
976 /* Merge dependencies */
977 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
978 merge_dependencies(u
, other
, other_id
, d
);
980 other
->load_state
= UNIT_MERGED
;
981 other
->merged_into
= u
;
983 /* If there is still some data attached to the other node, we
984 * don't need it anymore, and can free it. */
985 if (other
->load_state
!= UNIT_STUB
)
986 if (UNIT_VTABLE(other
)->done
)
987 UNIT_VTABLE(other
)->done(other
);
989 unit_add_to_dbus_queue(u
);
990 unit_add_to_cleanup_queue(other
);
995 int unit_merge_by_name(Unit
*u
, const char *name
) {
996 _cleanup_free_
char *s
= NULL
;
1000 /* Either add name to u, or if a unit with name already exists, merge it with u.
1001 * If name is a template, do the same for name@instance, where instance is u's instance. */
1006 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
1010 r
= unit_name_replace_instance(name
, u
->instance
, &s
);
1017 other
= manager_get_unit(u
->manager
, name
);
1019 return unit_merge(u
, other
);
1021 return unit_add_name(u
, name
);
1024 Unit
* unit_follow_merge(Unit
*u
) {
1027 while (u
->load_state
== UNIT_MERGED
)
1028 assert_se(u
= u
->merged_into
);
1033 int unit_add_exec_dependencies(Unit
*u
, ExecContext
*c
) {
1039 if (c
->working_directory
&& !c
->working_directory_missing_ok
) {
1040 r
= unit_require_mounts_for(u
, c
->working_directory
, UNIT_DEPENDENCY_FILE
);
1045 if (c
->root_directory
) {
1046 r
= unit_require_mounts_for(u
, c
->root_directory
, UNIT_DEPENDENCY_FILE
);
1051 if (c
->root_image
) {
1052 r
= unit_require_mounts_for(u
, c
->root_image
, UNIT_DEPENDENCY_FILE
);
1057 for (ExecDirectoryType dt
= 0; dt
< _EXEC_DIRECTORY_TYPE_MAX
; dt
++) {
1058 if (!u
->manager
->prefix
[dt
])
1062 STRV_FOREACH(dp
, c
->directories
[dt
].paths
) {
1063 _cleanup_free_
char *p
;
1065 p
= path_join(u
->manager
->prefix
[dt
], *dp
);
1069 r
= unit_require_mounts_for(u
, p
, UNIT_DEPENDENCY_FILE
);
1075 if (!MANAGER_IS_SYSTEM(u
->manager
))
1078 /* For the following three directory types we need write access, and /var/ is possibly on the root
1079 * fs. Hence order after systemd-remount-fs.service, to ensure things are writable. */
1080 if (!strv_isempty(c
->directories
[EXEC_DIRECTORY_STATE
].paths
) ||
1081 !strv_isempty(c
->directories
[EXEC_DIRECTORY_CACHE
].paths
) ||
1082 !strv_isempty(c
->directories
[EXEC_DIRECTORY_LOGS
].paths
)) {
1083 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1088 if (c
->private_tmp
) {
1091 FOREACH_STRING(p
, "/tmp", "/var/tmp") {
1092 r
= unit_require_mounts_for(u
, p
, UNIT_DEPENDENCY_FILE
);
1097 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_TMPFILES_SETUP_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1102 if (c
->root_image
) {
1103 /* We need to wait for /dev/loopX to appear when doing RootImage=, hence let's add an
1104 * implicit dependency on udev */
1106 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_UDEVD_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1111 if (!IN_SET(c
->std_output
,
1112 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
1113 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
) &&
1114 !IN_SET(c
->std_error
,
1115 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
1116 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
) &&
1120 /* If syslog or kernel logging is requested (or log namespacing is), make sure our own logging daemon
1123 if (c
->log_namespace
) {
1124 _cleanup_free_
char *socket_unit
= NULL
, *varlink_socket_unit
= NULL
;
1126 r
= unit_name_build_from_type("systemd-journald", c
->log_namespace
, UNIT_SOCKET
, &socket_unit
);
1130 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, socket_unit
, true, UNIT_DEPENDENCY_FILE
);
1134 r
= unit_name_build_from_type("systemd-journald-varlink", c
->log_namespace
, UNIT_SOCKET
, &varlink_socket_unit
);
1138 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, varlink_socket_unit
, true, UNIT_DEPENDENCY_FILE
);
1142 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_JOURNALD_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
1149 const char *unit_description(Unit
*u
) {
1153 return u
->description
;
1155 return strna(u
->id
);
1158 const char *unit_status_string(Unit
*u
) {
1161 if (u
->manager
->status_unit_format
== STATUS_UNIT_FORMAT_NAME
&& u
->id
)
1164 return unit_description(u
);
1167 /* Common implementation for multiple backends */
1168 int unit_load_fragment_and_dropin(Unit
*u
, bool fragment_required
) {
1173 /* Load a .{service,socket,...} file */
1174 r
= unit_load_fragment(u
);
1178 if (u
->load_state
== UNIT_STUB
) {
1179 if (fragment_required
)
1182 u
->load_state
= UNIT_LOADED
;
1185 /* Load drop-in directory data. If u is an alias, we might be reloading the
1186 * target unit needlessly. But we cannot be sure which drops-ins have already
1187 * been loaded and which not, at least without doing complicated book-keeping,
1188 * so let's always reread all drop-ins. */
1189 r
= unit_load_dropin(unit_follow_merge(u
));
1193 if (u
->source_path
) {
1196 if (stat(u
->source_path
, &st
) >= 0)
1197 u
->source_mtime
= timespec_load(&st
.st_mtim
);
1199 u
->source_mtime
= 0;
1205 void unit_add_to_target_deps_queue(Unit
*u
) {
1206 Manager
*m
= u
->manager
;
1210 if (u
->in_target_deps_queue
)
1213 LIST_PREPEND(target_deps_queue
, m
->target_deps_queue
, u
);
1214 u
->in_target_deps_queue
= true;
1217 int unit_add_default_target_dependency(Unit
*u
, Unit
*target
) {
1221 if (target
->type
!= UNIT_TARGET
)
1224 /* Only add the dependency if both units are loaded, so that
1225 * that loop check below is reliable */
1226 if (u
->load_state
!= UNIT_LOADED
||
1227 target
->load_state
!= UNIT_LOADED
)
1230 /* If either side wants no automatic dependencies, then let's
1232 if (!u
->default_dependencies
||
1233 !target
->default_dependencies
)
1236 /* Don't create loops */
1237 if (hashmap_get(target
->dependencies
[UNIT_BEFORE
], u
))
1240 return unit_add_dependency(target
, UNIT_AFTER
, u
, true, UNIT_DEPENDENCY_DEFAULT
);
1243 static int unit_add_slice_dependencies(Unit
*u
) {
1246 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1249 /* Slice units are implicitly ordered against their parent slices (as this relationship is encoded in the
1250 name), while all other units are ordered based on configuration (as in their case Slice= configures the
1252 UnitDependencyMask mask
= u
->type
== UNIT_SLICE
? UNIT_DEPENDENCY_IMPLICIT
: UNIT_DEPENDENCY_FILE
;
1254 if (UNIT_ISSET(u
->slice
))
1255 return unit_add_two_dependencies(u
, UNIT_AFTER
, UNIT_REQUIRES
, UNIT_DEREF(u
->slice
), true, mask
);
1257 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1260 return unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_ROOT_SLICE
, true, mask
);
1263 static int unit_add_mount_dependencies(Unit
*u
) {
1264 UnitDependencyInfo di
;
1270 HASHMAP_FOREACH_KEY(di
.data
, path
, u
->requires_mounts_for
) {
1271 char prefix
[strlen(path
) + 1];
1273 PATH_FOREACH_PREFIX_MORE(prefix
, path
) {
1274 _cleanup_free_
char *p
= NULL
;
1277 r
= unit_name_from_path(prefix
, ".mount", &p
);
1281 m
= manager_get_unit(u
->manager
, p
);
1283 /* Make sure to load the mount unit if
1284 * it exists. If so the dependencies
1285 * on this unit will be added later
1286 * during the loading of the mount
1288 (void) manager_load_unit_prepare(u
->manager
, p
, NULL
, NULL
, &m
);
1294 if (m
->load_state
!= UNIT_LOADED
)
1297 r
= unit_add_dependency(u
, UNIT_AFTER
, m
, true, di
.origin_mask
);
1301 if (m
->fragment_path
) {
1302 r
= unit_add_dependency(u
, UNIT_REQUIRES
, m
, true, di
.origin_mask
);
1312 static int unit_add_oomd_dependencies(Unit
*u
) {
1319 if (!u
->default_dependencies
)
1322 c
= unit_get_cgroup_context(u
);
1326 wants_oomd
= (c
->moom_swap
== MANAGED_OOM_KILL
|| c
->moom_mem_pressure
== MANAGED_OOM_KILL
);
1330 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_WANTS
, "systemd-oomd.service", true, UNIT_DEPENDENCY_FILE
);
1337 static int unit_add_startup_units(Unit
*u
) {
1340 c
= unit_get_cgroup_context(u
);
1344 if (c
->startup_cpu_shares
== CGROUP_CPU_SHARES_INVALID
&&
1345 c
->startup_io_weight
== CGROUP_WEIGHT_INVALID
&&
1346 c
->startup_blockio_weight
== CGROUP_BLKIO_WEIGHT_INVALID
)
1349 return set_ensure_put(&u
->manager
->startup_units
, NULL
, u
);
1352 int unit_load(Unit
*u
) {
1357 if (u
->in_load_queue
) {
1358 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
1359 u
->in_load_queue
= false;
1362 if (u
->type
== _UNIT_TYPE_INVALID
)
1365 if (u
->load_state
!= UNIT_STUB
)
1368 if (u
->transient_file
) {
1369 /* Finalize transient file: if this is a transient unit file, as soon as we reach unit_load() the setup
1370 * is complete, hence let's synchronize the unit file we just wrote to disk. */
1372 r
= fflush_and_check(u
->transient_file
);
1376 u
->transient_file
= safe_fclose(u
->transient_file
);
1377 u
->fragment_mtime
= now(CLOCK_REALTIME
);
1380 r
= UNIT_VTABLE(u
)->load(u
);
1384 assert(u
->load_state
!= UNIT_STUB
);
1386 if (u
->load_state
== UNIT_LOADED
) {
1387 unit_add_to_target_deps_queue(u
);
1389 r
= unit_add_slice_dependencies(u
);
1393 r
= unit_add_mount_dependencies(u
);
1397 r
= unit_add_oomd_dependencies(u
);
1401 r
= unit_add_startup_units(u
);
1405 if (u
->on_failure_job_mode
== JOB_ISOLATE
&& hashmap_size(u
->dependencies
[UNIT_ON_FAILURE
]) > 1) {
1406 r
= log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOEXEC
),
1407 "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
1411 if (u
->job_running_timeout
!= USEC_INFINITY
&& u
->job_running_timeout
> u
->job_timeout
)
1412 log_unit_warning(u
, "JobRunningTimeoutSec= is greater than JobTimeoutSec=, it has no effect.");
1414 /* We finished loading, let's ensure our parents recalculate the members mask */
1415 unit_invalidate_cgroup_members_masks(u
);
1418 assert((u
->load_state
!= UNIT_MERGED
) == !u
->merged_into
);
1420 unit_add_to_dbus_queue(unit_follow_merge(u
));
1421 unit_add_to_gc_queue(u
);
1422 (void) manager_varlink_send_managed_oom_update(u
);
1427 /* We convert ENOEXEC errors to the UNIT_BAD_SETTING load state here. Configuration parsing code
1428 * should hence return ENOEXEC to ensure units are placed in this state after loading. */
1430 u
->load_state
= u
->load_state
== UNIT_STUB
? UNIT_NOT_FOUND
:
1431 r
== -ENOEXEC
? UNIT_BAD_SETTING
:
1435 /* Record the timestamp on the cache, so that if the cache gets updated between now and the next time
1436 * an attempt is made to load this unit, we know we need to check again. */
1437 if (u
->load_state
== UNIT_NOT_FOUND
)
1438 u
->fragment_not_found_timestamp_hash
= u
->manager
->unit_cache_timestamp_hash
;
1440 unit_add_to_dbus_queue(u
);
1441 unit_add_to_gc_queue(u
);
1443 return log_unit_debug_errno(u
, r
, "Failed to load configuration: %m");
1447 static int log_unit_internal(void *userdata
, int level
, int error
, const char *file
, int line
, const char *func
, const char *format
, ...) {
1452 va_start(ap
, format
);
1454 r
= log_object_internalv(level
, error
, file
, line
, func
,
1455 u
->manager
->unit_log_field
,
1457 u
->manager
->invocation_log_field
,
1458 u
->invocation_id_string
,
1461 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
1467 static bool unit_test_condition(Unit
*u
) {
1468 _cleanup_strv_free_
char **env
= NULL
;
1473 dual_timestamp_get(&u
->condition_timestamp
);
1475 r
= manager_get_effective_environment(u
->manager
, &env
);
1477 log_unit_error_errno(u
, r
, "Failed to determine effective environment: %m");
1478 u
->condition_result
= CONDITION_ERROR
;
1480 u
->condition_result
= condition_test_list(
1483 condition_type_to_string
,
1487 unit_add_to_dbus_queue(u
);
1488 return u
->condition_result
;
1491 static bool unit_test_assert(Unit
*u
) {
1492 _cleanup_strv_free_
char **env
= NULL
;
1497 dual_timestamp_get(&u
->assert_timestamp
);
1499 r
= manager_get_effective_environment(u
->manager
, &env
);
1501 log_unit_error_errno(u
, r
, "Failed to determine effective environment: %m");
1502 u
->assert_result
= CONDITION_ERROR
;
1504 u
->assert_result
= condition_test_list(
1507 assert_type_to_string
,
1511 unit_add_to_dbus_queue(u
);
1512 return u
->assert_result
;
1515 void unit_status_printf(Unit
*u
, StatusType status_type
, const char *status
, const char *unit_status_msg_format
) {
1518 d
= unit_status_string(u
);
1519 if (log_get_show_color())
1520 d
= strjoina(ANSI_HIGHLIGHT
, d
, ANSI_NORMAL
);
1522 DISABLE_WARNING_FORMAT_NONLITERAL
;
1523 manager_status_printf(u
->manager
, status_type
, status
, unit_status_msg_format
, d
);
1527 int unit_test_start_limit(Unit
*u
) {
1532 if (ratelimit_below(&u
->start_ratelimit
)) {
1533 u
->start_limit_hit
= false;
1537 log_unit_warning(u
, "Start request repeated too quickly.");
1538 u
->start_limit_hit
= true;
1540 reason
= strjoina("unit ", u
->id
, " failed");
1542 emergency_action(u
->manager
, u
->start_limit_action
,
1543 EMERGENCY_ACTION_IS_WATCHDOG
|EMERGENCY_ACTION_WARN
,
1544 u
->reboot_arg
, -1, reason
);
1549 bool unit_shall_confirm_spawn(Unit
*u
) {
1552 if (manager_is_confirm_spawn_disabled(u
->manager
))
1555 /* For some reasons units remaining in the same process group
1556 * as PID 1 fail to acquire the console even if it's not used
1557 * by any process. So skip the confirmation question for them. */
1558 return !unit_get_exec_context(u
)->same_pgrp
;
1561 static bool unit_verify_deps(Unit
*u
) {
1567 /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined with
1568 * After=. We do not check Requires= or Requisite= here as they only should have an effect on the job
1569 * processing, but do not have any effect afterwards. We don't check BindsTo= dependencies that are not used in
1570 * conjunction with After= as for them any such check would make things entirely racy. */
1572 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
]) {
1574 if (!hashmap_contains(u
->dependencies
[UNIT_AFTER
], other
))
1577 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other
))) {
1578 log_unit_notice(u
, "Bound to unit %s, but unit isn't active.", other
->id
);
1586 /* Errors that aren't really errors:
1587 * -EALREADY: Unit is already started.
1588 * -ECOMM: Condition failed
1589 * -EAGAIN: An operation is already in progress. Retry later.
1591 * Errors that are real errors:
1592 * -EBADR: This unit type does not support starting.
1593 * -ECANCELED: Start limit hit, too many requests for now
1594 * -EPROTO: Assert failed
1595 * -EINVAL: Unit not loaded
1596 * -EOPNOTSUPP: Unit type not supported
1597 * -ENOLINK: The necessary dependencies are not fulfilled.
1598 * -ESTALE: This unit has been started before and can't be started a second time
1599 * -ENOENT: This is a triggering unit and unit to trigger is not loaded
1601 int unit_start(Unit
*u
) {
1602 UnitActiveState state
;
1607 /* If this is already started, then this will succeed. Note that this will even succeed if this unit
1608 * is not startable by the user. This is relied on to detect when we need to wait for units and when
1609 * waiting is finished. */
1610 state
= unit_active_state(u
);
1611 if (UNIT_IS_ACTIVE_OR_RELOADING(state
))
1613 if (state
== UNIT_MAINTENANCE
)
1616 /* Units that aren't loaded cannot be started */
1617 if (u
->load_state
!= UNIT_LOADED
)
1620 /* Refuse starting scope units more than once */
1621 if (UNIT_VTABLE(u
)->once_only
&& dual_timestamp_is_set(&u
->inactive_enter_timestamp
))
1624 /* If the conditions failed, don't do anything at all. If we already are activating this call might
1625 * still be useful to speed up activation in case there is some hold-off time, but we don't want to
1626 * recheck the condition in that case. */
1627 if (state
!= UNIT_ACTIVATING
&&
1628 !unit_test_condition(u
))
1629 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(ECOMM
), "Starting requested but condition failed. Not starting unit.");
1631 /* If the asserts failed, fail the entire job */
1632 if (state
!= UNIT_ACTIVATING
&&
1633 !unit_test_assert(u
))
1634 return log_unit_notice_errno(u
, SYNTHETIC_ERRNO(EPROTO
), "Starting requested but asserts failed.");
1636 /* Units of types that aren't supported cannot be started. Note that we do this test only after the
1637 * condition checks, so that we rather return condition check errors (which are usually not
1638 * considered a true failure) than "not supported" errors (which are considered a failure).
1640 if (!unit_type_supported(u
->type
))
1643 /* Let's make sure that the deps really are in order before we start this. Normally the job engine
1644 * should have taken care of this already, but let's check this here again. After all, our
1645 * dependencies might not be in effect anymore, due to a reload or due to a failed condition. */
1646 if (!unit_verify_deps(u
))
1649 /* Forward to the main object, if we aren't it. */
1650 following
= unit_following(u
);
1652 log_unit_debug(u
, "Redirecting start request from %s to %s.", u
->id
, following
->id
);
1653 return unit_start(following
);
1656 /* If it is stopped, but we cannot start it, then fail */
1657 if (!UNIT_VTABLE(u
)->start
)
1660 /* We don't suppress calls to ->start() here when we are already starting, to allow this request to
1661 * be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
1662 * waits for a holdoff timer to elapse before it will start again. */
1664 unit_add_to_dbus_queue(u
);
1665 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1667 return UNIT_VTABLE(u
)->start(u
);
1670 bool unit_can_start(Unit
*u
) {
1673 if (u
->load_state
!= UNIT_LOADED
)
1676 if (!unit_type_supported(u
->type
))
1679 /* Scope units may be started only once */
1680 if (UNIT_VTABLE(u
)->once_only
&& dual_timestamp_is_set(&u
->inactive_exit_timestamp
))
1683 return !!UNIT_VTABLE(u
)->start
;
1686 bool unit_can_isolate(Unit
*u
) {
1689 return unit_can_start(u
) &&
1694 * -EBADR: This unit type does not support stopping.
1695 * -EALREADY: Unit is already stopped.
1696 * -EAGAIN: An operation is already in progress. Retry later.
1698 int unit_stop(Unit
*u
) {
1699 UnitActiveState state
;
1704 state
= unit_active_state(u
);
1705 if (UNIT_IS_INACTIVE_OR_FAILED(state
))
1708 following
= unit_following(u
);
1710 log_unit_debug(u
, "Redirecting stop request from %s to %s.", u
->id
, following
->id
);
1711 return unit_stop(following
);
1714 if (!UNIT_VTABLE(u
)->stop
)
1717 unit_add_to_dbus_queue(u
);
1718 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1720 return UNIT_VTABLE(u
)->stop(u
);
1723 bool unit_can_stop(Unit
*u
) {
1726 /* Note: if we return true here, it does not mean that the unit may be successfully stopped.
1727 * Extrinsic units follow external state and they may stop following external state changes
1728 * (hence we return true here), but an attempt to do this through the manager will fail. */
1730 if (!unit_type_supported(u
->type
))
1736 return !!UNIT_VTABLE(u
)->stop
;
1740 * -EBADR: This unit type does not support reloading.
1741 * -ENOEXEC: Unit is not started.
1742 * -EAGAIN: An operation is already in progress. Retry later.
1744 int unit_reload(Unit
*u
) {
1745 UnitActiveState state
;
1750 if (u
->load_state
!= UNIT_LOADED
)
1753 if (!unit_can_reload(u
))
1756 state
= unit_active_state(u
);
1757 if (state
== UNIT_RELOADING
)
1760 if (state
!= UNIT_ACTIVE
)
1761 return log_unit_warning_errno(u
, SYNTHETIC_ERRNO(ENOEXEC
), "Unit cannot be reloaded because it is inactive.");
1763 following
= unit_following(u
);
1765 log_unit_debug(u
, "Redirecting reload request from %s to %s.", u
->id
, following
->id
);
1766 return unit_reload(following
);
1769 unit_add_to_dbus_queue(u
);
1771 if (!UNIT_VTABLE(u
)->reload
) {
1772 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
1773 unit_notify(u
, unit_active_state(u
), unit_active_state(u
), 0);
1777 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1779 return UNIT_VTABLE(u
)->reload(u
);
1782 bool unit_can_reload(Unit
*u
) {
1785 if (UNIT_VTABLE(u
)->can_reload
)
1786 return UNIT_VTABLE(u
)->can_reload(u
);
1788 if (!hashmap_isempty(u
->dependencies
[UNIT_PROPAGATES_RELOAD_TO
]))
1791 return UNIT_VTABLE(u
)->reload
;
1794 bool unit_is_unneeded(Unit
*u
) {
1795 static const UnitDependency deps
[] = {
1804 if (!u
->stop_when_unneeded
)
1807 /* Don't clean up while the unit is transitioning or is even inactive. */
1808 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
)))
1813 for (size_t j
= 0; j
< ELEMENTSOF(deps
); j
++) {
1817 /* If a dependent unit has a job queued, is active or transitioning, or is marked for
1818 * restart, then don't clean this one up. */
1820 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[deps
[j
]]) {
1824 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
1827 if (unit_will_restart(other
))
1835 static void check_unneeded_dependencies(Unit
*u
) {
1837 static const UnitDependency deps
[] = {
1846 /* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
1848 for (size_t j
= 0; j
< ELEMENTSOF(deps
); j
++) {
1852 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[deps
[j
]])
1853 unit_submit_to_stop_when_unneeded_queue(other
);
1857 static void unit_check_binds_to(Unit
*u
) {
1858 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1869 if (unit_active_state(u
) != UNIT_ACTIVE
)
1872 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
]) {
1876 if (!other
->coldplugged
)
1877 /* We might yet create a job for the other unit… */
1880 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
1890 /* If stopping a unit fails continuously we might enter a stop
1891 * loop here, hence stop acting on the service being
1892 * unnecessary after a while. */
1893 if (!ratelimit_below(&u
->auto_stop_ratelimit
)) {
1894 log_unit_warning(u
, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other
->id
);
1899 log_unit_info(u
, "Unit is bound to inactive unit %s. Stopping, too.", other
->id
);
1901 /* A unit we need to run is gone. Sniff. Let's stop this. */
1902 r
= manager_add_job(u
->manager
, JOB_STOP
, u
, JOB_FAIL
, NULL
, &error
, NULL
);
1904 log_unit_warning_errno(u
, r
, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error
, r
));
1907 static void retroactively_start_dependencies(Unit
*u
) {
1912 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)));
1914 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_REQUIRES
])
1915 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
1916 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
1917 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
1919 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
])
1920 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
1921 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
1922 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
1924 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_WANTS
])
1925 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
1926 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
1927 manager_add_job(u
->manager
, JOB_START
, other
, JOB_FAIL
, NULL
, NULL
, NULL
);
1929 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_CONFLICTS
])
1930 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1931 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
1933 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_CONFLICTED_BY
])
1934 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1935 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
1938 static void retroactively_stop_dependencies(Unit
*u
) {
1943 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)));
1945 /* Pull down units which are bound to us recursively if enabled */
1946 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BOUND_BY
])
1947 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1948 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
1951 void unit_start_on_failure(Unit
*u
) {
1958 if (hashmap_size(u
->dependencies
[UNIT_ON_FAILURE
]) <= 0)
1961 log_unit_info(u
, "Triggering OnFailure= dependencies.");
1963 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_ON_FAILURE
]) {
1964 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1966 r
= manager_add_job(u
->manager
, JOB_START
, other
, u
->on_failure_job_mode
, NULL
, &error
, NULL
);
1968 log_unit_warning_errno(u
, r
, "Failed to enqueue OnFailure= job, ignoring: %s", bus_error_message(&error
, r
));
1972 void unit_trigger_notify(Unit
*u
) {
1978 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_TRIGGERED_BY
])
1979 if (UNIT_VTABLE(other
)->trigger_notify
)
1980 UNIT_VTABLE(other
)->trigger_notify(other
, u
);
1983 static int raise_level(int log_level
, bool condition_info
, bool condition_notice
) {
1984 if (condition_notice
&& log_level
> LOG_NOTICE
)
1986 if (condition_info
&& log_level
> LOG_INFO
)
1991 static int unit_log_resources(Unit
*u
) {
1992 struct iovec iovec
[1 + _CGROUP_IP_ACCOUNTING_METRIC_MAX
+ _CGROUP_IO_ACCOUNTING_METRIC_MAX
+ 4];
1993 bool any_traffic
= false, have_ip_accounting
= false, any_io
= false, have_io_accounting
= false;
1994 _cleanup_free_
char *igress
= NULL
, *egress
= NULL
, *rr
= NULL
, *wr
= NULL
;
1995 int log_level
= LOG_DEBUG
; /* May be raised if resources consumed over a threshold */
1996 size_t n_message_parts
= 0, n_iovec
= 0;
1997 char* message_parts
[1 + 2 + 2 + 1], *t
;
1998 nsec_t nsec
= NSEC_INFINITY
;
2000 const char* const ip_fields
[_CGROUP_IP_ACCOUNTING_METRIC_MAX
] = {
2001 [CGROUP_IP_INGRESS_BYTES
] = "IP_METRIC_INGRESS_BYTES",
2002 [CGROUP_IP_INGRESS_PACKETS
] = "IP_METRIC_INGRESS_PACKETS",
2003 [CGROUP_IP_EGRESS_BYTES
] = "IP_METRIC_EGRESS_BYTES",
2004 [CGROUP_IP_EGRESS_PACKETS
] = "IP_METRIC_EGRESS_PACKETS",
2006 const char* const io_fields
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
2007 [CGROUP_IO_READ_BYTES
] = "IO_METRIC_READ_BYTES",
2008 [CGROUP_IO_WRITE_BYTES
] = "IO_METRIC_WRITE_BYTES",
2009 [CGROUP_IO_READ_OPERATIONS
] = "IO_METRIC_READ_OPERATIONS",
2010 [CGROUP_IO_WRITE_OPERATIONS
] = "IO_METRIC_WRITE_OPERATIONS",
2015 /* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
2016 * accounting was enabled for a unit. It does this in two ways: a friendly human readable string with reduced
2017 * information and the complete data in structured fields. */
2019 (void) unit_get_cpu_usage(u
, &nsec
);
2020 if (nsec
!= NSEC_INFINITY
) {
2021 char buf
[FORMAT_TIMESPAN_MAX
] = "";
2023 /* Format the CPU time for inclusion in the structured log message */
2024 if (asprintf(&t
, "CPU_USAGE_NSEC=%" PRIu64
, nsec
) < 0) {
2028 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2030 /* Format the CPU time for inclusion in the human language message string */
2031 format_timespan(buf
, sizeof(buf
), nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
);
2032 t
= strjoin("consumed ", buf
, " CPU time");
2038 message_parts
[n_message_parts
++] = t
;
2040 log_level
= raise_level(log_level
,
2041 nsec
> NOTICEWORTHY_CPU_NSEC
,
2042 nsec
> MENTIONWORTHY_CPU_NSEC
);
2045 for (CGroupIOAccountingMetric k
= 0; k
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; k
++) {
2046 char buf
[FORMAT_BYTES_MAX
] = "";
2047 uint64_t value
= UINT64_MAX
;
2049 assert(io_fields
[k
]);
2051 (void) unit_get_io_accounting(u
, k
, k
> 0, &value
);
2052 if (value
== UINT64_MAX
)
2055 have_io_accounting
= true;
2059 /* Format IO accounting data for inclusion in the structured log message */
2060 if (asprintf(&t
, "%s=%" PRIu64
, io_fields
[k
], value
) < 0) {
2064 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2066 /* Format the IO accounting data for inclusion in the human language message string, but only
2067 * for the bytes counters (and not for the operations counters) */
2068 if (k
== CGROUP_IO_READ_BYTES
) {
2070 rr
= strjoin("read ", format_bytes(buf
, sizeof(buf
), value
), " from disk");
2075 } else if (k
== CGROUP_IO_WRITE_BYTES
) {
2077 wr
= strjoin("written ", format_bytes(buf
, sizeof(buf
), value
), " to disk");
2084 if (IN_SET(k
, CGROUP_IO_READ_BYTES
, CGROUP_IO_WRITE_BYTES
))
2085 log_level
= raise_level(log_level
,
2086 value
> MENTIONWORTHY_IO_BYTES
,
2087 value
> NOTICEWORTHY_IO_BYTES
);
2090 if (have_io_accounting
) {
2093 message_parts
[n_message_parts
++] = TAKE_PTR(rr
);
2095 message_parts
[n_message_parts
++] = TAKE_PTR(wr
);
2100 k
= strdup("no IO");
2106 message_parts
[n_message_parts
++] = k
;
2110 for (CGroupIPAccountingMetric m
= 0; m
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
; m
++) {
2111 char buf
[FORMAT_BYTES_MAX
] = "";
2112 uint64_t value
= UINT64_MAX
;
2114 assert(ip_fields
[m
]);
2116 (void) unit_get_ip_accounting(u
, m
, &value
);
2117 if (value
== UINT64_MAX
)
2120 have_ip_accounting
= true;
2124 /* Format IP accounting data for inclusion in the structured log message */
2125 if (asprintf(&t
, "%s=%" PRIu64
, ip_fields
[m
], value
) < 0) {
2129 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2131 /* Format the IP accounting data for inclusion in the human language message string, but only for the
2132 * bytes counters (and not for the packets counters) */
2133 if (m
== CGROUP_IP_INGRESS_BYTES
) {
2135 igress
= strjoin("received ", format_bytes(buf
, sizeof(buf
), value
), " IP traffic");
2140 } else if (m
== CGROUP_IP_EGRESS_BYTES
) {
2142 egress
= strjoin("sent ", format_bytes(buf
, sizeof(buf
), value
), " IP traffic");
2149 if (IN_SET(m
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2150 log_level
= raise_level(log_level
,
2151 value
> MENTIONWORTHY_IP_BYTES
,
2152 value
> NOTICEWORTHY_IP_BYTES
);
2155 if (have_ip_accounting
) {
2158 message_parts
[n_message_parts
++] = TAKE_PTR(igress
);
2160 message_parts
[n_message_parts
++] = TAKE_PTR(egress
);
2165 k
= strdup("no IP traffic");
2171 message_parts
[n_message_parts
++] = k
;
2175 /* Is there any accounting data available at all? */
2181 if (n_message_parts
== 0)
2182 t
= strjoina("MESSAGE=", u
->id
, ": Completed.");
2184 _cleanup_free_
char *joined
;
2186 message_parts
[n_message_parts
] = NULL
;
2188 joined
= strv_join(message_parts
, ", ");
2194 joined
[0] = ascii_toupper(joined
[0]);
2195 t
= strjoina("MESSAGE=", u
->id
, ": ", joined
, ".");
2198 /* The following four fields we allocate on the stack or are static strings, we hence don't want to free them,
2199 * and hence don't increase n_iovec for them */
2200 iovec
[n_iovec
] = IOVEC_MAKE_STRING(t
);
2201 iovec
[n_iovec
+ 1] = IOVEC_MAKE_STRING("MESSAGE_ID=" SD_MESSAGE_UNIT_RESOURCES_STR
);
2203 t
= strjoina(u
->manager
->unit_log_field
, u
->id
);
2204 iovec
[n_iovec
+ 2] = IOVEC_MAKE_STRING(t
);
2206 t
= strjoina(u
->manager
->invocation_log_field
, u
->invocation_id_string
);
2207 iovec
[n_iovec
+ 3] = IOVEC_MAKE_STRING(t
);
2209 log_struct_iovec(log_level
, iovec
, n_iovec
+ 4);
2213 for (size_t i
= 0; i
< n_message_parts
; i
++)
2214 free(message_parts
[i
]);
2216 for (size_t i
= 0; i
< n_iovec
; i
++)
2217 free(iovec
[i
].iov_base
);
2223 static void unit_update_on_console(Unit
*u
) {
2228 b
= unit_needs_console(u
);
2229 if (u
->on_console
== b
)
2234 manager_ref_console(u
->manager
);
2236 manager_unref_console(u
->manager
);
2239 static void unit_emit_audit_start(Unit
*u
) {
2242 if (u
->type
!= UNIT_SERVICE
)
2245 /* Write audit record if we have just finished starting up */
2246 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_START
, true);
2250 static void unit_emit_audit_stop(Unit
*u
, UnitActiveState state
) {
2253 if (u
->type
!= UNIT_SERVICE
)
2257 /* Write audit record if we have just finished shutting down */
2258 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_STOP
, state
== UNIT_INACTIVE
);
2259 u
->in_audit
= false;
2261 /* Hmm, if there was no start record written write it now, so that we always have a nice pair */
2262 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_START
, state
== UNIT_INACTIVE
);
2264 if (state
== UNIT_INACTIVE
)
2265 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_STOP
, true);
2269 static bool unit_process_job(Job
*j
, UnitActiveState ns
, UnitNotifyFlags flags
) {
2270 bool unexpected
= false;
2275 if (j
->state
== JOB_WAITING
)
2277 /* So we reached a different state for this job. Let's see if we can run it now if it failed previously
2279 job_add_to_run_queue(j
);
2281 /* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
2282 * hence needs to invalidate jobs. */
2287 case JOB_VERIFY_ACTIVE
:
2289 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2290 job_finish_and_invalidate(j
, JOB_DONE
, true, false);
2291 else if (j
->state
== JOB_RUNNING
&& ns
!= UNIT_ACTIVATING
) {
2294 if (UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2295 if (ns
== UNIT_FAILED
)
2296 result
= JOB_FAILED
;
2300 job_finish_and_invalidate(j
, result
, true, false);
2307 case JOB_RELOAD_OR_START
:
2308 case JOB_TRY_RELOAD
:
2310 if (j
->state
== JOB_RUNNING
) {
2311 if (ns
== UNIT_ACTIVE
)
2312 job_finish_and_invalidate(j
, (flags
& UNIT_NOTIFY_RELOAD_FAILURE
) ? JOB_FAILED
: JOB_DONE
, true, false);
2313 else if (!IN_SET(ns
, UNIT_ACTIVATING
, UNIT_RELOADING
)) {
2316 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2317 job_finish_and_invalidate(j
, ns
== UNIT_FAILED
? JOB_FAILED
: JOB_DONE
, true, false);
2325 case JOB_TRY_RESTART
:
2327 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2328 job_finish_and_invalidate(j
, JOB_DONE
, true, false);
2329 else if (j
->state
== JOB_RUNNING
&& ns
!= UNIT_DEACTIVATING
) {
2331 job_finish_and_invalidate(j
, JOB_FAILED
, true, false);
2337 assert_not_reached("Job type unknown");
2343 void unit_notify(Unit
*u
, UnitActiveState os
, UnitActiveState ns
, UnitNotifyFlags flags
) {
2348 assert(os
< _UNIT_ACTIVE_STATE_MAX
);
2349 assert(ns
< _UNIT_ACTIVE_STATE_MAX
);
2351 /* Note that this is called for all low-level state changes, even if they might map to the same high-level
2352 * UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
2353 * remounted this function will be called too! */
2357 /* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
2358 * the bus queue, so that any job change signal queued will force out the unit change signal first. */
2359 unit_add_to_dbus_queue(u
);
2361 /* Update systemd-oomd on the property/state change */
2363 /* Always send an update if the unit is going into an inactive state so systemd-oomd knows to stop
2365 * Also send an update whenever the unit goes active; this is to handle a case where an override file
2366 * sets one of the ManagedOOM*= properties to "kill", then later removes it. systemd-oomd needs to
2367 * know to stop monitoring when the unit changes from "kill" -> "auto" on daemon-reload, but we don't
2368 * have the information on the property. Thus, indiscriminately send an update. */
2369 if (UNIT_IS_INACTIVE_OR_FAILED(ns
) || UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2370 (void) manager_varlink_send_managed_oom_update(u
);
2373 /* Update timestamps for state changes */
2374 if (!MANAGER_IS_RELOADING(m
)) {
2375 dual_timestamp_get(&u
->state_change_timestamp
);
2377 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && !UNIT_IS_INACTIVE_OR_FAILED(ns
))
2378 u
->inactive_exit_timestamp
= u
->state_change_timestamp
;
2379 else if (!UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_INACTIVE_OR_FAILED(ns
))
2380 u
->inactive_enter_timestamp
= u
->state_change_timestamp
;
2382 if (!UNIT_IS_ACTIVE_OR_RELOADING(os
) && UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2383 u
->active_enter_timestamp
= u
->state_change_timestamp
;
2384 else if (UNIT_IS_ACTIVE_OR_RELOADING(os
) && !UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2385 u
->active_exit_timestamp
= u
->state_change_timestamp
;
2388 /* Keep track of failed units */
2389 (void) manager_update_failed_units(m
, u
, ns
== UNIT_FAILED
);
2391 /* Make sure the cgroup and state files are always removed when we become inactive */
2392 if (UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2393 SET_FLAG(u
->markers
,
2394 (1u << UNIT_MARKER_NEEDS_RELOAD
)|(1u << UNIT_MARKER_NEEDS_RESTART
),
2396 unit_prune_cgroup(u
);
2397 unit_unlink_state_files(u
);
2398 } else if (ns
!= os
&& ns
== UNIT_RELOADING
)
2399 SET_FLAG(u
->markers
, 1u << UNIT_MARKER_NEEDS_RELOAD
, false);
2401 unit_update_on_console(u
);
2403 if (!MANAGER_IS_RELOADING(m
)) {
2406 /* Let's propagate state changes to the job */
2408 unexpected
= unit_process_job(u
->job
, ns
, flags
);
2412 /* If this state change happened without being requested by a job, then let's retroactively start or
2413 * stop dependencies. We skip that step when deserializing, since we don't want to create any
2414 * additional jobs just because something is already activated. */
2417 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns
))
2418 retroactively_start_dependencies(u
);
2419 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os
) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns
))
2420 retroactively_stop_dependencies(u
);
2423 /* stop unneeded units regardless if going down was expected or not */
2424 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2425 check_unneeded_dependencies(u
);
2427 if (ns
!= os
&& ns
== UNIT_FAILED
) {
2428 log_unit_debug(u
, "Unit entered failed state.");
2430 if (!(flags
& UNIT_NOTIFY_WILL_AUTO_RESTART
))
2431 unit_start_on_failure(u
);
2434 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
) && !UNIT_IS_ACTIVE_OR_RELOADING(os
)) {
2435 /* This unit just finished starting up */
2437 unit_emit_audit_start(u
);
2438 manager_send_unit_plymouth(m
, u
);
2441 if (UNIT_IS_INACTIVE_OR_FAILED(ns
) && !UNIT_IS_INACTIVE_OR_FAILED(os
)) {
2442 /* This unit just stopped/failed. */
2444 unit_emit_audit_stop(u
, ns
);
2445 unit_log_resources(u
);
2449 manager_recheck_journal(m
);
2450 manager_recheck_dbus(m
);
2452 unit_trigger_notify(u
);
2454 if (!MANAGER_IS_RELOADING(m
)) {
2455 /* Maybe we finished startup and are now ready for being stopped because unneeded? */
2456 unit_submit_to_stop_when_unneeded_queue(u
);
2458 /* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens when
2459 * something BindsTo= to a Type=oneshot unit, as these units go directly from starting to inactive,
2460 * without ever entering started.) */
2461 unit_check_binds_to(u
);
2463 if (os
!= UNIT_FAILED
&& ns
== UNIT_FAILED
) {
2464 reason
= strjoina("unit ", u
->id
, " failed");
2465 emergency_action(m
, u
->failure_action
, 0, u
->reboot_arg
, unit_failure_action_exit_status(u
), reason
);
2466 } else if (!UNIT_IS_INACTIVE_OR_FAILED(os
) && ns
== UNIT_INACTIVE
) {
2467 reason
= strjoina("unit ", u
->id
, " succeeded");
2468 emergency_action(m
, u
->success_action
, 0, u
->reboot_arg
, unit_success_action_exit_status(u
), reason
);
2472 unit_add_to_gc_queue(u
);
2475 int unit_watch_pid(Unit
*u
, pid_t pid
, bool exclusive
) {
2479 assert(pid_is_valid(pid
));
2481 /* Watch a specific PID */
2483 /* Caller might be sure that this PID belongs to this unit only. Let's take this
2484 * opportunity to remove any stalled references to this PID as they can be created
2485 * easily (when watching a process which is not our direct child). */
2487 manager_unwatch_pid(u
->manager
, pid
);
2489 r
= set_ensure_allocated(&u
->pids
, NULL
);
2493 r
= hashmap_ensure_allocated(&u
->manager
->watch_pids
, NULL
);
2497 /* First try, let's add the unit keyed by "pid". */
2498 r
= hashmap_put(u
->manager
->watch_pids
, PID_TO_PTR(pid
), u
);
2504 /* OK, the "pid" key is already assigned to a different unit. Let's see if the "-pid" key (which points
2505 * to an array of Units rather than just a Unit), lists us already. */
2507 array
= hashmap_get(u
->manager
->watch_pids
, PID_TO_PTR(-pid
));
2509 for (; array
[n
]; n
++)
2513 if (found
) /* Found it already? if so, do nothing */
2518 /* Allocate a new array */
2519 new_array
= new(Unit
*, n
+ 2);
2523 memcpy_safe(new_array
, array
, sizeof(Unit
*) * n
);
2525 new_array
[n
+1] = NULL
;
2527 /* Add or replace the old array */
2528 r
= hashmap_replace(u
->manager
->watch_pids
, PID_TO_PTR(-pid
), new_array
);
2539 r
= set_put(u
->pids
, PID_TO_PTR(pid
));
2546 void unit_unwatch_pid(Unit
*u
, pid_t pid
) {
2550 assert(pid_is_valid(pid
));
2552 /* First let's drop the unit in case it's keyed as "pid". */
2553 (void) hashmap_remove_value(u
->manager
->watch_pids
, PID_TO_PTR(pid
), u
);
2555 /* Then, let's also drop the unit, in case it's in the array keyed by -pid */
2556 array
= hashmap_get(u
->manager
->watch_pids
, PID_TO_PTR(-pid
));
2558 /* Let's iterate through the array, dropping our own entry */
2561 for (size_t n
= 0; array
[n
]; n
++)
2563 array
[m
++] = array
[n
];
2567 /* The array is now empty, remove the entire entry */
2568 assert_se(hashmap_remove(u
->manager
->watch_pids
, PID_TO_PTR(-pid
)) == array
);
2573 (void) set_remove(u
->pids
, PID_TO_PTR(pid
));
2576 void unit_unwatch_all_pids(Unit
*u
) {
2579 while (!set_isempty(u
->pids
))
2580 unit_unwatch_pid(u
, PTR_TO_PID(set_first(u
->pids
)));
2582 u
->pids
= set_free(u
->pids
);
2585 static void unit_tidy_watch_pids(Unit
*u
) {
2586 pid_t except1
, except2
;
2591 /* Cleans dead PIDs from our list */
2593 except1
= unit_main_pid(u
);
2594 except2
= unit_control_pid(u
);
2596 SET_FOREACH(e
, u
->pids
) {
2597 pid_t pid
= PTR_TO_PID(e
);
2599 if (pid
== except1
|| pid
== except2
)
2602 if (!pid_is_unwaited(pid
))
2603 unit_unwatch_pid(u
, pid
);
2607 static int on_rewatch_pids_event(sd_event_source
*s
, void *userdata
) {
2613 unit_tidy_watch_pids(u
);
2614 unit_watch_all_pids(u
);
2616 /* If the PID set is empty now, then let's finish this off. */
2617 unit_synthesize_cgroup_empty_event(u
);
2622 int unit_enqueue_rewatch_pids(Unit
*u
) {
2627 if (!u
->cgroup_path
)
2630 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2633 if (r
> 0) /* On unified we can use proper notifications */
2636 /* Enqueues a low-priority job that will clean up dead PIDs from our list of PIDs to watch and subscribe to new
2637 * PIDs that might have appeared. We do this in a delayed job because the work might be quite slow, as it
2638 * involves issuing kill(pid, 0) on all processes we watch. */
2640 if (!u
->rewatch_pids_event_source
) {
2641 _cleanup_(sd_event_source_unrefp
) sd_event_source
*s
= NULL
;
2643 r
= sd_event_add_defer(u
->manager
->event
, &s
, on_rewatch_pids_event
, u
);
2645 return log_error_errno(r
, "Failed to allocate event source for tidying watched PIDs: %m");
2647 r
= sd_event_source_set_priority(s
, SD_EVENT_PRIORITY_IDLE
);
2649 return log_error_errno(r
, "Failed to adjust priority of event source for tidying watched PIDs: %m");
2651 (void) sd_event_source_set_description(s
, "tidy-watch-pids");
2653 u
->rewatch_pids_event_source
= TAKE_PTR(s
);
2656 r
= sd_event_source_set_enabled(u
->rewatch_pids_event_source
, SD_EVENT_ONESHOT
);
2658 return log_error_errno(r
, "Failed to enable event source for tidying watched PIDs: %m");
2663 void unit_dequeue_rewatch_pids(Unit
*u
) {
2667 if (!u
->rewatch_pids_event_source
)
2670 r
= sd_event_source_set_enabled(u
->rewatch_pids_event_source
, SD_EVENT_OFF
);
2672 log_warning_errno(r
, "Failed to disable event source for tidying watched PIDs, ignoring: %m");
2674 u
->rewatch_pids_event_source
= sd_event_source_unref(u
->rewatch_pids_event_source
);
2677 bool unit_job_is_applicable(Unit
*u
, JobType j
) {
2679 assert(j
>= 0 && j
< _JOB_TYPE_MAX
);
2683 case JOB_VERIFY_ACTIVE
:
2686 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
2687 * startable by us but may appear due to external events, and it thus makes sense to permit enqueuing
2692 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
2693 * external events), hence it makes no sense to permit enqueuing such a request either. */
2694 return !u
->perpetual
;
2697 case JOB_TRY_RESTART
:
2698 return unit_can_stop(u
) && unit_can_start(u
);
2701 case JOB_TRY_RELOAD
:
2702 return unit_can_reload(u
);
2704 case JOB_RELOAD_OR_START
:
2705 return unit_can_reload(u
) && unit_can_start(u
);
2708 assert_not_reached("Invalid job type");
2712 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
) {
2715 /* Only warn about some unit types */
2716 if (!IN_SET(dependency
, UNIT_CONFLICTS
, UNIT_CONFLICTED_BY
, UNIT_BEFORE
, UNIT_AFTER
, UNIT_ON_FAILURE
, UNIT_TRIGGERS
, UNIT_TRIGGERED_BY
))
2719 if (streq_ptr(u
->id
, other
))
2720 log_unit_warning(u
, "Dependency %s=%s dropped", unit_dependency_to_string(dependency
), u
->id
);
2722 log_unit_warning(u
, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency
), strna(other
), u
->id
);
2725 static int unit_add_dependency_hashmap(
2728 UnitDependencyMask origin_mask
,
2729 UnitDependencyMask destination_mask
) {
2731 UnitDependencyInfo info
;
2736 assert(origin_mask
< _UNIT_DEPENDENCY_MASK_FULL
);
2737 assert(destination_mask
< _UNIT_DEPENDENCY_MASK_FULL
);
2738 assert(origin_mask
> 0 || destination_mask
> 0);
2740 r
= hashmap_ensure_allocated(h
, NULL
);
2744 assert_cc(sizeof(void*) == sizeof(info
));
2746 info
.data
= hashmap_get(*h
, other
);
2748 /* Entry already exists. Add in our mask. */
2750 if (FLAGS_SET(origin_mask
, info
.origin_mask
) &&
2751 FLAGS_SET(destination_mask
, info
.destination_mask
))
2754 info
.origin_mask
|= origin_mask
;
2755 info
.destination_mask
|= destination_mask
;
2757 r
= hashmap_update(*h
, other
, info
.data
);
2759 info
= (UnitDependencyInfo
) {
2760 .origin_mask
= origin_mask
,
2761 .destination_mask
= destination_mask
,
2764 r
= hashmap_put(*h
, other
, info
.data
);
2772 int unit_add_dependency(
2777 UnitDependencyMask mask
) {
2779 static const UnitDependency inverse_table
[_UNIT_DEPENDENCY_MAX
] = {
2780 [UNIT_REQUIRES
] = UNIT_REQUIRED_BY
,
2781 [UNIT_WANTS
] = UNIT_WANTED_BY
,
2782 [UNIT_REQUISITE
] = UNIT_REQUISITE_OF
,
2783 [UNIT_BINDS_TO
] = UNIT_BOUND_BY
,
2784 [UNIT_PART_OF
] = UNIT_CONSISTS_OF
,
2785 [UNIT_REQUIRED_BY
] = UNIT_REQUIRES
,
2786 [UNIT_REQUISITE_OF
] = UNIT_REQUISITE
,
2787 [UNIT_WANTED_BY
] = UNIT_WANTS
,
2788 [UNIT_BOUND_BY
] = UNIT_BINDS_TO
,
2789 [UNIT_CONSISTS_OF
] = UNIT_PART_OF
,
2790 [UNIT_CONFLICTS
] = UNIT_CONFLICTED_BY
,
2791 [UNIT_CONFLICTED_BY
] = UNIT_CONFLICTS
,
2792 [UNIT_BEFORE
] = UNIT_AFTER
,
2793 [UNIT_AFTER
] = UNIT_BEFORE
,
2794 [UNIT_ON_FAILURE
] = _UNIT_DEPENDENCY_INVALID
,
2795 [UNIT_REFERENCES
] = UNIT_REFERENCED_BY
,
2796 [UNIT_REFERENCED_BY
] = UNIT_REFERENCES
,
2797 [UNIT_TRIGGERS
] = UNIT_TRIGGERED_BY
,
2798 [UNIT_TRIGGERED_BY
] = UNIT_TRIGGERS
,
2799 [UNIT_PROPAGATES_RELOAD_TO
] = UNIT_RELOAD_PROPAGATED_FROM
,
2800 [UNIT_RELOAD_PROPAGATED_FROM
] = UNIT_PROPAGATES_RELOAD_TO
,
2801 [UNIT_JOINS_NAMESPACE_OF
] = UNIT_JOINS_NAMESPACE_OF
,
2803 Unit
*original_u
= u
, *original_other
= other
;
2805 /* Helper to know whether sending a notification is necessary or not:
2806 * if the dependency is already there, no need to notify! */
2810 assert(d
>= 0 && d
< _UNIT_DEPENDENCY_MAX
);
2813 u
= unit_follow_merge(u
);
2814 other
= unit_follow_merge(other
);
2816 /* We won't allow dependencies on ourselves. We will not
2817 * consider them an error however. */
2819 maybe_warn_about_dependency(original_u
, original_other
->id
, d
);
2823 /* Note that ordering a device unit after a unit is permitted since it
2824 * allows to start its job running timeout at a specific time. */
2825 if (d
== UNIT_BEFORE
&& other
->type
== UNIT_DEVICE
) {
2826 log_unit_warning(u
, "Dependency Before=%s ignored (.device units cannot be delayed)", other
->id
);
2830 if (d
== UNIT_ON_FAILURE
&& !UNIT_VTABLE(u
)->can_fail
) {
2831 log_unit_warning(u
, "Requested dependency OnFailure=%s ignored (%s units cannot fail).", other
->id
, unit_type_to_string(u
->type
));
2835 if (d
== UNIT_TRIGGERS
&& !UNIT_VTABLE(u
)->can_trigger
)
2836 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
2837 "Requested dependency Triggers=%s refused (%s units cannot trigger other units).", other
->id
, unit_type_to_string(u
->type
));
2838 if (d
== UNIT_TRIGGERED_BY
&& !UNIT_VTABLE(other
)->can_trigger
)
2839 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
2840 "Requested dependency TriggeredBy=%s refused (%s units cannot trigger other units).", other
->id
, unit_type_to_string(other
->type
));
2842 r
= unit_add_dependency_hashmap(u
->dependencies
+ d
, other
, mask
, 0);
2848 if (inverse_table
[d
] != _UNIT_DEPENDENCY_INVALID
&& inverse_table
[d
] != d
) {
2849 r
= unit_add_dependency_hashmap(other
->dependencies
+ inverse_table
[d
], u
, 0, mask
);
2856 if (add_reference
) {
2857 r
= unit_add_dependency_hashmap(u
->dependencies
+ UNIT_REFERENCES
, other
, mask
, 0);
2863 r
= unit_add_dependency_hashmap(other
->dependencies
+ UNIT_REFERENCED_BY
, u
, 0, mask
);
2871 unit_add_to_dbus_queue(u
);
2875 int unit_add_two_dependencies(Unit
*u
, UnitDependency d
, UnitDependency e
, Unit
*other
, bool add_reference
, UnitDependencyMask mask
) {
2880 r
= unit_add_dependency(u
, d
, other
, add_reference
, mask
);
2884 return unit_add_dependency(u
, e
, other
, add_reference
, mask
);
2887 static int resolve_template(Unit
*u
, const char *name
, char **buf
, const char **ret
) {
2895 if (!unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2902 r
= unit_name_replace_instance(name
, u
->instance
, buf
);
2904 _cleanup_free_
char *i
= NULL
;
2906 r
= unit_name_to_prefix(u
->id
, &i
);
2910 r
= unit_name_replace_instance(name
, i
, buf
);
2919 int unit_add_dependency_by_name(Unit
*u
, UnitDependency d
, const char *name
, bool add_reference
, UnitDependencyMask mask
) {
2920 _cleanup_free_
char *buf
= NULL
;
2927 r
= resolve_template(u
, name
, &buf
, &name
);
2931 r
= manager_load_unit(u
->manager
, name
, NULL
, NULL
, &other
);
2935 return unit_add_dependency(u
, d
, other
, add_reference
, mask
);
2938 int unit_add_two_dependencies_by_name(Unit
*u
, UnitDependency d
, UnitDependency e
, const char *name
, bool add_reference
, UnitDependencyMask mask
) {
2939 _cleanup_free_
char *buf
= NULL
;
2946 r
= resolve_template(u
, name
, &buf
, &name
);
2950 r
= manager_load_unit(u
->manager
, name
, NULL
, NULL
, &other
);
2954 return unit_add_two_dependencies(u
, d
, e
, other
, add_reference
, mask
);
2957 int set_unit_path(const char *p
) {
2958 /* This is mostly for debug purposes */
2959 if (setenv("SYSTEMD_UNIT_PATH", p
, 1) < 0)
2965 char *unit_dbus_path(Unit
*u
) {
2971 return unit_dbus_path_from_name(u
->id
);
2974 char *unit_dbus_path_invocation_id(Unit
*u
) {
2977 if (sd_id128_is_null(u
->invocation_id
))
2980 return unit_dbus_path_from_name(u
->invocation_id_string
);
2983 int unit_set_invocation_id(Unit
*u
, sd_id128_t id
) {
2988 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
2990 if (sd_id128_equal(u
->invocation_id
, id
))
2993 if (!sd_id128_is_null(u
->invocation_id
))
2994 (void) hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
2996 if (sd_id128_is_null(id
)) {
3001 r
= hashmap_ensure_allocated(&u
->manager
->units_by_invocation_id
, &id128_hash_ops
);
3005 u
->invocation_id
= id
;
3006 sd_id128_to_string(id
, u
->invocation_id_string
);
3008 r
= hashmap_put(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
3015 u
->invocation_id
= SD_ID128_NULL
;
3016 u
->invocation_id_string
[0] = 0;
3020 int unit_set_slice(Unit
*u
, Unit
*slice
) {
3024 /* Sets the unit slice if it has not been set before. Is extra
3025 * careful, to only allow this for units that actually have a
3026 * cgroup context. Also, we don't allow to set this for slices
3027 * (since the parent slice is derived from the name). Make
3028 * sure the unit we set is actually a slice. */
3030 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
3033 if (u
->type
== UNIT_SLICE
)
3036 if (unit_active_state(u
) != UNIT_INACTIVE
)
3039 if (slice
->type
!= UNIT_SLICE
)
3042 if (unit_has_name(u
, SPECIAL_INIT_SCOPE
) &&
3043 !unit_has_name(slice
, SPECIAL_ROOT_SLICE
))
3046 if (UNIT_DEREF(u
->slice
) == slice
)
3049 /* Disallow slice changes if @u is already bound to cgroups */
3050 if (UNIT_ISSET(u
->slice
) && u
->cgroup_realized
)
3053 unit_ref_set(&u
->slice
, u
, slice
);
3057 int unit_set_default_slice(Unit
*u
) {
3058 const char *slice_name
;
3064 if (UNIT_ISSET(u
->slice
))
3068 _cleanup_free_
char *prefix
= NULL
, *escaped
= NULL
;
3070 /* Implicitly place all instantiated units in their
3071 * own per-template slice */
3073 r
= unit_name_to_prefix(u
->id
, &prefix
);
3077 /* The prefix is already escaped, but it might include
3078 * "-" which has a special meaning for slice units,
3079 * hence escape it here extra. */
3080 escaped
= unit_name_escape(prefix
);
3084 if (MANAGER_IS_SYSTEM(u
->manager
))
3085 slice_name
= strjoina("system-", escaped
, ".slice");
3087 slice_name
= strjoina("app-", escaped
, ".slice");
3089 } else if (unit_is_extrinsic(u
))
3090 /* Keep all extrinsic units (e.g. perpetual units and swap and mount units in user mode) in
3091 * the root slice. They don't really belong in one of the subslices. */
3092 slice_name
= SPECIAL_ROOT_SLICE
;
3094 else if (MANAGER_IS_SYSTEM(u
->manager
))
3095 slice_name
= SPECIAL_SYSTEM_SLICE
;
3097 slice_name
= SPECIAL_APP_SLICE
;
3099 r
= manager_load_unit(u
->manager
, slice_name
, NULL
, NULL
, &slice
);
3103 return unit_set_slice(u
, slice
);
3106 const char *unit_slice_name(Unit
*u
) {
3109 if (!UNIT_ISSET(u
->slice
))
3112 return UNIT_DEREF(u
->slice
)->id
;
3115 int unit_load_related_unit(Unit
*u
, const char *type
, Unit
**_found
) {
3116 _cleanup_free_
char *t
= NULL
;
3123 r
= unit_name_change_suffix(u
->id
, type
, &t
);
3126 if (unit_has_name(u
, t
))
3129 r
= manager_load_unit(u
->manager
, t
, NULL
, NULL
, _found
);
3130 assert(r
< 0 || *_found
!= u
);
3134 static int signal_name_owner_changed(sd_bus_message
*message
, void *userdata
, sd_bus_error
*error
) {
3135 const char *new_owner
;
3142 r
= sd_bus_message_read(message
, "sss", NULL
, NULL
, &new_owner
);
3144 bus_log_parse_error(r
);
3148 if (UNIT_VTABLE(u
)->bus_name_owner_change
)
3149 UNIT_VTABLE(u
)->bus_name_owner_change(u
, empty_to_null(new_owner
));
3154 static int get_name_owner_handler(sd_bus_message
*message
, void *userdata
, sd_bus_error
*error
) {
3155 const sd_bus_error
*e
;
3156 const char *new_owner
;
3163 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3165 e
= sd_bus_message_get_error(message
);
3167 if (!sd_bus_error_has_name(e
, "org.freedesktop.DBus.Error.NameHasNoOwner"))
3168 log_unit_error(u
, "Unexpected error response from GetNameOwner(): %s", e
->message
);
3172 r
= sd_bus_message_read(message
, "s", &new_owner
);
3174 return bus_log_parse_error(r
);
3176 assert(!isempty(new_owner
));
3179 if (UNIT_VTABLE(u
)->bus_name_owner_change
)
3180 UNIT_VTABLE(u
)->bus_name_owner_change(u
, new_owner
);
3185 int unit_install_bus_match(Unit
*u
, sd_bus
*bus
, const char *name
) {
3193 if (u
->match_bus_slot
|| u
->get_name_owner_slot
)
3196 match
= strjoina("type='signal',"
3197 "sender='org.freedesktop.DBus',"
3198 "path='/org/freedesktop/DBus',"
3199 "interface='org.freedesktop.DBus',"
3200 "member='NameOwnerChanged',"
3201 "arg0='", name
, "'");
3203 r
= sd_bus_add_match_async(bus
, &u
->match_bus_slot
, match
, signal_name_owner_changed
, NULL
, u
);
3207 r
= sd_bus_call_method_async(
3209 &u
->get_name_owner_slot
,
3210 "org.freedesktop.DBus",
3211 "/org/freedesktop/DBus",
3212 "org.freedesktop.DBus",
3214 get_name_owner_handler
,
3218 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3222 log_unit_debug(u
, "Watching D-Bus name '%s'.", name
);
3226 int unit_watch_bus_name(Unit
*u
, const char *name
) {
3232 /* Watch a specific name on the bus. We only support one unit
3233 * watching each name for now. */
3235 if (u
->manager
->api_bus
) {
3236 /* If the bus is already available, install the match directly.
3237 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
3238 r
= unit_install_bus_match(u
, u
->manager
->api_bus
, name
);
3240 return log_warning_errno(r
, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name
);
3243 r
= hashmap_put(u
->manager
->watch_bus
, name
, u
);
3245 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3246 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3247 return log_warning_errno(r
, "Failed to put bus name to hashmap: %m");
3253 void unit_unwatch_bus_name(Unit
*u
, const char *name
) {
3257 (void) hashmap_remove_value(u
->manager
->watch_bus
, name
, u
);
3258 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3259 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3262 bool unit_can_serialize(Unit
*u
) {
3265 return UNIT_VTABLE(u
)->serialize
&& UNIT_VTABLE(u
)->deserialize_item
;
3268 int unit_add_node_dependency(Unit
*u
, const char *what
, UnitDependency dep
, UnitDependencyMask mask
) {
3269 _cleanup_free_
char *e
= NULL
;
3275 /* Adds in links to the device node that this unit is based on */
3279 if (!is_device_path(what
))
3282 /* When device units aren't supported (such as in a container), don't create dependencies on them. */
3283 if (!unit_type_supported(UNIT_DEVICE
))
3286 r
= unit_name_from_path(what
, ".device", &e
);
3290 r
= manager_load_unit(u
->manager
, e
, NULL
, NULL
, &device
);
3294 if (dep
== UNIT_REQUIRES
&& device_shall_be_bound_by(device
, u
))
3295 dep
= UNIT_BINDS_TO
;
3297 return unit_add_two_dependencies(u
, UNIT_AFTER
,
3298 MANAGER_IS_SYSTEM(u
->manager
) ? dep
: UNIT_WANTS
,
3299 device
, true, mask
);
3302 int unit_add_blockdev_dependency(Unit
*u
, const char *what
, UnitDependencyMask mask
) {
3303 _cleanup_free_
char *escaped
= NULL
, *target
= NULL
;
3311 if (!path_startswith(what
, "/dev/"))
3314 /* If we don't support devices, then also don't bother with blockdev@.target */
3315 if (!unit_type_supported(UNIT_DEVICE
))
3318 r
= unit_name_path_escape(what
, &escaped
);
3322 r
= unit_name_build("blockdev", escaped
, ".target", &target
);
3326 return unit_add_dependency_by_name(u
, UNIT_AFTER
, target
, true, mask
);
3329 int unit_coldplug(Unit
*u
) {
3336 /* Make sure we don't enter a loop, when coldplugging recursively. */
3340 u
->coldplugged
= true;
3342 STRV_FOREACH(i
, u
->deserialized_refs
) {
3343 q
= bus_unit_track_add_name(u
, *i
);
3344 if (q
< 0 && r
>= 0)
3347 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
3349 if (UNIT_VTABLE(u
)->coldplug
) {
3350 q
= UNIT_VTABLE(u
)->coldplug(u
);
3351 if (q
< 0 && r
>= 0)
3355 uj
= u
->job
?: u
->nop_job
;
3357 q
= job_coldplug(uj
);
3358 if (q
< 0 && r
>= 0)
3365 void unit_catchup(Unit
*u
) {
3368 if (UNIT_VTABLE(u
)->catchup
)
3369 UNIT_VTABLE(u
)->catchup(u
);
3372 static bool fragment_mtime_newer(const char *path
, usec_t mtime
, bool path_masked
) {
3378 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
3379 * are never out-of-date. */
3380 if (PATH_STARTSWITH_SET(path
, "/proc", "/sys"))
3383 if (stat(path
, &st
) < 0)
3384 /* What, cannot access this anymore? */
3388 /* For masked files check if they are still so */
3389 return !null_or_empty(&st
);
3391 /* For non-empty files check the mtime */
3392 return timespec_load(&st
.st_mtim
) > mtime
;
3397 bool unit_need_daemon_reload(Unit
*u
) {
3398 _cleanup_strv_free_
char **t
= NULL
;
3403 /* For unit files, we allow masking… */
3404 if (fragment_mtime_newer(u
->fragment_path
, u
->fragment_mtime
,
3405 u
->load_state
== UNIT_MASKED
))
3408 /* Source paths should not be masked… */
3409 if (fragment_mtime_newer(u
->source_path
, u
->source_mtime
, false))
3412 if (u
->load_state
== UNIT_LOADED
)
3413 (void) unit_find_dropin_paths(u
, &t
);
3414 if (!strv_equal(u
->dropin_paths
, t
))
3417 /* … any drop-ins that are masked are simply omitted from the list. */
3418 STRV_FOREACH(path
, u
->dropin_paths
)
3419 if (fragment_mtime_newer(*path
, u
->dropin_mtime
, false))
3425 void unit_reset_failed(Unit
*u
) {
3428 if (UNIT_VTABLE(u
)->reset_failed
)
3429 UNIT_VTABLE(u
)->reset_failed(u
);
3431 ratelimit_reset(&u
->start_ratelimit
);
3432 u
->start_limit_hit
= false;
3435 Unit
*unit_following(Unit
*u
) {
3438 if (UNIT_VTABLE(u
)->following
)
3439 return UNIT_VTABLE(u
)->following(u
);
3444 bool unit_stop_pending(Unit
*u
) {
3447 /* This call does check the current state of the unit. It's
3448 * hence useful to be called from state change calls of the
3449 * unit itself, where the state isn't updated yet. This is
3450 * different from unit_inactive_or_pending() which checks both
3451 * the current state and for a queued job. */
3453 return unit_has_job_type(u
, JOB_STOP
);
3456 bool unit_inactive_or_pending(Unit
*u
) {
3459 /* Returns true if the unit is inactive or going down */
3461 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)))
3464 if (unit_stop_pending(u
))
3470 bool unit_active_or_pending(Unit
*u
) {
3473 /* Returns true if the unit is active or going up */
3475 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)))
3479 IN_SET(u
->job
->type
, JOB_START
, JOB_RELOAD_OR_START
, JOB_RESTART
))
3485 bool unit_will_restart_default(Unit
*u
) {
3488 return unit_has_job_type(u
, JOB_START
);
3491 bool unit_will_restart(Unit
*u
) {
3494 if (!UNIT_VTABLE(u
)->will_restart
)
3497 return UNIT_VTABLE(u
)->will_restart(u
);
3500 int unit_kill(Unit
*u
, KillWho w
, int signo
, sd_bus_error
*error
) {
3502 assert(w
>= 0 && w
< _KILL_WHO_MAX
);
3503 assert(SIGNAL_VALID(signo
));
3505 if (!UNIT_VTABLE(u
)->kill
)
3508 return UNIT_VTABLE(u
)->kill(u
, w
, signo
, error
);
3511 static Set
*unit_pid_set(pid_t main_pid
, pid_t control_pid
) {
3512 _cleanup_set_free_ Set
*pid_set
= NULL
;
3515 pid_set
= set_new(NULL
);
3519 /* Exclude the main/control pids from being killed via the cgroup */
3521 r
= set_put(pid_set
, PID_TO_PTR(main_pid
));
3526 if (control_pid
> 0) {
3527 r
= set_put(pid_set
, PID_TO_PTR(control_pid
));
3532 return TAKE_PTR(pid_set
);
3535 static int kill_common_log(pid_t pid
, int signo
, void *userdata
) {
3536 _cleanup_free_
char *comm
= NULL
;
3541 (void) get_process_comm(pid
, &comm
);
3542 log_unit_info(u
, "Sending signal SIG%s to process " PID_FMT
" (%s) on client request.",
3543 signal_to_string(signo
), pid
, strna(comm
));
3548 int unit_kill_common(
3554 sd_bus_error
*error
) {
3557 bool killed
= false;
3559 /* This is the common implementation for explicit user-requested killing of unit processes, shared by
3560 * various unit types. Do not confuse with unit_kill_context(), which is what we use when we want to
3561 * stop a service ourselves. */
3563 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
)) {
3565 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no main processes", unit_type_to_string(u
->type
));
3567 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No main process to kill");
3570 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
)) {
3571 if (control_pid
< 0)
3572 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no control processes", unit_type_to_string(u
->type
));
3573 if (control_pid
== 0)
3574 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No control process to kill");
3577 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
3578 if (control_pid
> 0) {
3579 _cleanup_free_
char *comm
= NULL
;
3580 (void) get_process_comm(control_pid
, &comm
);
3582 if (kill(control_pid
, signo
) < 0) {
3583 /* Report this failure both to the logs and to the client */
3584 sd_bus_error_set_errnof(
3586 "Failed to send signal SIG%s to control process " PID_FMT
" (%s): %m",
3587 signal_to_string(signo
), control_pid
, strna(comm
));
3588 r
= log_unit_warning_errno(
3590 "Failed to send signal SIG%s to control process " PID_FMT
" (%s) on client request: %m",
3591 signal_to_string(signo
), control_pid
, strna(comm
));
3593 log_unit_info(u
, "Sent signal SIG%s to control process " PID_FMT
" (%s) on client request.",
3594 signal_to_string(signo
), control_pid
, strna(comm
));
3599 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
3601 _cleanup_free_
char *comm
= NULL
;
3602 (void) get_process_comm(main_pid
, &comm
);
3604 if (kill(main_pid
, signo
) < 0) {
3606 sd_bus_error_set_errnof(
3608 "Failed to send signal SIG%s to main process " PID_FMT
" (%s): %m",
3609 signal_to_string(signo
), main_pid
, strna(comm
));
3611 r
= log_unit_warning_errno(
3613 "Failed to send signal SIG%s to main process " PID_FMT
" (%s) on client request: %m",
3614 signal_to_string(signo
), main_pid
, strna(comm
));
3616 log_unit_info(u
, "Sent signal SIG%s to main process " PID_FMT
" (%s) on client request.",
3617 signal_to_string(signo
), main_pid
, strna(comm
));
3622 if (IN_SET(who
, KILL_ALL
, KILL_ALL_FAIL
) && u
->cgroup_path
) {
3623 _cleanup_set_free_ Set
*pid_set
= NULL
;
3626 /* Exclude the main/control pids from being killed via the cgroup */
3627 pid_set
= unit_pid_set(main_pid
, control_pid
);
3631 q
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, signo
, 0, pid_set
, kill_common_log
, u
);
3633 if (!IN_SET(q
, -ESRCH
, -ENOENT
)) {
3635 sd_bus_error_set_errnof(
3637 "Failed to send signal SIG%s to auxiliary processes: %m",
3638 signal_to_string(signo
));
3640 r
= log_unit_warning_errno(
3642 "Failed to send signal SIG%s to auxiliary processes on client request: %m",
3643 signal_to_string(signo
));
3649 /* If the "fail" versions of the operation are requested, then complain if the set of processes we killed is empty */
3650 if (r
== 0 && !killed
&& IN_SET(who
, KILL_ALL_FAIL
, KILL_CONTROL_FAIL
, KILL_MAIN_FAIL
))
3651 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No matching processes to kill");
3656 int unit_following_set(Unit
*u
, Set
**s
) {
3660 if (UNIT_VTABLE(u
)->following_set
)
3661 return UNIT_VTABLE(u
)->following_set(u
, s
);
3667 UnitFileState
unit_get_unit_file_state(Unit
*u
) {
3672 if (u
->unit_file_state
< 0 && u
->fragment_path
) {
3673 r
= unit_file_get_state(
3674 u
->manager
->unit_file_scope
,
3677 &u
->unit_file_state
);
3679 u
->unit_file_state
= UNIT_FILE_BAD
;
3682 return u
->unit_file_state
;
3685 int unit_get_unit_file_preset(Unit
*u
) {
3688 if (u
->unit_file_preset
< 0 && u
->fragment_path
)
3689 u
->unit_file_preset
= unit_file_query_preset(
3690 u
->manager
->unit_file_scope
,
3692 basename(u
->fragment_path
),
3695 return u
->unit_file_preset
;
3698 Unit
* unit_ref_set(UnitRef
*ref
, Unit
*source
, Unit
*target
) {
3704 unit_ref_unset(ref
);
3706 ref
->source
= source
;
3707 ref
->target
= target
;
3708 LIST_PREPEND(refs_by_target
, target
->refs_by_target
, ref
);
3712 void unit_ref_unset(UnitRef
*ref
) {
3718 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
3719 * be unreferenced now. */
3720 unit_add_to_gc_queue(ref
->target
);
3722 LIST_REMOVE(refs_by_target
, ref
->target
->refs_by_target
, ref
);
3723 ref
->source
= ref
->target
= NULL
;
3726 static int user_from_unit_name(Unit
*u
, char **ret
) {
3728 static const uint8_t hash_key
[] = {
3729 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
3730 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
3733 _cleanup_free_
char *n
= NULL
;
3736 r
= unit_name_to_prefix(u
->id
, &n
);
3740 if (valid_user_group_name(n
, 0)) {
3745 /* If we can't use the unit name as a user name, then let's hash it and use that */
3746 if (asprintf(ret
, "_du%016" PRIx64
, siphash24(n
, strlen(n
), hash_key
)) < 0)
3752 int unit_patch_contexts(Unit
*u
) {
3759 /* Patch in the manager defaults into the exec and cgroup
3760 * contexts, _after_ the rest of the settings have been
3763 ec
= unit_get_exec_context(u
);
3765 /* This only copies in the ones that need memory */
3766 for (unsigned i
= 0; i
< _RLIMIT_MAX
; i
++)
3767 if (u
->manager
->rlimit
[i
] && !ec
->rlimit
[i
]) {
3768 ec
->rlimit
[i
] = newdup(struct rlimit
, u
->manager
->rlimit
[i
], 1);
3773 if (MANAGER_IS_USER(u
->manager
) &&
3774 !ec
->working_directory
) {
3776 r
= get_home_dir(&ec
->working_directory
);
3780 /* Allow user services to run, even if the
3781 * home directory is missing */
3782 ec
->working_directory_missing_ok
= true;
3785 if (ec
->private_devices
)
3786 ec
->capability_bounding_set
&= ~((UINT64_C(1) << CAP_MKNOD
) | (UINT64_C(1) << CAP_SYS_RAWIO
));
3788 if (ec
->protect_kernel_modules
)
3789 ec
->capability_bounding_set
&= ~(UINT64_C(1) << CAP_SYS_MODULE
);
3791 if (ec
->protect_kernel_logs
)
3792 ec
->capability_bounding_set
&= ~(UINT64_C(1) << CAP_SYSLOG
);
3794 if (ec
->protect_clock
)
3795 ec
->capability_bounding_set
&= ~((UINT64_C(1) << CAP_SYS_TIME
) | (UINT64_C(1) << CAP_WAKE_ALARM
));
3797 if (ec
->dynamic_user
) {
3799 r
= user_from_unit_name(u
, &ec
->user
);
3805 ec
->group
= strdup(ec
->user
);
3810 /* If the dynamic user option is on, let's make sure that the unit can't leave its
3811 * UID/GID around in the file system or on IPC objects. Hence enforce a strict
3814 ec
->private_tmp
= true;
3815 ec
->remove_ipc
= true;
3816 ec
->protect_system
= PROTECT_SYSTEM_STRICT
;
3817 if (ec
->protect_home
== PROTECT_HOME_NO
)
3818 ec
->protect_home
= PROTECT_HOME_READ_ONLY
;
3820 /* Make sure this service can neither benefit from SUID/SGID binaries nor create
3822 ec
->no_new_privileges
= true;
3823 ec
->restrict_suid_sgid
= true;
3827 cc
= unit_get_cgroup_context(u
);
3830 if (ec
->private_devices
&&
3831 cc
->device_policy
== CGROUP_DEVICE_POLICY_AUTO
)
3832 cc
->device_policy
= CGROUP_DEVICE_POLICY_CLOSED
;
3834 if ((ec
->root_image
|| !LIST_IS_EMPTY(ec
->mount_images
)) &&
3835 (cc
->device_policy
!= CGROUP_DEVICE_POLICY_AUTO
|| cc
->device_allow
)) {
3838 /* When RootImage= or MountImages= is specified, the following devices are touched. */
3839 FOREACH_STRING(p
, "/dev/loop-control", "/dev/mapper/control") {
3840 r
= cgroup_add_device_allow(cc
, p
, "rw");
3844 FOREACH_STRING(p
, "block-loop", "block-blkext", "block-device-mapper") {
3845 r
= cgroup_add_device_allow(cc
, p
, "rwm");
3850 /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices.
3851 * Same for mapper and verity. */
3852 FOREACH_STRING(p
, "modprobe@loop.service", "modprobe@dm_mod.service", "modprobe@dm_verity.service") {
3853 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_WANTS
, p
, true, UNIT_DEPENDENCY_FILE
);
3859 if (ec
->protect_clock
) {
3860 r
= cgroup_add_device_allow(cc
, "char-rtc", "r");
3869 ExecContext
*unit_get_exec_context(Unit
*u
) {
3876 offset
= UNIT_VTABLE(u
)->exec_context_offset
;
3880 return (ExecContext
*) ((uint8_t*) u
+ offset
);
3883 KillContext
*unit_get_kill_context(Unit
*u
) {
3890 offset
= UNIT_VTABLE(u
)->kill_context_offset
;
3894 return (KillContext
*) ((uint8_t*) u
+ offset
);
3897 CGroupContext
*unit_get_cgroup_context(Unit
*u
) {
3903 offset
= UNIT_VTABLE(u
)->cgroup_context_offset
;
3907 return (CGroupContext
*) ((uint8_t*) u
+ offset
);
3910 ExecRuntime
*unit_get_exec_runtime(Unit
*u
) {
3916 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
3920 return *(ExecRuntime
**) ((uint8_t*) u
+ offset
);
3923 static const char* unit_drop_in_dir(Unit
*u
, UnitWriteFlags flags
) {
3926 if (UNIT_WRITE_FLAGS_NOOP(flags
))
3929 if (u
->transient
) /* Redirect drop-ins for transient units always into the transient directory. */
3930 return u
->manager
->lookup_paths
.transient
;
3932 if (flags
& UNIT_PERSISTENT
)
3933 return u
->manager
->lookup_paths
.persistent_control
;
3935 if (flags
& UNIT_RUNTIME
)
3936 return u
->manager
->lookup_paths
.runtime_control
;
3941 char* unit_escape_setting(const char *s
, UnitWriteFlags flags
, char **buf
) {
3947 /* Escapes the input string as requested. Returns the escaped string. If 'buf' is specified then the allocated
3948 * return buffer pointer is also written to *buf, except if no escaping was necessary, in which case *buf is
3949 * set to NULL, and the input pointer is returned as-is. This means the return value always contains a properly
3950 * escaped version, but *buf when passed only contains a pointer if an allocation was necessary. If *buf is
3951 * not specified, then the return value always needs to be freed. Callers can use this to optimize memory
3954 if (flags
& UNIT_ESCAPE_SPECIFIERS
) {
3955 ret
= specifier_escape(s
);
3962 if (flags
& UNIT_ESCAPE_C
) {
3975 return ret
?: (char*) s
;
3978 return ret
?: strdup(s
);
3981 char* unit_concat_strv(char **l
, UnitWriteFlags flags
) {
3982 _cleanup_free_
char *result
= NULL
;
3983 size_t n
= 0, allocated
= 0;
3986 /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command lines in a
3987 * way suitable for ExecStart= stanzas */
3989 STRV_FOREACH(i
, l
) {
3990 _cleanup_free_
char *buf
= NULL
;
3995 p
= unit_escape_setting(*i
, flags
, &buf
);
3999 a
= (n
> 0) + 1 + strlen(p
) + 1; /* separating space + " + entry + " */
4000 if (!GREEDY_REALLOC(result
, allocated
, n
+ a
+ 1))
4014 if (!GREEDY_REALLOC(result
, allocated
, n
+ 1))
4019 return TAKE_PTR(result
);
4022 int unit_write_setting(Unit
*u
, UnitWriteFlags flags
, const char *name
, const char *data
) {
4023 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *escaped
= NULL
;
4024 const char *dir
, *wrapped
;
4031 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4034 data
= unit_escape_setting(data
, flags
, &escaped
);
4038 /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
4039 * previous section header is the same */
4041 if (flags
& UNIT_PRIVATE
) {
4042 if (!UNIT_VTABLE(u
)->private_section
)
4045 if (!u
->transient_file
|| u
->last_section_private
< 0)
4046 data
= strjoina("[", UNIT_VTABLE(u
)->private_section
, "]\n", data
);
4047 else if (u
->last_section_private
== 0)
4048 data
= strjoina("\n[", UNIT_VTABLE(u
)->private_section
, "]\n", data
);
4050 if (!u
->transient_file
|| u
->last_section_private
< 0)
4051 data
= strjoina("[Unit]\n", data
);
4052 else if (u
->last_section_private
> 0)
4053 data
= strjoina("\n[Unit]\n", data
);
4056 if (u
->transient_file
) {
4057 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
4058 * write to the transient unit file. */
4059 fputs(data
, u
->transient_file
);
4061 if (!endswith(data
, "\n"))
4062 fputc('\n', u
->transient_file
);
4064 /* Remember which section we wrote this entry to */
4065 u
->last_section_private
= !!(flags
& UNIT_PRIVATE
);
4069 dir
= unit_drop_in_dir(u
, flags
);
4073 wrapped
= strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
4074 "# or an equivalent operation. Do not edit.\n",
4078 r
= drop_in_file(dir
, u
->id
, 50, name
, &p
, &q
);
4082 (void) mkdir_p_label(p
, 0755);
4084 /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
4085 * recreate the cache after every drop-in we write. */
4086 if (u
->manager
->unit_path_cache
) {
4087 r
= set_put_strdup(&u
->manager
->unit_path_cache
, p
);
4092 r
= write_string_file_atomic_label(q
, wrapped
);
4096 r
= strv_push(&u
->dropin_paths
, q
);
4101 strv_uniq(u
->dropin_paths
);
4103 u
->dropin_mtime
= now(CLOCK_REALTIME
);
4108 int unit_write_settingf(Unit
*u
, UnitWriteFlags flags
, const char *name
, const char *format
, ...) {
4109 _cleanup_free_
char *p
= NULL
;
4117 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4120 va_start(ap
, format
);
4121 r
= vasprintf(&p
, format
, ap
);
4127 return unit_write_setting(u
, flags
, name
, p
);
4130 int unit_make_transient(Unit
*u
) {
4131 _cleanup_free_
char *path
= NULL
;
4136 if (!UNIT_VTABLE(u
)->can_transient
)
4139 (void) mkdir_p_label(u
->manager
->lookup_paths
.transient
, 0755);
4141 path
= path_join(u
->manager
->lookup_paths
.transient
, u
->id
);
4145 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
4146 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
4148 RUN_WITH_UMASK(0022) {
4149 f
= fopen(path
, "we");
4154 safe_fclose(u
->transient_file
);
4155 u
->transient_file
= f
;
4157 free_and_replace(u
->fragment_path
, path
);
4159 u
->source_path
= mfree(u
->source_path
);
4160 u
->dropin_paths
= strv_free(u
->dropin_paths
);
4161 u
->fragment_mtime
= u
->source_mtime
= u
->dropin_mtime
= 0;
4163 u
->load_state
= UNIT_STUB
;
4165 u
->transient
= true;
4167 unit_add_to_dbus_queue(u
);
4168 unit_add_to_gc_queue(u
);
4170 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
4176 static int log_kill(pid_t pid
, int sig
, void *userdata
) {
4177 _cleanup_free_
char *comm
= NULL
;
4179 (void) get_process_comm(pid
, &comm
);
4181 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
4182 only, like for example systemd's own PAM stub process. */
4183 if (comm
&& comm
[0] == '(')
4186 log_unit_notice(userdata
,
4187 "Killing process " PID_FMT
" (%s) with signal SIG%s.",
4190 signal_to_string(sig
));
4195 static int operation_to_signal(const KillContext
*c
, KillOperation k
, bool *noteworthy
) {
4200 case KILL_TERMINATE
:
4201 case KILL_TERMINATE_AND_LOG
:
4202 *noteworthy
= false;
4203 return c
->kill_signal
;
4206 *noteworthy
= false;
4207 return restart_kill_signal(c
);
4211 return c
->final_kill_signal
;
4215 return c
->watchdog_signal
;
4218 assert_not_reached("KillOperation unknown");
4222 int unit_kill_context(
4228 bool main_pid_alien
) {
4230 bool wait_for_exit
= false, send_sighup
;
4231 cg_kill_log_func_t log_func
= NULL
;
4237 /* Kill the processes belonging to this unit, in preparation for shutting the unit down. Returns > 0
4238 * if we killed something worth waiting for, 0 otherwise. Do not confuse with unit_kill_common()
4239 * which is used for user-requested killing of unit processes. */
4241 if (c
->kill_mode
== KILL_NONE
)
4245 sig
= operation_to_signal(c
, k
, ¬eworthy
);
4247 log_func
= log_kill
;
4251 IN_SET(k
, KILL_TERMINATE
, KILL_TERMINATE_AND_LOG
) &&
4256 log_func(main_pid
, sig
, u
);
4258 r
= kill_and_sigcont(main_pid
, sig
);
4259 if (r
< 0 && r
!= -ESRCH
) {
4260 _cleanup_free_
char *comm
= NULL
;
4261 (void) get_process_comm(main_pid
, &comm
);
4263 log_unit_warning_errno(u
, r
, "Failed to kill main process " PID_FMT
" (%s), ignoring: %m", main_pid
, strna(comm
));
4265 if (!main_pid_alien
)
4266 wait_for_exit
= true;
4268 if (r
!= -ESRCH
&& send_sighup
)
4269 (void) kill(main_pid
, SIGHUP
);
4273 if (control_pid
> 0) {
4275 log_func(control_pid
, sig
, u
);
4277 r
= kill_and_sigcont(control_pid
, sig
);
4278 if (r
< 0 && r
!= -ESRCH
) {
4279 _cleanup_free_
char *comm
= NULL
;
4280 (void) get_process_comm(control_pid
, &comm
);
4282 log_unit_warning_errno(u
, r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m", control_pid
, strna(comm
));
4284 wait_for_exit
= true;
4286 if (r
!= -ESRCH
&& send_sighup
)
4287 (void) kill(control_pid
, SIGHUP
);
4291 if (u
->cgroup_path
&&
4292 (c
->kill_mode
== KILL_CONTROL_GROUP
|| (c
->kill_mode
== KILL_MIXED
&& k
== KILL_KILL
))) {
4293 _cleanup_set_free_ Set
*pid_set
= NULL
;
4295 /* Exclude the main/control pids from being killed via the cgroup */
4296 pid_set
= unit_pid_set(main_pid
, control_pid
);
4300 r
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
4302 CGROUP_SIGCONT
|CGROUP_IGNORE_SELF
,
4306 if (!IN_SET(r
, -EAGAIN
, -ESRCH
, -ENOENT
))
4307 log_unit_warning_errno(u
, r
, "Failed to kill control group %s, ignoring: %m", u
->cgroup_path
);
4311 /* FIXME: For now, on the legacy hierarchy, we will not wait for the cgroup members to die if
4312 * we are running in a container or if this is a delegation unit, simply because cgroup
4313 * notification is unreliable in these cases. It doesn't work at all in containers, and outside
4314 * of containers it can be confused easily by left-over directories in the cgroup — which
4315 * however should not exist in non-delegated units. On the unified hierarchy that's different,
4316 * there we get proper events. Hence rely on them. */
4318 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0 ||
4319 (detect_container() == 0 && !unit_cgroup_delegate(u
)))
4320 wait_for_exit
= true;
4325 pid_set
= unit_pid_set(main_pid
, control_pid
);
4329 (void) cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
4338 return wait_for_exit
;
4341 int unit_require_mounts_for(Unit
*u
, const char *path
, UnitDependencyMask mask
) {
4342 _cleanup_free_
char *p
= NULL
;
4343 UnitDependencyInfo di
;
4349 /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these paths in
4350 * the unit (from the path to the UnitDependencyInfo structure indicating how to the dependency came to
4351 * be). However, we build a prefix table for all possible prefixes so that new appearing mount units can easily
4352 * determine which units to make themselves a dependency of. */
4354 if (!path_is_absolute(path
))
4357 r
= hashmap_ensure_allocated(&u
->requires_mounts_for
, &path_hash_ops
);
4365 path
= path_simplify(p
, true);
4367 if (!path_is_normalized(path
))
4370 if (hashmap_contains(u
->requires_mounts_for
, path
))
4373 di
= (UnitDependencyInfo
) {
4377 r
= hashmap_put(u
->requires_mounts_for
, path
, di
.data
);
4382 char prefix
[strlen(path
) + 1];
4383 PATH_FOREACH_PREFIX_MORE(prefix
, path
) {
4386 x
= hashmap_get(u
->manager
->units_requiring_mounts_for
, prefix
);
4388 _cleanup_free_
char *q
= NULL
;
4390 r
= hashmap_ensure_allocated(&u
->manager
->units_requiring_mounts_for
, &path_hash_ops
);
4402 r
= hashmap_put(u
->manager
->units_requiring_mounts_for
, q
, x
);
4418 int unit_setup_exec_runtime(Unit
*u
) {
4425 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
4428 /* Check if there already is an ExecRuntime for this unit? */
4429 rt
= (ExecRuntime
**) ((uint8_t*) u
+ offset
);
4433 /* Try to get it from somebody else */
4434 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_JOINS_NAMESPACE_OF
]) {
4435 r
= exec_runtime_acquire(u
->manager
, NULL
, other
->id
, false, rt
);
4440 return exec_runtime_acquire(u
->manager
, unit_get_exec_context(u
), u
->id
, true, rt
);
4443 int unit_setup_dynamic_creds(Unit
*u
) {
4445 DynamicCreds
*dcreds
;
4450 offset
= UNIT_VTABLE(u
)->dynamic_creds_offset
;
4452 dcreds
= (DynamicCreds
*) ((uint8_t*) u
+ offset
);
4454 ec
= unit_get_exec_context(u
);
4457 if (!ec
->dynamic_user
)
4460 return dynamic_creds_acquire(dcreds
, u
->manager
, ec
->user
, ec
->group
);
4463 bool unit_type_supported(UnitType t
) {
4464 if (_unlikely_(t
< 0))
4466 if (_unlikely_(t
>= _UNIT_TYPE_MAX
))
4469 if (!unit_vtable
[t
]->supported
)
4472 return unit_vtable
[t
]->supported();
4475 void unit_warn_if_dir_nonempty(Unit
*u
, const char* where
) {
4481 r
= dir_is_empty(where
);
4482 if (r
> 0 || r
== -ENOTDIR
)
4485 log_unit_warning_errno(u
, r
, "Failed to check directory %s: %m", where
);
4489 log_struct(LOG_NOTICE
,
4490 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
4492 LOG_UNIT_INVOCATION_ID(u
),
4493 LOG_UNIT_MESSAGE(u
, "Directory %s to mount over is not empty, mounting anyway.", where
),
4497 int unit_fail_if_noncanonical(Unit
*u
, const char* where
) {
4498 _cleanup_free_
char *canonical_where
= NULL
;
4504 r
= chase_symlinks(where
, NULL
, CHASE_NONEXISTENT
, &canonical_where
, NULL
);
4506 log_unit_debug_errno(u
, r
, "Failed to check %s for symlinks, ignoring: %m", where
);
4510 /* We will happily ignore a trailing slash (or any redundant slashes) */
4511 if (path_equal(where
, canonical_where
))
4514 /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
4516 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
4518 LOG_UNIT_INVOCATION_ID(u
),
4519 LOG_UNIT_MESSAGE(u
, "Mount path %s is not canonical (contains a symlink).", where
),
4525 bool unit_is_pristine(Unit
*u
) {
4528 /* Check if the unit already exists or is already around,
4529 * in a number of different ways. Note that to cater for unit
4530 * types such as slice, we are generally fine with units that
4531 * are marked UNIT_LOADED even though nothing was actually
4532 * loaded, as those unit types don't require a file on disk. */
4534 return !(!IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_LOADED
) ||
4537 !strv_isempty(u
->dropin_paths
) ||
4542 pid_t
unit_control_pid(Unit
*u
) {
4545 if (UNIT_VTABLE(u
)->control_pid
)
4546 return UNIT_VTABLE(u
)->control_pid(u
);
4551 pid_t
unit_main_pid(Unit
*u
) {
4554 if (UNIT_VTABLE(u
)->main_pid
)
4555 return UNIT_VTABLE(u
)->main_pid(u
);
4560 static void unit_unref_uid_internal(
4564 void (*_manager_unref_uid
)(Manager
*m
, uid_t uid
, bool destroy_now
)) {
4568 assert(_manager_unref_uid
);
4570 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
4571 * gid_t are actually the same time, with the same validity rules.
4573 * Drops a reference to UID/GID from a unit. */
4575 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
4576 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
4578 if (!uid_is_valid(*ref_uid
))
4581 _manager_unref_uid(u
->manager
, *ref_uid
, destroy_now
);
4582 *ref_uid
= UID_INVALID
;
4585 static void unit_unref_uid(Unit
*u
, bool destroy_now
) {
4586 unit_unref_uid_internal(u
, &u
->ref_uid
, destroy_now
, manager_unref_uid
);
4589 static void unit_unref_gid(Unit
*u
, bool destroy_now
) {
4590 unit_unref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, destroy_now
, manager_unref_gid
);
4593 void unit_unref_uid_gid(Unit
*u
, bool destroy_now
) {
4596 unit_unref_uid(u
, destroy_now
);
4597 unit_unref_gid(u
, destroy_now
);
4600 static int unit_ref_uid_internal(
4605 int (*_manager_ref_uid
)(Manager
*m
, uid_t uid
, bool clean_ipc
)) {
4611 assert(uid_is_valid(uid
));
4612 assert(_manager_ref_uid
);
4614 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
4615 * are actually the same type, and have the same validity rules.
4617 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
4618 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
4621 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
4622 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
4624 if (*ref_uid
== uid
)
4627 if (uid_is_valid(*ref_uid
)) /* Already set? */
4630 r
= _manager_ref_uid(u
->manager
, uid
, clean_ipc
);
4638 static int unit_ref_uid(Unit
*u
, uid_t uid
, bool clean_ipc
) {
4639 return unit_ref_uid_internal(u
, &u
->ref_uid
, uid
, clean_ipc
, manager_ref_uid
);
4642 static int unit_ref_gid(Unit
*u
, gid_t gid
, bool clean_ipc
) {
4643 return unit_ref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, (uid_t
) gid
, clean_ipc
, manager_ref_gid
);
4646 static int unit_ref_uid_gid_internal(Unit
*u
, uid_t uid
, gid_t gid
, bool clean_ipc
) {
4651 /* Reference both a UID and a GID in one go. Either references both, or neither. */
4653 if (uid_is_valid(uid
)) {
4654 r
= unit_ref_uid(u
, uid
, clean_ipc
);
4659 if (gid_is_valid(gid
)) {
4660 q
= unit_ref_gid(u
, gid
, clean_ipc
);
4663 unit_unref_uid(u
, false);
4669 return r
> 0 || q
> 0;
4672 int unit_ref_uid_gid(Unit
*u
, uid_t uid
, gid_t gid
) {
4678 c
= unit_get_exec_context(u
);
4680 r
= unit_ref_uid_gid_internal(u
, uid
, gid
, c
? c
->remove_ipc
: false);
4682 return log_unit_warning_errno(u
, r
, "Couldn't add UID/GID reference to unit, proceeding without: %m");
4687 void unit_notify_user_lookup(Unit
*u
, uid_t uid
, gid_t gid
) {
4692 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
4693 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
4694 * objects when no service references the UID/GID anymore. */
4696 r
= unit_ref_uid_gid(u
, uid
, gid
);
4698 unit_add_to_dbus_queue(u
);
4701 int unit_acquire_invocation_id(Unit
*u
) {
4707 r
= sd_id128_randomize(&id
);
4709 return log_unit_error_errno(u
, r
, "Failed to generate invocation ID for unit: %m");
4711 r
= unit_set_invocation_id(u
, id
);
4713 return log_unit_error_errno(u
, r
, "Failed to set invocation ID for unit: %m");
4715 unit_add_to_dbus_queue(u
);
4719 int unit_set_exec_params(Unit
*u
, ExecParameters
*p
) {
4725 /* Copy parameters from manager */
4726 r
= manager_get_effective_environment(u
->manager
, &p
->environment
);
4730 p
->confirm_spawn
= manager_get_confirm_spawn(u
->manager
);
4731 p
->cgroup_supported
= u
->manager
->cgroup_supported
;
4732 p
->prefix
= u
->manager
->prefix
;
4733 SET_FLAG(p
->flags
, EXEC_PASS_LOG_UNIT
|EXEC_CHOWN_DIRECTORIES
, MANAGER_IS_SYSTEM(u
->manager
));
4735 /* Copy parameters from unit */
4736 p
->cgroup_path
= u
->cgroup_path
;
4737 SET_FLAG(p
->flags
, EXEC_CGROUP_DELEGATE
, unit_cgroup_delegate(u
));
4739 p
->received_credentials
= u
->manager
->received_credentials
;
4744 int unit_fork_helper_process(Unit
*u
, const char *name
, pid_t
*ret
) {
4750 /* Forks off a helper process and makes sure it is a member of the unit's cgroup. Returns == 0 in the child,
4751 * and > 0 in the parent. The pid parameter is always filled in with the child's PID. */
4753 (void) unit_realize_cgroup(u
);
4755 r
= safe_fork(name
, FORK_REOPEN_LOG
, ret
);
4759 (void) default_signals(SIGNALS_CRASH_HANDLER
, SIGNALS_IGNORE
);
4760 (void) ignore_signals(SIGPIPE
);
4762 (void) prctl(PR_SET_PDEATHSIG
, SIGTERM
);
4764 if (u
->cgroup_path
) {
4765 r
= cg_attach_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, 0, NULL
, NULL
);
4767 log_unit_error_errno(u
, r
, "Failed to join unit cgroup %s: %m", u
->cgroup_path
);
4775 int unit_fork_and_watch_rm_rf(Unit
*u
, char **paths
, pid_t
*ret_pid
) {
4782 r
= unit_fork_helper_process(u
, "(sd-rmrf)", &pid
);
4786 int ret
= EXIT_SUCCESS
;
4789 STRV_FOREACH(i
, paths
) {
4790 r
= rm_rf(*i
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_MISSING_OK
);
4792 log_error_errno(r
, "Failed to remove '%s': %m", *i
);
4800 r
= unit_watch_pid(u
, pid
, true);
4808 static void unit_update_dependency_mask(Unit
*u
, UnitDependency d
, Unit
*other
, UnitDependencyInfo di
) {
4811 assert(d
< _UNIT_DEPENDENCY_MAX
);
4814 if (di
.origin_mask
== 0 && di
.destination_mask
== 0) {
4815 /* No bit set anymore, let's drop the whole entry */
4816 assert_se(hashmap_remove(u
->dependencies
[d
], other
));
4817 log_unit_debug(u
, "lost dependency %s=%s", unit_dependency_to_string(d
), other
->id
);
4819 /* Mask was reduced, let's update the entry */
4820 assert_se(hashmap_update(u
->dependencies
[d
], other
, di
.data
) == 0);
4823 void unit_remove_dependencies(Unit
*u
, UnitDependencyMask mask
) {
4826 /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
4831 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
4835 UnitDependencyInfo di
;
4840 HASHMAP_FOREACH_KEY(di
.data
, other
, u
->dependencies
[d
]) {
4841 if (FLAGS_SET(~mask
, di
.origin_mask
))
4843 di
.origin_mask
&= ~mask
;
4844 unit_update_dependency_mask(u
, d
, other
, di
);
4846 /* We updated the dependency from our unit to the other unit now. But most dependencies
4847 * imply a reverse dependency. Hence, let's delete that one too. For that we go through
4848 * all dependency types on the other unit and delete all those which point to us and
4849 * have the right mask set. */
4851 for (UnitDependency q
= 0; q
< _UNIT_DEPENDENCY_MAX
; q
++) {
4852 UnitDependencyInfo dj
;
4854 dj
.data
= hashmap_get(other
->dependencies
[q
], u
);
4855 if (FLAGS_SET(~mask
, dj
.destination_mask
))
4857 dj
.destination_mask
&= ~mask
;
4859 unit_update_dependency_mask(other
, q
, u
, dj
);
4862 unit_add_to_gc_queue(other
);
4872 static int unit_get_invocation_path(Unit
*u
, char **ret
) {
4879 if (MANAGER_IS_SYSTEM(u
->manager
))
4880 p
= strjoin("/run/systemd/units/invocation:", u
->id
);
4882 _cleanup_free_
char *user_path
= NULL
;
4883 r
= xdg_user_runtime_dir(&user_path
, "/systemd/units/invocation:");
4886 p
= strjoin(user_path
, u
->id
);
4896 static int unit_export_invocation_id(Unit
*u
) {
4897 _cleanup_free_
char *p
= NULL
;
4902 if (u
->exported_invocation_id
)
4905 if (sd_id128_is_null(u
->invocation_id
))
4908 r
= unit_get_invocation_path(u
, &p
);
4910 return log_unit_debug_errno(u
, r
, "Failed to get invocation path: %m");
4912 r
= symlink_atomic_label(u
->invocation_id_string
, p
);
4914 return log_unit_debug_errno(u
, r
, "Failed to create invocation ID symlink %s: %m", p
);
4916 u
->exported_invocation_id
= true;
4920 static int unit_export_log_level_max(Unit
*u
, const ExecContext
*c
) {
4928 if (u
->exported_log_level_max
)
4931 if (c
->log_level_max
< 0)
4934 assert(c
->log_level_max
<= 7);
4936 buf
[0] = '0' + c
->log_level_max
;
4939 p
= strjoina("/run/systemd/units/log-level-max:", u
->id
);
4940 r
= symlink_atomic(buf
, p
);
4942 return log_unit_debug_errno(u
, r
, "Failed to create maximum log level symlink %s: %m", p
);
4944 u
->exported_log_level_max
= true;
4948 static int unit_export_log_extra_fields(Unit
*u
, const ExecContext
*c
) {
4949 _cleanup_close_
int fd
= -1;
4950 struct iovec
*iovec
;
4957 if (u
->exported_log_extra_fields
)
4960 if (c
->n_log_extra_fields
<= 0)
4963 sizes
= newa(le64_t
, c
->n_log_extra_fields
);
4964 iovec
= newa(struct iovec
, c
->n_log_extra_fields
* 2);
4966 for (size_t i
= 0; i
< c
->n_log_extra_fields
; i
++) {
4967 sizes
[i
] = htole64(c
->log_extra_fields
[i
].iov_len
);
4969 iovec
[i
*2] = IOVEC_MAKE(sizes
+ i
, sizeof(le64_t
));
4970 iovec
[i
*2+1] = c
->log_extra_fields
[i
];
4973 p
= strjoina("/run/systemd/units/log-extra-fields:", u
->id
);
4974 pattern
= strjoina(p
, ".XXXXXX");
4976 fd
= mkostemp_safe(pattern
);
4978 return log_unit_debug_errno(u
, fd
, "Failed to create extra fields file %s: %m", p
);
4980 n
= writev(fd
, iovec
, c
->n_log_extra_fields
*2);
4982 r
= log_unit_debug_errno(u
, errno
, "Failed to write extra fields: %m");
4986 (void) fchmod(fd
, 0644);
4988 if (rename(pattern
, p
) < 0) {
4989 r
= log_unit_debug_errno(u
, errno
, "Failed to rename extra fields file: %m");
4993 u
->exported_log_extra_fields
= true;
4997 (void) unlink(pattern
);
5001 static int unit_export_log_ratelimit_interval(Unit
*u
, const ExecContext
*c
) {
5002 _cleanup_free_
char *buf
= NULL
;
5009 if (u
->exported_log_ratelimit_interval
)
5012 if (c
->log_ratelimit_interval_usec
== 0)
5015 p
= strjoina("/run/systemd/units/log-rate-limit-interval:", u
->id
);
5017 if (asprintf(&buf
, "%" PRIu64
, c
->log_ratelimit_interval_usec
) < 0)
5020 r
= symlink_atomic(buf
, p
);
5022 return log_unit_debug_errno(u
, r
, "Failed to create log rate limit interval symlink %s: %m", p
);
5024 u
->exported_log_ratelimit_interval
= true;
5028 static int unit_export_log_ratelimit_burst(Unit
*u
, const ExecContext
*c
) {
5029 _cleanup_free_
char *buf
= NULL
;
5036 if (u
->exported_log_ratelimit_burst
)
5039 if (c
->log_ratelimit_burst
== 0)
5042 p
= strjoina("/run/systemd/units/log-rate-limit-burst:", u
->id
);
5044 if (asprintf(&buf
, "%u", c
->log_ratelimit_burst
) < 0)
5047 r
= symlink_atomic(buf
, p
);
5049 return log_unit_debug_errno(u
, r
, "Failed to create log rate limit burst symlink %s: %m", p
);
5051 u
->exported_log_ratelimit_burst
= true;
5055 void unit_export_state_files(Unit
*u
) {
5056 const ExecContext
*c
;
5063 if (MANAGER_IS_TEST_RUN(u
->manager
))
5066 /* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
5067 * from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
5068 * the IPC system itself and PID 1 also log to the journal.
5070 * Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
5071 * IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
5072 * apply to communication between the journal and systemd, as we assume that these two daemons live in the same
5073 * namespace at least.
5075 * Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
5076 * better for storing small bits of data, in particular as we can write them with two system calls, and read
5079 (void) unit_export_invocation_id(u
);
5081 if (!MANAGER_IS_SYSTEM(u
->manager
))
5084 c
= unit_get_exec_context(u
);
5086 (void) unit_export_log_level_max(u
, c
);
5087 (void) unit_export_log_extra_fields(u
, c
);
5088 (void) unit_export_log_ratelimit_interval(u
, c
);
5089 (void) unit_export_log_ratelimit_burst(u
, c
);
5093 void unit_unlink_state_files(Unit
*u
) {
5101 /* Undoes the effect of unit_export_state() */
5103 if (u
->exported_invocation_id
) {
5104 _cleanup_free_
char *invocation_path
= NULL
;
5105 int r
= unit_get_invocation_path(u
, &invocation_path
);
5107 (void) unlink(invocation_path
);
5108 u
->exported_invocation_id
= false;
5112 if (!MANAGER_IS_SYSTEM(u
->manager
))
5115 if (u
->exported_log_level_max
) {
5116 p
= strjoina("/run/systemd/units/log-level-max:", u
->id
);
5119 u
->exported_log_level_max
= false;
5122 if (u
->exported_log_extra_fields
) {
5123 p
= strjoina("/run/systemd/units/extra-fields:", u
->id
);
5126 u
->exported_log_extra_fields
= false;
5129 if (u
->exported_log_ratelimit_interval
) {
5130 p
= strjoina("/run/systemd/units/log-rate-limit-interval:", u
->id
);
5133 u
->exported_log_ratelimit_interval
= false;
5136 if (u
->exported_log_ratelimit_burst
) {
5137 p
= strjoina("/run/systemd/units/log-rate-limit-burst:", u
->id
);
5140 u
->exported_log_ratelimit_burst
= false;
5144 int unit_prepare_exec(Unit
*u
) {
5149 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
5150 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
5151 r
= bpf_firewall_load_custom(u
);
5155 /* Prepares everything so that we can fork of a process for this unit */
5157 (void) unit_realize_cgroup(u
);
5159 if (u
->reset_accounting
) {
5160 (void) unit_reset_accounting(u
);
5161 u
->reset_accounting
= false;
5164 unit_export_state_files(u
);
5166 r
= unit_setup_exec_runtime(u
);
5170 r
= unit_setup_dynamic_creds(u
);
5177 static bool ignore_leftover_process(const char *comm
) {
5178 return comm
&& comm
[0] == '('; /* Most likely our own helper process (PAM?), ignore */
5181 int unit_log_leftover_process_start(pid_t pid
, int sig
, void *userdata
) {
5182 _cleanup_free_
char *comm
= NULL
;
5184 (void) get_process_comm(pid
, &comm
);
5186 if (ignore_leftover_process(comm
))
5189 /* During start we print a warning */
5191 log_unit_warning(userdata
,
5192 "Found left-over process " PID_FMT
" (%s) in control group while starting unit. Ignoring.\n"
5193 "This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
5199 int unit_log_leftover_process_stop(pid_t pid
, int sig
, void *userdata
) {
5200 _cleanup_free_
char *comm
= NULL
;
5202 (void) get_process_comm(pid
, &comm
);
5204 if (ignore_leftover_process(comm
))
5207 /* During stop we only print an informational message */
5209 log_unit_info(userdata
,
5210 "Unit process " PID_FMT
" (%s) remains running after unit stopped.",
5216 int unit_warn_leftover_processes(Unit
*u
, cg_kill_log_func_t log_func
) {
5219 (void) unit_pick_cgroup_path(u
);
5221 if (!u
->cgroup_path
)
5224 return cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, 0, 0, NULL
, log_func
, u
);
5227 bool unit_needs_console(Unit
*u
) {
5229 UnitActiveState state
;
5233 state
= unit_active_state(u
);
5235 if (UNIT_IS_INACTIVE_OR_FAILED(state
))
5238 if (UNIT_VTABLE(u
)->needs_console
)
5239 return UNIT_VTABLE(u
)->needs_console(u
);
5241 /* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
5242 ec
= unit_get_exec_context(u
);
5246 return exec_context_may_touch_console(ec
);
5249 const char *unit_label_path(const Unit
*u
) {
5254 /* Returns the file system path to use for MAC access decisions, i.e. the file to read the SELinux label off
5255 * when validating access checks. */
5257 p
= u
->source_path
?: u
->fragment_path
;
5261 /* If a unit is masked, then don't read the SELinux label of /dev/null, as that really makes no sense */
5262 if (null_or_empty_path(p
) > 0)
5268 int unit_pid_attachable(Unit
*u
, pid_t pid
, sd_bus_error
*error
) {
5273 /* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
5274 * and not a kernel thread either */
5276 /* First, a simple range check */
5277 if (!pid_is_valid(pid
))
5278 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process identifier " PID_FMT
" is not valid.", pid
);
5280 /* Some extra safety check */
5281 if (pid
== 1 || pid
== getpid_cached())
5282 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process " PID_FMT
" is a manager process, refusing.", pid
);
5284 /* Don't even begin to bother with kernel threads */
5285 r
= is_kernel_thread(pid
);
5287 return sd_bus_error_setf(error
, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN
, "Process with ID " PID_FMT
" does not exist.", pid
);
5289 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether process " PID_FMT
" is a kernel thread: %m", pid
);
5291 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process " PID_FMT
" is a kernel thread, refusing.", pid
);
5296 void unit_log_success(Unit
*u
) {
5299 log_struct(LOG_INFO
,
5300 "MESSAGE_ID=" SD_MESSAGE_UNIT_SUCCESS_STR
,
5302 LOG_UNIT_INVOCATION_ID(u
),
5303 LOG_UNIT_MESSAGE(u
, "Deactivated successfully."));
5306 void unit_log_failure(Unit
*u
, const char *result
) {
5310 log_struct(LOG_WARNING
,
5311 "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILURE_RESULT_STR
,
5313 LOG_UNIT_INVOCATION_ID(u
),
5314 LOG_UNIT_MESSAGE(u
, "Failed with result '%s'.", result
),
5315 "UNIT_RESULT=%s", result
);
5318 void unit_log_skip(Unit
*u
, const char *result
) {
5322 log_struct(LOG_INFO
,
5323 "MESSAGE_ID=" SD_MESSAGE_UNIT_SKIPPED_STR
,
5325 LOG_UNIT_INVOCATION_ID(u
),
5326 LOG_UNIT_MESSAGE(u
, "Skipped due to '%s'.", result
),
5327 "UNIT_RESULT=%s", result
);
5330 void unit_log_process_exit(
5333 const char *command
,
5343 /* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
5344 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
5345 * that the service already logged the reason at a higher log level on its own. Otherwise, make it a
5349 else if (code
== CLD_EXITED
)
5352 level
= LOG_WARNING
;
5355 "MESSAGE_ID=" SD_MESSAGE_UNIT_PROCESS_EXIT_STR
,
5356 LOG_UNIT_MESSAGE(u
, "%s exited, code=%s, status=%i/%s",
5358 sigchld_code_to_string(code
), status
,
5359 strna(code
== CLD_EXITED
5360 ? exit_status_to_string(status
, EXIT_STATUS_FULL
)
5361 : signal_to_string(status
))),
5362 "EXIT_CODE=%s", sigchld_code_to_string(code
),
5363 "EXIT_STATUS=%i", status
,
5364 "COMMAND=%s", strna(command
),
5366 LOG_UNIT_INVOCATION_ID(u
));
5369 int unit_exit_status(Unit
*u
) {
5372 /* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
5373 * 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
5374 * if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
5375 * service process has exited abnormally (signal/coredump). */
5377 if (!UNIT_VTABLE(u
)->exit_status
)
5380 return UNIT_VTABLE(u
)->exit_status(u
);
5383 int unit_failure_action_exit_status(Unit
*u
) {
5388 /* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
5390 if (u
->failure_action_exit_status
>= 0)
5391 return u
->failure_action_exit_status
;
5393 r
= unit_exit_status(u
);
5394 if (r
== -EBADE
) /* Exited, but not cleanly (i.e. by signal or such) */
5400 int unit_success_action_exit_status(Unit
*u
) {
5405 /* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
5407 if (u
->success_action_exit_status
>= 0)
5408 return u
->success_action_exit_status
;
5410 r
= unit_exit_status(u
);
5411 if (r
== -EBADE
) /* Exited, but not cleanly (i.e. by signal or such) */
5417 int unit_test_trigger_loaded(Unit
*u
) {
5420 /* Tests whether the unit to trigger is loaded */
5422 trigger
= UNIT_TRIGGER(u
);
5424 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
5425 "Refusing to start, no unit to trigger.");
5426 if (trigger
->load_state
!= UNIT_LOADED
)
5427 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
5428 "Refusing to start, unit %s to trigger not loaded.", trigger
->id
);
5433 void unit_destroy_runtime_data(Unit
*u
, const ExecContext
*context
) {
5437 if (context
->runtime_directory_preserve_mode
== EXEC_PRESERVE_NO
||
5438 (context
->runtime_directory_preserve_mode
== EXEC_PRESERVE_RESTART
&& !unit_will_restart(u
)))
5439 exec_context_destroy_runtime_directory(context
, u
->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
5441 exec_context_destroy_credentials(context
, u
->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
], u
->id
);
5444 int unit_clean(Unit
*u
, ExecCleanMask mask
) {
5445 UnitActiveState state
;
5449 /* Special return values:
5451 * -EOPNOTSUPP → cleaning not supported for this unit type
5452 * -EUNATCH → cleaning not defined for this resource type
5453 * -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
5454 * a job queued or similar
5457 if (!UNIT_VTABLE(u
)->clean
)
5463 if (u
->load_state
!= UNIT_LOADED
)
5469 state
= unit_active_state(u
);
5470 if (!IN_SET(state
, UNIT_INACTIVE
))
5473 return UNIT_VTABLE(u
)->clean(u
, mask
);
5476 int unit_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
5479 if (!UNIT_VTABLE(u
)->clean
||
5480 u
->load_state
!= UNIT_LOADED
) {
5485 /* When the clean() method is set, can_clean() really should be set too */
5486 assert(UNIT_VTABLE(u
)->can_clean
);
5488 return UNIT_VTABLE(u
)->can_clean(u
, ret
);
5491 bool unit_can_freeze(Unit
*u
) {
5494 if (UNIT_VTABLE(u
)->can_freeze
)
5495 return UNIT_VTABLE(u
)->can_freeze(u
);
5497 return UNIT_VTABLE(u
)->freeze
;
5500 void unit_frozen(Unit
*u
) {
5503 u
->freezer_state
= FREEZER_FROZEN
;
5505 bus_unit_send_pending_freezer_message(u
);
5508 void unit_thawed(Unit
*u
) {
5511 u
->freezer_state
= FREEZER_RUNNING
;
5513 bus_unit_send_pending_freezer_message(u
);
5516 static int unit_freezer_action(Unit
*u
, FreezerAction action
) {
5518 int (*method
)(Unit
*);
5522 assert(IN_SET(action
, FREEZER_FREEZE
, FREEZER_THAW
));
5524 method
= action
== FREEZER_FREEZE
? UNIT_VTABLE(u
)->freeze
: UNIT_VTABLE(u
)->thaw
;
5525 if (!method
|| !cg_freezer_supported())
5531 if (u
->load_state
!= UNIT_LOADED
)
5534 s
= unit_active_state(u
);
5535 if (s
!= UNIT_ACTIVE
)
5538 if (IN_SET(u
->freezer_state
, FREEZER_FREEZING
, FREEZER_THAWING
))
5548 int unit_freeze(Unit
*u
) {
5549 return unit_freezer_action(u
, FREEZER_FREEZE
);
5552 int unit_thaw(Unit
*u
) {
5553 return unit_freezer_action(u
, FREEZER_THAW
);
5556 /* Wrappers around low-level cgroup freezer operations common for service and scope units */
5557 int unit_freeze_vtable_common(Unit
*u
) {
5558 return unit_cgroup_freezer_action(u
, FREEZER_FREEZE
);
5561 int unit_thaw_vtable_common(Unit
*u
) {
5562 return unit_cgroup_freezer_action(u
, FREEZER_THAW
);
5565 static const char* const collect_mode_table
[_COLLECT_MODE_MAX
] = {
5566 [COLLECT_INACTIVE
] = "inactive",
5567 [COLLECT_INACTIVE_OR_FAILED
] = "inactive-or-failed",
5570 DEFINE_STRING_TABLE_LOOKUP(collect_mode
, CollectMode
);