1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 "dbus-unit.h"
24 #include "fileio-label.h"
26 #include "format-util.h"
28 #include "id128-util.h"
31 #include "load-dropin.h"
32 #include "load-fragment.h"
35 #include "missing_audit.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "process-util.h"
41 #include "serialize.h"
43 #include "signal-util.h"
44 #include "sparse-endian.h"
46 #include "specifier.h"
47 #include "stat-util.h"
48 #include "stdio-util.h"
49 #include "string-table.h"
50 #include "string-util.h"
52 #include "terminal-util.h"
53 #include "tmpfile-util.h"
54 #include "umask-util.h"
55 #include "unit-name.h"
57 #include "user-util.h"
60 /* Thresholds for logging at INFO level about resource consumption */
61 #define MENTIONWORTHY_CPU_NSEC (1 * NSEC_PER_SEC)
62 #define MENTIONWORTHY_IO_BYTES (1024 * 1024ULL)
63 #define MENTIONWORTHY_IP_BYTES (0ULL)
65 /* Thresholds for logging at INFO level about resource consumption */
66 #define NOTICEWORTHY_CPU_NSEC (10*60 * NSEC_PER_SEC) /* 10 minutes */
67 #define NOTICEWORTHY_IO_BYTES (10 * 1024 * 1024ULL) /* 10 MB */
68 #define NOTICEWORTHY_IP_BYTES (128 * 1024 * 1024ULL) /* 128 MB */
70 const UnitVTable
* const unit_vtable
[_UNIT_TYPE_MAX
] = {
71 [UNIT_SERVICE
] = &service_vtable
,
72 [UNIT_SOCKET
] = &socket_vtable
,
73 [UNIT_TARGET
] = &target_vtable
,
74 [UNIT_DEVICE
] = &device_vtable
,
75 [UNIT_MOUNT
] = &mount_vtable
,
76 [UNIT_AUTOMOUNT
] = &automount_vtable
,
77 [UNIT_SWAP
] = &swap_vtable
,
78 [UNIT_TIMER
] = &timer_vtable
,
79 [UNIT_PATH
] = &path_vtable
,
80 [UNIT_SLICE
] = &slice_vtable
,
81 [UNIT_SCOPE
] = &scope_vtable
,
84 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
);
86 Unit
*unit_new(Manager
*m
, size_t size
) {
90 assert(size
>= sizeof(Unit
));
96 u
->names
= set_new(&string_hash_ops
);
101 u
->type
= _UNIT_TYPE_INVALID
;
102 u
->default_dependencies
= true;
103 u
->unit_file_state
= _UNIT_FILE_STATE_INVALID
;
104 u
->unit_file_preset
= -1;
105 u
->on_failure_job_mode
= JOB_REPLACE
;
106 u
->cgroup_control_inotify_wd
= -1;
107 u
->cgroup_memory_inotify_wd
= -1;
108 u
->job_timeout
= USEC_INFINITY
;
109 u
->job_running_timeout
= USEC_INFINITY
;
110 u
->ref_uid
= UID_INVALID
;
111 u
->ref_gid
= GID_INVALID
;
112 u
->cpu_usage_last
= NSEC_INFINITY
;
113 u
->cgroup_invalidated_mask
|= CGROUP_MASK_BPF_FIREWALL
;
114 u
->failure_action_exit_status
= u
->success_action_exit_status
= -1;
116 u
->ip_accounting_ingress_map_fd
= -1;
117 u
->ip_accounting_egress_map_fd
= -1;
118 u
->ipv4_allow_map_fd
= -1;
119 u
->ipv6_allow_map_fd
= -1;
120 u
->ipv4_deny_map_fd
= -1;
121 u
->ipv6_deny_map_fd
= -1;
123 u
->last_section_private
= -1;
125 u
->start_ratelimit
= (RateLimit
) { m
->default_start_limit_interval
, m
->default_start_limit_burst
};
126 u
->auto_stop_ratelimit
= (RateLimit
) { 10 * USEC_PER_SEC
, 16 };
128 for (CGroupIOAccountingMetric i
= 0; i
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; i
++)
129 u
->io_accounting_last
[i
] = UINT64_MAX
;
134 int unit_new_for_name(Manager
*m
, size_t size
, const char *name
, Unit
**ret
) {
135 _cleanup_(unit_freep
) Unit
*u
= NULL
;
138 u
= unit_new(m
, size
);
142 r
= unit_add_name(u
, name
);
151 bool unit_has_name(const Unit
*u
, const char *name
) {
155 return set_contains(u
->names
, (char*) name
);
158 static void unit_init(Unit
*u
) {
165 assert(u
->type
>= 0);
167 cc
= unit_get_cgroup_context(u
);
169 cgroup_context_init(cc
);
171 /* Copy in the manager defaults into the cgroup
172 * context, _before_ the rest of the settings have
173 * been initialized */
175 cc
->cpu_accounting
= u
->manager
->default_cpu_accounting
;
176 cc
->io_accounting
= u
->manager
->default_io_accounting
;
177 cc
->blockio_accounting
= u
->manager
->default_blockio_accounting
;
178 cc
->memory_accounting
= u
->manager
->default_memory_accounting
;
179 cc
->tasks_accounting
= u
->manager
->default_tasks_accounting
;
180 cc
->ip_accounting
= u
->manager
->default_ip_accounting
;
182 if (u
->type
!= UNIT_SLICE
)
183 cc
->tasks_max
= u
->manager
->default_tasks_max
;
186 ec
= unit_get_exec_context(u
);
188 exec_context_init(ec
);
190 if (MANAGER_IS_SYSTEM(u
->manager
))
191 ec
->keyring_mode
= EXEC_KEYRING_SHARED
;
193 ec
->keyring_mode
= EXEC_KEYRING_INHERIT
;
195 /* User manager might have its umask redefined by PAM or UMask=. In this
196 * case let the units it manages inherit this value by default. They can
197 * still tune this value through their own unit file */
198 (void) get_process_umask(getpid_cached(), &ec
->umask
);
202 kc
= unit_get_kill_context(u
);
204 kill_context_init(kc
);
206 if (UNIT_VTABLE(u
)->init
)
207 UNIT_VTABLE(u
)->init(u
);
210 int unit_add_name(Unit
*u
, const char *text
) {
211 _cleanup_free_
char *s
= NULL
, *i
= NULL
;
218 if (unit_name_is_valid(text
, UNIT_NAME_TEMPLATE
)) {
221 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
222 "instance is not set when adding name '%s': %m", text
);
224 r
= unit_name_replace_instance(text
, u
->instance
, &s
);
226 return log_unit_debug_errno(u
, r
,
227 "failed to build instance name from '%s': %m", text
);
234 if (set_contains(u
->names
, s
))
236 if (hashmap_contains(u
->manager
->units
, s
))
237 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EEXIST
),
238 "unit already exist when adding name '%s': %m", text
);
240 if (!unit_name_is_valid(s
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
241 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
242 "name '%s' is invalid: %m", text
);
244 t
= unit_name_to_type(s
);
246 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
247 "failed to to derive unit type from name '%s': %m", text
);
249 if (u
->type
!= _UNIT_TYPE_INVALID
&& t
!= u
->type
)
250 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
251 "unit type is illegal: u->type(%d) and t(%d) for name '%s': %m",
254 r
= unit_name_to_instance(s
, &i
);
256 return log_unit_debug_errno(u
, r
, "failed to extract instance from name '%s': %m", text
);
258 if (i
&& !unit_type_may_template(t
))
259 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
), "templates are not allowed for name '%s': %m", text
);
261 /* Ensure that this unit is either instanced or not instanced,
262 * but not both. Note that we do allow names with different
263 * instance names however! */
264 if (u
->type
!= _UNIT_TYPE_INVALID
&& !u
->instance
!= !i
)
265 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
266 "instance is illegal: u->type(%d), u->instance(%s) and i(%s) for name '%s': %m",
267 u
->type
, u
->instance
, i
, text
);
269 if (!unit_type_may_alias(t
) && !set_isempty(u
->names
))
270 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EEXIST
), "symlinks are not allowed for name '%s': %m", text
);
272 if (hashmap_size(u
->manager
->units
) >= MANAGER_MAX_NAMES
)
273 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(E2BIG
), "too many units: %m");
275 r
= set_put(u
->names
, s
);
280 r
= hashmap_put(u
->manager
->units
, s
, u
);
282 (void) set_remove(u
->names
, s
);
283 return log_unit_debug_errno(u
, r
, "add unit to hashmap failed for name '%s': %m", text
);
286 if (u
->type
== _UNIT_TYPE_INVALID
) {
289 u
->instance
= TAKE_PTR(i
);
291 LIST_PREPEND(units_by_type
, u
->manager
->units_by_type
[t
], u
);
298 unit_add_to_dbus_queue(u
);
302 int unit_choose_id(Unit
*u
, const char *name
) {
303 _cleanup_free_
char *t
= NULL
;
310 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
315 r
= unit_name_replace_instance(name
, u
->instance
, &t
);
322 /* Selects one of the names of this unit as the id */
323 s
= set_get(u
->names
, (char*) name
);
327 /* Determine the new instance from the new id */
328 r
= unit_name_to_instance(s
, &i
);
337 unit_add_to_dbus_queue(u
);
342 int unit_set_description(Unit
*u
, const char *description
) {
347 r
= free_and_strdup(&u
->description
, empty_to_null(description
));
351 unit_add_to_dbus_queue(u
);
356 bool unit_may_gc(Unit
*u
) {
357 UnitActiveState state
;
362 /* Checks whether the unit is ready to be unloaded for garbage collection.
363 * Returns true when the unit may be collected, and false if there's some
364 * reason to keep it loaded.
366 * References from other units are *not* checked here. Instead, this is done
367 * in unit_gc_sweep(), but using markers to properly collect dependency loops.
376 state
= unit_active_state(u
);
378 /* If the unit is inactive and failed and no job is queued for it, then release its runtime resources */
379 if (UNIT_IS_INACTIVE_OR_FAILED(state
) &&
380 UNIT_VTABLE(u
)->release_resources
)
381 UNIT_VTABLE(u
)->release_resources(u
);
386 if (sd_bus_track_count(u
->bus_track
) > 0)
389 /* But we keep the unit object around for longer when it is referenced or configured to not be gc'ed */
390 switch (u
->collect_mode
) {
392 case COLLECT_INACTIVE
:
393 if (state
!= UNIT_INACTIVE
)
398 case COLLECT_INACTIVE_OR_FAILED
:
399 if (!IN_SET(state
, UNIT_INACTIVE
, UNIT_FAILED
))
405 assert_not_reached("Unknown garbage collection mode");
408 if (u
->cgroup_path
) {
409 /* If the unit has a cgroup, then check whether there's anything in it. If so, we should stay
410 * around. Units with active processes should never be collected. */
412 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
414 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
419 if (UNIT_VTABLE(u
)->may_gc
&& !UNIT_VTABLE(u
)->may_gc(u
))
425 void unit_add_to_load_queue(Unit
*u
) {
427 assert(u
->type
!= _UNIT_TYPE_INVALID
);
429 if (u
->load_state
!= UNIT_STUB
|| u
->in_load_queue
)
432 LIST_PREPEND(load_queue
, u
->manager
->load_queue
, u
);
433 u
->in_load_queue
= true;
436 void unit_add_to_cleanup_queue(Unit
*u
) {
439 if (u
->in_cleanup_queue
)
442 LIST_PREPEND(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
443 u
->in_cleanup_queue
= true;
446 void unit_add_to_gc_queue(Unit
*u
) {
449 if (u
->in_gc_queue
|| u
->in_cleanup_queue
)
455 LIST_PREPEND(gc_queue
, u
->manager
->gc_unit_queue
, u
);
456 u
->in_gc_queue
= true;
459 void unit_add_to_dbus_queue(Unit
*u
) {
461 assert(u
->type
!= _UNIT_TYPE_INVALID
);
463 if (u
->load_state
== UNIT_STUB
|| u
->in_dbus_queue
)
466 /* Shortcut things if nobody cares */
467 if (sd_bus_track_count(u
->manager
->subscribed
) <= 0 &&
468 sd_bus_track_count(u
->bus_track
) <= 0 &&
469 set_isempty(u
->manager
->private_buses
)) {
470 u
->sent_dbus_new_signal
= true;
474 LIST_PREPEND(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
475 u
->in_dbus_queue
= true;
478 void unit_submit_to_stop_when_unneeded_queue(Unit
*u
) {
481 if (u
->in_stop_when_unneeded_queue
)
484 if (!u
->stop_when_unneeded
)
487 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
)))
490 LIST_PREPEND(stop_when_unneeded_queue
, u
->manager
->stop_when_unneeded_queue
, u
);
491 u
->in_stop_when_unneeded_queue
= true;
494 static void bidi_set_free(Unit
*u
, Hashmap
*h
) {
501 /* Frees the hashmap and makes sure we are dropped from the inverse pointers */
503 HASHMAP_FOREACH_KEY(v
, other
, h
, i
) {
506 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
507 hashmap_remove(other
->dependencies
[d
], u
);
509 unit_add_to_gc_queue(other
);
515 static void unit_remove_transient(Unit
*u
) {
523 if (u
->fragment_path
)
524 (void) unlink(u
->fragment_path
);
526 STRV_FOREACH(i
, u
->dropin_paths
) {
527 _cleanup_free_
char *p
= NULL
, *pp
= NULL
;
529 p
= dirname_malloc(*i
); /* Get the drop-in directory from the drop-in file */
533 pp
= dirname_malloc(p
); /* Get the config directory from the drop-in directory */
537 /* Only drop transient drop-ins */
538 if (!path_equal(u
->manager
->lookup_paths
.transient
, pp
))
546 static void unit_free_requires_mounts_for(Unit
*u
) {
550 _cleanup_free_
char *path
;
552 path
= hashmap_steal_first_key(u
->requires_mounts_for
);
556 char s
[strlen(path
) + 1];
558 PATH_FOREACH_PREFIX_MORE(s
, path
) {
562 x
= hashmap_get2(u
->manager
->units_requiring_mounts_for
, s
, (void**) &y
);
566 (void) set_remove(x
, u
);
568 if (set_isempty(x
)) {
569 (void) hashmap_remove(u
->manager
->units_requiring_mounts_for
, y
);
577 u
->requires_mounts_for
= hashmap_free(u
->requires_mounts_for
);
580 static void unit_done(Unit
*u
) {
589 if (UNIT_VTABLE(u
)->done
)
590 UNIT_VTABLE(u
)->done(u
);
592 ec
= unit_get_exec_context(u
);
594 exec_context_done(ec
);
596 cc
= unit_get_cgroup_context(u
);
598 cgroup_context_done(cc
);
601 void unit_free(Unit
*u
) {
609 if (UNIT_ISSET(u
->slice
)) {
610 /* A unit is being dropped from the tree, make sure our parent slice recalculates the member mask */
611 unit_invalidate_cgroup_members_masks(UNIT_DEREF(u
->slice
));
613 /* And make sure the parent is realized again, updating cgroup memberships */
614 unit_add_to_cgroup_realize_queue(UNIT_DEREF(u
->slice
));
617 u
->transient_file
= safe_fclose(u
->transient_file
);
619 if (!MANAGER_IS_RELOADING(u
->manager
))
620 unit_remove_transient(u
);
622 bus_unit_send_removed_signal(u
);
626 unit_dequeue_rewatch_pids(u
);
628 sd_bus_slot_unref(u
->match_bus_slot
);
629 sd_bus_track_unref(u
->bus_track
);
630 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
631 u
->pending_freezer_message
= sd_bus_message_unref(u
->pending_freezer_message
);
633 unit_free_requires_mounts_for(u
);
635 SET_FOREACH(t
, u
->names
, i
)
636 hashmap_remove_value(u
->manager
->units
, t
, u
);
638 if (!sd_id128_is_null(u
->invocation_id
))
639 hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
653 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
654 bidi_set_free(u
, u
->dependencies
[d
]);
657 manager_unref_console(u
->manager
);
659 unit_release_cgroup(u
);
661 if (!MANAGER_IS_RELOADING(u
->manager
))
662 unit_unlink_state_files(u
);
664 unit_unref_uid_gid(u
, false);
666 (void) manager_update_failed_units(u
->manager
, u
, false);
667 set_remove(u
->manager
->startup_units
, u
);
669 unit_unwatch_all_pids(u
);
671 unit_ref_unset(&u
->slice
);
672 while (u
->refs_by_target
)
673 unit_ref_unset(u
->refs_by_target
);
675 if (u
->type
!= _UNIT_TYPE_INVALID
)
676 LIST_REMOVE(units_by_type
, u
->manager
->units_by_type
[u
->type
], u
);
678 if (u
->in_load_queue
)
679 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
681 if (u
->in_dbus_queue
)
682 LIST_REMOVE(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
685 LIST_REMOVE(gc_queue
, u
->manager
->gc_unit_queue
, u
);
687 if (u
->in_cgroup_realize_queue
)
688 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
690 if (u
->in_cgroup_empty_queue
)
691 LIST_REMOVE(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
693 if (u
->in_cleanup_queue
)
694 LIST_REMOVE(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
696 if (u
->in_target_deps_queue
)
697 LIST_REMOVE(target_deps_queue
, u
->manager
->target_deps_queue
, u
);
699 if (u
->in_stop_when_unneeded_queue
)
700 LIST_REMOVE(stop_when_unneeded_queue
, u
->manager
->stop_when_unneeded_queue
, u
);
702 safe_close(u
->ip_accounting_ingress_map_fd
);
703 safe_close(u
->ip_accounting_egress_map_fd
);
705 safe_close(u
->ipv4_allow_map_fd
);
706 safe_close(u
->ipv6_allow_map_fd
);
707 safe_close(u
->ipv4_deny_map_fd
);
708 safe_close(u
->ipv6_deny_map_fd
);
710 bpf_program_unref(u
->ip_bpf_ingress
);
711 bpf_program_unref(u
->ip_bpf_ingress_installed
);
712 bpf_program_unref(u
->ip_bpf_egress
);
713 bpf_program_unref(u
->ip_bpf_egress_installed
);
715 set_free(u
->ip_bpf_custom_ingress
);
716 set_free(u
->ip_bpf_custom_egress
);
717 set_free(u
->ip_bpf_custom_ingress_installed
);
718 set_free(u
->ip_bpf_custom_egress_installed
);
720 bpf_program_unref(u
->bpf_device_control_installed
);
722 condition_free_list(u
->conditions
);
723 condition_free_list(u
->asserts
);
725 free(u
->description
);
726 strv_free(u
->documentation
);
727 free(u
->fragment_path
);
728 free(u
->source_path
);
729 strv_free(u
->dropin_paths
);
732 free(u
->job_timeout_reboot_arg
);
734 set_free_free(u
->names
);
741 FreezerState
unit_freezer_state(Unit
*u
) {
744 return u
->freezer_state
;
747 int unit_freezer_state_kernel(Unit
*u
, FreezerState
*ret
) {
748 char *values
[1] = {};
753 r
= cg_get_keyed_attribute(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events",
754 STRV_MAKE("frozen"), values
);
758 r
= _FREEZER_STATE_INVALID
;
761 if (streq(values
[0], "0"))
763 else if (streq(values
[0], "1"))
773 UnitActiveState
unit_active_state(Unit
*u
) {
776 if (u
->load_state
== UNIT_MERGED
)
777 return unit_active_state(unit_follow_merge(u
));
779 /* After a reload it might happen that a unit is not correctly
780 * loaded but still has a process around. That's why we won't
781 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
783 return UNIT_VTABLE(u
)->active_state(u
);
786 const char* unit_sub_state_to_string(Unit
*u
) {
789 return UNIT_VTABLE(u
)->sub_state_to_string(u
);
792 static int set_complete_move(Set
**s
, Set
**other
) {
800 return set_move(*s
, *other
);
802 *s
= TAKE_PTR(*other
);
807 static int hashmap_complete_move(Hashmap
**s
, Hashmap
**other
) {
815 return hashmap_move(*s
, *other
);
817 *s
= TAKE_PTR(*other
);
822 static int merge_names(Unit
*u
, Unit
*other
) {
830 r
= set_complete_move(&u
->names
, &other
->names
);
834 set_free_free(other
->names
);
838 SET_FOREACH(t
, u
->names
, i
)
839 assert_se(hashmap_replace(u
->manager
->units
, t
, u
) == 0);
844 static int reserve_dependencies(Unit
*u
, Unit
*other
, UnitDependency d
) {
849 assert(d
< _UNIT_DEPENDENCY_MAX
);
852 * If u does not have this dependency set allocated, there is no need
853 * to reserve anything. In that case other's set will be transferred
854 * as a whole to u by complete_move().
856 if (!u
->dependencies
[d
])
859 /* merge_dependencies() will skip a u-on-u dependency */
860 n_reserve
= hashmap_size(other
->dependencies
[d
]) - !!hashmap_get(other
->dependencies
[d
], u
);
862 return hashmap_reserve(u
->dependencies
[d
], n_reserve
);
865 static void merge_dependencies(Unit
*u
, Unit
*other
, const char *other_id
, UnitDependency d
) {
871 /* Merges all dependencies of type 'd' of the unit 'other' into the deps of the unit 'u' */
875 assert(d
< _UNIT_DEPENDENCY_MAX
);
877 /* Fix backwards pointers. Let's iterate through all dependent units of the other unit. */
878 HASHMAP_FOREACH_KEY(v
, back
, other
->dependencies
[d
], i
) {
881 /* Let's now iterate through the dependencies of that dependencies of the other units, looking for
882 * pointers back, and let's fix them up, to instead point to 'u'. */
884 for (k
= 0; k
< _UNIT_DEPENDENCY_MAX
; k
++) {
886 /* Do not add dependencies between u and itself. */
887 if (hashmap_remove(back
->dependencies
[k
], other
))
888 maybe_warn_about_dependency(u
, other_id
, k
);
890 UnitDependencyInfo di_u
, di_other
, di_merged
;
892 /* Let's drop this dependency between "back" and "other", and let's create it between
893 * "back" and "u" instead. Let's merge the bit masks of the dependency we are moving,
894 * and any such dependency which might already exist */
896 di_other
.data
= hashmap_get(back
->dependencies
[k
], other
);
898 continue; /* dependency isn't set, let's try the next one */
900 di_u
.data
= hashmap_get(back
->dependencies
[k
], u
);
902 di_merged
= (UnitDependencyInfo
) {
903 .origin_mask
= di_u
.origin_mask
| di_other
.origin_mask
,
904 .destination_mask
= di_u
.destination_mask
| di_other
.destination_mask
,
907 r
= hashmap_remove_and_replace(back
->dependencies
[k
], other
, u
, di_merged
.data
);
909 log_warning_errno(r
, "Failed to remove/replace: back=%s other=%s u=%s: %m", back
->id
, other_id
, u
->id
);
912 /* assert_se(hashmap_remove_and_replace(back->dependencies[k], other, u, di_merged.data) >= 0); */
918 /* Also do not move dependencies on u to itself */
919 back
= hashmap_remove(other
->dependencies
[d
], u
);
921 maybe_warn_about_dependency(u
, other_id
, d
);
923 /* The move cannot fail. The caller must have performed a reservation. */
924 assert_se(hashmap_complete_move(&u
->dependencies
[d
], &other
->dependencies
[d
]) == 0);
926 other
->dependencies
[d
] = hashmap_free(other
->dependencies
[d
]);
929 int unit_merge(Unit
*u
, Unit
*other
) {
931 const char *other_id
= NULL
;
936 assert(u
->manager
== other
->manager
);
937 assert(u
->type
!= _UNIT_TYPE_INVALID
);
939 other
= unit_follow_merge(other
);
944 if (u
->type
!= other
->type
)
947 if (!u
->instance
!= !other
->instance
)
950 if (!unit_type_may_alias(u
->type
)) /* Merging only applies to unit names that support aliases */
953 if (!IN_SET(other
->load_state
, UNIT_STUB
, UNIT_NOT_FOUND
))
962 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
966 other_id
= strdupa(other
->id
);
968 /* Make reservations to ensure merge_dependencies() won't fail */
969 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
970 r
= reserve_dependencies(u
, other
, d
);
972 * We don't rollback reservations if we fail. We don't have
973 * a way to undo reservations. A reservation is not a leak.
980 r
= merge_names(u
, other
);
984 /* Redirect all references */
985 while (other
->refs_by_target
)
986 unit_ref_set(other
->refs_by_target
, other
->refs_by_target
->source
, u
);
988 /* Merge dependencies */
989 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
990 merge_dependencies(u
, other
, other_id
, d
);
992 other
->load_state
= UNIT_MERGED
;
993 other
->merged_into
= u
;
995 /* If there is still some data attached to the other node, we
996 * don't need it anymore, and can free it. */
997 if (other
->load_state
!= UNIT_STUB
)
998 if (UNIT_VTABLE(other
)->done
)
999 UNIT_VTABLE(other
)->done(other
);
1001 unit_add_to_dbus_queue(u
);
1002 unit_add_to_cleanup_queue(other
);
1007 int unit_merge_by_name(Unit
*u
, const char *name
) {
1008 _cleanup_free_
char *s
= NULL
;
1012 /* Either add name to u, or if a unit with name already exists, merge it with u.
1013 * If name is a template, do the same for name@instance, where instance is u's instance. */
1018 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
1022 r
= unit_name_replace_instance(name
, u
->instance
, &s
);
1029 other
= manager_get_unit(u
->manager
, name
);
1031 return unit_merge(u
, other
);
1033 return unit_add_name(u
, name
);
1036 Unit
* unit_follow_merge(Unit
*u
) {
1039 while (u
->load_state
== UNIT_MERGED
)
1040 assert_se(u
= u
->merged_into
);
1045 int unit_add_exec_dependencies(Unit
*u
, ExecContext
*c
) {
1046 ExecDirectoryType dt
;
1053 if (c
->working_directory
&& !c
->working_directory_missing_ok
) {
1054 r
= unit_require_mounts_for(u
, c
->working_directory
, UNIT_DEPENDENCY_FILE
);
1059 if (c
->root_directory
) {
1060 r
= unit_require_mounts_for(u
, c
->root_directory
, UNIT_DEPENDENCY_FILE
);
1065 if (c
->root_image
) {
1066 r
= unit_require_mounts_for(u
, c
->root_image
, UNIT_DEPENDENCY_FILE
);
1071 for (dt
= 0; dt
< _EXEC_DIRECTORY_TYPE_MAX
; dt
++) {
1072 if (!u
->manager
->prefix
[dt
])
1075 STRV_FOREACH(dp
, c
->directories
[dt
].paths
) {
1076 _cleanup_free_
char *p
;
1078 p
= path_join(u
->manager
->prefix
[dt
], *dp
);
1082 r
= unit_require_mounts_for(u
, p
, UNIT_DEPENDENCY_FILE
);
1088 if (!MANAGER_IS_SYSTEM(u
->manager
))
1091 /* For the following three directory types we need write access, and /var/ is possibly on the root
1092 * fs. Hence order after systemd-remount-fs.service, to ensure things are writable. */
1093 if (!strv_isempty(c
->directories
[EXEC_DIRECTORY_STATE
].paths
) ||
1094 !strv_isempty(c
->directories
[EXEC_DIRECTORY_CACHE
].paths
) ||
1095 !strv_isempty(c
->directories
[EXEC_DIRECTORY_LOGS
].paths
)) {
1096 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1101 if (c
->private_tmp
) {
1104 FOREACH_STRING(p
, "/tmp", "/var/tmp") {
1105 r
= unit_require_mounts_for(u
, p
, UNIT_DEPENDENCY_FILE
);
1110 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_TMPFILES_SETUP_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1115 if (c
->root_image
) {
1116 /* We need to wait for /dev/loopX to appear when doing RootImage=, hence let's add an
1117 * implicit dependency on udev */
1119 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_UDEVD_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1124 if (!IN_SET(c
->std_output
,
1125 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
1126 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
) &&
1127 !IN_SET(c
->std_error
,
1128 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
1129 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
) &&
1133 /* If syslog or kernel logging is requested (or log namespacing is), make sure our own logging daemon
1136 if (c
->log_namespace
) {
1137 _cleanup_free_
char *socket_unit
= NULL
, *varlink_socket_unit
= NULL
;
1139 r
= unit_name_build_from_type("systemd-journald", c
->log_namespace
, UNIT_SOCKET
, &socket_unit
);
1143 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, socket_unit
, true, UNIT_DEPENDENCY_FILE
);
1147 r
= unit_name_build_from_type("systemd-journald-varlink", c
->log_namespace
, UNIT_SOCKET
, &varlink_socket_unit
);
1151 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, varlink_socket_unit
, true, UNIT_DEPENDENCY_FILE
);
1155 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_JOURNALD_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
1162 const char *unit_description(Unit
*u
) {
1166 return u
->description
;
1168 return strna(u
->id
);
1171 const char *unit_status_string(Unit
*u
) {
1174 if (u
->manager
->status_unit_format
== STATUS_UNIT_FORMAT_NAME
&& u
->id
)
1177 return unit_description(u
);
1180 static void print_unit_dependency_mask(FILE *f
, const char *kind
, UnitDependencyMask mask
, bool *space
) {
1182 UnitDependencyMask mask
;
1185 { UNIT_DEPENDENCY_FILE
, "file" },
1186 { UNIT_DEPENDENCY_IMPLICIT
, "implicit" },
1187 { UNIT_DEPENDENCY_DEFAULT
, "default" },
1188 { UNIT_DEPENDENCY_UDEV
, "udev" },
1189 { UNIT_DEPENDENCY_PATH
, "path" },
1190 { UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT
, "mountinfo-implicit" },
1191 { UNIT_DEPENDENCY_MOUNTINFO_DEFAULT
, "mountinfo-default" },
1192 { UNIT_DEPENDENCY_PROC_SWAP
, "proc-swap" },
1200 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1205 if (FLAGS_SET(mask
, table
[i
].mask
)) {
1213 fputs(table
[i
].name
, f
);
1215 mask
&= ~table
[i
].mask
;
1222 void unit_dump(Unit
*u
, FILE *f
, const char *prefix
) {
1226 const char *prefix2
;
1227 char timestamp
[5][FORMAT_TIMESTAMP_MAX
], timespan
[FORMAT_TIMESPAN_MAX
];
1229 _cleanup_set_free_ Set
*following_set
= NULL
;
1235 assert(u
->type
>= 0);
1237 prefix
= strempty(prefix
);
1238 prefix2
= strjoina(prefix
, "\t");
1244 SET_FOREACH(t
, u
->names
, i
)
1245 if (!streq(t
, u
->id
))
1246 fprintf(f
, "%s\tAlias: %s\n", prefix
, t
);
1249 "%s\tDescription: %s\n"
1250 "%s\tInstance: %s\n"
1251 "%s\tUnit Load State: %s\n"
1252 "%s\tUnit Active State: %s\n"
1253 "%s\tState Change Timestamp: %s\n"
1254 "%s\tInactive Exit Timestamp: %s\n"
1255 "%s\tActive Enter Timestamp: %s\n"
1256 "%s\tActive Exit Timestamp: %s\n"
1257 "%s\tInactive Enter Timestamp: %s\n"
1259 "%s\tNeed Daemon Reload: %s\n"
1260 "%s\tTransient: %s\n"
1261 "%s\tPerpetual: %s\n"
1262 "%s\tGarbage Collection Mode: %s\n"
1265 "%s\tCGroup realized: %s\n",
1266 prefix
, unit_description(u
),
1267 prefix
, strna(u
->instance
),
1268 prefix
, unit_load_state_to_string(u
->load_state
),
1269 prefix
, unit_active_state_to_string(unit_active_state(u
)),
1270 prefix
, strna(format_timestamp(timestamp
[0], sizeof(timestamp
[0]), u
->state_change_timestamp
.realtime
)),
1271 prefix
, strna(format_timestamp(timestamp
[1], sizeof(timestamp
[1]), u
->inactive_exit_timestamp
.realtime
)),
1272 prefix
, strna(format_timestamp(timestamp
[2], sizeof(timestamp
[2]), u
->active_enter_timestamp
.realtime
)),
1273 prefix
, strna(format_timestamp(timestamp
[3], sizeof(timestamp
[3]), u
->active_exit_timestamp
.realtime
)),
1274 prefix
, strna(format_timestamp(timestamp
[4], sizeof(timestamp
[4]), u
->inactive_enter_timestamp
.realtime
)),
1275 prefix
, yes_no(unit_may_gc(u
)),
1276 prefix
, yes_no(unit_need_daemon_reload(u
)),
1277 prefix
, yes_no(u
->transient
),
1278 prefix
, yes_no(u
->perpetual
),
1279 prefix
, collect_mode_to_string(u
->collect_mode
),
1280 prefix
, strna(unit_slice_name(u
)),
1281 prefix
, strna(u
->cgroup_path
),
1282 prefix
, yes_no(u
->cgroup_realized
));
1284 if (u
->cgroup_realized_mask
!= 0) {
1285 _cleanup_free_
char *s
= NULL
;
1286 (void) cg_mask_to_string(u
->cgroup_realized_mask
, &s
);
1287 fprintf(f
, "%s\tCGroup realized mask: %s\n", prefix
, strnull(s
));
1290 if (u
->cgroup_enabled_mask
!= 0) {
1291 _cleanup_free_
char *s
= NULL
;
1292 (void) cg_mask_to_string(u
->cgroup_enabled_mask
, &s
);
1293 fprintf(f
, "%s\tCGroup enabled mask: %s\n", prefix
, strnull(s
));
1296 m
= unit_get_own_mask(u
);
1298 _cleanup_free_
char *s
= NULL
;
1299 (void) cg_mask_to_string(m
, &s
);
1300 fprintf(f
, "%s\tCGroup own mask: %s\n", prefix
, strnull(s
));
1303 m
= unit_get_members_mask(u
);
1305 _cleanup_free_
char *s
= NULL
;
1306 (void) cg_mask_to_string(m
, &s
);
1307 fprintf(f
, "%s\tCGroup members mask: %s\n", prefix
, strnull(s
));
1310 m
= unit_get_delegate_mask(u
);
1312 _cleanup_free_
char *s
= NULL
;
1313 (void) cg_mask_to_string(m
, &s
);
1314 fprintf(f
, "%s\tCGroup delegate mask: %s\n", prefix
, strnull(s
));
1317 if (!sd_id128_is_null(u
->invocation_id
))
1318 fprintf(f
, "%s\tInvocation ID: " SD_ID128_FORMAT_STR
"\n",
1319 prefix
, SD_ID128_FORMAT_VAL(u
->invocation_id
));
1321 STRV_FOREACH(j
, u
->documentation
)
1322 fprintf(f
, "%s\tDocumentation: %s\n", prefix
, *j
);
1324 following
= unit_following(u
);
1326 fprintf(f
, "%s\tFollowing: %s\n", prefix
, following
->id
);
1328 r
= unit_following_set(u
, &following_set
);
1332 SET_FOREACH(other
, following_set
, i
)
1333 fprintf(f
, "%s\tFollowing Set Member: %s\n", prefix
, other
->id
);
1336 if (u
->fragment_path
)
1337 fprintf(f
, "%s\tFragment Path: %s\n", prefix
, u
->fragment_path
);
1340 fprintf(f
, "%s\tSource Path: %s\n", prefix
, u
->source_path
);
1342 STRV_FOREACH(j
, u
->dropin_paths
)
1343 fprintf(f
, "%s\tDropIn Path: %s\n", prefix
, *j
);
1345 if (u
->failure_action
!= EMERGENCY_ACTION_NONE
)
1346 fprintf(f
, "%s\tFailure Action: %s\n", prefix
, emergency_action_to_string(u
->failure_action
));
1347 if (u
->failure_action_exit_status
>= 0)
1348 fprintf(f
, "%s\tFailure Action Exit Status: %i\n", prefix
, u
->failure_action_exit_status
);
1349 if (u
->success_action
!= EMERGENCY_ACTION_NONE
)
1350 fprintf(f
, "%s\tSuccess Action: %s\n", prefix
, emergency_action_to_string(u
->success_action
));
1351 if (u
->success_action_exit_status
>= 0)
1352 fprintf(f
, "%s\tSuccess Action Exit Status: %i\n", prefix
, u
->success_action_exit_status
);
1354 if (u
->job_timeout
!= USEC_INFINITY
)
1355 fprintf(f
, "%s\tJob Timeout: %s\n", prefix
, format_timespan(timespan
, sizeof(timespan
), u
->job_timeout
, 0));
1357 if (u
->job_timeout_action
!= EMERGENCY_ACTION_NONE
)
1358 fprintf(f
, "%s\tJob Timeout Action: %s\n", prefix
, emergency_action_to_string(u
->job_timeout_action
));
1360 if (u
->job_timeout_reboot_arg
)
1361 fprintf(f
, "%s\tJob Timeout Reboot Argument: %s\n", prefix
, u
->job_timeout_reboot_arg
);
1363 condition_dump_list(u
->conditions
, f
, prefix
, condition_type_to_string
);
1364 condition_dump_list(u
->asserts
, f
, prefix
, assert_type_to_string
);
1366 if (dual_timestamp_is_set(&u
->condition_timestamp
))
1368 "%s\tCondition Timestamp: %s\n"
1369 "%s\tCondition Result: %s\n",
1370 prefix
, strna(format_timestamp(timestamp
[0], sizeof(timestamp
[0]), u
->condition_timestamp
.realtime
)),
1371 prefix
, yes_no(u
->condition_result
));
1373 if (dual_timestamp_is_set(&u
->assert_timestamp
))
1375 "%s\tAssert Timestamp: %s\n"
1376 "%s\tAssert Result: %s\n",
1377 prefix
, strna(format_timestamp(timestamp
[0], sizeof(timestamp
[0]), u
->assert_timestamp
.realtime
)),
1378 prefix
, yes_no(u
->assert_result
));
1380 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
1381 UnitDependencyInfo di
;
1384 HASHMAP_FOREACH_KEY(di
.data
, other
, u
->dependencies
[d
], i
) {
1387 fprintf(f
, "%s\t%s: %s (", prefix
, unit_dependency_to_string(d
), other
->id
);
1389 print_unit_dependency_mask(f
, "origin", di
.origin_mask
, &space
);
1390 print_unit_dependency_mask(f
, "destination", di
.destination_mask
, &space
);
1396 if (!hashmap_isempty(u
->requires_mounts_for
)) {
1397 UnitDependencyInfo di
;
1400 HASHMAP_FOREACH_KEY(di
.data
, path
, u
->requires_mounts_for
, i
) {
1403 fprintf(f
, "%s\tRequiresMountsFor: %s (", prefix
, path
);
1405 print_unit_dependency_mask(f
, "origin", di
.origin_mask
, &space
);
1406 print_unit_dependency_mask(f
, "destination", di
.destination_mask
, &space
);
1412 if (u
->load_state
== UNIT_LOADED
) {
1415 "%s\tStopWhenUnneeded: %s\n"
1416 "%s\tRefuseManualStart: %s\n"
1417 "%s\tRefuseManualStop: %s\n"
1418 "%s\tDefaultDependencies: %s\n"
1419 "%s\tOnFailureJobMode: %s\n"
1420 "%s\tIgnoreOnIsolate: %s\n",
1421 prefix
, yes_no(u
->stop_when_unneeded
),
1422 prefix
, yes_no(u
->refuse_manual_start
),
1423 prefix
, yes_no(u
->refuse_manual_stop
),
1424 prefix
, yes_no(u
->default_dependencies
),
1425 prefix
, job_mode_to_string(u
->on_failure_job_mode
),
1426 prefix
, yes_no(u
->ignore_on_isolate
));
1428 if (UNIT_VTABLE(u
)->dump
)
1429 UNIT_VTABLE(u
)->dump(u
, f
, prefix2
);
1431 } else if (u
->load_state
== UNIT_MERGED
)
1433 "%s\tMerged into: %s\n",
1434 prefix
, u
->merged_into
->id
);
1435 else if (u
->load_state
== UNIT_ERROR
)
1436 fprintf(f
, "%s\tLoad Error Code: %s\n", prefix
, strerror_safe(u
->load_error
));
1438 for (n
= sd_bus_track_first(u
->bus_track
); n
; n
= sd_bus_track_next(u
->bus_track
))
1439 fprintf(f
, "%s\tBus Ref: %s\n", prefix
, n
);
1442 job_dump(u
->job
, f
, prefix2
);
1445 job_dump(u
->nop_job
, f
, prefix2
);
1448 /* Common implementation for multiple backends */
1449 int unit_load_fragment_and_dropin(Unit
*u
, bool fragment_required
) {
1454 /* Load a .{service,socket,...} file */
1455 r
= unit_load_fragment(u
);
1459 if (u
->load_state
== UNIT_STUB
) {
1460 if (fragment_required
)
1463 u
->load_state
= UNIT_LOADED
;
1466 /* Load drop-in directory data. If u is an alias, we might be reloading the
1467 * target unit needlessly. But we cannot be sure which drops-ins have already
1468 * been loaded and which not, at least without doing complicated book-keeping,
1469 * so let's always reread all drop-ins. */
1470 return unit_load_dropin(unit_follow_merge(u
));
1473 void unit_add_to_target_deps_queue(Unit
*u
) {
1474 Manager
*m
= u
->manager
;
1478 if (u
->in_target_deps_queue
)
1481 LIST_PREPEND(target_deps_queue
, m
->target_deps_queue
, u
);
1482 u
->in_target_deps_queue
= true;
1485 int unit_add_default_target_dependency(Unit
*u
, Unit
*target
) {
1489 if (target
->type
!= UNIT_TARGET
)
1492 /* Only add the dependency if both units are loaded, so that
1493 * that loop check below is reliable */
1494 if (u
->load_state
!= UNIT_LOADED
||
1495 target
->load_state
!= UNIT_LOADED
)
1498 /* If either side wants no automatic dependencies, then let's
1500 if (!u
->default_dependencies
||
1501 !target
->default_dependencies
)
1504 /* Don't create loops */
1505 if (hashmap_get(target
->dependencies
[UNIT_BEFORE
], u
))
1508 return unit_add_dependency(target
, UNIT_AFTER
, u
, true, UNIT_DEPENDENCY_DEFAULT
);
1511 static int unit_add_slice_dependencies(Unit
*u
) {
1512 UnitDependencyMask mask
;
1515 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1518 /* Slice units are implicitly ordered against their parent slices (as this relationship is encoded in the
1519 name), while all other units are ordered based on configuration (as in their case Slice= configures the
1521 mask
= u
->type
== UNIT_SLICE
? UNIT_DEPENDENCY_IMPLICIT
: UNIT_DEPENDENCY_FILE
;
1523 if (UNIT_ISSET(u
->slice
))
1524 return unit_add_two_dependencies(u
, UNIT_AFTER
, UNIT_REQUIRES
, UNIT_DEREF(u
->slice
), true, mask
);
1526 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1529 return unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_ROOT_SLICE
, true, mask
);
1532 static int unit_add_mount_dependencies(Unit
*u
) {
1533 UnitDependencyInfo di
;
1540 HASHMAP_FOREACH_KEY(di
.data
, path
, u
->requires_mounts_for
, i
) {
1541 char prefix
[strlen(path
) + 1];
1543 PATH_FOREACH_PREFIX_MORE(prefix
, path
) {
1544 _cleanup_free_
char *p
= NULL
;
1547 r
= unit_name_from_path(prefix
, ".mount", &p
);
1551 m
= manager_get_unit(u
->manager
, p
);
1553 /* Make sure to load the mount unit if
1554 * it exists. If so the dependencies
1555 * on this unit will be added later
1556 * during the loading of the mount
1558 (void) manager_load_unit_prepare(u
->manager
, p
, NULL
, NULL
, &m
);
1564 if (m
->load_state
!= UNIT_LOADED
)
1567 r
= unit_add_dependency(u
, UNIT_AFTER
, m
, true, di
.origin_mask
);
1571 if (m
->fragment_path
) {
1572 r
= unit_add_dependency(u
, UNIT_REQUIRES
, m
, true, di
.origin_mask
);
1582 static int unit_add_startup_units(Unit
*u
) {
1586 c
= unit_get_cgroup_context(u
);
1590 if (c
->startup_cpu_shares
== CGROUP_CPU_SHARES_INVALID
&&
1591 c
->startup_io_weight
== CGROUP_WEIGHT_INVALID
&&
1592 c
->startup_blockio_weight
== CGROUP_BLKIO_WEIGHT_INVALID
)
1595 r
= set_ensure_allocated(&u
->manager
->startup_units
, NULL
);
1599 return set_put(u
->manager
->startup_units
, u
);
1602 int unit_load(Unit
*u
) {
1607 if (u
->in_load_queue
) {
1608 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
1609 u
->in_load_queue
= false;
1612 if (u
->type
== _UNIT_TYPE_INVALID
)
1615 if (u
->load_state
!= UNIT_STUB
)
1618 if (u
->transient_file
) {
1619 /* Finalize transient file: if this is a transient unit file, as soon as we reach unit_load() the setup
1620 * is complete, hence let's synchronize the unit file we just wrote to disk. */
1622 r
= fflush_and_check(u
->transient_file
);
1626 u
->transient_file
= safe_fclose(u
->transient_file
);
1627 u
->fragment_mtime
= now(CLOCK_REALTIME
);
1630 r
= UNIT_VTABLE(u
)->load(u
);
1634 assert(u
->load_state
!= UNIT_STUB
);
1636 if (u
->load_state
== UNIT_LOADED
) {
1637 unit_add_to_target_deps_queue(u
);
1639 r
= unit_add_slice_dependencies(u
);
1643 r
= unit_add_mount_dependencies(u
);
1647 r
= unit_add_startup_units(u
);
1651 if (u
->on_failure_job_mode
== JOB_ISOLATE
&& hashmap_size(u
->dependencies
[UNIT_ON_FAILURE
]) > 1) {
1652 log_unit_error(u
, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
1657 if (u
->job_running_timeout
!= USEC_INFINITY
&& u
->job_running_timeout
> u
->job_timeout
)
1658 log_unit_warning(u
, "JobRunningTimeoutSec= is greater than JobTimeoutSec=, it has no effect.");
1660 /* We finished loading, let's ensure our parents recalculate the members mask */
1661 unit_invalidate_cgroup_members_masks(u
);
1664 assert((u
->load_state
!= UNIT_MERGED
) == !u
->merged_into
);
1666 unit_add_to_dbus_queue(unit_follow_merge(u
));
1667 unit_add_to_gc_queue(u
);
1672 /* We convert ENOEXEC errors to the UNIT_BAD_SETTING load state here. Configuration parsing code should hence
1673 * return ENOEXEC to ensure units are placed in this state after loading */
1675 u
->load_state
= u
->load_state
== UNIT_STUB
? UNIT_NOT_FOUND
:
1676 r
== -ENOEXEC
? UNIT_BAD_SETTING
:
1680 unit_add_to_dbus_queue(u
);
1681 unit_add_to_gc_queue(u
);
1683 return log_unit_debug_errno(u
, r
, "Failed to load configuration: %m");
1687 static int log_unit_internal(void *userdata
, int level
, int error
, const char *file
, int line
, const char *func
, const char *format
, ...) {
1692 va_start(ap
, format
);
1694 r
= log_object_internalv(level
, error
, file
, line
, func
,
1695 u
->manager
->unit_log_field
,
1697 u
->manager
->invocation_log_field
,
1698 u
->invocation_id_string
,
1701 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
1707 static bool unit_test_condition(Unit
*u
) {
1710 dual_timestamp_get(&u
->condition_timestamp
);
1711 u
->condition_result
= condition_test_list(u
->conditions
, condition_type_to_string
, log_unit_internal
, u
);
1713 unit_add_to_dbus_queue(u
);
1715 return u
->condition_result
;
1718 static bool unit_test_assert(Unit
*u
) {
1721 dual_timestamp_get(&u
->assert_timestamp
);
1722 u
->assert_result
= condition_test_list(u
->asserts
, assert_type_to_string
, log_unit_internal
, u
);
1724 unit_add_to_dbus_queue(u
);
1726 return u
->assert_result
;
1729 void unit_status_printf(Unit
*u
, StatusType status_type
, const char *status
, const char *unit_status_msg_format
) {
1732 d
= unit_status_string(u
);
1733 if (log_get_show_color())
1734 d
= strjoina(ANSI_HIGHLIGHT
, d
, ANSI_NORMAL
);
1736 DISABLE_WARNING_FORMAT_NONLITERAL
;
1737 manager_status_printf(u
->manager
, status_type
, status
, unit_status_msg_format
, d
);
1741 int unit_test_start_limit(Unit
*u
) {
1746 if (ratelimit_below(&u
->start_ratelimit
)) {
1747 u
->start_limit_hit
= false;
1751 log_unit_warning(u
, "Start request repeated too quickly.");
1752 u
->start_limit_hit
= true;
1754 reason
= strjoina("unit ", u
->id
, " failed");
1756 emergency_action(u
->manager
, u
->start_limit_action
,
1757 EMERGENCY_ACTION_IS_WATCHDOG
|EMERGENCY_ACTION_WARN
,
1758 u
->reboot_arg
, -1, reason
);
1763 bool unit_shall_confirm_spawn(Unit
*u
) {
1766 if (manager_is_confirm_spawn_disabled(u
->manager
))
1769 /* For some reasons units remaining in the same process group
1770 * as PID 1 fail to acquire the console even if it's not used
1771 * by any process. So skip the confirmation question for them. */
1772 return !unit_get_exec_context(u
)->same_pgrp
;
1775 static bool unit_verify_deps(Unit
*u
) {
1782 /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined with
1783 * After=. We do not check Requires= or Requisite= here as they only should have an effect on the job
1784 * processing, but do not have any effect afterwards. We don't check BindsTo= dependencies that are not used in
1785 * conjunction with After= as for them any such check would make things entirely racy. */
1787 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
], j
) {
1789 if (!hashmap_contains(u
->dependencies
[UNIT_AFTER
], other
))
1792 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other
))) {
1793 log_unit_notice(u
, "Bound to unit %s, but unit isn't active.", other
->id
);
1801 /* Errors that aren't really errors:
1802 * -EALREADY: Unit is already started.
1803 * -ECOMM: Condition failed
1804 * -EAGAIN: An operation is already in progress. Retry later.
1806 * Errors that are real errors:
1807 * -EBADR: This unit type does not support starting.
1808 * -ECANCELED: Start limit hit, too many requests for now
1809 * -EPROTO: Assert failed
1810 * -EINVAL: Unit not loaded
1811 * -EOPNOTSUPP: Unit type not supported
1812 * -ENOLINK: The necessary dependencies are not fulfilled.
1813 * -ESTALE: This unit has been started before and can't be started a second time
1814 * -ENOENT: This is a triggering unit and unit to trigger is not loaded
1816 int unit_start(Unit
*u
) {
1817 UnitActiveState state
;
1822 /* If this is already started, then this will succeed. Note that this will even succeed if this unit
1823 * is not startable by the user. This is relied on to detect when we need to wait for units and when
1824 * waiting is finished. */
1825 state
= unit_active_state(u
);
1826 if (UNIT_IS_ACTIVE_OR_RELOADING(state
))
1828 if (state
== UNIT_MAINTENANCE
)
1831 /* Units that aren't loaded cannot be started */
1832 if (u
->load_state
!= UNIT_LOADED
)
1835 /* Refuse starting scope units more than once */
1836 if (UNIT_VTABLE(u
)->once_only
&& dual_timestamp_is_set(&u
->inactive_enter_timestamp
))
1839 /* If the conditions failed, don't do anything at all. If we already are activating this call might
1840 * still be useful to speed up activation in case there is some hold-off time, but we don't want to
1841 * recheck the condition in that case. */
1842 if (state
!= UNIT_ACTIVATING
&&
1843 !unit_test_condition(u
))
1844 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(ECOMM
), "Starting requested but condition failed. Not starting unit.");
1846 /* If the asserts failed, fail the entire job */
1847 if (state
!= UNIT_ACTIVATING
&&
1848 !unit_test_assert(u
))
1849 return log_unit_notice_errno(u
, SYNTHETIC_ERRNO(EPROTO
), "Starting requested but asserts failed.");
1851 /* Units of types that aren't supported cannot be started. Note that we do this test only after the
1852 * condition checks, so that we rather return condition check errors (which are usually not
1853 * considered a true failure) than "not supported" errors (which are considered a failure).
1855 if (!unit_type_supported(u
->type
))
1858 /* Let's make sure that the deps really are in order before we start this. Normally the job engine
1859 * should have taken care of this already, but let's check this here again. After all, our
1860 * dependencies might not be in effect anymore, due to a reload or due to a failed condition. */
1861 if (!unit_verify_deps(u
))
1864 /* Forward to the main object, if we aren't it. */
1865 following
= unit_following(u
);
1867 log_unit_debug(u
, "Redirecting start request from %s to %s.", u
->id
, following
->id
);
1868 return unit_start(following
);
1871 /* If it is stopped, but we cannot start it, then fail */
1872 if (!UNIT_VTABLE(u
)->start
)
1875 /* We don't suppress calls to ->start() here when we are already starting, to allow this request to
1876 * be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
1877 * waits for a holdoff timer to elapse before it will start again. */
1879 unit_add_to_dbus_queue(u
);
1880 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1882 return UNIT_VTABLE(u
)->start(u
);
1885 bool unit_can_start(Unit
*u
) {
1888 if (u
->load_state
!= UNIT_LOADED
)
1891 if (!unit_type_supported(u
->type
))
1894 /* Scope units may be started only once */
1895 if (UNIT_VTABLE(u
)->once_only
&& dual_timestamp_is_set(&u
->inactive_exit_timestamp
))
1898 return !!UNIT_VTABLE(u
)->start
;
1901 bool unit_can_isolate(Unit
*u
) {
1904 return unit_can_start(u
) &&
1909 * -EBADR: This unit type does not support stopping.
1910 * -EALREADY: Unit is already stopped.
1911 * -EAGAIN: An operation is already in progress. Retry later.
1913 int unit_stop(Unit
*u
) {
1914 UnitActiveState state
;
1919 state
= unit_active_state(u
);
1920 if (UNIT_IS_INACTIVE_OR_FAILED(state
))
1923 following
= unit_following(u
);
1925 log_unit_debug(u
, "Redirecting stop request from %s to %s.", u
->id
, following
->id
);
1926 return unit_stop(following
);
1929 if (!UNIT_VTABLE(u
)->stop
)
1932 unit_add_to_dbus_queue(u
);
1933 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1935 return UNIT_VTABLE(u
)->stop(u
);
1938 bool unit_can_stop(Unit
*u
) {
1941 if (!unit_type_supported(u
->type
))
1947 return !!UNIT_VTABLE(u
)->stop
;
1951 * -EBADR: This unit type does not support reloading.
1952 * -ENOEXEC: Unit is not started.
1953 * -EAGAIN: An operation is already in progress. Retry later.
1955 int unit_reload(Unit
*u
) {
1956 UnitActiveState state
;
1961 if (u
->load_state
!= UNIT_LOADED
)
1964 if (!unit_can_reload(u
))
1967 state
= unit_active_state(u
);
1968 if (state
== UNIT_RELOADING
)
1971 if (state
!= UNIT_ACTIVE
) {
1972 log_unit_warning(u
, "Unit cannot be reloaded because it is inactive.");
1976 following
= unit_following(u
);
1978 log_unit_debug(u
, "Redirecting reload request from %s to %s.", u
->id
, following
->id
);
1979 return unit_reload(following
);
1982 unit_add_to_dbus_queue(u
);
1984 if (!UNIT_VTABLE(u
)->reload
) {
1985 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
1986 unit_notify(u
, unit_active_state(u
), unit_active_state(u
), 0);
1990 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1992 return UNIT_VTABLE(u
)->reload(u
);
1995 bool unit_can_reload(Unit
*u
) {
1998 if (UNIT_VTABLE(u
)->can_reload
)
1999 return UNIT_VTABLE(u
)->can_reload(u
);
2001 if (!hashmap_isempty(u
->dependencies
[UNIT_PROPAGATES_RELOAD_TO
]))
2004 return UNIT_VTABLE(u
)->reload
;
2007 bool unit_is_unneeded(Unit
*u
) {
2008 static const UnitDependency deps
[] = {
2018 if (!u
->stop_when_unneeded
)
2021 /* Don't clean up while the unit is transitioning or is even inactive. */
2022 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
)))
2027 for (j
= 0; j
< ELEMENTSOF(deps
); j
++) {
2032 /* If a dependent unit has a job queued, is active or transitioning, or is marked for
2033 * restart, then don't clean this one up. */
2035 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[deps
[j
]], i
) {
2039 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
2042 if (unit_will_restart(other
))
2050 static void check_unneeded_dependencies(Unit
*u
) {
2052 static const UnitDependency deps
[] = {
2062 /* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
2064 for (j
= 0; j
< ELEMENTSOF(deps
); j
++) {
2069 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[deps
[j
]], i
)
2070 unit_submit_to_stop_when_unneeded_queue(other
);
2074 static void unit_check_binds_to(Unit
*u
) {
2075 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2087 if (unit_active_state(u
) != UNIT_ACTIVE
)
2090 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
], i
) {
2094 if (!other
->coldplugged
)
2095 /* We might yet create a job for the other unit… */
2098 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
2108 /* If stopping a unit fails continuously we might enter a stop
2109 * loop here, hence stop acting on the service being
2110 * unnecessary after a while. */
2111 if (!ratelimit_below(&u
->auto_stop_ratelimit
)) {
2112 log_unit_warning(u
, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other
->id
);
2117 log_unit_info(u
, "Unit is bound to inactive unit %s. Stopping, too.", other
->id
);
2119 /* A unit we need to run is gone. Sniff. Let's stop this. */
2120 r
= manager_add_job(u
->manager
, JOB_STOP
, u
, JOB_FAIL
, NULL
, &error
, NULL
);
2122 log_unit_warning_errno(u
, r
, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error
, r
));
2125 static void retroactively_start_dependencies(Unit
*u
) {
2131 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)));
2133 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_REQUIRES
], i
)
2134 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
2135 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
2136 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2138 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
], i
)
2139 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
2140 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
2141 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2143 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_WANTS
], i
)
2144 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
2145 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
2146 manager_add_job(u
->manager
, JOB_START
, other
, JOB_FAIL
, NULL
, NULL
, NULL
);
2148 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_CONFLICTS
], i
)
2149 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
2150 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2152 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_CONFLICTED_BY
], i
)
2153 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
2154 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2157 static void retroactively_stop_dependencies(Unit
*u
) {
2163 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)));
2165 /* Pull down units which are bound to us recursively if enabled */
2166 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BOUND_BY
], i
)
2167 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
2168 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2171 void unit_start_on_failure(Unit
*u
) {
2179 if (hashmap_size(u
->dependencies
[UNIT_ON_FAILURE
]) <= 0)
2182 log_unit_info(u
, "Triggering OnFailure= dependencies.");
2184 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_ON_FAILURE
], i
) {
2185 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2187 r
= manager_add_job(u
->manager
, JOB_START
, other
, u
->on_failure_job_mode
, NULL
, &error
, NULL
);
2189 log_unit_warning_errno(u
, r
, "Failed to enqueue OnFailure= job, ignoring: %s", bus_error_message(&error
, r
));
2193 void unit_trigger_notify(Unit
*u
) {
2200 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_TRIGGERED_BY
], i
)
2201 if (UNIT_VTABLE(other
)->trigger_notify
)
2202 UNIT_VTABLE(other
)->trigger_notify(other
, u
);
2205 static int raise_level(int log_level
, bool condition_info
, bool condition_notice
) {
2206 if (condition_notice
&& log_level
> LOG_NOTICE
)
2208 if (condition_info
&& log_level
> LOG_INFO
)
2213 static int unit_log_resources(Unit
*u
) {
2214 struct iovec iovec
[1 + _CGROUP_IP_ACCOUNTING_METRIC_MAX
+ _CGROUP_IO_ACCOUNTING_METRIC_MAX
+ 4];
2215 bool any_traffic
= false, have_ip_accounting
= false, any_io
= false, have_io_accounting
= false;
2216 _cleanup_free_
char *igress
= NULL
, *egress
= NULL
, *rr
= NULL
, *wr
= NULL
;
2217 int log_level
= LOG_DEBUG
; /* May be raised if resources consumed over a threshold */
2218 size_t n_message_parts
= 0, n_iovec
= 0;
2219 char* message_parts
[1 + 2 + 2 + 1], *t
;
2220 nsec_t nsec
= NSEC_INFINITY
;
2221 CGroupIPAccountingMetric m
;
2224 const char* const ip_fields
[_CGROUP_IP_ACCOUNTING_METRIC_MAX
] = {
2225 [CGROUP_IP_INGRESS_BYTES
] = "IP_METRIC_INGRESS_BYTES",
2226 [CGROUP_IP_INGRESS_PACKETS
] = "IP_METRIC_INGRESS_PACKETS",
2227 [CGROUP_IP_EGRESS_BYTES
] = "IP_METRIC_EGRESS_BYTES",
2228 [CGROUP_IP_EGRESS_PACKETS
] = "IP_METRIC_EGRESS_PACKETS",
2230 const char* const io_fields
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
2231 [CGROUP_IO_READ_BYTES
] = "IO_METRIC_READ_BYTES",
2232 [CGROUP_IO_WRITE_BYTES
] = "IO_METRIC_WRITE_BYTES",
2233 [CGROUP_IO_READ_OPERATIONS
] = "IO_METRIC_READ_OPERATIONS",
2234 [CGROUP_IO_WRITE_OPERATIONS
] = "IO_METRIC_WRITE_OPERATIONS",
2239 /* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
2240 * accounting was enabled for a unit. It does this in two ways: a friendly human readable string with reduced
2241 * information and the complete data in structured fields. */
2243 (void) unit_get_cpu_usage(u
, &nsec
);
2244 if (nsec
!= NSEC_INFINITY
) {
2245 char buf
[FORMAT_TIMESPAN_MAX
] = "";
2247 /* Format the CPU time for inclusion in the structured log message */
2248 if (asprintf(&t
, "CPU_USAGE_NSEC=%" PRIu64
, nsec
) < 0) {
2252 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2254 /* Format the CPU time for inclusion in the human language message string */
2255 format_timespan(buf
, sizeof(buf
), nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
);
2256 t
= strjoin("consumed ", buf
, " CPU time");
2262 message_parts
[n_message_parts
++] = t
;
2264 log_level
= raise_level(log_level
,
2265 nsec
> NOTICEWORTHY_CPU_NSEC
,
2266 nsec
> MENTIONWORTHY_CPU_NSEC
);
2269 for (CGroupIOAccountingMetric k
= 0; k
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; k
++) {
2270 char buf
[FORMAT_BYTES_MAX
] = "";
2271 uint64_t value
= UINT64_MAX
;
2273 assert(io_fields
[k
]);
2275 (void) unit_get_io_accounting(u
, k
, k
> 0, &value
);
2276 if (value
== UINT64_MAX
)
2279 have_io_accounting
= true;
2283 /* Format IO accounting data for inclusion in the structured log message */
2284 if (asprintf(&t
, "%s=%" PRIu64
, io_fields
[k
], value
) < 0) {
2288 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2290 /* Format the IO accounting data for inclusion in the human language message string, but only
2291 * for the bytes counters (and not for the operations counters) */
2292 if (k
== CGROUP_IO_READ_BYTES
) {
2294 rr
= strjoin("read ", format_bytes(buf
, sizeof(buf
), value
), " from disk");
2299 } else if (k
== CGROUP_IO_WRITE_BYTES
) {
2301 wr
= strjoin("written ", format_bytes(buf
, sizeof(buf
), value
), " to disk");
2308 if (IN_SET(k
, CGROUP_IO_READ_BYTES
, CGROUP_IO_WRITE_BYTES
))
2309 log_level
= raise_level(log_level
,
2310 value
> MENTIONWORTHY_IO_BYTES
,
2311 value
> NOTICEWORTHY_IO_BYTES
);
2314 if (have_io_accounting
) {
2317 message_parts
[n_message_parts
++] = TAKE_PTR(rr
);
2319 message_parts
[n_message_parts
++] = TAKE_PTR(wr
);
2324 k
= strdup("no IO");
2330 message_parts
[n_message_parts
++] = k
;
2334 for (m
= 0; m
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
; m
++) {
2335 char buf
[FORMAT_BYTES_MAX
] = "";
2336 uint64_t value
= UINT64_MAX
;
2338 assert(ip_fields
[m
]);
2340 (void) unit_get_ip_accounting(u
, m
, &value
);
2341 if (value
== UINT64_MAX
)
2344 have_ip_accounting
= true;
2348 /* Format IP accounting data for inclusion in the structured log message */
2349 if (asprintf(&t
, "%s=%" PRIu64
, ip_fields
[m
], value
) < 0) {
2353 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2355 /* Format the IP accounting data for inclusion in the human language message string, but only for the
2356 * bytes counters (and not for the packets counters) */
2357 if (m
== CGROUP_IP_INGRESS_BYTES
) {
2359 igress
= strjoin("received ", format_bytes(buf
, sizeof(buf
), value
), " IP traffic");
2364 } else if (m
== CGROUP_IP_EGRESS_BYTES
) {
2366 egress
= strjoin("sent ", format_bytes(buf
, sizeof(buf
), value
), " IP traffic");
2373 if (IN_SET(m
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2374 log_level
= raise_level(log_level
,
2375 value
> MENTIONWORTHY_IP_BYTES
,
2376 value
> NOTICEWORTHY_IP_BYTES
);
2379 if (have_ip_accounting
) {
2382 message_parts
[n_message_parts
++] = TAKE_PTR(igress
);
2384 message_parts
[n_message_parts
++] = TAKE_PTR(egress
);
2389 k
= strdup("no IP traffic");
2395 message_parts
[n_message_parts
++] = k
;
2399 /* Is there any accounting data available at all? */
2405 if (n_message_parts
== 0)
2406 t
= strjoina("MESSAGE=", u
->id
, ": Completed.");
2408 _cleanup_free_
char *joined
;
2410 message_parts
[n_message_parts
] = NULL
;
2412 joined
= strv_join(message_parts
, ", ");
2418 joined
[0] = ascii_toupper(joined
[0]);
2419 t
= strjoina("MESSAGE=", u
->id
, ": ", joined
, ".");
2422 /* The following four fields we allocate on the stack or are static strings, we hence don't want to free them,
2423 * and hence don't increase n_iovec for them */
2424 iovec
[n_iovec
] = IOVEC_MAKE_STRING(t
);
2425 iovec
[n_iovec
+ 1] = IOVEC_MAKE_STRING("MESSAGE_ID=" SD_MESSAGE_UNIT_RESOURCES_STR
);
2427 t
= strjoina(u
->manager
->unit_log_field
, u
->id
);
2428 iovec
[n_iovec
+ 2] = IOVEC_MAKE_STRING(t
);
2430 t
= strjoina(u
->manager
->invocation_log_field
, u
->invocation_id_string
);
2431 iovec
[n_iovec
+ 3] = IOVEC_MAKE_STRING(t
);
2433 log_struct_iovec(log_level
, iovec
, n_iovec
+ 4);
2437 for (i
= 0; i
< n_message_parts
; i
++)
2438 free(message_parts
[i
]);
2440 for (i
= 0; i
< n_iovec
; i
++)
2441 free(iovec
[i
].iov_base
);
2447 static void unit_update_on_console(Unit
*u
) {
2452 b
= unit_needs_console(u
);
2453 if (u
->on_console
== b
)
2458 manager_ref_console(u
->manager
);
2460 manager_unref_console(u
->manager
);
2463 static void unit_emit_audit_start(Unit
*u
) {
2466 if (u
->type
!= UNIT_SERVICE
)
2469 /* Write audit record if we have just finished starting up */
2470 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_START
, true);
2474 static void unit_emit_audit_stop(Unit
*u
, UnitActiveState state
) {
2477 if (u
->type
!= UNIT_SERVICE
)
2481 /* Write audit record if we have just finished shutting down */
2482 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_STOP
, state
== UNIT_INACTIVE
);
2483 u
->in_audit
= false;
2485 /* Hmm, if there was no start record written write it now, so that we always have a nice pair */
2486 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_START
, state
== UNIT_INACTIVE
);
2488 if (state
== UNIT_INACTIVE
)
2489 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_STOP
, true);
2493 static bool unit_process_job(Job
*j
, UnitActiveState ns
, UnitNotifyFlags flags
) {
2494 bool unexpected
= false;
2499 if (j
->state
== JOB_WAITING
)
2501 /* So we reached a different state for this job. Let's see if we can run it now if it failed previously
2503 job_add_to_run_queue(j
);
2505 /* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
2506 * hence needs to invalidate jobs. */
2511 case JOB_VERIFY_ACTIVE
:
2513 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2514 job_finish_and_invalidate(j
, JOB_DONE
, true, false);
2515 else if (j
->state
== JOB_RUNNING
&& ns
!= UNIT_ACTIVATING
) {
2518 if (UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2519 if (ns
== UNIT_FAILED
)
2520 result
= JOB_FAILED
;
2521 else if (FLAGS_SET(flags
, UNIT_NOTIFY_SKIP_CONDITION
))
2522 result
= JOB_SKIPPED
;
2526 job_finish_and_invalidate(j
, result
, true, false);
2533 case JOB_RELOAD_OR_START
:
2534 case JOB_TRY_RELOAD
:
2536 if (j
->state
== JOB_RUNNING
) {
2537 if (ns
== UNIT_ACTIVE
)
2538 job_finish_and_invalidate(j
, (flags
& UNIT_NOTIFY_RELOAD_FAILURE
) ? JOB_FAILED
: JOB_DONE
, true, false);
2539 else if (!IN_SET(ns
, UNIT_ACTIVATING
, UNIT_RELOADING
)) {
2542 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2543 job_finish_and_invalidate(j
, ns
== UNIT_FAILED
? JOB_FAILED
: JOB_DONE
, true, false);
2551 case JOB_TRY_RESTART
:
2553 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2554 job_finish_and_invalidate(j
, JOB_DONE
, true, false);
2555 else if (j
->state
== JOB_RUNNING
&& ns
!= UNIT_DEACTIVATING
) {
2557 job_finish_and_invalidate(j
, JOB_FAILED
, true, false);
2563 assert_not_reached("Job type unknown");
2569 void unit_notify(Unit
*u
, UnitActiveState os
, UnitActiveState ns
, UnitNotifyFlags flags
) {
2574 assert(os
< _UNIT_ACTIVE_STATE_MAX
);
2575 assert(ns
< _UNIT_ACTIVE_STATE_MAX
);
2577 /* Note that this is called for all low-level state changes, even if they might map to the same high-level
2578 * UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
2579 * remounted this function will be called too! */
2583 /* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
2584 * the bus queue, so that any job change signal queued will force out the unit change signal first. */
2585 unit_add_to_dbus_queue(u
);
2587 /* Update timestamps for state changes */
2588 if (!MANAGER_IS_RELOADING(m
)) {
2589 dual_timestamp_get(&u
->state_change_timestamp
);
2591 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && !UNIT_IS_INACTIVE_OR_FAILED(ns
))
2592 u
->inactive_exit_timestamp
= u
->state_change_timestamp
;
2593 else if (!UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_INACTIVE_OR_FAILED(ns
))
2594 u
->inactive_enter_timestamp
= u
->state_change_timestamp
;
2596 if (!UNIT_IS_ACTIVE_OR_RELOADING(os
) && UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2597 u
->active_enter_timestamp
= u
->state_change_timestamp
;
2598 else if (UNIT_IS_ACTIVE_OR_RELOADING(os
) && !UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2599 u
->active_exit_timestamp
= u
->state_change_timestamp
;
2602 /* Keep track of failed units */
2603 (void) manager_update_failed_units(m
, u
, ns
== UNIT_FAILED
);
2605 /* Make sure the cgroup and state files are always removed when we become inactive */
2606 if (UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2607 unit_prune_cgroup(u
);
2608 unit_unlink_state_files(u
);
2611 unit_update_on_console(u
);
2613 if (!MANAGER_IS_RELOADING(m
)) {
2616 /* Let's propagate state changes to the job */
2618 unexpected
= unit_process_job(u
->job
, ns
, flags
);
2622 /* If this state change happened without being requested by a job, then let's retroactively start or
2623 * stop dependencies. We skip that step when deserializing, since we don't want to create any
2624 * additional jobs just because something is already activated. */
2627 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns
))
2628 retroactively_start_dependencies(u
);
2629 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os
) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns
))
2630 retroactively_stop_dependencies(u
);
2633 /* stop unneeded units regardless if going down was expected or not */
2634 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2635 check_unneeded_dependencies(u
);
2637 if (ns
!= os
&& ns
== UNIT_FAILED
) {
2638 log_unit_debug(u
, "Unit entered failed state.");
2640 if (!(flags
& UNIT_NOTIFY_WILL_AUTO_RESTART
))
2641 unit_start_on_failure(u
);
2644 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
) && !UNIT_IS_ACTIVE_OR_RELOADING(os
)) {
2645 /* This unit just finished starting up */
2647 unit_emit_audit_start(u
);
2648 manager_send_unit_plymouth(m
, u
);
2651 if (UNIT_IS_INACTIVE_OR_FAILED(ns
) && !UNIT_IS_INACTIVE_OR_FAILED(os
)) {
2652 /* This unit just stopped/failed. */
2654 unit_emit_audit_stop(u
, ns
);
2655 unit_log_resources(u
);
2659 manager_recheck_journal(m
);
2660 manager_recheck_dbus(m
);
2662 unit_trigger_notify(u
);
2664 if (!MANAGER_IS_RELOADING(m
)) {
2665 /* Maybe we finished startup and are now ready for being stopped because unneeded? */
2666 unit_submit_to_stop_when_unneeded_queue(u
);
2668 /* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens when
2669 * something BindsTo= to a Type=oneshot unit, as these units go directly from starting to inactive,
2670 * without ever entering started.) */
2671 unit_check_binds_to(u
);
2673 if (os
!= UNIT_FAILED
&& ns
== UNIT_FAILED
) {
2674 reason
= strjoina("unit ", u
->id
, " failed");
2675 emergency_action(m
, u
->failure_action
, 0, u
->reboot_arg
, unit_failure_action_exit_status(u
), reason
);
2676 } else if (!UNIT_IS_INACTIVE_OR_FAILED(os
) && ns
== UNIT_INACTIVE
) {
2677 reason
= strjoina("unit ", u
->id
, " succeeded");
2678 emergency_action(m
, u
->success_action
, 0, u
->reboot_arg
, unit_success_action_exit_status(u
), reason
);
2682 unit_add_to_gc_queue(u
);
2685 int unit_watch_pid(Unit
*u
, pid_t pid
, bool exclusive
) {
2689 assert(pid_is_valid(pid
));
2691 /* Watch a specific PID */
2693 /* Caller might be sure that this PID belongs to this unit only. Let's take this
2694 * opportunity to remove any stalled references to this PID as they can be created
2695 * easily (when watching a process which is not our direct child). */
2697 manager_unwatch_pid(u
->manager
, pid
);
2699 r
= set_ensure_allocated(&u
->pids
, NULL
);
2703 r
= hashmap_ensure_allocated(&u
->manager
->watch_pids
, NULL
);
2707 /* First try, let's add the unit keyed by "pid". */
2708 r
= hashmap_put(u
->manager
->watch_pids
, PID_TO_PTR(pid
), u
);
2714 /* OK, the "pid" key is already assigned to a different unit. Let's see if the "-pid" key (which points
2715 * to an array of Units rather than just a Unit), lists us already. */
2717 array
= hashmap_get(u
->manager
->watch_pids
, PID_TO_PTR(-pid
));
2719 for (; array
[n
]; n
++)
2723 if (found
) /* Found it already? if so, do nothing */
2728 /* Allocate a new array */
2729 new_array
= new(Unit
*, n
+ 2);
2733 memcpy_safe(new_array
, array
, sizeof(Unit
*) * n
);
2735 new_array
[n
+1] = NULL
;
2737 /* Add or replace the old array */
2738 r
= hashmap_replace(u
->manager
->watch_pids
, PID_TO_PTR(-pid
), new_array
);
2749 r
= set_put(u
->pids
, PID_TO_PTR(pid
));
2756 void unit_unwatch_pid(Unit
*u
, pid_t pid
) {
2760 assert(pid_is_valid(pid
));
2762 /* First let's drop the unit in case it's keyed as "pid". */
2763 (void) hashmap_remove_value(u
->manager
->watch_pids
, PID_TO_PTR(pid
), u
);
2765 /* Then, let's also drop the unit, in case it's in the array keyed by -pid */
2766 array
= hashmap_get(u
->manager
->watch_pids
, PID_TO_PTR(-pid
));
2770 /* Let's iterate through the array, dropping our own entry */
2771 for (n
= 0; array
[n
]; n
++)
2773 array
[m
++] = array
[n
];
2777 /* The array is now empty, remove the entire entry */
2778 assert_se(hashmap_remove(u
->manager
->watch_pids
, PID_TO_PTR(-pid
)) == array
);
2783 (void) set_remove(u
->pids
, PID_TO_PTR(pid
));
2786 void unit_unwatch_all_pids(Unit
*u
) {
2789 while (!set_isempty(u
->pids
))
2790 unit_unwatch_pid(u
, PTR_TO_PID(set_first(u
->pids
)));
2792 u
->pids
= set_free(u
->pids
);
2795 static void unit_tidy_watch_pids(Unit
*u
) {
2796 pid_t except1
, except2
;
2802 /* Cleans dead PIDs from our list */
2804 except1
= unit_main_pid(u
);
2805 except2
= unit_control_pid(u
);
2807 SET_FOREACH(e
, u
->pids
, i
) {
2808 pid_t pid
= PTR_TO_PID(e
);
2810 if (pid
== except1
|| pid
== except2
)
2813 if (!pid_is_unwaited(pid
))
2814 unit_unwatch_pid(u
, pid
);
2818 static int on_rewatch_pids_event(sd_event_source
*s
, void *userdata
) {
2824 unit_tidy_watch_pids(u
);
2825 unit_watch_all_pids(u
);
2827 /* If the PID set is empty now, then let's finish this off. */
2828 unit_synthesize_cgroup_empty_event(u
);
2833 int unit_enqueue_rewatch_pids(Unit
*u
) {
2838 if (!u
->cgroup_path
)
2841 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2844 if (r
> 0) /* On unified we can use proper notifications */
2847 /* Enqueues a low-priority job that will clean up dead PIDs from our list of PIDs to watch and subscribe to new
2848 * PIDs that might have appeared. We do this in a delayed job because the work might be quite slow, as it
2849 * involves issuing kill(pid, 0) on all processes we watch. */
2851 if (!u
->rewatch_pids_event_source
) {
2852 _cleanup_(sd_event_source_unrefp
) sd_event_source
*s
= NULL
;
2854 r
= sd_event_add_defer(u
->manager
->event
, &s
, on_rewatch_pids_event
, u
);
2856 return log_error_errno(r
, "Failed to allocate event source for tidying watched PIDs: %m");
2858 r
= sd_event_source_set_priority(s
, SD_EVENT_PRIORITY_IDLE
);
2860 return log_error_errno(r
, "Failed to adjust priority of event source for tidying watched PIDs: %m");
2862 (void) sd_event_source_set_description(s
, "tidy-watch-pids");
2864 u
->rewatch_pids_event_source
= TAKE_PTR(s
);
2867 r
= sd_event_source_set_enabled(u
->rewatch_pids_event_source
, SD_EVENT_ONESHOT
);
2869 return log_error_errno(r
, "Failed to enable event source for tidying watched PIDs: %m");
2874 void unit_dequeue_rewatch_pids(Unit
*u
) {
2878 if (!u
->rewatch_pids_event_source
)
2881 r
= sd_event_source_set_enabled(u
->rewatch_pids_event_source
, SD_EVENT_OFF
);
2883 log_warning_errno(r
, "Failed to disable event source for tidying watched PIDs, ignoring: %m");
2885 u
->rewatch_pids_event_source
= sd_event_source_unref(u
->rewatch_pids_event_source
);
2888 bool unit_job_is_applicable(Unit
*u
, JobType j
) {
2890 assert(j
>= 0 && j
< _JOB_TYPE_MAX
);
2894 case JOB_VERIFY_ACTIVE
:
2897 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
2898 * startable by us but may appear due to external events, and it thus makes sense to permit enqueuing
2903 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
2904 * external events), hence it makes no sense to permit enqueuing such a request either. */
2905 return !u
->perpetual
;
2908 case JOB_TRY_RESTART
:
2909 return unit_can_stop(u
) && unit_can_start(u
);
2912 case JOB_TRY_RELOAD
:
2913 return unit_can_reload(u
);
2915 case JOB_RELOAD_OR_START
:
2916 return unit_can_reload(u
) && unit_can_start(u
);
2919 assert_not_reached("Invalid job type");
2923 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
) {
2926 /* Only warn about some unit types */
2927 if (!IN_SET(dependency
, UNIT_CONFLICTS
, UNIT_CONFLICTED_BY
, UNIT_BEFORE
, UNIT_AFTER
, UNIT_ON_FAILURE
, UNIT_TRIGGERS
, UNIT_TRIGGERED_BY
))
2930 if (streq_ptr(u
->id
, other
))
2931 log_unit_warning(u
, "Dependency %s=%s dropped", unit_dependency_to_string(dependency
), u
->id
);
2933 log_unit_warning(u
, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency
), strna(other
), u
->id
);
2936 static int unit_add_dependency_hashmap(
2939 UnitDependencyMask origin_mask
,
2940 UnitDependencyMask destination_mask
) {
2942 UnitDependencyInfo info
;
2947 assert(origin_mask
< _UNIT_DEPENDENCY_MASK_FULL
);
2948 assert(destination_mask
< _UNIT_DEPENDENCY_MASK_FULL
);
2949 assert(origin_mask
> 0 || destination_mask
> 0);
2951 r
= hashmap_ensure_allocated(h
, NULL
);
2955 assert_cc(sizeof(void*) == sizeof(info
));
2957 info
.data
= hashmap_get(*h
, other
);
2959 /* Entry already exists. Add in our mask. */
2961 if (FLAGS_SET(origin_mask
, info
.origin_mask
) &&
2962 FLAGS_SET(destination_mask
, info
.destination_mask
))
2965 info
.origin_mask
|= origin_mask
;
2966 info
.destination_mask
|= destination_mask
;
2968 r
= hashmap_update(*h
, other
, info
.data
);
2970 info
= (UnitDependencyInfo
) {
2971 .origin_mask
= origin_mask
,
2972 .destination_mask
= destination_mask
,
2975 r
= hashmap_put(*h
, other
, info
.data
);
2983 int unit_add_dependency(
2988 UnitDependencyMask mask
) {
2990 static const UnitDependency inverse_table
[_UNIT_DEPENDENCY_MAX
] = {
2991 [UNIT_REQUIRES
] = UNIT_REQUIRED_BY
,
2992 [UNIT_WANTS
] = UNIT_WANTED_BY
,
2993 [UNIT_REQUISITE
] = UNIT_REQUISITE_OF
,
2994 [UNIT_BINDS_TO
] = UNIT_BOUND_BY
,
2995 [UNIT_PART_OF
] = UNIT_CONSISTS_OF
,
2996 [UNIT_REQUIRED_BY
] = UNIT_REQUIRES
,
2997 [UNIT_REQUISITE_OF
] = UNIT_REQUISITE
,
2998 [UNIT_WANTED_BY
] = UNIT_WANTS
,
2999 [UNIT_BOUND_BY
] = UNIT_BINDS_TO
,
3000 [UNIT_CONSISTS_OF
] = UNIT_PART_OF
,
3001 [UNIT_CONFLICTS
] = UNIT_CONFLICTED_BY
,
3002 [UNIT_CONFLICTED_BY
] = UNIT_CONFLICTS
,
3003 [UNIT_BEFORE
] = UNIT_AFTER
,
3004 [UNIT_AFTER
] = UNIT_BEFORE
,
3005 [UNIT_ON_FAILURE
] = _UNIT_DEPENDENCY_INVALID
,
3006 [UNIT_REFERENCES
] = UNIT_REFERENCED_BY
,
3007 [UNIT_REFERENCED_BY
] = UNIT_REFERENCES
,
3008 [UNIT_TRIGGERS
] = UNIT_TRIGGERED_BY
,
3009 [UNIT_TRIGGERED_BY
] = UNIT_TRIGGERS
,
3010 [UNIT_PROPAGATES_RELOAD_TO
] = UNIT_RELOAD_PROPAGATED_FROM
,
3011 [UNIT_RELOAD_PROPAGATED_FROM
] = UNIT_PROPAGATES_RELOAD_TO
,
3012 [UNIT_JOINS_NAMESPACE_OF
] = UNIT_JOINS_NAMESPACE_OF
,
3014 Unit
*original_u
= u
, *original_other
= other
;
3018 assert(d
>= 0 && d
< _UNIT_DEPENDENCY_MAX
);
3021 u
= unit_follow_merge(u
);
3022 other
= unit_follow_merge(other
);
3024 /* We won't allow dependencies on ourselves. We will not
3025 * consider them an error however. */
3027 maybe_warn_about_dependency(original_u
, original_other
->id
, d
);
3031 /* Note that ordering a device unit after a unit is permitted since it
3032 * allows to start its job running timeout at a specific time. */
3033 if (d
== UNIT_BEFORE
&& other
->type
== UNIT_DEVICE
) {
3034 log_unit_warning(u
, "Dependency Before=%s ignored (.device units cannot be delayed)", other
->id
);
3038 if (d
== UNIT_ON_FAILURE
&& !UNIT_VTABLE(u
)->can_fail
) {
3039 log_unit_warning(u
, "Requested dependency OnFailure=%s ignored (%s units cannot fail).", other
->id
, unit_type_to_string(u
->type
));
3043 if (d
== UNIT_TRIGGERS
&& !UNIT_VTABLE(u
)->can_trigger
)
3044 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
3045 "Requested dependency Triggers=%s refused (%s units cannot trigger other units).", other
->id
, unit_type_to_string(u
->type
));
3046 if (d
== UNIT_TRIGGERED_BY
&& !UNIT_VTABLE(other
)->can_trigger
)
3047 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
3048 "Requested dependency TriggeredBy=%s refused (%s units cannot trigger other units).", other
->id
, unit_type_to_string(other
->type
));
3050 r
= unit_add_dependency_hashmap(u
->dependencies
+ d
, other
, mask
, 0);
3054 if (inverse_table
[d
] != _UNIT_DEPENDENCY_INVALID
&& inverse_table
[d
] != d
) {
3055 r
= unit_add_dependency_hashmap(other
->dependencies
+ inverse_table
[d
], u
, 0, mask
);
3060 if (add_reference
) {
3061 r
= unit_add_dependency_hashmap(u
->dependencies
+ UNIT_REFERENCES
, other
, mask
, 0);
3065 r
= unit_add_dependency_hashmap(other
->dependencies
+ UNIT_REFERENCED_BY
, u
, 0, mask
);
3070 unit_add_to_dbus_queue(u
);
3074 int unit_add_two_dependencies(Unit
*u
, UnitDependency d
, UnitDependency e
, Unit
*other
, bool add_reference
, UnitDependencyMask mask
) {
3079 r
= unit_add_dependency(u
, d
, other
, add_reference
, mask
);
3083 return unit_add_dependency(u
, e
, other
, add_reference
, mask
);
3086 static int resolve_template(Unit
*u
, const char *name
, char **buf
, const char **ret
) {
3094 if (!unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
3101 r
= unit_name_replace_instance(name
, u
->instance
, buf
);
3103 _cleanup_free_
char *i
= NULL
;
3105 r
= unit_name_to_prefix(u
->id
, &i
);
3109 r
= unit_name_replace_instance(name
, i
, buf
);
3118 int unit_add_dependency_by_name(Unit
*u
, UnitDependency d
, const char *name
, bool add_reference
, UnitDependencyMask mask
) {
3119 _cleanup_free_
char *buf
= NULL
;
3126 r
= resolve_template(u
, name
, &buf
, &name
);
3130 r
= manager_load_unit(u
->manager
, name
, NULL
, NULL
, &other
);
3134 return unit_add_dependency(u
, d
, other
, add_reference
, mask
);
3137 int unit_add_two_dependencies_by_name(Unit
*u
, UnitDependency d
, UnitDependency e
, const char *name
, bool add_reference
, UnitDependencyMask mask
) {
3138 _cleanup_free_
char *buf
= NULL
;
3145 r
= resolve_template(u
, name
, &buf
, &name
);
3149 r
= manager_load_unit(u
->manager
, name
, NULL
, NULL
, &other
);
3153 return unit_add_two_dependencies(u
, d
, e
, other
, add_reference
, mask
);
3156 int set_unit_path(const char *p
) {
3157 /* This is mostly for debug purposes */
3158 if (setenv("SYSTEMD_UNIT_PATH", p
, 1) < 0)
3164 char *unit_dbus_path(Unit
*u
) {
3170 return unit_dbus_path_from_name(u
->id
);
3173 char *unit_dbus_path_invocation_id(Unit
*u
) {
3176 if (sd_id128_is_null(u
->invocation_id
))
3179 return unit_dbus_path_from_name(u
->invocation_id_string
);
3182 int unit_set_slice(Unit
*u
, Unit
*slice
) {
3186 /* Sets the unit slice if it has not been set before. Is extra
3187 * careful, to only allow this for units that actually have a
3188 * cgroup context. Also, we don't allow to set this for slices
3189 * (since the parent slice is derived from the name). Make
3190 * sure the unit we set is actually a slice. */
3192 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
3195 if (u
->type
== UNIT_SLICE
)
3198 if (unit_active_state(u
) != UNIT_INACTIVE
)
3201 if (slice
->type
!= UNIT_SLICE
)
3204 if (unit_has_name(u
, SPECIAL_INIT_SCOPE
) &&
3205 !unit_has_name(slice
, SPECIAL_ROOT_SLICE
))
3208 if (UNIT_DEREF(u
->slice
) == slice
)
3211 /* Disallow slice changes if @u is already bound to cgroups */
3212 if (UNIT_ISSET(u
->slice
) && u
->cgroup_realized
)
3215 unit_ref_set(&u
->slice
, u
, slice
);
3219 int unit_set_default_slice(Unit
*u
) {
3220 const char *slice_name
;
3226 if (UNIT_ISSET(u
->slice
))
3230 _cleanup_free_
char *prefix
= NULL
, *escaped
= NULL
;
3232 /* Implicitly place all instantiated units in their
3233 * own per-template slice */
3235 r
= unit_name_to_prefix(u
->id
, &prefix
);
3239 /* The prefix is already escaped, but it might include
3240 * "-" which has a special meaning for slice units,
3241 * hence escape it here extra. */
3242 escaped
= unit_name_escape(prefix
);
3246 if (MANAGER_IS_SYSTEM(u
->manager
))
3247 slice_name
= strjoina("system-", escaped
, ".slice");
3249 slice_name
= strjoina(escaped
, ".slice");
3252 MANAGER_IS_SYSTEM(u
->manager
) && !unit_has_name(u
, SPECIAL_INIT_SCOPE
)
3253 ? SPECIAL_SYSTEM_SLICE
3254 : SPECIAL_ROOT_SLICE
;
3256 r
= manager_load_unit(u
->manager
, slice_name
, NULL
, NULL
, &slice
);
3260 return unit_set_slice(u
, slice
);
3263 const char *unit_slice_name(Unit
*u
) {
3266 if (!UNIT_ISSET(u
->slice
))
3269 return UNIT_DEREF(u
->slice
)->id
;
3272 int unit_load_related_unit(Unit
*u
, const char *type
, Unit
**_found
) {
3273 _cleanup_free_
char *t
= NULL
;
3280 r
= unit_name_change_suffix(u
->id
, type
, &t
);
3283 if (unit_has_name(u
, t
))
3286 r
= manager_load_unit(u
->manager
, t
, NULL
, NULL
, _found
);
3287 assert(r
< 0 || *_found
!= u
);
3291 static int signal_name_owner_changed(sd_bus_message
*message
, void *userdata
, sd_bus_error
*error
) {
3292 const char *new_owner
;
3299 r
= sd_bus_message_read(message
, "sss", NULL
, NULL
, &new_owner
);
3301 bus_log_parse_error(r
);
3305 if (UNIT_VTABLE(u
)->bus_name_owner_change
)
3306 UNIT_VTABLE(u
)->bus_name_owner_change(u
, empty_to_null(new_owner
));
3311 static int get_name_owner_handler(sd_bus_message
*message
, void *userdata
, sd_bus_error
*error
) {
3312 const sd_bus_error
*e
;
3313 const char *new_owner
;
3320 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3322 e
= sd_bus_message_get_error(message
);
3324 if (!sd_bus_error_has_name(e
, "org.freedesktop.DBus.Error.NameHasNoOwner"))
3325 log_unit_error(u
, "Unexpected error response from GetNameOwner(): %s", e
->message
);
3329 r
= sd_bus_message_read(message
, "s", &new_owner
);
3331 return bus_log_parse_error(r
);
3333 assert(!isempty(new_owner
));
3336 if (UNIT_VTABLE(u
)->bus_name_owner_change
)
3337 UNIT_VTABLE(u
)->bus_name_owner_change(u
, new_owner
);
3342 int unit_install_bus_match(Unit
*u
, sd_bus
*bus
, const char *name
) {
3350 if (u
->match_bus_slot
|| u
->get_name_owner_slot
)
3353 match
= strjoina("type='signal',"
3354 "sender='org.freedesktop.DBus',"
3355 "path='/org/freedesktop/DBus',"
3356 "interface='org.freedesktop.DBus',"
3357 "member='NameOwnerChanged',"
3358 "arg0='", name
, "'");
3360 r
= sd_bus_add_match_async(bus
, &u
->match_bus_slot
, match
, signal_name_owner_changed
, NULL
, u
);
3364 r
= sd_bus_call_method_async(
3366 &u
->get_name_owner_slot
,
3367 "org.freedesktop.DBus",
3368 "/org/freedesktop/DBus",
3369 "org.freedesktop.DBus",
3371 get_name_owner_handler
,
3375 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3379 log_unit_debug(u
, "Watching D-Bus name '%s'.", name
);
3383 int unit_watch_bus_name(Unit
*u
, const char *name
) {
3389 /* Watch a specific name on the bus. We only support one unit
3390 * watching each name for now. */
3392 if (u
->manager
->api_bus
) {
3393 /* If the bus is already available, install the match directly.
3394 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
3395 r
= unit_install_bus_match(u
, u
->manager
->api_bus
, name
);
3397 return log_warning_errno(r
, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name
);
3400 r
= hashmap_put(u
->manager
->watch_bus
, name
, u
);
3402 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3403 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3404 return log_warning_errno(r
, "Failed to put bus name to hashmap: %m");
3410 void unit_unwatch_bus_name(Unit
*u
, const char *name
) {
3414 (void) hashmap_remove_value(u
->manager
->watch_bus
, name
, u
);
3415 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3416 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3419 bool unit_can_serialize(Unit
*u
) {
3422 return UNIT_VTABLE(u
)->serialize
&& UNIT_VTABLE(u
)->deserialize_item
;
3425 static int serialize_cgroup_mask(FILE *f
, const char *key
, CGroupMask mask
) {
3426 _cleanup_free_
char *s
= NULL
;
3435 r
= cg_mask_to_string(mask
, &s
);
3437 return log_error_errno(r
, "Failed to format cgroup mask: %m");
3439 return serialize_item(f
, key
, s
);
3442 static const char *const ip_accounting_metric_field
[_CGROUP_IP_ACCOUNTING_METRIC_MAX
] = {
3443 [CGROUP_IP_INGRESS_BYTES
] = "ip-accounting-ingress-bytes",
3444 [CGROUP_IP_INGRESS_PACKETS
] = "ip-accounting-ingress-packets",
3445 [CGROUP_IP_EGRESS_BYTES
] = "ip-accounting-egress-bytes",
3446 [CGROUP_IP_EGRESS_PACKETS
] = "ip-accounting-egress-packets",
3449 static const char *const io_accounting_metric_field_base
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
3450 [CGROUP_IO_READ_BYTES
] = "io-accounting-read-bytes-base",
3451 [CGROUP_IO_WRITE_BYTES
] = "io-accounting-write-bytes-base",
3452 [CGROUP_IO_READ_OPERATIONS
] = "io-accounting-read-operations-base",
3453 [CGROUP_IO_WRITE_OPERATIONS
] = "io-accounting-write-operations-base",
3456 static const char *const io_accounting_metric_field_last
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
3457 [CGROUP_IO_READ_BYTES
] = "io-accounting-read-bytes-last",
3458 [CGROUP_IO_WRITE_BYTES
] = "io-accounting-write-bytes-last",
3459 [CGROUP_IO_READ_OPERATIONS
] = "io-accounting-read-operations-last",
3460 [CGROUP_IO_WRITE_OPERATIONS
] = "io-accounting-write-operations-last",
3463 int unit_serialize(Unit
*u
, FILE *f
, FDSet
*fds
, bool serialize_jobs
) {
3464 CGroupIPAccountingMetric m
;
3471 if (unit_can_serialize(u
)) {
3472 r
= UNIT_VTABLE(u
)->serialize(u
, f
, fds
);
3477 (void) serialize_dual_timestamp(f
, "state-change-timestamp", &u
->state_change_timestamp
);
3479 (void) serialize_dual_timestamp(f
, "inactive-exit-timestamp", &u
->inactive_exit_timestamp
);
3480 (void) serialize_dual_timestamp(f
, "active-enter-timestamp", &u
->active_enter_timestamp
);
3481 (void) serialize_dual_timestamp(f
, "active-exit-timestamp", &u
->active_exit_timestamp
);
3482 (void) serialize_dual_timestamp(f
, "inactive-enter-timestamp", &u
->inactive_enter_timestamp
);
3484 (void) serialize_dual_timestamp(f
, "condition-timestamp", &u
->condition_timestamp
);
3485 (void) serialize_dual_timestamp(f
, "assert-timestamp", &u
->assert_timestamp
);
3487 if (dual_timestamp_is_set(&u
->condition_timestamp
))
3488 (void) serialize_bool(f
, "condition-result", u
->condition_result
);
3490 if (dual_timestamp_is_set(&u
->assert_timestamp
))
3491 (void) serialize_bool(f
, "assert-result", u
->assert_result
);
3493 (void) serialize_bool(f
, "transient", u
->transient
);
3494 (void) serialize_bool(f
, "in-audit", u
->in_audit
);
3496 (void) serialize_bool(f
, "exported-invocation-id", u
->exported_invocation_id
);
3497 (void) serialize_bool(f
, "exported-log-level-max", u
->exported_log_level_max
);
3498 (void) serialize_bool(f
, "exported-log-extra-fields", u
->exported_log_extra_fields
);
3499 (void) serialize_bool(f
, "exported-log-rate-limit-interval", u
->exported_log_ratelimit_interval
);
3500 (void) serialize_bool(f
, "exported-log-rate-limit-burst", u
->exported_log_ratelimit_burst
);
3502 (void) serialize_item_format(f
, "cpu-usage-base", "%" PRIu64
, u
->cpu_usage_base
);
3503 if (u
->cpu_usage_last
!= NSEC_INFINITY
)
3504 (void) serialize_item_format(f
, "cpu-usage-last", "%" PRIu64
, u
->cpu_usage_last
);
3506 if (u
->oom_kill_last
> 0)
3507 (void) serialize_item_format(f
, "oom-kill-last", "%" PRIu64
, u
->oom_kill_last
);
3509 for (CGroupIOAccountingMetric im
= 0; im
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; im
++) {
3510 (void) serialize_item_format(f
, io_accounting_metric_field_base
[im
], "%" PRIu64
, u
->io_accounting_base
[im
]);
3512 if (u
->io_accounting_last
[im
] != UINT64_MAX
)
3513 (void) serialize_item_format(f
, io_accounting_metric_field_last
[im
], "%" PRIu64
, u
->io_accounting_last
[im
]);
3517 (void) serialize_item(f
, "cgroup", u
->cgroup_path
);
3519 (void) serialize_bool(f
, "cgroup-realized", u
->cgroup_realized
);
3520 (void) serialize_cgroup_mask(f
, "cgroup-realized-mask", u
->cgroup_realized_mask
);
3521 (void) serialize_cgroup_mask(f
, "cgroup-enabled-mask", u
->cgroup_enabled_mask
);
3522 (void) serialize_cgroup_mask(f
, "cgroup-invalidated-mask", u
->cgroup_invalidated_mask
);
3524 if (uid_is_valid(u
->ref_uid
))
3525 (void) serialize_item_format(f
, "ref-uid", UID_FMT
, u
->ref_uid
);
3526 if (gid_is_valid(u
->ref_gid
))
3527 (void) serialize_item_format(f
, "ref-gid", GID_FMT
, u
->ref_gid
);
3529 if (!sd_id128_is_null(u
->invocation_id
))
3530 (void) serialize_item_format(f
, "invocation-id", SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(u
->invocation_id
));
3532 (void) serialize_item_format(f
, "freezer-state", "%s", freezer_state_to_string(unit_freezer_state(u
)));
3534 bus_track_serialize(u
->bus_track
, f
, "ref");
3536 for (m
= 0; m
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
; m
++) {
3539 r
= unit_get_ip_accounting(u
, m
, &v
);
3541 (void) serialize_item_format(f
, ip_accounting_metric_field
[m
], "%" PRIu64
, v
);
3544 if (serialize_jobs
) {
3547 job_serialize(u
->job
, f
);
3552 job_serialize(u
->nop_job
, f
);
3561 static int unit_deserialize_job(Unit
*u
, FILE *f
) {
3562 _cleanup_(job_freep
) Job
*j
= NULL
;
3572 r
= job_deserialize(j
, f
);
3576 r
= job_install_deserialized(j
);
3584 int unit_deserialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
3592 _cleanup_free_
char *line
= NULL
;
3597 r
= read_line(f
, LONG_LINE_MAX
, &line
);
3599 return log_error_errno(r
, "Failed to read serialization line: %m");
3600 if (r
== 0) /* eof */
3604 if (isempty(l
)) /* End marker */
3607 k
= strcspn(l
, "=");
3615 if (streq(l
, "job")) {
3617 /* New-style serialized job */
3618 r
= unit_deserialize_job(u
, f
);
3621 } else /* Legacy for pre-44 */
3622 log_unit_warning(u
, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v
);
3624 } else if (streq(l
, "state-change-timestamp")) {
3625 (void) deserialize_dual_timestamp(v
, &u
->state_change_timestamp
);
3627 } else if (streq(l
, "inactive-exit-timestamp")) {
3628 (void) deserialize_dual_timestamp(v
, &u
->inactive_exit_timestamp
);
3630 } else if (streq(l
, "active-enter-timestamp")) {
3631 (void) deserialize_dual_timestamp(v
, &u
->active_enter_timestamp
);
3633 } else if (streq(l
, "active-exit-timestamp")) {
3634 (void) deserialize_dual_timestamp(v
, &u
->active_exit_timestamp
);
3636 } else if (streq(l
, "inactive-enter-timestamp")) {
3637 (void) deserialize_dual_timestamp(v
, &u
->inactive_enter_timestamp
);
3639 } else if (streq(l
, "condition-timestamp")) {
3640 (void) deserialize_dual_timestamp(v
, &u
->condition_timestamp
);
3642 } else if (streq(l
, "assert-timestamp")) {
3643 (void) deserialize_dual_timestamp(v
, &u
->assert_timestamp
);
3645 } else if (streq(l
, "condition-result")) {
3647 r
= parse_boolean(v
);
3649 log_unit_debug(u
, "Failed to parse condition result value %s, ignoring.", v
);
3651 u
->condition_result
= r
;
3655 } else if (streq(l
, "assert-result")) {
3657 r
= parse_boolean(v
);
3659 log_unit_debug(u
, "Failed to parse assert result value %s, ignoring.", v
);
3661 u
->assert_result
= r
;
3665 } else if (streq(l
, "transient")) {
3667 r
= parse_boolean(v
);
3669 log_unit_debug(u
, "Failed to parse transient bool %s, ignoring.", v
);
3675 } else if (streq(l
, "in-audit")) {
3677 r
= parse_boolean(v
);
3679 log_unit_debug(u
, "Failed to parse in-audit bool %s, ignoring.", v
);
3685 } else if (streq(l
, "exported-invocation-id")) {
3687 r
= parse_boolean(v
);
3689 log_unit_debug(u
, "Failed to parse exported invocation ID bool %s, ignoring.", v
);
3691 u
->exported_invocation_id
= r
;
3695 } else if (streq(l
, "exported-log-level-max")) {
3697 r
= parse_boolean(v
);
3699 log_unit_debug(u
, "Failed to parse exported log level max bool %s, ignoring.", v
);
3701 u
->exported_log_level_max
= r
;
3705 } else if (streq(l
, "exported-log-extra-fields")) {
3707 r
= parse_boolean(v
);
3709 log_unit_debug(u
, "Failed to parse exported log extra fields bool %s, ignoring.", v
);
3711 u
->exported_log_extra_fields
= r
;
3715 } else if (streq(l
, "exported-log-rate-limit-interval")) {
3717 r
= parse_boolean(v
);
3719 log_unit_debug(u
, "Failed to parse exported log rate limit interval %s, ignoring.", v
);
3721 u
->exported_log_ratelimit_interval
= r
;
3725 } else if (streq(l
, "exported-log-rate-limit-burst")) {
3727 r
= parse_boolean(v
);
3729 log_unit_debug(u
, "Failed to parse exported log rate limit burst %s, ignoring.", v
);
3731 u
->exported_log_ratelimit_burst
= r
;
3735 } else if (STR_IN_SET(l
, "cpu-usage-base", "cpuacct-usage-base")) {
3737 r
= safe_atou64(v
, &u
->cpu_usage_base
);
3739 log_unit_debug(u
, "Failed to parse CPU usage base %s, ignoring.", v
);
3743 } else if (streq(l
, "cpu-usage-last")) {
3745 r
= safe_atou64(v
, &u
->cpu_usage_last
);
3747 log_unit_debug(u
, "Failed to read CPU usage last %s, ignoring.", v
);
3751 } else if (streq(l
, "oom-kill-last")) {
3753 r
= safe_atou64(v
, &u
->oom_kill_last
);
3755 log_unit_debug(u
, "Failed to read OOM kill last %s, ignoring.", v
);
3759 } else if (streq(l
, "cgroup")) {
3761 r
= unit_set_cgroup_path(u
, v
);
3763 log_unit_debug_errno(u
, r
, "Failed to set cgroup path %s, ignoring: %m", v
);
3765 (void) unit_watch_cgroup(u
);
3766 (void) unit_watch_cgroup_memory(u
);
3769 } else if (streq(l
, "cgroup-realized")) {
3772 b
= parse_boolean(v
);
3774 log_unit_debug(u
, "Failed to parse cgroup-realized bool %s, ignoring.", v
);
3776 u
->cgroup_realized
= b
;
3780 } else if (streq(l
, "cgroup-realized-mask")) {
3782 r
= cg_mask_from_string(v
, &u
->cgroup_realized_mask
);
3784 log_unit_debug(u
, "Failed to parse cgroup-realized-mask %s, ignoring.", v
);
3787 } else if (streq(l
, "cgroup-enabled-mask")) {
3789 r
= cg_mask_from_string(v
, &u
->cgroup_enabled_mask
);
3791 log_unit_debug(u
, "Failed to parse cgroup-enabled-mask %s, ignoring.", v
);
3794 } else if (streq(l
, "cgroup-invalidated-mask")) {
3796 r
= cg_mask_from_string(v
, &u
->cgroup_invalidated_mask
);
3798 log_unit_debug(u
, "Failed to parse cgroup-invalidated-mask %s, ignoring.", v
);
3801 } else if (streq(l
, "ref-uid")) {
3804 r
= parse_uid(v
, &uid
);
3806 log_unit_debug(u
, "Failed to parse referenced UID %s, ignoring.", v
);
3808 unit_ref_uid_gid(u
, uid
, GID_INVALID
);
3812 } else if (streq(l
, "ref-gid")) {
3815 r
= parse_gid(v
, &gid
);
3817 log_unit_debug(u
, "Failed to parse referenced GID %s, ignoring.", v
);
3819 unit_ref_uid_gid(u
, UID_INVALID
, gid
);
3823 } else if (streq(l
, "ref")) {
3825 r
= strv_extend(&u
->deserialized_refs
, v
);
3830 } else if (streq(l
, "invocation-id")) {
3833 r
= sd_id128_from_string(v
, &id
);
3835 log_unit_debug(u
, "Failed to parse invocation id %s, ignoring.", v
);
3837 r
= unit_set_invocation_id(u
, id
);
3839 log_unit_warning_errno(u
, r
, "Failed to set invocation ID for unit: %m");
3843 } else if (streq(l
, "freezer-state")) {
3846 s
= freezer_state_from_string(v
);
3848 log_unit_debug(u
, "Failed to deserialize freezer-state '%s', ignoring.", v
);
3850 u
->freezer_state
= s
;
3855 /* Check if this is an IP accounting metric serialization field */
3856 m
= string_table_lookup(ip_accounting_metric_field
, ELEMENTSOF(ip_accounting_metric_field
), l
);
3860 r
= safe_atou64(v
, &c
);
3862 log_unit_debug(u
, "Failed to parse IP accounting value %s, ignoring.", v
);
3864 u
->ip_accounting_extra
[m
] = c
;
3868 m
= string_table_lookup(io_accounting_metric_field_base
, ELEMENTSOF(io_accounting_metric_field_base
), l
);
3872 r
= safe_atou64(v
, &c
);
3874 log_unit_debug(u
, "Failed to parse IO accounting base value %s, ignoring.", v
);
3876 u
->io_accounting_base
[m
] = c
;
3880 m
= string_table_lookup(io_accounting_metric_field_last
, ELEMENTSOF(io_accounting_metric_field_last
), l
);
3884 r
= safe_atou64(v
, &c
);
3886 log_unit_debug(u
, "Failed to parse IO accounting last value %s, ignoring.", v
);
3888 u
->io_accounting_last
[m
] = c
;
3892 if (unit_can_serialize(u
)) {
3893 r
= exec_runtime_deserialize_compat(u
, l
, v
, fds
);
3895 log_unit_warning(u
, "Failed to deserialize runtime parameter '%s', ignoring.", l
);
3899 /* Returns positive if key was handled by the call */
3903 r
= UNIT_VTABLE(u
)->deserialize_item(u
, l
, v
, fds
);
3905 log_unit_warning(u
, "Failed to deserialize unit parameter '%s', ignoring.", l
);
3909 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
3910 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
3911 * before 228 where the base for timeouts was not persistent across reboots. */
3913 if (!dual_timestamp_is_set(&u
->state_change_timestamp
))
3914 dual_timestamp_get(&u
->state_change_timestamp
);
3916 /* Let's make sure that everything that is deserialized also gets any potential new cgroup settings applied
3917 * after we are done. For that we invalidate anything already realized, so that we can realize it again. */
3918 unit_invalidate_cgroup(u
, _CGROUP_MASK_ALL
);
3919 unit_invalidate_cgroup_bpf(u
);
3924 int unit_deserialize_skip(FILE *f
) {
3928 /* Skip serialized data for this unit. We don't know what it is. */
3931 _cleanup_free_
char *line
= NULL
;
3934 r
= read_line(f
, LONG_LINE_MAX
, &line
);
3936 return log_error_errno(r
, "Failed to read serialization line: %m");
3948 int unit_add_node_dependency(Unit
*u
, const char *what
, UnitDependency dep
, UnitDependencyMask mask
) {
3949 _cleanup_free_
char *e
= NULL
;
3955 /* Adds in links to the device node that this unit is based on */
3959 if (!is_device_path(what
))
3962 /* When device units aren't supported (such as in a container), don't create dependencies on them. */
3963 if (!unit_type_supported(UNIT_DEVICE
))
3966 r
= unit_name_from_path(what
, ".device", &e
);
3970 r
= manager_load_unit(u
->manager
, e
, NULL
, NULL
, &device
);
3974 if (dep
== UNIT_REQUIRES
&& device_shall_be_bound_by(device
, u
))
3975 dep
= UNIT_BINDS_TO
;
3977 return unit_add_two_dependencies(u
, UNIT_AFTER
,
3978 MANAGER_IS_SYSTEM(u
->manager
) ? dep
: UNIT_WANTS
,
3979 device
, true, mask
);
3982 int unit_add_blockdev_dependency(Unit
*u
, const char *what
, UnitDependencyMask mask
) {
3983 _cleanup_free_
char *escaped
= NULL
, *target
= NULL
;
3991 if (!path_startswith(what
, "/dev/"))
3994 /* If we don't support devices, then also don't bother with blockdev@.target */
3995 if (!unit_type_supported(UNIT_DEVICE
))
3998 r
= unit_name_path_escape(what
, &escaped
);
4002 r
= unit_name_build("blockdev", escaped
, ".target", &target
);
4006 return unit_add_dependency_by_name(u
, UNIT_AFTER
, target
, true, mask
);
4009 int unit_coldplug(Unit
*u
) {
4016 /* Make sure we don't enter a loop, when coldplugging recursively. */
4020 u
->coldplugged
= true;
4022 STRV_FOREACH(i
, u
->deserialized_refs
) {
4023 q
= bus_unit_track_add_name(u
, *i
);
4024 if (q
< 0 && r
>= 0)
4027 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
4029 if (UNIT_VTABLE(u
)->coldplug
) {
4030 q
= UNIT_VTABLE(u
)->coldplug(u
);
4031 if (q
< 0 && r
>= 0)
4035 uj
= u
->job
?: u
->nop_job
;
4037 q
= job_coldplug(uj
);
4038 if (q
< 0 && r
>= 0)
4045 void unit_catchup(Unit
*u
) {
4048 if (UNIT_VTABLE(u
)->catchup
)
4049 UNIT_VTABLE(u
)->catchup(u
);
4052 static bool fragment_mtime_newer(const char *path
, usec_t mtime
, bool path_masked
) {
4058 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
4059 * are never out-of-date. */
4060 if (PATH_STARTSWITH_SET(path
, "/proc", "/sys"))
4063 if (stat(path
, &st
) < 0)
4064 /* What, cannot access this anymore? */
4068 /* For masked files check if they are still so */
4069 return !null_or_empty(&st
);
4071 /* For non-empty files check the mtime */
4072 return timespec_load(&st
.st_mtim
) > mtime
;
4077 bool unit_need_daemon_reload(Unit
*u
) {
4078 _cleanup_strv_free_
char **t
= NULL
;
4083 /* For unit files, we allow masking… */
4084 if (fragment_mtime_newer(u
->fragment_path
, u
->fragment_mtime
,
4085 u
->load_state
== UNIT_MASKED
))
4088 /* Source paths should not be masked… */
4089 if (fragment_mtime_newer(u
->source_path
, u
->source_mtime
, false))
4092 if (u
->load_state
== UNIT_LOADED
)
4093 (void) unit_find_dropin_paths(u
, &t
);
4094 if (!strv_equal(u
->dropin_paths
, t
))
4097 /* … any drop-ins that are masked are simply omitted from the list. */
4098 STRV_FOREACH(path
, u
->dropin_paths
)
4099 if (fragment_mtime_newer(*path
, u
->dropin_mtime
, false))
4105 void unit_reset_failed(Unit
*u
) {
4108 if (UNIT_VTABLE(u
)->reset_failed
)
4109 UNIT_VTABLE(u
)->reset_failed(u
);
4111 ratelimit_reset(&u
->start_ratelimit
);
4112 u
->start_limit_hit
= false;
4115 Unit
*unit_following(Unit
*u
) {
4118 if (UNIT_VTABLE(u
)->following
)
4119 return UNIT_VTABLE(u
)->following(u
);
4124 bool unit_stop_pending(Unit
*u
) {
4127 /* This call does check the current state of the unit. It's
4128 * hence useful to be called from state change calls of the
4129 * unit itself, where the state isn't updated yet. This is
4130 * different from unit_inactive_or_pending() which checks both
4131 * the current state and for a queued job. */
4133 return unit_has_job_type(u
, JOB_STOP
);
4136 bool unit_inactive_or_pending(Unit
*u
) {
4139 /* Returns true if the unit is inactive or going down */
4141 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)))
4144 if (unit_stop_pending(u
))
4150 bool unit_active_or_pending(Unit
*u
) {
4153 /* Returns true if the unit is active or going up */
4155 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)))
4159 IN_SET(u
->job
->type
, JOB_START
, JOB_RELOAD_OR_START
, JOB_RESTART
))
4165 bool unit_will_restart_default(Unit
*u
) {
4168 return unit_has_job_type(u
, JOB_START
);
4171 bool unit_will_restart(Unit
*u
) {
4174 if (!UNIT_VTABLE(u
)->will_restart
)
4177 return UNIT_VTABLE(u
)->will_restart(u
);
4180 int unit_kill(Unit
*u
, KillWho w
, int signo
, sd_bus_error
*error
) {
4182 assert(w
>= 0 && w
< _KILL_WHO_MAX
);
4183 assert(SIGNAL_VALID(signo
));
4185 if (!UNIT_VTABLE(u
)->kill
)
4188 return UNIT_VTABLE(u
)->kill(u
, w
, signo
, error
);
4191 static Set
*unit_pid_set(pid_t main_pid
, pid_t control_pid
) {
4192 _cleanup_set_free_ Set
*pid_set
= NULL
;
4195 pid_set
= set_new(NULL
);
4199 /* Exclude the main/control pids from being killed via the cgroup */
4201 r
= set_put(pid_set
, PID_TO_PTR(main_pid
));
4206 if (control_pid
> 0) {
4207 r
= set_put(pid_set
, PID_TO_PTR(control_pid
));
4212 return TAKE_PTR(pid_set
);
4215 int unit_kill_common(
4221 sd_bus_error
*error
) {
4224 bool killed
= false;
4226 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
)) {
4228 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no main processes", unit_type_to_string(u
->type
));
4229 else if (main_pid
== 0)
4230 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No main process to kill");
4233 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
)) {
4234 if (control_pid
< 0)
4235 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no control processes", unit_type_to_string(u
->type
));
4236 else if (control_pid
== 0)
4237 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No control process to kill");
4240 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
4241 if (control_pid
> 0) {
4242 if (kill(control_pid
, signo
) < 0)
4248 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
4250 if (kill(main_pid
, signo
) < 0)
4256 if (IN_SET(who
, KILL_ALL
, KILL_ALL_FAIL
) && u
->cgroup_path
) {
4257 _cleanup_set_free_ Set
*pid_set
= NULL
;
4260 /* Exclude the main/control pids from being killed via the cgroup */
4261 pid_set
= unit_pid_set(main_pid
, control_pid
);
4265 q
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, signo
, 0, pid_set
, NULL
, NULL
);
4266 if (q
< 0 && !IN_SET(q
, -EAGAIN
, -ESRCH
, -ENOENT
))
4272 if (r
== 0 && !killed
&& IN_SET(who
, KILL_ALL_FAIL
, KILL_CONTROL_FAIL
))
4278 int unit_following_set(Unit
*u
, Set
**s
) {
4282 if (UNIT_VTABLE(u
)->following_set
)
4283 return UNIT_VTABLE(u
)->following_set(u
, s
);
4289 UnitFileState
unit_get_unit_file_state(Unit
*u
) {
4294 if (u
->unit_file_state
< 0 && u
->fragment_path
) {
4295 r
= unit_file_get_state(
4296 u
->manager
->unit_file_scope
,
4299 &u
->unit_file_state
);
4301 u
->unit_file_state
= UNIT_FILE_BAD
;
4304 return u
->unit_file_state
;
4307 int unit_get_unit_file_preset(Unit
*u
) {
4310 if (u
->unit_file_preset
< 0 && u
->fragment_path
)
4311 u
->unit_file_preset
= unit_file_query_preset(
4312 u
->manager
->unit_file_scope
,
4314 basename(u
->fragment_path
),
4317 return u
->unit_file_preset
;
4320 Unit
* unit_ref_set(UnitRef
*ref
, Unit
*source
, Unit
*target
) {
4326 unit_ref_unset(ref
);
4328 ref
->source
= source
;
4329 ref
->target
= target
;
4330 LIST_PREPEND(refs_by_target
, target
->refs_by_target
, ref
);
4334 void unit_ref_unset(UnitRef
*ref
) {
4340 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
4341 * be unreferenced now. */
4342 unit_add_to_gc_queue(ref
->target
);
4344 LIST_REMOVE(refs_by_target
, ref
->target
->refs_by_target
, ref
);
4345 ref
->source
= ref
->target
= NULL
;
4348 static int user_from_unit_name(Unit
*u
, char **ret
) {
4350 static const uint8_t hash_key
[] = {
4351 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
4352 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
4355 _cleanup_free_
char *n
= NULL
;
4358 r
= unit_name_to_prefix(u
->id
, &n
);
4362 if (valid_user_group_name(n
, 0)) {
4367 /* If we can't use the unit name as a user name, then let's hash it and use that */
4368 if (asprintf(ret
, "_du%016" PRIx64
, siphash24(n
, strlen(n
), hash_key
)) < 0)
4374 int unit_patch_contexts(Unit
*u
) {
4382 /* Patch in the manager defaults into the exec and cgroup
4383 * contexts, _after_ the rest of the settings have been
4386 ec
= unit_get_exec_context(u
);
4388 /* This only copies in the ones that need memory */
4389 for (i
= 0; i
< _RLIMIT_MAX
; i
++)
4390 if (u
->manager
->rlimit
[i
] && !ec
->rlimit
[i
]) {
4391 ec
->rlimit
[i
] = newdup(struct rlimit
, u
->manager
->rlimit
[i
], 1);
4396 if (MANAGER_IS_USER(u
->manager
) &&
4397 !ec
->working_directory
) {
4399 r
= get_home_dir(&ec
->working_directory
);
4403 /* Allow user services to run, even if the
4404 * home directory is missing */
4405 ec
->working_directory_missing_ok
= true;
4408 if (ec
->private_devices
)
4409 ec
->capability_bounding_set
&= ~((UINT64_C(1) << CAP_MKNOD
) | (UINT64_C(1) << CAP_SYS_RAWIO
));
4411 if (ec
->protect_kernel_modules
)
4412 ec
->capability_bounding_set
&= ~(UINT64_C(1) << CAP_SYS_MODULE
);
4414 if (ec
->protect_kernel_logs
)
4415 ec
->capability_bounding_set
&= ~(UINT64_C(1) << CAP_SYSLOG
);
4417 if (ec
->protect_clock
)
4418 ec
->capability_bounding_set
&= ~((UINT64_C(1) << CAP_SYS_TIME
) | (UINT64_C(1) << CAP_WAKE_ALARM
));
4420 if (ec
->dynamic_user
) {
4422 r
= user_from_unit_name(u
, &ec
->user
);
4428 ec
->group
= strdup(ec
->user
);
4433 /* If the dynamic user option is on, let's make sure that the unit can't leave its
4434 * UID/GID around in the file system or on IPC objects. Hence enforce a strict
4437 ec
->private_tmp
= true;
4438 ec
->remove_ipc
= true;
4439 ec
->protect_system
= PROTECT_SYSTEM_STRICT
;
4440 if (ec
->protect_home
== PROTECT_HOME_NO
)
4441 ec
->protect_home
= PROTECT_HOME_READ_ONLY
;
4443 /* Make sure this service can neither benefit from SUID/SGID binaries nor create
4445 ec
->no_new_privileges
= true;
4446 ec
->restrict_suid_sgid
= true;
4450 cc
= unit_get_cgroup_context(u
);
4453 if (ec
->private_devices
&&
4454 cc
->device_policy
== CGROUP_DEVICE_POLICY_AUTO
)
4455 cc
->device_policy
= CGROUP_DEVICE_POLICY_CLOSED
;
4457 if (ec
->root_image
&&
4458 (cc
->device_policy
!= CGROUP_DEVICE_POLICY_AUTO
|| cc
->device_allow
)) {
4460 /* When RootImage= is specified, the following devices are touched. */
4461 r
= cgroup_add_device_allow(cc
, "/dev/loop-control", "rw");
4465 r
= cgroup_add_device_allow(cc
, "block-loop", "rwm");
4469 r
= cgroup_add_device_allow(cc
, "block-blkext", "rwm");
4473 /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices */
4474 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_WANTS
, "modprobe@loop.service", true, UNIT_DEPENDENCY_FILE
);
4479 if (ec
->protect_clock
) {
4480 r
= cgroup_add_device_allow(cc
, "char-rtc", "r");
4489 ExecContext
*unit_get_exec_context(Unit
*u
) {
4496 offset
= UNIT_VTABLE(u
)->exec_context_offset
;
4500 return (ExecContext
*) ((uint8_t*) u
+ offset
);
4503 KillContext
*unit_get_kill_context(Unit
*u
) {
4510 offset
= UNIT_VTABLE(u
)->kill_context_offset
;
4514 return (KillContext
*) ((uint8_t*) u
+ offset
);
4517 CGroupContext
*unit_get_cgroup_context(Unit
*u
) {
4523 offset
= UNIT_VTABLE(u
)->cgroup_context_offset
;
4527 return (CGroupContext
*) ((uint8_t*) u
+ offset
);
4530 ExecRuntime
*unit_get_exec_runtime(Unit
*u
) {
4536 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
4540 return *(ExecRuntime
**) ((uint8_t*) u
+ offset
);
4543 static const char* unit_drop_in_dir(Unit
*u
, UnitWriteFlags flags
) {
4546 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4549 if (u
->transient
) /* Redirect drop-ins for transient units always into the transient directory. */
4550 return u
->manager
->lookup_paths
.transient
;
4552 if (flags
& UNIT_PERSISTENT
)
4553 return u
->manager
->lookup_paths
.persistent_control
;
4555 if (flags
& UNIT_RUNTIME
)
4556 return u
->manager
->lookup_paths
.runtime_control
;
4561 char* unit_escape_setting(const char *s
, UnitWriteFlags flags
, char **buf
) {
4567 /* Escapes the input string as requested. Returns the escaped string. If 'buf' is specified then the allocated
4568 * return buffer pointer is also written to *buf, except if no escaping was necessary, in which case *buf is
4569 * set to NULL, and the input pointer is returned as-is. This means the return value always contains a properly
4570 * escaped version, but *buf when passed only contains a pointer if an allocation was necessary. If *buf is
4571 * not specified, then the return value always needs to be freed. Callers can use this to optimize memory
4574 if (flags
& UNIT_ESCAPE_SPECIFIERS
) {
4575 ret
= specifier_escape(s
);
4582 if (flags
& UNIT_ESCAPE_C
) {
4595 return ret
?: (char*) s
;
4598 return ret
?: strdup(s
);
4601 char* unit_concat_strv(char **l
, UnitWriteFlags flags
) {
4602 _cleanup_free_
char *result
= NULL
;
4603 size_t n
= 0, allocated
= 0;
4606 /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command lines in a
4607 * way suitable for ExecStart= stanzas */
4609 STRV_FOREACH(i
, l
) {
4610 _cleanup_free_
char *buf
= NULL
;
4615 p
= unit_escape_setting(*i
, flags
, &buf
);
4619 a
= (n
> 0) + 1 + strlen(p
) + 1; /* separating space + " + entry + " */
4620 if (!GREEDY_REALLOC(result
, allocated
, n
+ a
+ 1))
4634 if (!GREEDY_REALLOC(result
, allocated
, n
+ 1))
4639 return TAKE_PTR(result
);
4642 int unit_write_setting(Unit
*u
, UnitWriteFlags flags
, const char *name
, const char *data
) {
4643 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *escaped
= NULL
;
4644 const char *dir
, *wrapped
;
4651 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4654 data
= unit_escape_setting(data
, flags
, &escaped
);
4658 /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
4659 * previous section header is the same */
4661 if (flags
& UNIT_PRIVATE
) {
4662 if (!UNIT_VTABLE(u
)->private_section
)
4665 if (!u
->transient_file
|| u
->last_section_private
< 0)
4666 data
= strjoina("[", UNIT_VTABLE(u
)->private_section
, "]\n", data
);
4667 else if (u
->last_section_private
== 0)
4668 data
= strjoina("\n[", UNIT_VTABLE(u
)->private_section
, "]\n", data
);
4670 if (!u
->transient_file
|| u
->last_section_private
< 0)
4671 data
= strjoina("[Unit]\n", data
);
4672 else if (u
->last_section_private
> 0)
4673 data
= strjoina("\n[Unit]\n", data
);
4676 if (u
->transient_file
) {
4677 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
4678 * write to the transient unit file. */
4679 fputs(data
, u
->transient_file
);
4681 if (!endswith(data
, "\n"))
4682 fputc('\n', u
->transient_file
);
4684 /* Remember which section we wrote this entry to */
4685 u
->last_section_private
= !!(flags
& UNIT_PRIVATE
);
4689 dir
= unit_drop_in_dir(u
, flags
);
4693 wrapped
= strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
4694 "# or an equivalent operation. Do not edit.\n",
4698 r
= drop_in_file(dir
, u
->id
, 50, name
, &p
, &q
);
4702 (void) mkdir_p_label(p
, 0755);
4704 /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
4705 * recreate the cache after every drop-in we write. */
4706 if (u
->manager
->unit_path_cache
) {
4707 r
= set_put_strdup(&u
->manager
->unit_path_cache
, p
);
4712 r
= write_string_file_atomic_label(q
, wrapped
);
4716 r
= strv_push(&u
->dropin_paths
, q
);
4721 strv_uniq(u
->dropin_paths
);
4723 u
->dropin_mtime
= now(CLOCK_REALTIME
);
4728 int unit_write_settingf(Unit
*u
, UnitWriteFlags flags
, const char *name
, const char *format
, ...) {
4729 _cleanup_free_
char *p
= NULL
;
4737 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4740 va_start(ap
, format
);
4741 r
= vasprintf(&p
, format
, ap
);
4747 return unit_write_setting(u
, flags
, name
, p
);
4750 int unit_make_transient(Unit
*u
) {
4751 _cleanup_free_
char *path
= NULL
;
4756 if (!UNIT_VTABLE(u
)->can_transient
)
4759 (void) mkdir_p_label(u
->manager
->lookup_paths
.transient
, 0755);
4761 path
= path_join(u
->manager
->lookup_paths
.transient
, u
->id
);
4765 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
4766 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
4768 RUN_WITH_UMASK(0022) {
4769 f
= fopen(path
, "we");
4774 safe_fclose(u
->transient_file
);
4775 u
->transient_file
= f
;
4777 free_and_replace(u
->fragment_path
, path
);
4779 u
->source_path
= mfree(u
->source_path
);
4780 u
->dropin_paths
= strv_free(u
->dropin_paths
);
4781 u
->fragment_mtime
= u
->source_mtime
= u
->dropin_mtime
= 0;
4783 u
->load_state
= UNIT_STUB
;
4785 u
->transient
= true;
4787 unit_add_to_dbus_queue(u
);
4788 unit_add_to_gc_queue(u
);
4790 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
4796 static int log_kill(pid_t pid
, int sig
, void *userdata
) {
4797 _cleanup_free_
char *comm
= NULL
;
4799 (void) get_process_comm(pid
, &comm
);
4801 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
4802 only, like for example systemd's own PAM stub process. */
4803 if (comm
&& comm
[0] == '(')
4806 log_unit_notice(userdata
,
4807 "Killing process " PID_FMT
" (%s) with signal SIG%s.",
4810 signal_to_string(sig
));
4815 static int operation_to_signal(const KillContext
*c
, KillOperation k
, bool *noteworthy
) {
4820 case KILL_TERMINATE
:
4821 case KILL_TERMINATE_AND_LOG
:
4822 *noteworthy
= false;
4823 return c
->kill_signal
;
4826 *noteworthy
= false;
4827 return restart_kill_signal(c
);
4831 return c
->final_kill_signal
;
4835 return c
->watchdog_signal
;
4838 assert_not_reached("KillOperation unknown");
4842 int unit_kill_context(
4848 bool main_pid_alien
) {
4850 bool wait_for_exit
= false, send_sighup
;
4851 cg_kill_log_func_t log_func
= NULL
;
4857 /* Kill the processes belonging to this unit, in preparation for shutting the unit down.
4858 * Returns > 0 if we killed something worth waiting for, 0 otherwise. */
4860 if (c
->kill_mode
== KILL_NONE
)
4864 sig
= operation_to_signal(c
, k
, ¬eworthy
);
4866 log_func
= log_kill
;
4870 IN_SET(k
, KILL_TERMINATE
, KILL_TERMINATE_AND_LOG
) &&
4875 log_func(main_pid
, sig
, u
);
4877 r
= kill_and_sigcont(main_pid
, sig
);
4878 if (r
< 0 && r
!= -ESRCH
) {
4879 _cleanup_free_
char *comm
= NULL
;
4880 (void) get_process_comm(main_pid
, &comm
);
4882 log_unit_warning_errno(u
, r
, "Failed to kill main process " PID_FMT
" (%s), ignoring: %m", main_pid
, strna(comm
));
4884 if (!main_pid_alien
)
4885 wait_for_exit
= true;
4887 if (r
!= -ESRCH
&& send_sighup
)
4888 (void) kill(main_pid
, SIGHUP
);
4892 if (control_pid
> 0) {
4894 log_func(control_pid
, sig
, u
);
4896 r
= kill_and_sigcont(control_pid
, sig
);
4897 if (r
< 0 && r
!= -ESRCH
) {
4898 _cleanup_free_
char *comm
= NULL
;
4899 (void) get_process_comm(control_pid
, &comm
);
4901 log_unit_warning_errno(u
, r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m", control_pid
, strna(comm
));
4903 wait_for_exit
= true;
4905 if (r
!= -ESRCH
&& send_sighup
)
4906 (void) kill(control_pid
, SIGHUP
);
4910 if (u
->cgroup_path
&&
4911 (c
->kill_mode
== KILL_CONTROL_GROUP
|| (c
->kill_mode
== KILL_MIXED
&& k
== KILL_KILL
))) {
4912 _cleanup_set_free_ Set
*pid_set
= NULL
;
4914 /* Exclude the main/control pids from being killed via the cgroup */
4915 pid_set
= unit_pid_set(main_pid
, control_pid
);
4919 r
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
4921 CGROUP_SIGCONT
|CGROUP_IGNORE_SELF
,
4925 if (!IN_SET(r
, -EAGAIN
, -ESRCH
, -ENOENT
))
4926 log_unit_warning_errno(u
, r
, "Failed to kill control group %s, ignoring: %m", u
->cgroup_path
);
4930 /* FIXME: For now, on the legacy hierarchy, we will not wait for the cgroup members to die if
4931 * we are running in a container or if this is a delegation unit, simply because cgroup
4932 * notification is unreliable in these cases. It doesn't work at all in containers, and outside
4933 * of containers it can be confused easily by left-over directories in the cgroup — which
4934 * however should not exist in non-delegated units. On the unified hierarchy that's different,
4935 * there we get proper events. Hence rely on them. */
4937 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0 ||
4938 (detect_container() == 0 && !unit_cgroup_delegate(u
)))
4939 wait_for_exit
= true;
4944 pid_set
= unit_pid_set(main_pid
, control_pid
);
4948 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
4957 return wait_for_exit
;
4960 int unit_require_mounts_for(Unit
*u
, const char *path
, UnitDependencyMask mask
) {
4961 _cleanup_free_
char *p
= NULL
;
4962 UnitDependencyInfo di
;
4968 /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these paths in
4969 * the unit (from the path to the UnitDependencyInfo structure indicating how to the dependency came to
4970 * be). However, we build a prefix table for all possible prefixes so that new appearing mount units can easily
4971 * determine which units to make themselves a dependency of. */
4973 if (!path_is_absolute(path
))
4976 r
= hashmap_ensure_allocated(&u
->requires_mounts_for
, &path_hash_ops
);
4984 path
= path_simplify(p
, true);
4986 if (!path_is_normalized(path
))
4989 if (hashmap_contains(u
->requires_mounts_for
, path
))
4992 di
= (UnitDependencyInfo
) {
4996 r
= hashmap_put(u
->requires_mounts_for
, path
, di
.data
);
5001 char prefix
[strlen(path
) + 1];
5002 PATH_FOREACH_PREFIX_MORE(prefix
, path
) {
5005 x
= hashmap_get(u
->manager
->units_requiring_mounts_for
, prefix
);
5007 _cleanup_free_
char *q
= NULL
;
5009 r
= hashmap_ensure_allocated(&u
->manager
->units_requiring_mounts_for
, &path_hash_ops
);
5021 r
= hashmap_put(u
->manager
->units_requiring_mounts_for
, q
, x
);
5037 int unit_setup_exec_runtime(Unit
*u
) {
5045 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
5048 /* Check if there already is an ExecRuntime for this unit? */
5049 rt
= (ExecRuntime
**) ((uint8_t*) u
+ offset
);
5053 /* Try to get it from somebody else */
5054 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_JOINS_NAMESPACE_OF
], i
) {
5055 r
= exec_runtime_acquire(u
->manager
, NULL
, other
->id
, false, rt
);
5060 return exec_runtime_acquire(u
->manager
, unit_get_exec_context(u
), u
->id
, true, rt
);
5063 int unit_setup_dynamic_creds(Unit
*u
) {
5065 DynamicCreds
*dcreds
;
5070 offset
= UNIT_VTABLE(u
)->dynamic_creds_offset
;
5072 dcreds
= (DynamicCreds
*) ((uint8_t*) u
+ offset
);
5074 ec
= unit_get_exec_context(u
);
5077 if (!ec
->dynamic_user
)
5080 return dynamic_creds_acquire(dcreds
, u
->manager
, ec
->user
, ec
->group
);
5083 bool unit_type_supported(UnitType t
) {
5084 if (_unlikely_(t
< 0))
5086 if (_unlikely_(t
>= _UNIT_TYPE_MAX
))
5089 if (!unit_vtable
[t
]->supported
)
5092 return unit_vtable
[t
]->supported();
5095 void unit_warn_if_dir_nonempty(Unit
*u
, const char* where
) {
5101 r
= dir_is_empty(where
);
5102 if (r
> 0 || r
== -ENOTDIR
)
5105 log_unit_warning_errno(u
, r
, "Failed to check directory %s: %m", where
);
5109 log_struct(LOG_NOTICE
,
5110 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
5112 LOG_UNIT_INVOCATION_ID(u
),
5113 LOG_UNIT_MESSAGE(u
, "Directory %s to mount over is not empty, mounting anyway.", where
),
5117 int unit_fail_if_noncanonical(Unit
*u
, const char* where
) {
5118 _cleanup_free_
char *canonical_where
= NULL
;
5124 r
= chase_symlinks(where
, NULL
, CHASE_NONEXISTENT
, &canonical_where
, NULL
);
5126 log_unit_debug_errno(u
, r
, "Failed to check %s for symlinks, ignoring: %m", where
);
5130 /* We will happily ignore a trailing slash (or any redundant slashes) */
5131 if (path_equal(where
, canonical_where
))
5134 /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
5136 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
5138 LOG_UNIT_INVOCATION_ID(u
),
5139 LOG_UNIT_MESSAGE(u
, "Mount path %s is not canonical (contains a symlink).", where
),
5145 bool unit_is_pristine(Unit
*u
) {
5148 /* Check if the unit already exists or is already around,
5149 * in a number of different ways. Note that to cater for unit
5150 * types such as slice, we are generally fine with units that
5151 * are marked UNIT_LOADED even though nothing was actually
5152 * loaded, as those unit types don't require a file on disk. */
5154 return !(!IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_LOADED
) ||
5157 !strv_isempty(u
->dropin_paths
) ||
5162 pid_t
unit_control_pid(Unit
*u
) {
5165 if (UNIT_VTABLE(u
)->control_pid
)
5166 return UNIT_VTABLE(u
)->control_pid(u
);
5171 pid_t
unit_main_pid(Unit
*u
) {
5174 if (UNIT_VTABLE(u
)->main_pid
)
5175 return UNIT_VTABLE(u
)->main_pid(u
);
5180 static void unit_unref_uid_internal(
5184 void (*_manager_unref_uid
)(Manager
*m
, uid_t uid
, bool destroy_now
)) {
5188 assert(_manager_unref_uid
);
5190 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
5191 * gid_t are actually the same time, with the same validity rules.
5193 * Drops a reference to UID/GID from a unit. */
5195 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
5196 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
5198 if (!uid_is_valid(*ref_uid
))
5201 _manager_unref_uid(u
->manager
, *ref_uid
, destroy_now
);
5202 *ref_uid
= UID_INVALID
;
5205 static void unit_unref_uid(Unit
*u
, bool destroy_now
) {
5206 unit_unref_uid_internal(u
, &u
->ref_uid
, destroy_now
, manager_unref_uid
);
5209 static void unit_unref_gid(Unit
*u
, bool destroy_now
) {
5210 unit_unref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, destroy_now
, manager_unref_gid
);
5213 void unit_unref_uid_gid(Unit
*u
, bool destroy_now
) {
5216 unit_unref_uid(u
, destroy_now
);
5217 unit_unref_gid(u
, destroy_now
);
5220 static int unit_ref_uid_internal(
5225 int (*_manager_ref_uid
)(Manager
*m
, uid_t uid
, bool clean_ipc
)) {
5231 assert(uid_is_valid(uid
));
5232 assert(_manager_ref_uid
);
5234 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
5235 * are actually the same type, and have the same validity rules.
5237 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
5238 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
5241 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
5242 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
5244 if (*ref_uid
== uid
)
5247 if (uid_is_valid(*ref_uid
)) /* Already set? */
5250 r
= _manager_ref_uid(u
->manager
, uid
, clean_ipc
);
5258 static int unit_ref_uid(Unit
*u
, uid_t uid
, bool clean_ipc
) {
5259 return unit_ref_uid_internal(u
, &u
->ref_uid
, uid
, clean_ipc
, manager_ref_uid
);
5262 static int unit_ref_gid(Unit
*u
, gid_t gid
, bool clean_ipc
) {
5263 return unit_ref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, (uid_t
) gid
, clean_ipc
, manager_ref_gid
);
5266 static int unit_ref_uid_gid_internal(Unit
*u
, uid_t uid
, gid_t gid
, bool clean_ipc
) {
5271 /* Reference both a UID and a GID in one go. Either references both, or neither. */
5273 if (uid_is_valid(uid
)) {
5274 r
= unit_ref_uid(u
, uid
, clean_ipc
);
5279 if (gid_is_valid(gid
)) {
5280 q
= unit_ref_gid(u
, gid
, clean_ipc
);
5283 unit_unref_uid(u
, false);
5289 return r
> 0 || q
> 0;
5292 int unit_ref_uid_gid(Unit
*u
, uid_t uid
, gid_t gid
) {
5298 c
= unit_get_exec_context(u
);
5300 r
= unit_ref_uid_gid_internal(u
, uid
, gid
, c
? c
->remove_ipc
: false);
5302 return log_unit_warning_errno(u
, r
, "Couldn't add UID/GID reference to unit, proceeding without: %m");
5307 void unit_notify_user_lookup(Unit
*u
, uid_t uid
, gid_t gid
) {
5312 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
5313 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
5314 * objects when no service references the UID/GID anymore. */
5316 r
= unit_ref_uid_gid(u
, uid
, gid
);
5318 unit_add_to_dbus_queue(u
);
5321 int unit_set_invocation_id(Unit
*u
, sd_id128_t id
) {
5326 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
5328 if (sd_id128_equal(u
->invocation_id
, id
))
5331 if (!sd_id128_is_null(u
->invocation_id
))
5332 (void) hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
5334 if (sd_id128_is_null(id
)) {
5339 r
= hashmap_ensure_allocated(&u
->manager
->units_by_invocation_id
, &id128_hash_ops
);
5343 u
->invocation_id
= id
;
5344 sd_id128_to_string(id
, u
->invocation_id_string
);
5346 r
= hashmap_put(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
5353 u
->invocation_id
= SD_ID128_NULL
;
5354 u
->invocation_id_string
[0] = 0;
5358 int unit_acquire_invocation_id(Unit
*u
) {
5364 r
= sd_id128_randomize(&id
);
5366 return log_unit_error_errno(u
, r
, "Failed to generate invocation ID for unit: %m");
5368 r
= unit_set_invocation_id(u
, id
);
5370 return log_unit_error_errno(u
, r
, "Failed to set invocation ID for unit: %m");
5372 unit_add_to_dbus_queue(u
);
5376 int unit_set_exec_params(Unit
*u
, ExecParameters
*p
) {
5382 /* Copy parameters from manager */
5383 r
= manager_get_effective_environment(u
->manager
, &p
->environment
);
5387 p
->confirm_spawn
= manager_get_confirm_spawn(u
->manager
);
5388 p
->cgroup_supported
= u
->manager
->cgroup_supported
;
5389 p
->prefix
= u
->manager
->prefix
;
5390 SET_FLAG(p
->flags
, EXEC_PASS_LOG_UNIT
|EXEC_CHOWN_DIRECTORIES
, MANAGER_IS_SYSTEM(u
->manager
));
5392 /* Copy parameters from unit */
5393 p
->cgroup_path
= u
->cgroup_path
;
5394 SET_FLAG(p
->flags
, EXEC_CGROUP_DELEGATE
, unit_cgroup_delegate(u
));
5399 int unit_fork_helper_process(Unit
*u
, const char *name
, pid_t
*ret
) {
5405 /* Forks off a helper process and makes sure it is a member of the unit's cgroup. Returns == 0 in the child,
5406 * and > 0 in the parent. The pid parameter is always filled in with the child's PID. */
5408 (void) unit_realize_cgroup(u
);
5410 r
= safe_fork(name
, FORK_REOPEN_LOG
, ret
);
5414 (void) default_signals(SIGNALS_CRASH_HANDLER
, SIGNALS_IGNORE
, -1);
5415 (void) ignore_signals(SIGPIPE
, -1);
5417 (void) prctl(PR_SET_PDEATHSIG
, SIGTERM
);
5419 if (u
->cgroup_path
) {
5420 r
= cg_attach_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, 0, NULL
, NULL
);
5422 log_unit_error_errno(u
, r
, "Failed to join unit cgroup %s: %m", u
->cgroup_path
);
5430 int unit_fork_and_watch_rm_rf(Unit
*u
, char **paths
, pid_t
*ret_pid
) {
5437 r
= unit_fork_helper_process(u
, "(sd-rmrf)", &pid
);
5441 int ret
= EXIT_SUCCESS
;
5444 STRV_FOREACH(i
, paths
) {
5445 r
= rm_rf(*i
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_MISSING_OK
);
5447 log_error_errno(r
, "Failed to remove '%s': %m", *i
);
5455 r
= unit_watch_pid(u
, pid
, true);
5463 static void unit_update_dependency_mask(Unit
*u
, UnitDependency d
, Unit
*other
, UnitDependencyInfo di
) {
5466 assert(d
< _UNIT_DEPENDENCY_MAX
);
5469 if (di
.origin_mask
== 0 && di
.destination_mask
== 0) {
5470 /* No bit set anymore, let's drop the whole entry */
5471 assert_se(hashmap_remove(u
->dependencies
[d
], other
));
5472 log_unit_debug(u
, "lost dependency %s=%s", unit_dependency_to_string(d
), other
->id
);
5474 /* Mask was reduced, let's update the entry */
5475 assert_se(hashmap_update(u
->dependencies
[d
], other
, di
.data
) == 0);
5478 void unit_remove_dependencies(Unit
*u
, UnitDependencyMask mask
) {
5483 /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
5488 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
5492 UnitDependencyInfo di
;
5498 HASHMAP_FOREACH_KEY(di
.data
, other
, u
->dependencies
[d
], i
) {
5501 if ((di
.origin_mask
& ~mask
) == di
.origin_mask
)
5503 di
.origin_mask
&= ~mask
;
5504 unit_update_dependency_mask(u
, d
, other
, di
);
5506 /* We updated the dependency from our unit to the other unit now. But most dependencies
5507 * imply a reverse dependency. Hence, let's delete that one too. For that we go through
5508 * all dependency types on the other unit and delete all those which point to us and
5509 * have the right mask set. */
5511 for (q
= 0; q
< _UNIT_DEPENDENCY_MAX
; q
++) {
5512 UnitDependencyInfo dj
;
5514 dj
.data
= hashmap_get(other
->dependencies
[q
], u
);
5515 if ((dj
.destination_mask
& ~mask
) == dj
.destination_mask
)
5517 dj
.destination_mask
&= ~mask
;
5519 unit_update_dependency_mask(other
, q
, u
, dj
);
5522 unit_add_to_gc_queue(other
);
5532 static int unit_get_invocation_path(Unit
*u
, char **ret
) {
5539 if (MANAGER_IS_SYSTEM(u
->manager
))
5540 p
= strjoin("/run/systemd/units/invocation:", u
->id
);
5542 _cleanup_free_
char *user_path
= NULL
;
5543 r
= xdg_user_runtime_dir(&user_path
, "/systemd/units/invocation:");
5546 p
= strjoin(user_path
, u
->id
);
5556 static int unit_export_invocation_id(Unit
*u
) {
5557 _cleanup_free_
char *p
= NULL
;
5562 if (u
->exported_invocation_id
)
5565 if (sd_id128_is_null(u
->invocation_id
))
5568 r
= unit_get_invocation_path(u
, &p
);
5570 return log_unit_debug_errno(u
, r
, "Failed to get invocation path: %m");
5572 r
= symlink_atomic(u
->invocation_id_string
, p
);
5574 return log_unit_debug_errno(u
, r
, "Failed to create invocation ID symlink %s: %m", p
);
5576 u
->exported_invocation_id
= true;
5580 static int unit_export_log_level_max(Unit
*u
, const ExecContext
*c
) {
5588 if (u
->exported_log_level_max
)
5591 if (c
->log_level_max
< 0)
5594 assert(c
->log_level_max
<= 7);
5596 buf
[0] = '0' + c
->log_level_max
;
5599 p
= strjoina("/run/systemd/units/log-level-max:", u
->id
);
5600 r
= symlink_atomic(buf
, p
);
5602 return log_unit_debug_errno(u
, r
, "Failed to create maximum log level symlink %s: %m", p
);
5604 u
->exported_log_level_max
= true;
5608 static int unit_export_log_extra_fields(Unit
*u
, const ExecContext
*c
) {
5609 _cleanup_close_
int fd
= -1;
5610 struct iovec
*iovec
;
5618 if (u
->exported_log_extra_fields
)
5621 if (c
->n_log_extra_fields
<= 0)
5624 sizes
= newa(le64_t
, c
->n_log_extra_fields
);
5625 iovec
= newa(struct iovec
, c
->n_log_extra_fields
* 2);
5627 for (i
= 0; i
< c
->n_log_extra_fields
; i
++) {
5628 sizes
[i
] = htole64(c
->log_extra_fields
[i
].iov_len
);
5630 iovec
[i
*2] = IOVEC_MAKE(sizes
+ i
, sizeof(le64_t
));
5631 iovec
[i
*2+1] = c
->log_extra_fields
[i
];
5634 p
= strjoina("/run/systemd/units/log-extra-fields:", u
->id
);
5635 pattern
= strjoina(p
, ".XXXXXX");
5637 fd
= mkostemp_safe(pattern
);
5639 return log_unit_debug_errno(u
, fd
, "Failed to create extra fields file %s: %m", p
);
5641 n
= writev(fd
, iovec
, c
->n_log_extra_fields
*2);
5643 r
= log_unit_debug_errno(u
, errno
, "Failed to write extra fields: %m");
5647 (void) fchmod(fd
, 0644);
5649 if (rename(pattern
, p
) < 0) {
5650 r
= log_unit_debug_errno(u
, errno
, "Failed to rename extra fields file: %m");
5654 u
->exported_log_extra_fields
= true;
5658 (void) unlink(pattern
);
5662 static int unit_export_log_ratelimit_interval(Unit
*u
, const ExecContext
*c
) {
5663 _cleanup_free_
char *buf
= NULL
;
5670 if (u
->exported_log_ratelimit_interval
)
5673 if (c
->log_ratelimit_interval_usec
== 0)
5676 p
= strjoina("/run/systemd/units/log-rate-limit-interval:", u
->id
);
5678 if (asprintf(&buf
, "%" PRIu64
, c
->log_ratelimit_interval_usec
) < 0)
5681 r
= symlink_atomic(buf
, p
);
5683 return log_unit_debug_errno(u
, r
, "Failed to create log rate limit interval symlink %s: %m", p
);
5685 u
->exported_log_ratelimit_interval
= true;
5689 static int unit_export_log_ratelimit_burst(Unit
*u
, const ExecContext
*c
) {
5690 _cleanup_free_
char *buf
= NULL
;
5697 if (u
->exported_log_ratelimit_burst
)
5700 if (c
->log_ratelimit_burst
== 0)
5703 p
= strjoina("/run/systemd/units/log-rate-limit-burst:", u
->id
);
5705 if (asprintf(&buf
, "%u", c
->log_ratelimit_burst
) < 0)
5708 r
= symlink_atomic(buf
, p
);
5710 return log_unit_debug_errno(u
, r
, "Failed to create log rate limit burst symlink %s: %m", p
);
5712 u
->exported_log_ratelimit_burst
= true;
5716 void unit_export_state_files(Unit
*u
) {
5717 const ExecContext
*c
;
5724 if (MANAGER_IS_TEST_RUN(u
->manager
))
5727 /* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
5728 * from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
5729 * the IPC system itself and PID 1 also log to the journal.
5731 * Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
5732 * IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
5733 * apply to communication between the journal and systemd, as we assume that these two daemons live in the same
5734 * namespace at least.
5736 * Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
5737 * better for storing small bits of data, in particular as we can write them with two system calls, and read
5740 (void) unit_export_invocation_id(u
);
5742 if (!MANAGER_IS_SYSTEM(u
->manager
))
5745 c
= unit_get_exec_context(u
);
5747 (void) unit_export_log_level_max(u
, c
);
5748 (void) unit_export_log_extra_fields(u
, c
);
5749 (void) unit_export_log_ratelimit_interval(u
, c
);
5750 (void) unit_export_log_ratelimit_burst(u
, c
);
5754 void unit_unlink_state_files(Unit
*u
) {
5762 /* Undoes the effect of unit_export_state() */
5764 if (u
->exported_invocation_id
) {
5765 _cleanup_free_
char *invocation_path
= NULL
;
5766 int r
= unit_get_invocation_path(u
, &invocation_path
);
5768 (void) unlink(invocation_path
);
5769 u
->exported_invocation_id
= false;
5773 if (!MANAGER_IS_SYSTEM(u
->manager
))
5776 if (u
->exported_log_level_max
) {
5777 p
= strjoina("/run/systemd/units/log-level-max:", u
->id
);
5780 u
->exported_log_level_max
= false;
5783 if (u
->exported_log_extra_fields
) {
5784 p
= strjoina("/run/systemd/units/extra-fields:", u
->id
);
5787 u
->exported_log_extra_fields
= false;
5790 if (u
->exported_log_ratelimit_interval
) {
5791 p
= strjoina("/run/systemd/units/log-rate-limit-interval:", u
->id
);
5794 u
->exported_log_ratelimit_interval
= false;
5797 if (u
->exported_log_ratelimit_burst
) {
5798 p
= strjoina("/run/systemd/units/log-rate-limit-burst:", u
->id
);
5801 u
->exported_log_ratelimit_burst
= false;
5805 int unit_prepare_exec(Unit
*u
) {
5810 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
5811 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
5812 r
= bpf_firewall_load_custom(u
);
5816 /* Prepares everything so that we can fork of a process for this unit */
5818 (void) unit_realize_cgroup(u
);
5820 if (u
->reset_accounting
) {
5821 (void) unit_reset_accounting(u
);
5822 u
->reset_accounting
= false;
5825 unit_export_state_files(u
);
5827 r
= unit_setup_exec_runtime(u
);
5831 r
= unit_setup_dynamic_creds(u
);
5838 static int log_leftover(pid_t pid
, int sig
, void *userdata
) {
5839 _cleanup_free_
char *comm
= NULL
;
5841 (void) get_process_comm(pid
, &comm
);
5843 if (comm
&& comm
[0] == '(') /* Most likely our own helper process (PAM?), ignore */
5846 log_unit_warning(userdata
,
5847 "Found left-over process " PID_FMT
" (%s) in control group while starting unit. Ignoring.\n"
5848 "This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
5854 int unit_warn_leftover_processes(Unit
*u
) {
5857 (void) unit_pick_cgroup_path(u
);
5859 if (!u
->cgroup_path
)
5862 return cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, 0, 0, NULL
, log_leftover
, u
);
5865 bool unit_needs_console(Unit
*u
) {
5867 UnitActiveState state
;
5871 state
= unit_active_state(u
);
5873 if (UNIT_IS_INACTIVE_OR_FAILED(state
))
5876 if (UNIT_VTABLE(u
)->needs_console
)
5877 return UNIT_VTABLE(u
)->needs_console(u
);
5879 /* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
5880 ec
= unit_get_exec_context(u
);
5884 return exec_context_may_touch_console(ec
);
5887 const char *unit_label_path(const Unit
*u
) {
5892 /* Returns the file system path to use for MAC access decisions, i.e. the file to read the SELinux label off
5893 * when validating access checks. */
5895 p
= u
->source_path
?: u
->fragment_path
;
5899 /* If a unit is masked, then don't read the SELinux label of /dev/null, as that really makes no sense */
5900 if (path_equal(p
, "/dev/null"))
5906 int unit_pid_attachable(Unit
*u
, pid_t pid
, sd_bus_error
*error
) {
5911 /* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
5912 * and not a kernel thread either */
5914 /* First, a simple range check */
5915 if (!pid_is_valid(pid
))
5916 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process identifier " PID_FMT
" is not valid.", pid
);
5918 /* Some extra safety check */
5919 if (pid
== 1 || pid
== getpid_cached())
5920 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process " PID_FMT
" is a manager process, refusing.", pid
);
5922 /* Don't even begin to bother with kernel threads */
5923 r
= is_kernel_thread(pid
);
5925 return sd_bus_error_setf(error
, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN
, "Process with ID " PID_FMT
" does not exist.", pid
);
5927 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether process " PID_FMT
" is a kernel thread: %m", pid
);
5929 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process " PID_FMT
" is a kernel thread, refusing.", pid
);
5934 void unit_log_success(Unit
*u
) {
5937 log_struct(LOG_INFO
,
5938 "MESSAGE_ID=" SD_MESSAGE_UNIT_SUCCESS_STR
,
5940 LOG_UNIT_INVOCATION_ID(u
),
5941 LOG_UNIT_MESSAGE(u
, "Succeeded."));
5944 void unit_log_failure(Unit
*u
, const char *result
) {
5948 log_struct(LOG_WARNING
,
5949 "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILURE_RESULT_STR
,
5951 LOG_UNIT_INVOCATION_ID(u
),
5952 LOG_UNIT_MESSAGE(u
, "Failed with result '%s'.", result
),
5953 "UNIT_RESULT=%s", result
);
5956 void unit_log_skip(Unit
*u
, const char *result
) {
5960 log_struct(LOG_INFO
,
5961 "MESSAGE_ID=" SD_MESSAGE_UNIT_SKIPPED_STR
,
5963 LOG_UNIT_INVOCATION_ID(u
),
5964 LOG_UNIT_MESSAGE(u
, "Skipped due to '%s'.", result
),
5965 "UNIT_RESULT=%s", result
);
5968 void unit_log_process_exit(
5971 const char *command
,
5981 /* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
5982 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
5983 * that the service already logged the reason at a higher log level on its own. Otherwise, make it a
5987 else if (code
== CLD_EXITED
)
5990 level
= LOG_WARNING
;
5993 "MESSAGE_ID=" SD_MESSAGE_UNIT_PROCESS_EXIT_STR
,
5994 LOG_UNIT_MESSAGE(u
, "%s exited, code=%s, status=%i/%s",
5996 sigchld_code_to_string(code
), status
,
5997 strna(code
== CLD_EXITED
5998 ? exit_status_to_string(status
, EXIT_STATUS_FULL
)
5999 : signal_to_string(status
))),
6000 "EXIT_CODE=%s", sigchld_code_to_string(code
),
6001 "EXIT_STATUS=%i", status
,
6002 "COMMAND=%s", strna(command
),
6004 LOG_UNIT_INVOCATION_ID(u
));
6007 int unit_exit_status(Unit
*u
) {
6010 /* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
6011 * 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
6012 * if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
6013 * service process has exited abnormally (signal/coredump). */
6015 if (!UNIT_VTABLE(u
)->exit_status
)
6018 return UNIT_VTABLE(u
)->exit_status(u
);
6021 int unit_failure_action_exit_status(Unit
*u
) {
6026 /* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
6028 if (u
->failure_action_exit_status
>= 0)
6029 return u
->failure_action_exit_status
;
6031 r
= unit_exit_status(u
);
6032 if (r
== -EBADE
) /* Exited, but not cleanly (i.e. by signal or such) */
6038 int unit_success_action_exit_status(Unit
*u
) {
6043 /* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
6045 if (u
->success_action_exit_status
>= 0)
6046 return u
->success_action_exit_status
;
6048 r
= unit_exit_status(u
);
6049 if (r
== -EBADE
) /* Exited, but not cleanly (i.e. by signal or such) */
6055 int unit_test_trigger_loaded(Unit
*u
) {
6058 /* Tests whether the unit to trigger is loaded */
6060 trigger
= UNIT_TRIGGER(u
);
6062 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
6063 "Refusing to start, no unit to trigger.");
6064 if (trigger
->load_state
!= UNIT_LOADED
)
6065 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
6066 "Refusing to start, unit %s to trigger not loaded.", trigger
->id
);
6071 void unit_destroy_runtime_directory(Unit
*u
, const ExecContext
*context
) {
6072 if (context
->runtime_directory_preserve_mode
== EXEC_PRESERVE_NO
||
6073 (context
->runtime_directory_preserve_mode
== EXEC_PRESERVE_RESTART
&& !unit_will_restart(u
)))
6074 exec_context_destroy_runtime_directory(context
, u
->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
6077 int unit_clean(Unit
*u
, ExecCleanMask mask
) {
6078 UnitActiveState state
;
6082 /* Special return values:
6084 * -EOPNOTSUPP → cleaning not supported for this unit type
6085 * -EUNATCH → cleaning not defined for this resource type
6086 * -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
6087 * a job queued or similar
6090 if (!UNIT_VTABLE(u
)->clean
)
6096 if (u
->load_state
!= UNIT_LOADED
)
6102 state
= unit_active_state(u
);
6103 if (!IN_SET(state
, UNIT_INACTIVE
))
6106 return UNIT_VTABLE(u
)->clean(u
, mask
);
6109 int unit_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
6112 if (!UNIT_VTABLE(u
)->clean
||
6113 u
->load_state
!= UNIT_LOADED
) {
6118 /* When the clean() method is set, can_clean() really should be set too */
6119 assert(UNIT_VTABLE(u
)->can_clean
);
6121 return UNIT_VTABLE(u
)->can_clean(u
, ret
);
6124 bool unit_can_freeze(Unit
*u
) {
6127 if (UNIT_VTABLE(u
)->can_freeze
)
6128 return UNIT_VTABLE(u
)->can_freeze(u
);
6130 return UNIT_VTABLE(u
)->freeze
;
6133 void unit_frozen(Unit
*u
) {
6136 u
->freezer_state
= FREEZER_FROZEN
;
6138 bus_unit_send_pending_freezer_message(u
);
6141 void unit_thawed(Unit
*u
) {
6144 u
->freezer_state
= FREEZER_RUNNING
;
6146 bus_unit_send_pending_freezer_message(u
);
6149 static int unit_freezer_action(Unit
*u
, FreezerAction action
) {
6151 int (*method
)(Unit
*);
6155 assert(IN_SET(action
, FREEZER_FREEZE
, FREEZER_THAW
));
6157 method
= action
== FREEZER_FREEZE
? UNIT_VTABLE(u
)->freeze
: UNIT_VTABLE(u
)->thaw
;
6158 if (!method
|| !cg_freezer_supported())
6164 if (u
->load_state
!= UNIT_LOADED
)
6167 s
= unit_active_state(u
);
6168 if (s
!= UNIT_ACTIVE
)
6171 if (IN_SET(u
->freezer_state
, FREEZER_FREEZING
, FREEZER_THAWING
))
6181 int unit_freeze(Unit
*u
) {
6182 return unit_freezer_action(u
, FREEZER_FREEZE
);
6185 int unit_thaw(Unit
*u
) {
6186 return unit_freezer_action(u
, FREEZER_THAW
);
6189 /* Wrappers around low-level cgroup freezer operations common for service and scope units */
6190 int unit_freeze_vtable_common(Unit
*u
) {
6191 return unit_cgroup_freezer_action(u
, FREEZER_FREEZE
);
6194 int unit_thaw_vtable_common(Unit
*u
) {
6195 return unit_cgroup_freezer_action(u
, FREEZER_THAW
);
6198 static const char* const collect_mode_table
[_COLLECT_MODE_MAX
] = {
6199 [COLLECT_INACTIVE
] = "inactive",
6200 [COLLECT_INACTIVE_OR_FAILED
] = "inactive-or-failed",
6203 DEFINE_STRING_TABLE_LOOKUP(collect_mode
, CollectMode
);