1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "sd-messages.h"
11 #include "all-units.h"
12 #include "alloc-util.h"
13 #include "bpf-firewall.h"
14 #include "bus-common-errors.h"
16 #include "cgroup-setup.h"
17 #include "cgroup-util.h"
18 #include "core-varlink.h"
19 #include "dbus-unit.h"
25 #include "fileio-label.h"
27 #include "format-util.h"
28 #include "id128-util.h"
32 #include "load-dropin.h"
33 #include "load-fragment.h"
36 #include "missing_audit.h"
38 #include "parse-util.h"
39 #include "path-util.h"
40 #include "process-util.h"
42 #include "serialize.h"
44 #include "signal-util.h"
45 #include "sparse-endian.h"
47 #include "specifier.h"
48 #include "stat-util.h"
49 #include "stdio-util.h"
50 #include "string-table.h"
51 #include "string-util.h"
53 #include "terminal-util.h"
54 #include "tmpfile-util.h"
55 #include "umask-util.h"
56 #include "unit-name.h"
58 #include "user-util.h"
61 /* Thresholds for logging at INFO level about resource consumption */
62 #define MENTIONWORTHY_CPU_NSEC (1 * NSEC_PER_SEC)
63 #define MENTIONWORTHY_IO_BYTES (1024 * 1024ULL)
64 #define MENTIONWORTHY_IP_BYTES (0ULL)
66 /* Thresholds for logging at INFO level about resource consumption */
67 #define NOTICEWORTHY_CPU_NSEC (10*60 * NSEC_PER_SEC) /* 10 minutes */
68 #define NOTICEWORTHY_IO_BYTES (10 * 1024 * 1024ULL) /* 10 MB */
69 #define NOTICEWORTHY_IP_BYTES (128 * 1024 * 1024ULL) /* 128 MB */
71 const UnitVTable
* const unit_vtable
[_UNIT_TYPE_MAX
] = {
72 [UNIT_SERVICE
] = &service_vtable
,
73 [UNIT_SOCKET
] = &socket_vtable
,
74 [UNIT_TARGET
] = &target_vtable
,
75 [UNIT_DEVICE
] = &device_vtable
,
76 [UNIT_MOUNT
] = &mount_vtable
,
77 [UNIT_AUTOMOUNT
] = &automount_vtable
,
78 [UNIT_SWAP
] = &swap_vtable
,
79 [UNIT_TIMER
] = &timer_vtable
,
80 [UNIT_PATH
] = &path_vtable
,
81 [UNIT_SLICE
] = &slice_vtable
,
82 [UNIT_SCOPE
] = &scope_vtable
,
85 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
);
87 Unit
*unit_new(Manager
*m
, size_t size
) {
91 assert(size
>= sizeof(Unit
));
98 u
->type
= _UNIT_TYPE_INVALID
;
99 u
->default_dependencies
= true;
100 u
->unit_file_state
= _UNIT_FILE_STATE_INVALID
;
101 u
->unit_file_preset
= -1;
102 u
->on_failure_job_mode
= JOB_REPLACE
;
103 u
->cgroup_control_inotify_wd
= -1;
104 u
->cgroup_memory_inotify_wd
= -1;
105 u
->job_timeout
= USEC_INFINITY
;
106 u
->job_running_timeout
= USEC_INFINITY
;
107 u
->ref_uid
= UID_INVALID
;
108 u
->ref_gid
= GID_INVALID
;
109 u
->cpu_usage_last
= NSEC_INFINITY
;
110 u
->cgroup_invalidated_mask
|= CGROUP_MASK_BPF_FIREWALL
;
111 u
->failure_action_exit_status
= u
->success_action_exit_status
= -1;
113 u
->ip_accounting_ingress_map_fd
= -1;
114 u
->ip_accounting_egress_map_fd
= -1;
115 u
->ipv4_allow_map_fd
= -1;
116 u
->ipv6_allow_map_fd
= -1;
117 u
->ipv4_deny_map_fd
= -1;
118 u
->ipv6_deny_map_fd
= -1;
120 u
->last_section_private
= -1;
122 u
->start_ratelimit
= (RateLimit
) { m
->default_start_limit_interval
, m
->default_start_limit_burst
};
123 u
->auto_stop_ratelimit
= (RateLimit
) { 10 * USEC_PER_SEC
, 16 };
125 for (CGroupIOAccountingMetric i
= 0; i
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; i
++)
126 u
->io_accounting_last
[i
] = UINT64_MAX
;
131 int unit_new_for_name(Manager
*m
, size_t size
, const char *name
, Unit
**ret
) {
132 _cleanup_(unit_freep
) Unit
*u
= NULL
;
135 u
= unit_new(m
, size
);
139 r
= unit_add_name(u
, name
);
148 bool unit_has_name(const Unit
*u
, const char *name
) {
152 return streq_ptr(name
, u
->id
) ||
153 set_contains(u
->aliases
, name
);
156 static void unit_init(Unit
*u
) {
163 assert(u
->type
>= 0);
165 cc
= unit_get_cgroup_context(u
);
167 cgroup_context_init(cc
);
169 /* Copy in the manager defaults into the cgroup
170 * context, _before_ the rest of the settings have
171 * been initialized */
173 cc
->cpu_accounting
= u
->manager
->default_cpu_accounting
;
174 cc
->io_accounting
= u
->manager
->default_io_accounting
;
175 cc
->blockio_accounting
= u
->manager
->default_blockio_accounting
;
176 cc
->memory_accounting
= u
->manager
->default_memory_accounting
;
177 cc
->tasks_accounting
= u
->manager
->default_tasks_accounting
;
178 cc
->ip_accounting
= u
->manager
->default_ip_accounting
;
180 if (u
->type
!= UNIT_SLICE
)
181 cc
->tasks_max
= u
->manager
->default_tasks_max
;
184 ec
= unit_get_exec_context(u
);
186 exec_context_init(ec
);
188 if (MANAGER_IS_SYSTEM(u
->manager
))
189 ec
->keyring_mode
= EXEC_KEYRING_SHARED
;
191 ec
->keyring_mode
= EXEC_KEYRING_INHERIT
;
193 /* User manager might have its umask redefined by PAM or UMask=. In this
194 * case let the units it manages inherit this value by default. They can
195 * still tune this value through their own unit file */
196 (void) get_process_umask(getpid_cached(), &ec
->umask
);
200 kc
= unit_get_kill_context(u
);
202 kill_context_init(kc
);
204 if (UNIT_VTABLE(u
)->init
)
205 UNIT_VTABLE(u
)->init(u
);
208 static int unit_add_alias(Unit
*u
, char *donated_name
) {
211 /* Make sure that u->names is allocated. We may leave u->names
212 * empty if we fail later, but this is not a problem. */
213 r
= set_ensure_put(&u
->aliases
, &string_hash_ops
, donated_name
);
221 int unit_add_name(Unit
*u
, const char *text
) {
222 _cleanup_free_
char *name
= NULL
, *instance
= NULL
;
229 if (unit_name_is_valid(text
, UNIT_NAME_TEMPLATE
)) {
231 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
232 "instance is not set when adding name '%s': %m", text
);
234 r
= unit_name_replace_instance(text
, u
->instance
, &name
);
236 return log_unit_debug_errno(u
, r
,
237 "failed to build instance name from '%s': %m", text
);
244 if (unit_has_name(u
, name
))
247 if (hashmap_contains(u
->manager
->units
, name
))
248 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EEXIST
),
249 "unit already exist when adding name '%s': %m", name
);
251 if (!unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
252 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
253 "name '%s' is invalid: %m", name
);
255 t
= unit_name_to_type(name
);
257 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
258 "failed to derive unit type from name '%s': %m", name
);
260 if (u
->type
!= _UNIT_TYPE_INVALID
&& t
!= u
->type
)
261 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
262 "unit type is illegal: u->type(%d) and t(%d) for name '%s': %m",
265 r
= unit_name_to_instance(name
, &instance
);
267 return log_unit_debug_errno(u
, r
, "failed to extract instance from name '%s': %m", name
);
269 if (instance
&& !unit_type_may_template(t
))
270 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
), "templates are not allowed for name '%s': %m", name
);
272 /* Ensure that this unit either has no instance, or that the instance matches. */
273 if (u
->type
!= _UNIT_TYPE_INVALID
&& !streq_ptr(u
->instance
, instance
))
274 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
275 "cannot add name %s, the instances don't match (\"%s\" != \"%s\").",
276 name
, instance
, u
->instance
);
278 if (u
->id
&& !unit_type_may_alias(t
))
279 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(EEXIST
),
280 "cannot add name %s, aliases are not allowed for %s units.",
281 name
, unit_type_to_string(t
));
283 if (hashmap_size(u
->manager
->units
) >= MANAGER_MAX_NAMES
)
284 return log_unit_warning_errno(u
, SYNTHETIC_ERRNO(E2BIG
), "cannot add name, manager has too many units: %m");
286 /* Add name to the global hashmap first, because that's easier to undo */
287 r
= hashmap_put(u
->manager
->units
, name
, u
);
289 return log_unit_debug_errno(u
, r
, "add unit to hashmap failed for name '%s': %m", text
);
292 r
= unit_add_alias(u
, name
); /* unit_add_alias() takes ownership of the name on success */
294 hashmap_remove(u
->manager
->units
, name
);
300 /* A new name, we don't need the set yet. */
301 assert(u
->type
== _UNIT_TYPE_INVALID
);
302 assert(!u
->instance
);
305 u
->id
= TAKE_PTR(name
);
306 u
->instance
= TAKE_PTR(instance
);
308 LIST_PREPEND(units_by_type
, u
->manager
->units_by_type
[t
], u
);
312 unit_add_to_dbus_queue(u
);
316 int unit_choose_id(Unit
*u
, const char *name
) {
317 _cleanup_free_
char *t
= NULL
;
324 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
328 r
= unit_name_replace_instance(name
, u
->instance
, &t
);
335 if (streq_ptr(u
->id
, name
))
336 return 0; /* Nothing to do. */
338 /* Selects one of the aliases of this unit as the id */
339 s
= set_get(u
->aliases
, (char*) name
);
344 r
= set_remove_and_put(u
->aliases
, name
, u
->id
);
348 assert_se(set_remove(u
->aliases
, name
)); /* see set_get() above… */
350 u
->id
= s
; /* Old u->id is now stored in the set, and s is not stored anywhere */
351 unit_add_to_dbus_queue(u
);
356 int unit_set_description(Unit
*u
, const char *description
) {
361 r
= free_and_strdup(&u
->description
, empty_to_null(description
));
365 unit_add_to_dbus_queue(u
);
370 bool unit_may_gc(Unit
*u
) {
371 UnitActiveState state
;
376 /* Checks whether the unit is ready to be unloaded for garbage collection.
377 * Returns true when the unit may be collected, and false if there's some
378 * reason to keep it loaded.
380 * References from other units are *not* checked here. Instead, this is done
381 * in unit_gc_sweep(), but using markers to properly collect dependency loops.
390 state
= unit_active_state(u
);
392 /* If the unit is inactive and failed and no job is queued for it, then release its runtime resources */
393 if (UNIT_IS_INACTIVE_OR_FAILED(state
) &&
394 UNIT_VTABLE(u
)->release_resources
)
395 UNIT_VTABLE(u
)->release_resources(u
);
400 if (sd_bus_track_count(u
->bus_track
) > 0)
403 /* But we keep the unit object around for longer when it is referenced or configured to not be gc'ed */
404 switch (u
->collect_mode
) {
406 case COLLECT_INACTIVE
:
407 if (state
!= UNIT_INACTIVE
)
412 case COLLECT_INACTIVE_OR_FAILED
:
413 if (!IN_SET(state
, UNIT_INACTIVE
, UNIT_FAILED
))
419 assert_not_reached("Unknown garbage collection mode");
422 if (u
->cgroup_path
) {
423 /* If the unit has a cgroup, then check whether there's anything in it. If so, we should stay
424 * around. Units with active processes should never be collected. */
426 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
428 log_unit_debug_errno(u
, r
, "Failed to determine whether cgroup %s is empty: %m", u
->cgroup_path
);
433 if (UNIT_VTABLE(u
)->may_gc
&& !UNIT_VTABLE(u
)->may_gc(u
))
439 void unit_add_to_load_queue(Unit
*u
) {
441 assert(u
->type
!= _UNIT_TYPE_INVALID
);
443 if (u
->load_state
!= UNIT_STUB
|| u
->in_load_queue
)
446 LIST_PREPEND(load_queue
, u
->manager
->load_queue
, u
);
447 u
->in_load_queue
= true;
450 void unit_add_to_cleanup_queue(Unit
*u
) {
453 if (u
->in_cleanup_queue
)
456 LIST_PREPEND(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
457 u
->in_cleanup_queue
= true;
460 void unit_add_to_gc_queue(Unit
*u
) {
463 if (u
->in_gc_queue
|| u
->in_cleanup_queue
)
469 LIST_PREPEND(gc_queue
, u
->manager
->gc_unit_queue
, u
);
470 u
->in_gc_queue
= true;
473 void unit_add_to_dbus_queue(Unit
*u
) {
475 assert(u
->type
!= _UNIT_TYPE_INVALID
);
477 if (u
->load_state
== UNIT_STUB
|| u
->in_dbus_queue
)
480 /* Shortcut things if nobody cares */
481 if (sd_bus_track_count(u
->manager
->subscribed
) <= 0 &&
482 sd_bus_track_count(u
->bus_track
) <= 0 &&
483 set_isempty(u
->manager
->private_buses
)) {
484 u
->sent_dbus_new_signal
= true;
488 LIST_PREPEND(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
489 u
->in_dbus_queue
= true;
492 void unit_submit_to_stop_when_unneeded_queue(Unit
*u
) {
495 if (u
->in_stop_when_unneeded_queue
)
498 if (!u
->stop_when_unneeded
)
501 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
)))
504 LIST_PREPEND(stop_when_unneeded_queue
, u
->manager
->stop_when_unneeded_queue
, u
);
505 u
->in_stop_when_unneeded_queue
= true;
508 static void bidi_set_free(Unit
*u
, Hashmap
*h
) {
514 /* Frees the hashmap and makes sure we are dropped from the inverse pointers */
516 HASHMAP_FOREACH_KEY(v
, other
, h
) {
517 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
518 hashmap_remove(other
->dependencies
[d
], u
);
520 unit_add_to_gc_queue(other
);
526 static void unit_remove_transient(Unit
*u
) {
534 if (u
->fragment_path
)
535 (void) unlink(u
->fragment_path
);
537 STRV_FOREACH(i
, u
->dropin_paths
) {
538 _cleanup_free_
char *p
= NULL
, *pp
= NULL
;
540 p
= dirname_malloc(*i
); /* Get the drop-in directory from the drop-in file */
544 pp
= dirname_malloc(p
); /* Get the config directory from the drop-in directory */
548 /* Only drop transient drop-ins */
549 if (!path_equal(u
->manager
->lookup_paths
.transient
, pp
))
557 static void unit_free_requires_mounts_for(Unit
*u
) {
561 _cleanup_free_
char *path
;
563 path
= hashmap_steal_first_key(u
->requires_mounts_for
);
567 char s
[strlen(path
) + 1];
569 PATH_FOREACH_PREFIX_MORE(s
, path
) {
573 x
= hashmap_get2(u
->manager
->units_requiring_mounts_for
, s
, (void**) &y
);
577 (void) set_remove(x
, u
);
579 if (set_isempty(x
)) {
580 (void) hashmap_remove(u
->manager
->units_requiring_mounts_for
, y
);
588 u
->requires_mounts_for
= hashmap_free(u
->requires_mounts_for
);
591 static void unit_done(Unit
*u
) {
600 if (UNIT_VTABLE(u
)->done
)
601 UNIT_VTABLE(u
)->done(u
);
603 ec
= unit_get_exec_context(u
);
605 exec_context_done(ec
);
607 cc
= unit_get_cgroup_context(u
);
609 cgroup_context_done(cc
);
612 void unit_free(Unit
*u
) {
618 u
->transient_file
= safe_fclose(u
->transient_file
);
620 if (!MANAGER_IS_RELOADING(u
->manager
))
621 unit_remove_transient(u
);
623 bus_unit_send_removed_signal(u
);
627 unit_dequeue_rewatch_pids(u
);
629 sd_bus_slot_unref(u
->match_bus_slot
);
630 sd_bus_track_unref(u
->bus_track
);
631 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
632 u
->pending_freezer_message
= sd_bus_message_unref(u
->pending_freezer_message
);
634 unit_free_requires_mounts_for(u
);
636 SET_FOREACH(t
, u
->aliases
)
637 hashmap_remove_value(u
->manager
->units
, t
, u
);
639 hashmap_remove_value(u
->manager
->units
, u
->id
, u
);
641 if (!sd_id128_is_null(u
->invocation_id
))
642 hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
656 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
657 bidi_set_free(u
, u
->dependencies
[d
]);
659 /* A unit is being dropped from the tree, make sure our family is realized properly. Do this after we
660 * detach the unit from slice tree in order to eliminate its effect on controller masks. */
661 if (UNIT_ISSET(u
->slice
))
662 unit_add_family_to_cgroup_realize_queue(UNIT_DEREF(u
->slice
));
665 manager_unref_console(u
->manager
);
667 unit_release_cgroup(u
);
669 if (!MANAGER_IS_RELOADING(u
->manager
))
670 unit_unlink_state_files(u
);
672 unit_unref_uid_gid(u
, false);
674 (void) manager_update_failed_units(u
->manager
, u
, false);
675 set_remove(u
->manager
->startup_units
, u
);
677 unit_unwatch_all_pids(u
);
679 unit_ref_unset(&u
->slice
);
680 while (u
->refs_by_target
)
681 unit_ref_unset(u
->refs_by_target
);
683 if (u
->type
!= _UNIT_TYPE_INVALID
)
684 LIST_REMOVE(units_by_type
, u
->manager
->units_by_type
[u
->type
], u
);
686 if (u
->in_load_queue
)
687 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
689 if (u
->in_dbus_queue
)
690 LIST_REMOVE(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
693 LIST_REMOVE(gc_queue
, u
->manager
->gc_unit_queue
, u
);
695 if (u
->in_cgroup_realize_queue
)
696 LIST_REMOVE(cgroup_realize_queue
, u
->manager
->cgroup_realize_queue
, u
);
698 if (u
->in_cgroup_empty_queue
)
699 LIST_REMOVE(cgroup_empty_queue
, u
->manager
->cgroup_empty_queue
, u
);
701 if (u
->in_cleanup_queue
)
702 LIST_REMOVE(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
704 if (u
->in_target_deps_queue
)
705 LIST_REMOVE(target_deps_queue
, u
->manager
->target_deps_queue
, u
);
707 if (u
->in_stop_when_unneeded_queue
)
708 LIST_REMOVE(stop_when_unneeded_queue
, u
->manager
->stop_when_unneeded_queue
, u
);
710 safe_close(u
->ip_accounting_ingress_map_fd
);
711 safe_close(u
->ip_accounting_egress_map_fd
);
713 safe_close(u
->ipv4_allow_map_fd
);
714 safe_close(u
->ipv6_allow_map_fd
);
715 safe_close(u
->ipv4_deny_map_fd
);
716 safe_close(u
->ipv6_deny_map_fd
);
718 bpf_program_unref(u
->ip_bpf_ingress
);
719 bpf_program_unref(u
->ip_bpf_ingress_installed
);
720 bpf_program_unref(u
->ip_bpf_egress
);
721 bpf_program_unref(u
->ip_bpf_egress_installed
);
723 set_free(u
->ip_bpf_custom_ingress
);
724 set_free(u
->ip_bpf_custom_egress
);
725 set_free(u
->ip_bpf_custom_ingress_installed
);
726 set_free(u
->ip_bpf_custom_egress_installed
);
728 bpf_program_unref(u
->bpf_device_control_installed
);
730 condition_free_list(u
->conditions
);
731 condition_free_list(u
->asserts
);
733 free(u
->description
);
734 strv_free(u
->documentation
);
735 free(u
->fragment_path
);
736 free(u
->source_path
);
737 strv_free(u
->dropin_paths
);
740 free(u
->job_timeout_reboot_arg
);
743 set_free_free(u
->aliases
);
749 FreezerState
unit_freezer_state(Unit
*u
) {
752 return u
->freezer_state
;
755 int unit_freezer_state_kernel(Unit
*u
, FreezerState
*ret
) {
756 char *values
[1] = {};
761 r
= cg_get_keyed_attribute(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events",
762 STRV_MAKE("frozen"), values
);
766 r
= _FREEZER_STATE_INVALID
;
769 if (streq(values
[0], "0"))
771 else if (streq(values
[0], "1"))
781 UnitActiveState
unit_active_state(Unit
*u
) {
784 if (u
->load_state
== UNIT_MERGED
)
785 return unit_active_state(unit_follow_merge(u
));
787 /* After a reload it might happen that a unit is not correctly
788 * loaded but still has a process around. That's why we won't
789 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
791 return UNIT_VTABLE(u
)->active_state(u
);
794 const char* unit_sub_state_to_string(Unit
*u
) {
797 return UNIT_VTABLE(u
)->sub_state_to_string(u
);
800 static int hashmap_complete_move(Hashmap
**s
, Hashmap
**other
) {
808 return hashmap_move(*s
, *other
);
810 *s
= TAKE_PTR(*other
);
815 static int merge_names(Unit
*u
, Unit
*other
) {
822 r
= unit_add_alias(u
, other
->id
);
826 r
= set_move(u
->aliases
, other
->aliases
);
828 set_remove(u
->aliases
, other
->id
);
833 other
->aliases
= set_free_free(other
->aliases
);
835 SET_FOREACH(name
, u
->aliases
)
836 assert_se(hashmap_replace(u
->manager
->units
, name
, u
) == 0);
841 static int reserve_dependencies(Unit
*u
, Unit
*other
, UnitDependency d
) {
846 assert(d
< _UNIT_DEPENDENCY_MAX
);
849 * If u does not have this dependency set allocated, there is no need
850 * to reserve anything. In that case other's set will be transferred
851 * as a whole to u by complete_move().
853 if (!u
->dependencies
[d
])
856 /* merge_dependencies() will skip a u-on-u dependency */
857 n_reserve
= hashmap_size(other
->dependencies
[d
]) - !!hashmap_get(other
->dependencies
[d
], u
);
859 return hashmap_reserve(u
->dependencies
[d
], n_reserve
);
862 static void merge_dependencies(Unit
*u
, Unit
*other
, const char *other_id
, UnitDependency d
) {
867 /* Merges all dependencies of type 'd' of the unit 'other' into the deps of the unit 'u' */
871 assert(d
< _UNIT_DEPENDENCY_MAX
);
873 /* Fix backwards pointers. Let's iterate through all dependent units of the other unit. */
874 HASHMAP_FOREACH_KEY(v
, back
, other
->dependencies
[d
])
876 /* Let's now iterate through the dependencies of that dependencies of the other units,
877 * looking for pointers back, and let's fix them up, to instead point to 'u'. */
878 for (UnitDependency k
= 0; k
< _UNIT_DEPENDENCY_MAX
; k
++)
880 /* Do not add dependencies between u and itself. */
881 if (hashmap_remove(back
->dependencies
[k
], other
))
882 maybe_warn_about_dependency(u
, other_id
, k
);
884 UnitDependencyInfo di_u
, di_other
;
886 /* Let's drop this dependency between "back" and "other", and let's create it between
887 * "back" and "u" instead. Let's merge the bit masks of the dependency we are moving,
888 * and any such dependency which might already exist */
890 di_other
.data
= hashmap_get(back
->dependencies
[k
], other
);
892 continue; /* dependency isn't set, let's try the next one */
894 di_u
.data
= hashmap_get(back
->dependencies
[k
], u
);
896 UnitDependencyInfo di_merged
= {
897 .origin_mask
= di_u
.origin_mask
| di_other
.origin_mask
,
898 .destination_mask
= di_u
.destination_mask
| di_other
.destination_mask
,
901 r
= hashmap_remove_and_replace(back
->dependencies
[k
], other
, u
, di_merged
.data
);
903 log_warning_errno(r
, "Failed to remove/replace: back=%s other=%s u=%s: %m", back
->id
, other_id
, u
->id
);
906 /* assert_se(hashmap_remove_and_replace(back->dependencies[k], other, u, di_merged.data) >= 0); */
909 /* Also do not move dependencies on u to itself */
910 back
= hashmap_remove(other
->dependencies
[d
], u
);
912 maybe_warn_about_dependency(u
, other_id
, d
);
914 /* The move cannot fail. The caller must have performed a reservation. */
915 assert_se(hashmap_complete_move(&u
->dependencies
[d
], &other
->dependencies
[d
]) == 0);
917 other
->dependencies
[d
] = hashmap_free(other
->dependencies
[d
]);
920 int unit_merge(Unit
*u
, Unit
*other
) {
921 const char *other_id
= NULL
;
926 assert(u
->manager
== other
->manager
);
927 assert(u
->type
!= _UNIT_TYPE_INVALID
);
929 other
= unit_follow_merge(other
);
934 if (u
->type
!= other
->type
)
937 if (!unit_type_may_alias(u
->type
)) /* Merging only applies to unit names that support aliases */
940 if (!IN_SET(other
->load_state
, UNIT_STUB
, UNIT_NOT_FOUND
))
943 if (!streq_ptr(u
->instance
, other
->instance
))
952 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
956 other_id
= strdupa(other
->id
);
958 /* Make reservations to ensure merge_dependencies() won't fail */
959 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
960 r
= reserve_dependencies(u
, other
, d
);
962 * We don't rollback reservations if we fail. We don't have
963 * a way to undo reservations. A reservation is not a leak.
970 r
= merge_names(u
, other
);
974 /* Redirect all references */
975 while (other
->refs_by_target
)
976 unit_ref_set(other
->refs_by_target
, other
->refs_by_target
->source
, u
);
978 /* Merge dependencies */
979 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
980 merge_dependencies(u
, other
, other_id
, d
);
982 other
->load_state
= UNIT_MERGED
;
983 other
->merged_into
= u
;
985 /* If there is still some data attached to the other node, we
986 * don't need it anymore, and can free it. */
987 if (other
->load_state
!= UNIT_STUB
)
988 if (UNIT_VTABLE(other
)->done
)
989 UNIT_VTABLE(other
)->done(other
);
991 unit_add_to_dbus_queue(u
);
992 unit_add_to_cleanup_queue(other
);
997 int unit_merge_by_name(Unit
*u
, const char *name
) {
998 _cleanup_free_
char *s
= NULL
;
1002 /* Either add name to u, or if a unit with name already exists, merge it with u.
1003 * If name is a template, do the same for name@instance, where instance is u's instance. */
1008 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
1012 r
= unit_name_replace_instance(name
, u
->instance
, &s
);
1019 other
= manager_get_unit(u
->manager
, name
);
1021 return unit_merge(u
, other
);
1023 return unit_add_name(u
, name
);
1026 Unit
* unit_follow_merge(Unit
*u
) {
1029 while (u
->load_state
== UNIT_MERGED
)
1030 assert_se(u
= u
->merged_into
);
1035 int unit_add_exec_dependencies(Unit
*u
, ExecContext
*c
) {
1041 if (c
->working_directory
&& !c
->working_directory_missing_ok
) {
1042 r
= unit_require_mounts_for(u
, c
->working_directory
, UNIT_DEPENDENCY_FILE
);
1047 if (c
->root_directory
) {
1048 r
= unit_require_mounts_for(u
, c
->root_directory
, UNIT_DEPENDENCY_FILE
);
1053 if (c
->root_image
) {
1054 r
= unit_require_mounts_for(u
, c
->root_image
, UNIT_DEPENDENCY_FILE
);
1059 for (ExecDirectoryType dt
= 0; dt
< _EXEC_DIRECTORY_TYPE_MAX
; dt
++) {
1060 if (!u
->manager
->prefix
[dt
])
1064 STRV_FOREACH(dp
, c
->directories
[dt
].paths
) {
1065 _cleanup_free_
char *p
;
1067 p
= path_join(u
->manager
->prefix
[dt
], *dp
);
1071 r
= unit_require_mounts_for(u
, p
, UNIT_DEPENDENCY_FILE
);
1077 if (!MANAGER_IS_SYSTEM(u
->manager
))
1080 /* For the following three directory types we need write access, and /var/ is possibly on the root
1081 * fs. Hence order after systemd-remount-fs.service, to ensure things are writable. */
1082 if (!strv_isempty(c
->directories
[EXEC_DIRECTORY_STATE
].paths
) ||
1083 !strv_isempty(c
->directories
[EXEC_DIRECTORY_CACHE
].paths
) ||
1084 !strv_isempty(c
->directories
[EXEC_DIRECTORY_LOGS
].paths
)) {
1085 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_REMOUNT_FS_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1090 if (c
->private_tmp
) {
1093 FOREACH_STRING(p
, "/tmp", "/var/tmp") {
1094 r
= unit_require_mounts_for(u
, p
, UNIT_DEPENDENCY_FILE
);
1099 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_TMPFILES_SETUP_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1104 if (c
->root_image
) {
1105 /* We need to wait for /dev/loopX to appear when doing RootImage=, hence let's add an
1106 * implicit dependency on udev */
1108 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_UDEVD_SERVICE
, true, UNIT_DEPENDENCY_FILE
);
1113 if (!IN_SET(c
->std_output
,
1114 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
1115 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
) &&
1116 !IN_SET(c
->std_error
,
1117 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
1118 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
) &&
1122 /* If syslog or kernel logging is requested (or log namespacing is), make sure our own logging daemon
1125 if (c
->log_namespace
) {
1126 _cleanup_free_
char *socket_unit
= NULL
, *varlink_socket_unit
= NULL
;
1128 r
= unit_name_build_from_type("systemd-journald", c
->log_namespace
, UNIT_SOCKET
, &socket_unit
);
1132 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, socket_unit
, true, UNIT_DEPENDENCY_FILE
);
1136 r
= unit_name_build_from_type("systemd-journald-varlink", c
->log_namespace
, UNIT_SOCKET
, &varlink_socket_unit
);
1140 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, varlink_socket_unit
, true, UNIT_DEPENDENCY_FILE
);
1144 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_JOURNALD_SOCKET
, true, UNIT_DEPENDENCY_FILE
);
1151 const char *unit_description(Unit
*u
) {
1155 return u
->description
;
1157 return strna(u
->id
);
1160 const char *unit_status_string(Unit
*u
) {
1163 if (u
->manager
->status_unit_format
== STATUS_UNIT_FORMAT_NAME
&& u
->id
)
1166 return unit_description(u
);
1169 static void print_unit_dependency_mask(FILE *f
, const char *kind
, UnitDependencyMask mask
, bool *space
) {
1171 UnitDependencyMask mask
;
1174 { UNIT_DEPENDENCY_FILE
, "file" },
1175 { UNIT_DEPENDENCY_IMPLICIT
, "implicit" },
1176 { UNIT_DEPENDENCY_DEFAULT
, "default" },
1177 { UNIT_DEPENDENCY_UDEV
, "udev" },
1178 { UNIT_DEPENDENCY_PATH
, "path" },
1179 { UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT
, "mountinfo-implicit" },
1180 { UNIT_DEPENDENCY_MOUNTINFO_DEFAULT
, "mountinfo-default" },
1181 { UNIT_DEPENDENCY_PROC_SWAP
, "proc-swap" },
1188 for (size_t i
= 0; i
< ELEMENTSOF(table
); i
++) {
1193 if (FLAGS_SET(mask
, table
[i
].mask
)) {
1201 fputs(table
[i
].name
, f
);
1203 mask
&= ~table
[i
].mask
;
1210 void unit_dump(Unit
*u
, FILE *f
, const char *prefix
) {
1212 const char *prefix2
;
1213 char timestamp
[5][FORMAT_TIMESTAMP_MAX
], timespan
[FORMAT_TIMESPAN_MAX
];
1215 _cleanup_set_free_ Set
*following_set
= NULL
;
1220 assert(u
->type
>= 0);
1222 prefix
= strempty(prefix
);
1223 prefix2
= strjoina(prefix
, "\t");
1229 SET_FOREACH(t
, u
->aliases
)
1230 fprintf(f
, "%s\tAlias: %s\n", prefix
, t
);
1233 "%s\tDescription: %s\n"
1234 "%s\tInstance: %s\n"
1235 "%s\tUnit Load State: %s\n"
1236 "%s\tUnit Active State: %s\n"
1237 "%s\tState Change Timestamp: %s\n"
1238 "%s\tInactive Exit Timestamp: %s\n"
1239 "%s\tActive Enter Timestamp: %s\n"
1240 "%s\tActive Exit Timestamp: %s\n"
1241 "%s\tInactive Enter Timestamp: %s\n"
1243 "%s\tNeed Daemon Reload: %s\n"
1244 "%s\tTransient: %s\n"
1245 "%s\tPerpetual: %s\n"
1246 "%s\tGarbage Collection Mode: %s\n"
1249 "%s\tCGroup realized: %s\n",
1250 prefix
, unit_description(u
),
1251 prefix
, strna(u
->instance
),
1252 prefix
, unit_load_state_to_string(u
->load_state
),
1253 prefix
, unit_active_state_to_string(unit_active_state(u
)),
1254 prefix
, strna(format_timestamp(timestamp
[0], sizeof(timestamp
[0]), u
->state_change_timestamp
.realtime
)),
1255 prefix
, strna(format_timestamp(timestamp
[1], sizeof(timestamp
[1]), u
->inactive_exit_timestamp
.realtime
)),
1256 prefix
, strna(format_timestamp(timestamp
[2], sizeof(timestamp
[2]), u
->active_enter_timestamp
.realtime
)),
1257 prefix
, strna(format_timestamp(timestamp
[3], sizeof(timestamp
[3]), u
->active_exit_timestamp
.realtime
)),
1258 prefix
, strna(format_timestamp(timestamp
[4], sizeof(timestamp
[4]), u
->inactive_enter_timestamp
.realtime
)),
1259 prefix
, yes_no(unit_may_gc(u
)),
1260 prefix
, yes_no(unit_need_daemon_reload(u
)),
1261 prefix
, yes_no(u
->transient
),
1262 prefix
, yes_no(u
->perpetual
),
1263 prefix
, collect_mode_to_string(u
->collect_mode
),
1264 prefix
, strna(unit_slice_name(u
)),
1265 prefix
, strna(u
->cgroup_path
),
1266 prefix
, yes_no(u
->cgroup_realized
));
1268 if (u
->cgroup_realized_mask
!= 0) {
1269 _cleanup_free_
char *s
= NULL
;
1270 (void) cg_mask_to_string(u
->cgroup_realized_mask
, &s
);
1271 fprintf(f
, "%s\tCGroup realized mask: %s\n", prefix
, strnull(s
));
1274 if (u
->cgroup_enabled_mask
!= 0) {
1275 _cleanup_free_
char *s
= NULL
;
1276 (void) cg_mask_to_string(u
->cgroup_enabled_mask
, &s
);
1277 fprintf(f
, "%s\tCGroup enabled mask: %s\n", prefix
, strnull(s
));
1280 m
= unit_get_own_mask(u
);
1282 _cleanup_free_
char *s
= NULL
;
1283 (void) cg_mask_to_string(m
, &s
);
1284 fprintf(f
, "%s\tCGroup own mask: %s\n", prefix
, strnull(s
));
1287 m
= unit_get_members_mask(u
);
1289 _cleanup_free_
char *s
= NULL
;
1290 (void) cg_mask_to_string(m
, &s
);
1291 fprintf(f
, "%s\tCGroup members mask: %s\n", prefix
, strnull(s
));
1294 m
= unit_get_delegate_mask(u
);
1296 _cleanup_free_
char *s
= NULL
;
1297 (void) cg_mask_to_string(m
, &s
);
1298 fprintf(f
, "%s\tCGroup delegate mask: %s\n", prefix
, strnull(s
));
1301 if (!sd_id128_is_null(u
->invocation_id
))
1302 fprintf(f
, "%s\tInvocation ID: " SD_ID128_FORMAT_STR
"\n",
1303 prefix
, SD_ID128_FORMAT_VAL(u
->invocation_id
));
1305 STRV_FOREACH(j
, u
->documentation
)
1306 fprintf(f
, "%s\tDocumentation: %s\n", prefix
, *j
);
1308 following
= unit_following(u
);
1310 fprintf(f
, "%s\tFollowing: %s\n", prefix
, following
->id
);
1312 r
= unit_following_set(u
, &following_set
);
1316 SET_FOREACH(other
, following_set
)
1317 fprintf(f
, "%s\tFollowing Set Member: %s\n", prefix
, other
->id
);
1320 if (u
->fragment_path
)
1321 fprintf(f
, "%s\tFragment Path: %s\n", prefix
, u
->fragment_path
);
1324 fprintf(f
, "%s\tSource Path: %s\n", prefix
, u
->source_path
);
1326 STRV_FOREACH(j
, u
->dropin_paths
)
1327 fprintf(f
, "%s\tDropIn Path: %s\n", prefix
, *j
);
1329 if (u
->failure_action
!= EMERGENCY_ACTION_NONE
)
1330 fprintf(f
, "%s\tFailure Action: %s\n", prefix
, emergency_action_to_string(u
->failure_action
));
1331 if (u
->failure_action_exit_status
>= 0)
1332 fprintf(f
, "%s\tFailure Action Exit Status: %i\n", prefix
, u
->failure_action_exit_status
);
1333 if (u
->success_action
!= EMERGENCY_ACTION_NONE
)
1334 fprintf(f
, "%s\tSuccess Action: %s\n", prefix
, emergency_action_to_string(u
->success_action
));
1335 if (u
->success_action_exit_status
>= 0)
1336 fprintf(f
, "%s\tSuccess Action Exit Status: %i\n", prefix
, u
->success_action_exit_status
);
1338 if (u
->job_timeout
!= USEC_INFINITY
)
1339 fprintf(f
, "%s\tJob Timeout: %s\n", prefix
, format_timespan(timespan
, sizeof(timespan
), u
->job_timeout
, 0));
1341 if (u
->job_timeout_action
!= EMERGENCY_ACTION_NONE
)
1342 fprintf(f
, "%s\tJob Timeout Action: %s\n", prefix
, emergency_action_to_string(u
->job_timeout_action
));
1344 if (u
->job_timeout_reboot_arg
)
1345 fprintf(f
, "%s\tJob Timeout Reboot Argument: %s\n", prefix
, u
->job_timeout_reboot_arg
);
1347 condition_dump_list(u
->conditions
, f
, prefix
, condition_type_to_string
);
1348 condition_dump_list(u
->asserts
, f
, prefix
, assert_type_to_string
);
1350 if (dual_timestamp_is_set(&u
->condition_timestamp
))
1352 "%s\tCondition Timestamp: %s\n"
1353 "%s\tCondition Result: %s\n",
1354 prefix
, strna(format_timestamp(timestamp
[0], sizeof(timestamp
[0]), u
->condition_timestamp
.realtime
)),
1355 prefix
, yes_no(u
->condition_result
));
1357 if (dual_timestamp_is_set(&u
->assert_timestamp
))
1359 "%s\tAssert Timestamp: %s\n"
1360 "%s\tAssert Result: %s\n",
1361 prefix
, strna(format_timestamp(timestamp
[0], sizeof(timestamp
[0]), u
->assert_timestamp
.realtime
)),
1362 prefix
, yes_no(u
->assert_result
));
1364 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
1365 UnitDependencyInfo di
;
1368 HASHMAP_FOREACH_KEY(di
.data
, other
, u
->dependencies
[d
]) {
1371 fprintf(f
, "%s\t%s: %s (", prefix
, unit_dependency_to_string(d
), other
->id
);
1373 print_unit_dependency_mask(f
, "origin", di
.origin_mask
, &space
);
1374 print_unit_dependency_mask(f
, "destination", di
.destination_mask
, &space
);
1380 if (!hashmap_isempty(u
->requires_mounts_for
)) {
1381 UnitDependencyInfo di
;
1384 HASHMAP_FOREACH_KEY(di
.data
, path
, u
->requires_mounts_for
) {
1387 fprintf(f
, "%s\tRequiresMountsFor: %s (", prefix
, path
);
1389 print_unit_dependency_mask(f
, "origin", di
.origin_mask
, &space
);
1390 print_unit_dependency_mask(f
, "destination", di
.destination_mask
, &space
);
1396 if (u
->load_state
== UNIT_LOADED
) {
1399 "%s\tStopWhenUnneeded: %s\n"
1400 "%s\tRefuseManualStart: %s\n"
1401 "%s\tRefuseManualStop: %s\n"
1402 "%s\tDefaultDependencies: %s\n"
1403 "%s\tOnFailureJobMode: %s\n"
1404 "%s\tIgnoreOnIsolate: %s\n",
1405 prefix
, yes_no(u
->stop_when_unneeded
),
1406 prefix
, yes_no(u
->refuse_manual_start
),
1407 prefix
, yes_no(u
->refuse_manual_stop
),
1408 prefix
, yes_no(u
->default_dependencies
),
1409 prefix
, job_mode_to_string(u
->on_failure_job_mode
),
1410 prefix
, yes_no(u
->ignore_on_isolate
));
1412 if (UNIT_VTABLE(u
)->dump
)
1413 UNIT_VTABLE(u
)->dump(u
, f
, prefix2
);
1415 } else if (u
->load_state
== UNIT_MERGED
)
1417 "%s\tMerged into: %s\n",
1418 prefix
, u
->merged_into
->id
);
1419 else if (u
->load_state
== UNIT_ERROR
)
1420 fprintf(f
, "%s\tLoad Error Code: %s\n", prefix
, strerror_safe(u
->load_error
));
1422 for (const char *n
= sd_bus_track_first(u
->bus_track
); n
; n
= sd_bus_track_next(u
->bus_track
))
1423 fprintf(f
, "%s\tBus Ref: %s\n", prefix
, n
);
1426 job_dump(u
->job
, f
, prefix2
);
1429 job_dump(u
->nop_job
, f
, prefix2
);
1432 /* Common implementation for multiple backends */
1433 int unit_load_fragment_and_dropin(Unit
*u
, bool fragment_required
) {
1438 /* Load a .{service,socket,...} file */
1439 r
= unit_load_fragment(u
);
1443 if (u
->load_state
== UNIT_STUB
) {
1444 if (fragment_required
)
1447 u
->load_state
= UNIT_LOADED
;
1450 /* Load drop-in directory data. If u is an alias, we might be reloading the
1451 * target unit needlessly. But we cannot be sure which drops-ins have already
1452 * been loaded and which not, at least without doing complicated book-keeping,
1453 * so let's always reread all drop-ins. */
1454 r
= unit_load_dropin(unit_follow_merge(u
));
1458 if (u
->source_path
) {
1461 if (stat(u
->source_path
, &st
) >= 0)
1462 u
->source_mtime
= timespec_load(&st
.st_mtim
);
1464 u
->source_mtime
= 0;
1470 void unit_add_to_target_deps_queue(Unit
*u
) {
1471 Manager
*m
= u
->manager
;
1475 if (u
->in_target_deps_queue
)
1478 LIST_PREPEND(target_deps_queue
, m
->target_deps_queue
, u
);
1479 u
->in_target_deps_queue
= true;
1482 int unit_add_default_target_dependency(Unit
*u
, Unit
*target
) {
1486 if (target
->type
!= UNIT_TARGET
)
1489 /* Only add the dependency if both units are loaded, so that
1490 * that loop check below is reliable */
1491 if (u
->load_state
!= UNIT_LOADED
||
1492 target
->load_state
!= UNIT_LOADED
)
1495 /* If either side wants no automatic dependencies, then let's
1497 if (!u
->default_dependencies
||
1498 !target
->default_dependencies
)
1501 /* Don't create loops */
1502 if (hashmap_get(target
->dependencies
[UNIT_BEFORE
], u
))
1505 return unit_add_dependency(target
, UNIT_AFTER
, u
, true, UNIT_DEPENDENCY_DEFAULT
);
1508 static int unit_add_slice_dependencies(Unit
*u
) {
1511 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1514 /* Slice units are implicitly ordered against their parent slices (as this relationship is encoded in the
1515 name), while all other units are ordered based on configuration (as in their case Slice= configures the
1517 UnitDependencyMask mask
= u
->type
== UNIT_SLICE
? UNIT_DEPENDENCY_IMPLICIT
: UNIT_DEPENDENCY_FILE
;
1519 if (UNIT_ISSET(u
->slice
))
1520 return unit_add_two_dependencies(u
, UNIT_AFTER
, UNIT_REQUIRES
, UNIT_DEREF(u
->slice
), true, mask
);
1522 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1525 return unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_ROOT_SLICE
, true, mask
);
1528 static int unit_add_mount_dependencies(Unit
*u
) {
1529 UnitDependencyInfo di
;
1535 HASHMAP_FOREACH_KEY(di
.data
, path
, u
->requires_mounts_for
) {
1536 char prefix
[strlen(path
) + 1];
1538 PATH_FOREACH_PREFIX_MORE(prefix
, path
) {
1539 _cleanup_free_
char *p
= NULL
;
1542 r
= unit_name_from_path(prefix
, ".mount", &p
);
1546 m
= manager_get_unit(u
->manager
, p
);
1548 /* Make sure to load the mount unit if
1549 * it exists. If so the dependencies
1550 * on this unit will be added later
1551 * during the loading of the mount
1553 (void) manager_load_unit_prepare(u
->manager
, p
, NULL
, NULL
, &m
);
1559 if (m
->load_state
!= UNIT_LOADED
)
1562 r
= unit_add_dependency(u
, UNIT_AFTER
, m
, true, di
.origin_mask
);
1566 if (m
->fragment_path
) {
1567 r
= unit_add_dependency(u
, UNIT_REQUIRES
, m
, true, di
.origin_mask
);
1577 static int unit_add_oomd_dependencies(Unit
*u
) {
1584 if (!u
->default_dependencies
)
1587 c
= unit_get_cgroup_context(u
);
1591 wants_oomd
= (c
->moom_swap
== MANAGED_OOM_KILL
|| c
->moom_mem_pressure
== MANAGED_OOM_KILL
);
1595 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_WANTS
, "systemd-oomd.service", true, UNIT_DEPENDENCY_FILE
);
1602 static int unit_add_startup_units(Unit
*u
) {
1605 c
= unit_get_cgroup_context(u
);
1609 if (c
->startup_cpu_shares
== CGROUP_CPU_SHARES_INVALID
&&
1610 c
->startup_io_weight
== CGROUP_WEIGHT_INVALID
&&
1611 c
->startup_blockio_weight
== CGROUP_BLKIO_WEIGHT_INVALID
)
1614 return set_ensure_put(&u
->manager
->startup_units
, NULL
, u
);
1617 int unit_load(Unit
*u
) {
1622 if (u
->in_load_queue
) {
1623 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
1624 u
->in_load_queue
= false;
1627 if (u
->type
== _UNIT_TYPE_INVALID
)
1630 if (u
->load_state
!= UNIT_STUB
)
1633 if (u
->transient_file
) {
1634 /* Finalize transient file: if this is a transient unit file, as soon as we reach unit_load() the setup
1635 * is complete, hence let's synchronize the unit file we just wrote to disk. */
1637 r
= fflush_and_check(u
->transient_file
);
1641 u
->transient_file
= safe_fclose(u
->transient_file
);
1642 u
->fragment_mtime
= now(CLOCK_REALTIME
);
1645 r
= UNIT_VTABLE(u
)->load(u
);
1649 assert(u
->load_state
!= UNIT_STUB
);
1651 if (u
->load_state
== UNIT_LOADED
) {
1652 unit_add_to_target_deps_queue(u
);
1654 r
= unit_add_slice_dependencies(u
);
1658 r
= unit_add_mount_dependencies(u
);
1662 r
= unit_add_oomd_dependencies(u
);
1666 r
= unit_add_startup_units(u
);
1670 if (u
->on_failure_job_mode
== JOB_ISOLATE
&& hashmap_size(u
->dependencies
[UNIT_ON_FAILURE
]) > 1) {
1671 r
= log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOEXEC
),
1672 "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
1676 if (u
->job_running_timeout
!= USEC_INFINITY
&& u
->job_running_timeout
> u
->job_timeout
)
1677 log_unit_warning(u
, "JobRunningTimeoutSec= is greater than JobTimeoutSec=, it has no effect.");
1679 /* We finished loading, let's ensure our parents recalculate the members mask */
1680 unit_invalidate_cgroup_members_masks(u
);
1683 assert((u
->load_state
!= UNIT_MERGED
) == !u
->merged_into
);
1685 unit_add_to_dbus_queue(unit_follow_merge(u
));
1686 unit_add_to_gc_queue(u
);
1687 (void) manager_varlink_send_managed_oom_update(u
);
1692 /* We convert ENOEXEC errors to the UNIT_BAD_SETTING load state here. Configuration parsing code
1693 * should hence return ENOEXEC to ensure units are placed in this state after loading. */
1695 u
->load_state
= u
->load_state
== UNIT_STUB
? UNIT_NOT_FOUND
:
1696 r
== -ENOEXEC
? UNIT_BAD_SETTING
:
1700 /* Record the timestamp on the cache, so that if the cache gets updated between now and the next time
1701 * an attempt is made to load this unit, we know we need to check again. */
1702 if (u
->load_state
== UNIT_NOT_FOUND
)
1703 u
->fragment_not_found_timestamp_hash
= u
->manager
->unit_cache_timestamp_hash
;
1705 unit_add_to_dbus_queue(u
);
1706 unit_add_to_gc_queue(u
);
1708 return log_unit_debug_errno(u
, r
, "Failed to load configuration: %m");
1712 static int log_unit_internal(void *userdata
, int level
, int error
, const char *file
, int line
, const char *func
, const char *format
, ...) {
1717 va_start(ap
, format
);
1719 r
= log_object_internalv(level
, error
, file
, line
, func
,
1720 u
->manager
->unit_log_field
,
1722 u
->manager
->invocation_log_field
,
1723 u
->invocation_id_string
,
1726 r
= log_internalv(level
, error
, file
, line
, func
, format
, ap
);
1732 static bool unit_test_condition(Unit
*u
) {
1733 _cleanup_strv_free_
char **env
= NULL
;
1738 dual_timestamp_get(&u
->condition_timestamp
);
1740 r
= manager_get_effective_environment(u
->manager
, &env
);
1742 log_unit_error_errno(u
, r
, "Failed to determine effective environment: %m");
1743 u
->condition_result
= CONDITION_ERROR
;
1745 u
->condition_result
= condition_test_list(
1748 condition_type_to_string
,
1752 unit_add_to_dbus_queue(u
);
1753 return u
->condition_result
;
1756 static bool unit_test_assert(Unit
*u
) {
1757 _cleanup_strv_free_
char **env
= NULL
;
1762 dual_timestamp_get(&u
->assert_timestamp
);
1764 r
= manager_get_effective_environment(u
->manager
, &env
);
1766 log_unit_error_errno(u
, r
, "Failed to determine effective environment: %m");
1767 u
->assert_result
= CONDITION_ERROR
;
1769 u
->assert_result
= condition_test_list(
1772 assert_type_to_string
,
1776 unit_add_to_dbus_queue(u
);
1777 return u
->assert_result
;
1780 void unit_status_printf(Unit
*u
, StatusType status_type
, const char *status
, const char *unit_status_msg_format
) {
1783 d
= unit_status_string(u
);
1784 if (log_get_show_color())
1785 d
= strjoina(ANSI_HIGHLIGHT
, d
, ANSI_NORMAL
);
1787 DISABLE_WARNING_FORMAT_NONLITERAL
;
1788 manager_status_printf(u
->manager
, status_type
, status
, unit_status_msg_format
, d
);
1792 int unit_test_start_limit(Unit
*u
) {
1797 if (ratelimit_below(&u
->start_ratelimit
)) {
1798 u
->start_limit_hit
= false;
1802 log_unit_warning(u
, "Start request repeated too quickly.");
1803 u
->start_limit_hit
= true;
1805 reason
= strjoina("unit ", u
->id
, " failed");
1807 emergency_action(u
->manager
, u
->start_limit_action
,
1808 EMERGENCY_ACTION_IS_WATCHDOG
|EMERGENCY_ACTION_WARN
,
1809 u
->reboot_arg
, -1, reason
);
1814 bool unit_shall_confirm_spawn(Unit
*u
) {
1817 if (manager_is_confirm_spawn_disabled(u
->manager
))
1820 /* For some reasons units remaining in the same process group
1821 * as PID 1 fail to acquire the console even if it's not used
1822 * by any process. So skip the confirmation question for them. */
1823 return !unit_get_exec_context(u
)->same_pgrp
;
1826 static bool unit_verify_deps(Unit
*u
) {
1832 /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined with
1833 * After=. We do not check Requires= or Requisite= here as they only should have an effect on the job
1834 * processing, but do not have any effect afterwards. We don't check BindsTo= dependencies that are not used in
1835 * conjunction with After= as for them any such check would make things entirely racy. */
1837 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
]) {
1839 if (!hashmap_contains(u
->dependencies
[UNIT_AFTER
], other
))
1842 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other
))) {
1843 log_unit_notice(u
, "Bound to unit %s, but unit isn't active.", other
->id
);
1851 /* Errors that aren't really errors:
1852 * -EALREADY: Unit is already started.
1853 * -ECOMM: Condition failed
1854 * -EAGAIN: An operation is already in progress. Retry later.
1856 * Errors that are real errors:
1857 * -EBADR: This unit type does not support starting.
1858 * -ECANCELED: Start limit hit, too many requests for now
1859 * -EPROTO: Assert failed
1860 * -EINVAL: Unit not loaded
1861 * -EOPNOTSUPP: Unit type not supported
1862 * -ENOLINK: The necessary dependencies are not fulfilled.
1863 * -ESTALE: This unit has been started before and can't be started a second time
1864 * -ENOENT: This is a triggering unit and unit to trigger is not loaded
1866 int unit_start(Unit
*u
) {
1867 UnitActiveState state
;
1872 /* If this is already started, then this will succeed. Note that this will even succeed if this unit
1873 * is not startable by the user. This is relied on to detect when we need to wait for units and when
1874 * waiting is finished. */
1875 state
= unit_active_state(u
);
1876 if (UNIT_IS_ACTIVE_OR_RELOADING(state
))
1878 if (state
== UNIT_MAINTENANCE
)
1881 /* Units that aren't loaded cannot be started */
1882 if (u
->load_state
!= UNIT_LOADED
)
1885 /* Refuse starting scope units more than once */
1886 if (UNIT_VTABLE(u
)->once_only
&& dual_timestamp_is_set(&u
->inactive_enter_timestamp
))
1889 /* If the conditions failed, don't do anything at all. If we already are activating this call might
1890 * still be useful to speed up activation in case there is some hold-off time, but we don't want to
1891 * recheck the condition in that case. */
1892 if (state
!= UNIT_ACTIVATING
&&
1893 !unit_test_condition(u
))
1894 return log_unit_debug_errno(u
, SYNTHETIC_ERRNO(ECOMM
), "Starting requested but condition failed. Not starting unit.");
1896 /* If the asserts failed, fail the entire job */
1897 if (state
!= UNIT_ACTIVATING
&&
1898 !unit_test_assert(u
))
1899 return log_unit_notice_errno(u
, SYNTHETIC_ERRNO(EPROTO
), "Starting requested but asserts failed.");
1901 /* Units of types that aren't supported cannot be started. Note that we do this test only after the
1902 * condition checks, so that we rather return condition check errors (which are usually not
1903 * considered a true failure) than "not supported" errors (which are considered a failure).
1905 if (!unit_type_supported(u
->type
))
1908 /* Let's make sure that the deps really are in order before we start this. Normally the job engine
1909 * should have taken care of this already, but let's check this here again. After all, our
1910 * dependencies might not be in effect anymore, due to a reload or due to a failed condition. */
1911 if (!unit_verify_deps(u
))
1914 /* Forward to the main object, if we aren't it. */
1915 following
= unit_following(u
);
1917 log_unit_debug(u
, "Redirecting start request from %s to %s.", u
->id
, following
->id
);
1918 return unit_start(following
);
1921 /* If it is stopped, but we cannot start it, then fail */
1922 if (!UNIT_VTABLE(u
)->start
)
1925 /* We don't suppress calls to ->start() here when we are already starting, to allow this request to
1926 * be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
1927 * waits for a holdoff timer to elapse before it will start again. */
1929 unit_add_to_dbus_queue(u
);
1930 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1932 return UNIT_VTABLE(u
)->start(u
);
1935 bool unit_can_start(Unit
*u
) {
1938 if (u
->load_state
!= UNIT_LOADED
)
1941 if (!unit_type_supported(u
->type
))
1944 /* Scope units may be started only once */
1945 if (UNIT_VTABLE(u
)->once_only
&& dual_timestamp_is_set(&u
->inactive_exit_timestamp
))
1948 return !!UNIT_VTABLE(u
)->start
;
1951 bool unit_can_isolate(Unit
*u
) {
1954 return unit_can_start(u
) &&
1959 * -EBADR: This unit type does not support stopping.
1960 * -EALREADY: Unit is already stopped.
1961 * -EAGAIN: An operation is already in progress. Retry later.
1963 int unit_stop(Unit
*u
) {
1964 UnitActiveState state
;
1969 state
= unit_active_state(u
);
1970 if (UNIT_IS_INACTIVE_OR_FAILED(state
))
1973 following
= unit_following(u
);
1975 log_unit_debug(u
, "Redirecting stop request from %s to %s.", u
->id
, following
->id
);
1976 return unit_stop(following
);
1979 if (!UNIT_VTABLE(u
)->stop
)
1982 unit_add_to_dbus_queue(u
);
1983 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
1985 return UNIT_VTABLE(u
)->stop(u
);
1988 bool unit_can_stop(Unit
*u
) {
1991 /* Note: if we return true here, it does not mean that the unit may be successfully stopped.
1992 * Extrinsic units follow external state and they may stop following external state changes
1993 * (hence we return true here), but an attempt to do this through the manager will fail. */
1995 if (!unit_type_supported(u
->type
))
2001 return !!UNIT_VTABLE(u
)->stop
;
2005 * -EBADR: This unit type does not support reloading.
2006 * -ENOEXEC: Unit is not started.
2007 * -EAGAIN: An operation is already in progress. Retry later.
2009 int unit_reload(Unit
*u
) {
2010 UnitActiveState state
;
2015 if (u
->load_state
!= UNIT_LOADED
)
2018 if (!unit_can_reload(u
))
2021 state
= unit_active_state(u
);
2022 if (state
== UNIT_RELOADING
)
2025 if (state
!= UNIT_ACTIVE
)
2026 return log_unit_warning_errno(u
, SYNTHETIC_ERRNO(ENOEXEC
), "Unit cannot be reloaded because it is inactive.");
2028 following
= unit_following(u
);
2030 log_unit_debug(u
, "Redirecting reload request from %s to %s.", u
->id
, following
->id
);
2031 return unit_reload(following
);
2034 unit_add_to_dbus_queue(u
);
2036 if (!UNIT_VTABLE(u
)->reload
) {
2037 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
2038 unit_notify(u
, unit_active_state(u
), unit_active_state(u
), 0);
2042 unit_cgroup_freezer_action(u
, FREEZER_THAW
);
2044 return UNIT_VTABLE(u
)->reload(u
);
2047 bool unit_can_reload(Unit
*u
) {
2050 if (UNIT_VTABLE(u
)->can_reload
)
2051 return UNIT_VTABLE(u
)->can_reload(u
);
2053 if (!hashmap_isempty(u
->dependencies
[UNIT_PROPAGATES_RELOAD_TO
]))
2056 return UNIT_VTABLE(u
)->reload
;
2059 bool unit_is_unneeded(Unit
*u
) {
2060 static const UnitDependency deps
[] = {
2069 if (!u
->stop_when_unneeded
)
2072 /* Don't clean up while the unit is transitioning or is even inactive. */
2073 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u
)))
2078 for (size_t j
= 0; j
< ELEMENTSOF(deps
); j
++) {
2082 /* If a dependent unit has a job queued, is active or transitioning, or is marked for
2083 * restart, then don't clean this one up. */
2085 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[deps
[j
]]) {
2089 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
2092 if (unit_will_restart(other
))
2100 static void check_unneeded_dependencies(Unit
*u
) {
2102 static const UnitDependency deps
[] = {
2111 /* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
2113 for (size_t j
= 0; j
< ELEMENTSOF(deps
); j
++) {
2117 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[deps
[j
]])
2118 unit_submit_to_stop_when_unneeded_queue(other
);
2122 static void unit_check_binds_to(Unit
*u
) {
2123 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2134 if (unit_active_state(u
) != UNIT_ACTIVE
)
2137 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
]) {
2141 if (!other
->coldplugged
)
2142 /* We might yet create a job for the other unit… */
2145 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
2155 /* If stopping a unit fails continuously we might enter a stop
2156 * loop here, hence stop acting on the service being
2157 * unnecessary after a while. */
2158 if (!ratelimit_below(&u
->auto_stop_ratelimit
)) {
2159 log_unit_warning(u
, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other
->id
);
2164 log_unit_info(u
, "Unit is bound to inactive unit %s. Stopping, too.", other
->id
);
2166 /* A unit we need to run is gone. Sniff. Let's stop this. */
2167 r
= manager_add_job(u
->manager
, JOB_STOP
, u
, JOB_FAIL
, NULL
, &error
, NULL
);
2169 log_unit_warning_errno(u
, r
, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error
, r
));
2172 static void retroactively_start_dependencies(Unit
*u
) {
2177 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)));
2179 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_REQUIRES
])
2180 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
2181 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
2182 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2184 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BINDS_TO
])
2185 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
2186 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
2187 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2189 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_WANTS
])
2190 if (!hashmap_get(u
->dependencies
[UNIT_AFTER
], other
) &&
2191 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
2192 manager_add_job(u
->manager
, JOB_START
, other
, JOB_FAIL
, NULL
, NULL
, NULL
);
2194 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_CONFLICTS
])
2195 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
2196 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2198 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_CONFLICTED_BY
])
2199 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
2200 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2203 static void retroactively_stop_dependencies(Unit
*u
) {
2208 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)));
2210 /* Pull down units which are bound to us recursively if enabled */
2211 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_BOUND_BY
])
2212 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
2213 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
, NULL
);
2216 void unit_start_on_failure(Unit
*u
) {
2223 if (hashmap_size(u
->dependencies
[UNIT_ON_FAILURE
]) <= 0)
2226 log_unit_info(u
, "Triggering OnFailure= dependencies.");
2228 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_ON_FAILURE
]) {
2229 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2231 r
= manager_add_job(u
->manager
, JOB_START
, other
, u
->on_failure_job_mode
, NULL
, &error
, NULL
);
2233 log_unit_warning_errno(u
, r
, "Failed to enqueue OnFailure= job, ignoring: %s", bus_error_message(&error
, r
));
2237 void unit_trigger_notify(Unit
*u
) {
2243 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_TRIGGERED_BY
])
2244 if (UNIT_VTABLE(other
)->trigger_notify
)
2245 UNIT_VTABLE(other
)->trigger_notify(other
, u
);
2248 static int raise_level(int log_level
, bool condition_info
, bool condition_notice
) {
2249 if (condition_notice
&& log_level
> LOG_NOTICE
)
2251 if (condition_info
&& log_level
> LOG_INFO
)
2256 static int unit_log_resources(Unit
*u
) {
2257 struct iovec iovec
[1 + _CGROUP_IP_ACCOUNTING_METRIC_MAX
+ _CGROUP_IO_ACCOUNTING_METRIC_MAX
+ 4];
2258 bool any_traffic
= false, have_ip_accounting
= false, any_io
= false, have_io_accounting
= false;
2259 _cleanup_free_
char *igress
= NULL
, *egress
= NULL
, *rr
= NULL
, *wr
= NULL
;
2260 int log_level
= LOG_DEBUG
; /* May be raised if resources consumed over a threshold */
2261 size_t n_message_parts
= 0, n_iovec
= 0;
2262 char* message_parts
[1 + 2 + 2 + 1], *t
;
2263 nsec_t nsec
= NSEC_INFINITY
;
2265 const char* const ip_fields
[_CGROUP_IP_ACCOUNTING_METRIC_MAX
] = {
2266 [CGROUP_IP_INGRESS_BYTES
] = "IP_METRIC_INGRESS_BYTES",
2267 [CGROUP_IP_INGRESS_PACKETS
] = "IP_METRIC_INGRESS_PACKETS",
2268 [CGROUP_IP_EGRESS_BYTES
] = "IP_METRIC_EGRESS_BYTES",
2269 [CGROUP_IP_EGRESS_PACKETS
] = "IP_METRIC_EGRESS_PACKETS",
2271 const char* const io_fields
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
2272 [CGROUP_IO_READ_BYTES
] = "IO_METRIC_READ_BYTES",
2273 [CGROUP_IO_WRITE_BYTES
] = "IO_METRIC_WRITE_BYTES",
2274 [CGROUP_IO_READ_OPERATIONS
] = "IO_METRIC_READ_OPERATIONS",
2275 [CGROUP_IO_WRITE_OPERATIONS
] = "IO_METRIC_WRITE_OPERATIONS",
2280 /* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
2281 * accounting was enabled for a unit. It does this in two ways: a friendly human readable string with reduced
2282 * information and the complete data in structured fields. */
2284 (void) unit_get_cpu_usage(u
, &nsec
);
2285 if (nsec
!= NSEC_INFINITY
) {
2286 char buf
[FORMAT_TIMESPAN_MAX
] = "";
2288 /* Format the CPU time for inclusion in the structured log message */
2289 if (asprintf(&t
, "CPU_USAGE_NSEC=%" PRIu64
, nsec
) < 0) {
2293 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2295 /* Format the CPU time for inclusion in the human language message string */
2296 format_timespan(buf
, sizeof(buf
), nsec
/ NSEC_PER_USEC
, USEC_PER_MSEC
);
2297 t
= strjoin("consumed ", buf
, " CPU time");
2303 message_parts
[n_message_parts
++] = t
;
2305 log_level
= raise_level(log_level
,
2306 nsec
> NOTICEWORTHY_CPU_NSEC
,
2307 nsec
> MENTIONWORTHY_CPU_NSEC
);
2310 for (CGroupIOAccountingMetric k
= 0; k
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; k
++) {
2311 char buf
[FORMAT_BYTES_MAX
] = "";
2312 uint64_t value
= UINT64_MAX
;
2314 assert(io_fields
[k
]);
2316 (void) unit_get_io_accounting(u
, k
, k
> 0, &value
);
2317 if (value
== UINT64_MAX
)
2320 have_io_accounting
= true;
2324 /* Format IO accounting data for inclusion in the structured log message */
2325 if (asprintf(&t
, "%s=%" PRIu64
, io_fields
[k
], value
) < 0) {
2329 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2331 /* Format the IO accounting data for inclusion in the human language message string, but only
2332 * for the bytes counters (and not for the operations counters) */
2333 if (k
== CGROUP_IO_READ_BYTES
) {
2335 rr
= strjoin("read ", format_bytes(buf
, sizeof(buf
), value
), " from disk");
2340 } else if (k
== CGROUP_IO_WRITE_BYTES
) {
2342 wr
= strjoin("written ", format_bytes(buf
, sizeof(buf
), value
), " to disk");
2349 if (IN_SET(k
, CGROUP_IO_READ_BYTES
, CGROUP_IO_WRITE_BYTES
))
2350 log_level
= raise_level(log_level
,
2351 value
> MENTIONWORTHY_IO_BYTES
,
2352 value
> NOTICEWORTHY_IO_BYTES
);
2355 if (have_io_accounting
) {
2358 message_parts
[n_message_parts
++] = TAKE_PTR(rr
);
2360 message_parts
[n_message_parts
++] = TAKE_PTR(wr
);
2365 k
= strdup("no IO");
2371 message_parts
[n_message_parts
++] = k
;
2375 for (CGroupIPAccountingMetric m
= 0; m
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
; m
++) {
2376 char buf
[FORMAT_BYTES_MAX
] = "";
2377 uint64_t value
= UINT64_MAX
;
2379 assert(ip_fields
[m
]);
2381 (void) unit_get_ip_accounting(u
, m
, &value
);
2382 if (value
== UINT64_MAX
)
2385 have_ip_accounting
= true;
2389 /* Format IP accounting data for inclusion in the structured log message */
2390 if (asprintf(&t
, "%s=%" PRIu64
, ip_fields
[m
], value
) < 0) {
2394 iovec
[n_iovec
++] = IOVEC_MAKE_STRING(t
);
2396 /* Format the IP accounting data for inclusion in the human language message string, but only for the
2397 * bytes counters (and not for the packets counters) */
2398 if (m
== CGROUP_IP_INGRESS_BYTES
) {
2400 igress
= strjoin("received ", format_bytes(buf
, sizeof(buf
), value
), " IP traffic");
2405 } else if (m
== CGROUP_IP_EGRESS_BYTES
) {
2407 egress
= strjoin("sent ", format_bytes(buf
, sizeof(buf
), value
), " IP traffic");
2414 if (IN_SET(m
, CGROUP_IP_INGRESS_BYTES
, CGROUP_IP_EGRESS_BYTES
))
2415 log_level
= raise_level(log_level
,
2416 value
> MENTIONWORTHY_IP_BYTES
,
2417 value
> NOTICEWORTHY_IP_BYTES
);
2420 if (have_ip_accounting
) {
2423 message_parts
[n_message_parts
++] = TAKE_PTR(igress
);
2425 message_parts
[n_message_parts
++] = TAKE_PTR(egress
);
2430 k
= strdup("no IP traffic");
2436 message_parts
[n_message_parts
++] = k
;
2440 /* Is there any accounting data available at all? */
2446 if (n_message_parts
== 0)
2447 t
= strjoina("MESSAGE=", u
->id
, ": Completed.");
2449 _cleanup_free_
char *joined
;
2451 message_parts
[n_message_parts
] = NULL
;
2453 joined
= strv_join(message_parts
, ", ");
2459 joined
[0] = ascii_toupper(joined
[0]);
2460 t
= strjoina("MESSAGE=", u
->id
, ": ", joined
, ".");
2463 /* The following four fields we allocate on the stack or are static strings, we hence don't want to free them,
2464 * and hence don't increase n_iovec for them */
2465 iovec
[n_iovec
] = IOVEC_MAKE_STRING(t
);
2466 iovec
[n_iovec
+ 1] = IOVEC_MAKE_STRING("MESSAGE_ID=" SD_MESSAGE_UNIT_RESOURCES_STR
);
2468 t
= strjoina(u
->manager
->unit_log_field
, u
->id
);
2469 iovec
[n_iovec
+ 2] = IOVEC_MAKE_STRING(t
);
2471 t
= strjoina(u
->manager
->invocation_log_field
, u
->invocation_id_string
);
2472 iovec
[n_iovec
+ 3] = IOVEC_MAKE_STRING(t
);
2474 log_struct_iovec(log_level
, iovec
, n_iovec
+ 4);
2478 for (size_t i
= 0; i
< n_message_parts
; i
++)
2479 free(message_parts
[i
]);
2481 for (size_t i
= 0; i
< n_iovec
; i
++)
2482 free(iovec
[i
].iov_base
);
2488 static void unit_update_on_console(Unit
*u
) {
2493 b
= unit_needs_console(u
);
2494 if (u
->on_console
== b
)
2499 manager_ref_console(u
->manager
);
2501 manager_unref_console(u
->manager
);
2504 static void unit_emit_audit_start(Unit
*u
) {
2507 if (u
->type
!= UNIT_SERVICE
)
2510 /* Write audit record if we have just finished starting up */
2511 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_START
, true);
2515 static void unit_emit_audit_stop(Unit
*u
, UnitActiveState state
) {
2518 if (u
->type
!= UNIT_SERVICE
)
2522 /* Write audit record if we have just finished shutting down */
2523 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_STOP
, state
== UNIT_INACTIVE
);
2524 u
->in_audit
= false;
2526 /* Hmm, if there was no start record written write it now, so that we always have a nice pair */
2527 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_START
, state
== UNIT_INACTIVE
);
2529 if (state
== UNIT_INACTIVE
)
2530 manager_send_unit_audit(u
->manager
, u
, AUDIT_SERVICE_STOP
, true);
2534 static bool unit_process_job(Job
*j
, UnitActiveState ns
, UnitNotifyFlags flags
) {
2535 bool unexpected
= false;
2540 if (j
->state
== JOB_WAITING
)
2542 /* So we reached a different state for this job. Let's see if we can run it now if it failed previously
2544 job_add_to_run_queue(j
);
2546 /* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
2547 * hence needs to invalidate jobs. */
2552 case JOB_VERIFY_ACTIVE
:
2554 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2555 job_finish_and_invalidate(j
, JOB_DONE
, true, false);
2556 else if (j
->state
== JOB_RUNNING
&& ns
!= UNIT_ACTIVATING
) {
2559 if (UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2560 if (ns
== UNIT_FAILED
)
2561 result
= JOB_FAILED
;
2562 else if (FLAGS_SET(flags
, UNIT_NOTIFY_SKIP_CONDITION
))
2563 result
= JOB_SKIPPED
;
2567 job_finish_and_invalidate(j
, result
, true, false);
2574 case JOB_RELOAD_OR_START
:
2575 case JOB_TRY_RELOAD
:
2577 if (j
->state
== JOB_RUNNING
) {
2578 if (ns
== UNIT_ACTIVE
)
2579 job_finish_and_invalidate(j
, (flags
& UNIT_NOTIFY_RELOAD_FAILURE
) ? JOB_FAILED
: JOB_DONE
, true, false);
2580 else if (!IN_SET(ns
, UNIT_ACTIVATING
, UNIT_RELOADING
)) {
2583 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2584 job_finish_and_invalidate(j
, ns
== UNIT_FAILED
? JOB_FAILED
: JOB_DONE
, true, false);
2592 case JOB_TRY_RESTART
:
2594 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2595 job_finish_and_invalidate(j
, JOB_DONE
, true, false);
2596 else if (j
->state
== JOB_RUNNING
&& ns
!= UNIT_DEACTIVATING
) {
2598 job_finish_and_invalidate(j
, JOB_FAILED
, true, false);
2604 assert_not_reached("Job type unknown");
2610 void unit_notify(Unit
*u
, UnitActiveState os
, UnitActiveState ns
, UnitNotifyFlags flags
) {
2615 assert(os
< _UNIT_ACTIVE_STATE_MAX
);
2616 assert(ns
< _UNIT_ACTIVE_STATE_MAX
);
2618 /* Note that this is called for all low-level state changes, even if they might map to the same high-level
2619 * UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
2620 * remounted this function will be called too! */
2624 /* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
2625 * the bus queue, so that any job change signal queued will force out the unit change signal first. */
2626 unit_add_to_dbus_queue(u
);
2628 /* Update systemd-oomd on the property/state change */
2630 /* Always send an update if the unit is going into an inactive state so systemd-oomd knows to stop
2632 * Also send an update whenever the unit goes active; this is to handle a case where an override file
2633 * sets one of the ManagedOOM*= properties to "kill", then later removes it. systemd-oomd needs to
2634 * know to stop monitoring when the unit changes from "kill" -> "auto" on daemon-reload, but we don't
2635 * have the information on the property. Thus, indiscriminately send an update. */
2636 if (UNIT_IS_INACTIVE_OR_FAILED(ns
) || UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2637 (void) manager_varlink_send_managed_oom_update(u
);
2640 /* Update timestamps for state changes */
2641 if (!MANAGER_IS_RELOADING(m
)) {
2642 dual_timestamp_get(&u
->state_change_timestamp
);
2644 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && !UNIT_IS_INACTIVE_OR_FAILED(ns
))
2645 u
->inactive_exit_timestamp
= u
->state_change_timestamp
;
2646 else if (!UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_INACTIVE_OR_FAILED(ns
))
2647 u
->inactive_enter_timestamp
= u
->state_change_timestamp
;
2649 if (!UNIT_IS_ACTIVE_OR_RELOADING(os
) && UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2650 u
->active_enter_timestamp
= u
->state_change_timestamp
;
2651 else if (UNIT_IS_ACTIVE_OR_RELOADING(os
) && !UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2652 u
->active_exit_timestamp
= u
->state_change_timestamp
;
2655 /* Keep track of failed units */
2656 (void) manager_update_failed_units(m
, u
, ns
== UNIT_FAILED
);
2658 /* Make sure the cgroup and state files are always removed when we become inactive */
2659 if (UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2660 unit_prune_cgroup(u
);
2661 unit_unlink_state_files(u
);
2664 unit_update_on_console(u
);
2666 if (!MANAGER_IS_RELOADING(m
)) {
2669 /* Let's propagate state changes to the job */
2671 unexpected
= unit_process_job(u
->job
, ns
, flags
);
2675 /* If this state change happened without being requested by a job, then let's retroactively start or
2676 * stop dependencies. We skip that step when deserializing, since we don't want to create any
2677 * additional jobs just because something is already activated. */
2680 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns
))
2681 retroactively_start_dependencies(u
);
2682 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os
) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns
))
2683 retroactively_stop_dependencies(u
);
2686 /* stop unneeded units regardless if going down was expected or not */
2687 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2688 check_unneeded_dependencies(u
);
2690 if (ns
!= os
&& ns
== UNIT_FAILED
) {
2691 log_unit_debug(u
, "Unit entered failed state.");
2693 if (!(flags
& UNIT_NOTIFY_WILL_AUTO_RESTART
))
2694 unit_start_on_failure(u
);
2697 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
) && !UNIT_IS_ACTIVE_OR_RELOADING(os
)) {
2698 /* This unit just finished starting up */
2700 unit_emit_audit_start(u
);
2701 manager_send_unit_plymouth(m
, u
);
2704 if (UNIT_IS_INACTIVE_OR_FAILED(ns
) && !UNIT_IS_INACTIVE_OR_FAILED(os
)) {
2705 /* This unit just stopped/failed. */
2707 unit_emit_audit_stop(u
, ns
);
2708 unit_log_resources(u
);
2712 manager_recheck_journal(m
);
2713 manager_recheck_dbus(m
);
2715 unit_trigger_notify(u
);
2717 if (!MANAGER_IS_RELOADING(m
)) {
2718 /* Maybe we finished startup and are now ready for being stopped because unneeded? */
2719 unit_submit_to_stop_when_unneeded_queue(u
);
2721 /* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens when
2722 * something BindsTo= to a Type=oneshot unit, as these units go directly from starting to inactive,
2723 * without ever entering started.) */
2724 unit_check_binds_to(u
);
2726 if (os
!= UNIT_FAILED
&& ns
== UNIT_FAILED
) {
2727 reason
= strjoina("unit ", u
->id
, " failed");
2728 emergency_action(m
, u
->failure_action
, 0, u
->reboot_arg
, unit_failure_action_exit_status(u
), reason
);
2729 } else if (!UNIT_IS_INACTIVE_OR_FAILED(os
) && ns
== UNIT_INACTIVE
) {
2730 reason
= strjoina("unit ", u
->id
, " succeeded");
2731 emergency_action(m
, u
->success_action
, 0, u
->reboot_arg
, unit_success_action_exit_status(u
), reason
);
2735 unit_add_to_gc_queue(u
);
2738 int unit_watch_pid(Unit
*u
, pid_t pid
, bool exclusive
) {
2742 assert(pid_is_valid(pid
));
2744 /* Watch a specific PID */
2746 /* Caller might be sure that this PID belongs to this unit only. Let's take this
2747 * opportunity to remove any stalled references to this PID as they can be created
2748 * easily (when watching a process which is not our direct child). */
2750 manager_unwatch_pid(u
->manager
, pid
);
2752 r
= set_ensure_allocated(&u
->pids
, NULL
);
2756 r
= hashmap_ensure_allocated(&u
->manager
->watch_pids
, NULL
);
2760 /* First try, let's add the unit keyed by "pid". */
2761 r
= hashmap_put(u
->manager
->watch_pids
, PID_TO_PTR(pid
), u
);
2767 /* OK, the "pid" key is already assigned to a different unit. Let's see if the "-pid" key (which points
2768 * to an array of Units rather than just a Unit), lists us already. */
2770 array
= hashmap_get(u
->manager
->watch_pids
, PID_TO_PTR(-pid
));
2772 for (; array
[n
]; n
++)
2776 if (found
) /* Found it already? if so, do nothing */
2781 /* Allocate a new array */
2782 new_array
= new(Unit
*, n
+ 2);
2786 memcpy_safe(new_array
, array
, sizeof(Unit
*) * n
);
2788 new_array
[n
+1] = NULL
;
2790 /* Add or replace the old array */
2791 r
= hashmap_replace(u
->manager
->watch_pids
, PID_TO_PTR(-pid
), new_array
);
2802 r
= set_put(u
->pids
, PID_TO_PTR(pid
));
2809 void unit_unwatch_pid(Unit
*u
, pid_t pid
) {
2813 assert(pid_is_valid(pid
));
2815 /* First let's drop the unit in case it's keyed as "pid". */
2816 (void) hashmap_remove_value(u
->manager
->watch_pids
, PID_TO_PTR(pid
), u
);
2818 /* Then, let's also drop the unit, in case it's in the array keyed by -pid */
2819 array
= hashmap_get(u
->manager
->watch_pids
, PID_TO_PTR(-pid
));
2821 /* Let's iterate through the array, dropping our own entry */
2824 for (size_t n
= 0; array
[n
]; n
++)
2826 array
[m
++] = array
[n
];
2830 /* The array is now empty, remove the entire entry */
2831 assert_se(hashmap_remove(u
->manager
->watch_pids
, PID_TO_PTR(-pid
)) == array
);
2836 (void) set_remove(u
->pids
, PID_TO_PTR(pid
));
2839 void unit_unwatch_all_pids(Unit
*u
) {
2842 while (!set_isempty(u
->pids
))
2843 unit_unwatch_pid(u
, PTR_TO_PID(set_first(u
->pids
)));
2845 u
->pids
= set_free(u
->pids
);
2848 static void unit_tidy_watch_pids(Unit
*u
) {
2849 pid_t except1
, except2
;
2854 /* Cleans dead PIDs from our list */
2856 except1
= unit_main_pid(u
);
2857 except2
= unit_control_pid(u
);
2859 SET_FOREACH(e
, u
->pids
) {
2860 pid_t pid
= PTR_TO_PID(e
);
2862 if (pid
== except1
|| pid
== except2
)
2865 if (!pid_is_unwaited(pid
))
2866 unit_unwatch_pid(u
, pid
);
2870 static int on_rewatch_pids_event(sd_event_source
*s
, void *userdata
) {
2876 unit_tidy_watch_pids(u
);
2877 unit_watch_all_pids(u
);
2879 /* If the PID set is empty now, then let's finish this off. */
2880 unit_synthesize_cgroup_empty_event(u
);
2885 int unit_enqueue_rewatch_pids(Unit
*u
) {
2890 if (!u
->cgroup_path
)
2893 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
2896 if (r
> 0) /* On unified we can use proper notifications */
2899 /* Enqueues a low-priority job that will clean up dead PIDs from our list of PIDs to watch and subscribe to new
2900 * PIDs that might have appeared. We do this in a delayed job because the work might be quite slow, as it
2901 * involves issuing kill(pid, 0) on all processes we watch. */
2903 if (!u
->rewatch_pids_event_source
) {
2904 _cleanup_(sd_event_source_unrefp
) sd_event_source
*s
= NULL
;
2906 r
= sd_event_add_defer(u
->manager
->event
, &s
, on_rewatch_pids_event
, u
);
2908 return log_error_errno(r
, "Failed to allocate event source for tidying watched PIDs: %m");
2910 r
= sd_event_source_set_priority(s
, SD_EVENT_PRIORITY_IDLE
);
2912 return log_error_errno(r
, "Failed to adjust priority of event source for tidying watched PIDs: %m");
2914 (void) sd_event_source_set_description(s
, "tidy-watch-pids");
2916 u
->rewatch_pids_event_source
= TAKE_PTR(s
);
2919 r
= sd_event_source_set_enabled(u
->rewatch_pids_event_source
, SD_EVENT_ONESHOT
);
2921 return log_error_errno(r
, "Failed to enable event source for tidying watched PIDs: %m");
2926 void unit_dequeue_rewatch_pids(Unit
*u
) {
2930 if (!u
->rewatch_pids_event_source
)
2933 r
= sd_event_source_set_enabled(u
->rewatch_pids_event_source
, SD_EVENT_OFF
);
2935 log_warning_errno(r
, "Failed to disable event source for tidying watched PIDs, ignoring: %m");
2937 u
->rewatch_pids_event_source
= sd_event_source_unref(u
->rewatch_pids_event_source
);
2940 bool unit_job_is_applicable(Unit
*u
, JobType j
) {
2942 assert(j
>= 0 && j
< _JOB_TYPE_MAX
);
2946 case JOB_VERIFY_ACTIVE
:
2949 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
2950 * startable by us but may appear due to external events, and it thus makes sense to permit enqueuing
2955 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
2956 * external events), hence it makes no sense to permit enqueuing such a request either. */
2957 return !u
->perpetual
;
2960 case JOB_TRY_RESTART
:
2961 return unit_can_stop(u
) && unit_can_start(u
);
2964 case JOB_TRY_RELOAD
:
2965 return unit_can_reload(u
);
2967 case JOB_RELOAD_OR_START
:
2968 return unit_can_reload(u
) && unit_can_start(u
);
2971 assert_not_reached("Invalid job type");
2975 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
) {
2978 /* Only warn about some unit types */
2979 if (!IN_SET(dependency
, UNIT_CONFLICTS
, UNIT_CONFLICTED_BY
, UNIT_BEFORE
, UNIT_AFTER
, UNIT_ON_FAILURE
, UNIT_TRIGGERS
, UNIT_TRIGGERED_BY
))
2982 if (streq_ptr(u
->id
, other
))
2983 log_unit_warning(u
, "Dependency %s=%s dropped", unit_dependency_to_string(dependency
), u
->id
);
2985 log_unit_warning(u
, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency
), strna(other
), u
->id
);
2988 static int unit_add_dependency_hashmap(
2991 UnitDependencyMask origin_mask
,
2992 UnitDependencyMask destination_mask
) {
2994 UnitDependencyInfo info
;
2999 assert(origin_mask
< _UNIT_DEPENDENCY_MASK_FULL
);
3000 assert(destination_mask
< _UNIT_DEPENDENCY_MASK_FULL
);
3001 assert(origin_mask
> 0 || destination_mask
> 0);
3003 r
= hashmap_ensure_allocated(h
, NULL
);
3007 assert_cc(sizeof(void*) == sizeof(info
));
3009 info
.data
= hashmap_get(*h
, other
);
3011 /* Entry already exists. Add in our mask. */
3013 if (FLAGS_SET(origin_mask
, info
.origin_mask
) &&
3014 FLAGS_SET(destination_mask
, info
.destination_mask
))
3017 info
.origin_mask
|= origin_mask
;
3018 info
.destination_mask
|= destination_mask
;
3020 r
= hashmap_update(*h
, other
, info
.data
);
3022 info
= (UnitDependencyInfo
) {
3023 .origin_mask
= origin_mask
,
3024 .destination_mask
= destination_mask
,
3027 r
= hashmap_put(*h
, other
, info
.data
);
3035 int unit_add_dependency(
3040 UnitDependencyMask mask
) {
3042 static const UnitDependency inverse_table
[_UNIT_DEPENDENCY_MAX
] = {
3043 [UNIT_REQUIRES
] = UNIT_REQUIRED_BY
,
3044 [UNIT_WANTS
] = UNIT_WANTED_BY
,
3045 [UNIT_REQUISITE
] = UNIT_REQUISITE_OF
,
3046 [UNIT_BINDS_TO
] = UNIT_BOUND_BY
,
3047 [UNIT_PART_OF
] = UNIT_CONSISTS_OF
,
3048 [UNIT_REQUIRED_BY
] = UNIT_REQUIRES
,
3049 [UNIT_REQUISITE_OF
] = UNIT_REQUISITE
,
3050 [UNIT_WANTED_BY
] = UNIT_WANTS
,
3051 [UNIT_BOUND_BY
] = UNIT_BINDS_TO
,
3052 [UNIT_CONSISTS_OF
] = UNIT_PART_OF
,
3053 [UNIT_CONFLICTS
] = UNIT_CONFLICTED_BY
,
3054 [UNIT_CONFLICTED_BY
] = UNIT_CONFLICTS
,
3055 [UNIT_BEFORE
] = UNIT_AFTER
,
3056 [UNIT_AFTER
] = UNIT_BEFORE
,
3057 [UNIT_ON_FAILURE
] = _UNIT_DEPENDENCY_INVALID
,
3058 [UNIT_REFERENCES
] = UNIT_REFERENCED_BY
,
3059 [UNIT_REFERENCED_BY
] = UNIT_REFERENCES
,
3060 [UNIT_TRIGGERS
] = UNIT_TRIGGERED_BY
,
3061 [UNIT_TRIGGERED_BY
] = UNIT_TRIGGERS
,
3062 [UNIT_PROPAGATES_RELOAD_TO
] = UNIT_RELOAD_PROPAGATED_FROM
,
3063 [UNIT_RELOAD_PROPAGATED_FROM
] = UNIT_PROPAGATES_RELOAD_TO
,
3064 [UNIT_JOINS_NAMESPACE_OF
] = UNIT_JOINS_NAMESPACE_OF
,
3066 Unit
*original_u
= u
, *original_other
= other
;
3068 /* Helper to know whether sending a notification is necessary or not:
3069 * if the dependency is already there, no need to notify! */
3073 assert(d
>= 0 && d
< _UNIT_DEPENDENCY_MAX
);
3076 u
= unit_follow_merge(u
);
3077 other
= unit_follow_merge(other
);
3079 /* We won't allow dependencies on ourselves. We will not
3080 * consider them an error however. */
3082 maybe_warn_about_dependency(original_u
, original_other
->id
, d
);
3086 /* Note that ordering a device unit after a unit is permitted since it
3087 * allows to start its job running timeout at a specific time. */
3088 if (d
== UNIT_BEFORE
&& other
->type
== UNIT_DEVICE
) {
3089 log_unit_warning(u
, "Dependency Before=%s ignored (.device units cannot be delayed)", other
->id
);
3093 if (d
== UNIT_ON_FAILURE
&& !UNIT_VTABLE(u
)->can_fail
) {
3094 log_unit_warning(u
, "Requested dependency OnFailure=%s ignored (%s units cannot fail).", other
->id
, unit_type_to_string(u
->type
));
3098 if (d
== UNIT_TRIGGERS
&& !UNIT_VTABLE(u
)->can_trigger
)
3099 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
3100 "Requested dependency Triggers=%s refused (%s units cannot trigger other units).", other
->id
, unit_type_to_string(u
->type
));
3101 if (d
== UNIT_TRIGGERED_BY
&& !UNIT_VTABLE(other
)->can_trigger
)
3102 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EINVAL
),
3103 "Requested dependency TriggeredBy=%s refused (%s units cannot trigger other units).", other
->id
, unit_type_to_string(other
->type
));
3105 r
= unit_add_dependency_hashmap(u
->dependencies
+ d
, other
, mask
, 0);
3111 if (inverse_table
[d
] != _UNIT_DEPENDENCY_INVALID
&& inverse_table
[d
] != d
) {
3112 r
= unit_add_dependency_hashmap(other
->dependencies
+ inverse_table
[d
], u
, 0, mask
);
3119 if (add_reference
) {
3120 r
= unit_add_dependency_hashmap(u
->dependencies
+ UNIT_REFERENCES
, other
, mask
, 0);
3126 r
= unit_add_dependency_hashmap(other
->dependencies
+ UNIT_REFERENCED_BY
, u
, 0, mask
);
3134 unit_add_to_dbus_queue(u
);
3138 int unit_add_two_dependencies(Unit
*u
, UnitDependency d
, UnitDependency e
, Unit
*other
, bool add_reference
, UnitDependencyMask mask
) {
3143 r
= unit_add_dependency(u
, d
, other
, add_reference
, mask
);
3147 return unit_add_dependency(u
, e
, other
, add_reference
, mask
);
3150 static int resolve_template(Unit
*u
, const char *name
, char **buf
, const char **ret
) {
3158 if (!unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
3165 r
= unit_name_replace_instance(name
, u
->instance
, buf
);
3167 _cleanup_free_
char *i
= NULL
;
3169 r
= unit_name_to_prefix(u
->id
, &i
);
3173 r
= unit_name_replace_instance(name
, i
, buf
);
3182 int unit_add_dependency_by_name(Unit
*u
, UnitDependency d
, const char *name
, bool add_reference
, UnitDependencyMask mask
) {
3183 _cleanup_free_
char *buf
= NULL
;
3190 r
= resolve_template(u
, name
, &buf
, &name
);
3194 r
= manager_load_unit(u
->manager
, name
, NULL
, NULL
, &other
);
3198 return unit_add_dependency(u
, d
, other
, add_reference
, mask
);
3201 int unit_add_two_dependencies_by_name(Unit
*u
, UnitDependency d
, UnitDependency e
, const char *name
, bool add_reference
, UnitDependencyMask mask
) {
3202 _cleanup_free_
char *buf
= NULL
;
3209 r
= resolve_template(u
, name
, &buf
, &name
);
3213 r
= manager_load_unit(u
->manager
, name
, NULL
, NULL
, &other
);
3217 return unit_add_two_dependencies(u
, d
, e
, other
, add_reference
, mask
);
3220 int set_unit_path(const char *p
) {
3221 /* This is mostly for debug purposes */
3222 if (setenv("SYSTEMD_UNIT_PATH", p
, 1) < 0)
3228 char *unit_dbus_path(Unit
*u
) {
3234 return unit_dbus_path_from_name(u
->id
);
3237 char *unit_dbus_path_invocation_id(Unit
*u
) {
3240 if (sd_id128_is_null(u
->invocation_id
))
3243 return unit_dbus_path_from_name(u
->invocation_id_string
);
3246 static int unit_set_invocation_id(Unit
*u
, sd_id128_t id
) {
3251 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
3253 if (sd_id128_equal(u
->invocation_id
, id
))
3256 if (!sd_id128_is_null(u
->invocation_id
))
3257 (void) hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
3259 if (sd_id128_is_null(id
)) {
3264 r
= hashmap_ensure_allocated(&u
->manager
->units_by_invocation_id
, &id128_hash_ops
);
3268 u
->invocation_id
= id
;
3269 sd_id128_to_string(id
, u
->invocation_id_string
);
3271 r
= hashmap_put(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
3278 u
->invocation_id
= SD_ID128_NULL
;
3279 u
->invocation_id_string
[0] = 0;
3283 int unit_set_slice(Unit
*u
, Unit
*slice
) {
3287 /* Sets the unit slice if it has not been set before. Is extra
3288 * careful, to only allow this for units that actually have a
3289 * cgroup context. Also, we don't allow to set this for slices
3290 * (since the parent slice is derived from the name). Make
3291 * sure the unit we set is actually a slice. */
3293 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
3296 if (u
->type
== UNIT_SLICE
)
3299 if (unit_active_state(u
) != UNIT_INACTIVE
)
3302 if (slice
->type
!= UNIT_SLICE
)
3305 if (unit_has_name(u
, SPECIAL_INIT_SCOPE
) &&
3306 !unit_has_name(slice
, SPECIAL_ROOT_SLICE
))
3309 if (UNIT_DEREF(u
->slice
) == slice
)
3312 /* Disallow slice changes if @u is already bound to cgroups */
3313 if (UNIT_ISSET(u
->slice
) && u
->cgroup_realized
)
3316 unit_ref_set(&u
->slice
, u
, slice
);
3320 int unit_set_default_slice(Unit
*u
) {
3321 const char *slice_name
;
3327 if (UNIT_ISSET(u
->slice
))
3331 _cleanup_free_
char *prefix
= NULL
, *escaped
= NULL
;
3333 /* Implicitly place all instantiated units in their
3334 * own per-template slice */
3336 r
= unit_name_to_prefix(u
->id
, &prefix
);
3340 /* The prefix is already escaped, but it might include
3341 * "-" which has a special meaning for slice units,
3342 * hence escape it here extra. */
3343 escaped
= unit_name_escape(prefix
);
3347 if (MANAGER_IS_SYSTEM(u
->manager
))
3348 slice_name
= strjoina("system-", escaped
, ".slice");
3350 slice_name
= strjoina("app-", escaped
, ".slice");
3352 } else if (unit_is_extrinsic(u
))
3353 /* Keep all extrinsic units (e.g. perpetual units and swap and mount units in user mode) in
3354 * the root slice. They don't really belong in one of the subslices. */
3355 slice_name
= SPECIAL_ROOT_SLICE
;
3357 else if (MANAGER_IS_SYSTEM(u
->manager
))
3358 slice_name
= SPECIAL_SYSTEM_SLICE
;
3360 slice_name
= SPECIAL_APP_SLICE
;
3362 r
= manager_load_unit(u
->manager
, slice_name
, NULL
, NULL
, &slice
);
3366 return unit_set_slice(u
, slice
);
3369 const char *unit_slice_name(Unit
*u
) {
3372 if (!UNIT_ISSET(u
->slice
))
3375 return UNIT_DEREF(u
->slice
)->id
;
3378 int unit_load_related_unit(Unit
*u
, const char *type
, Unit
**_found
) {
3379 _cleanup_free_
char *t
= NULL
;
3386 r
= unit_name_change_suffix(u
->id
, type
, &t
);
3389 if (unit_has_name(u
, t
))
3392 r
= manager_load_unit(u
->manager
, t
, NULL
, NULL
, _found
);
3393 assert(r
< 0 || *_found
!= u
);
3397 static int signal_name_owner_changed(sd_bus_message
*message
, void *userdata
, sd_bus_error
*error
) {
3398 const char *new_owner
;
3405 r
= sd_bus_message_read(message
, "sss", NULL
, NULL
, &new_owner
);
3407 bus_log_parse_error(r
);
3411 if (UNIT_VTABLE(u
)->bus_name_owner_change
)
3412 UNIT_VTABLE(u
)->bus_name_owner_change(u
, empty_to_null(new_owner
));
3417 static int get_name_owner_handler(sd_bus_message
*message
, void *userdata
, sd_bus_error
*error
) {
3418 const sd_bus_error
*e
;
3419 const char *new_owner
;
3426 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3428 e
= sd_bus_message_get_error(message
);
3430 if (!sd_bus_error_has_name(e
, "org.freedesktop.DBus.Error.NameHasNoOwner"))
3431 log_unit_error(u
, "Unexpected error response from GetNameOwner(): %s", e
->message
);
3435 r
= sd_bus_message_read(message
, "s", &new_owner
);
3437 return bus_log_parse_error(r
);
3439 assert(!isempty(new_owner
));
3442 if (UNIT_VTABLE(u
)->bus_name_owner_change
)
3443 UNIT_VTABLE(u
)->bus_name_owner_change(u
, new_owner
);
3448 int unit_install_bus_match(Unit
*u
, sd_bus
*bus
, const char *name
) {
3456 if (u
->match_bus_slot
|| u
->get_name_owner_slot
)
3459 match
= strjoina("type='signal',"
3460 "sender='org.freedesktop.DBus',"
3461 "path='/org/freedesktop/DBus',"
3462 "interface='org.freedesktop.DBus',"
3463 "member='NameOwnerChanged',"
3464 "arg0='", name
, "'");
3466 r
= sd_bus_add_match_async(bus
, &u
->match_bus_slot
, match
, signal_name_owner_changed
, NULL
, u
);
3470 r
= sd_bus_call_method_async(
3472 &u
->get_name_owner_slot
,
3473 "org.freedesktop.DBus",
3474 "/org/freedesktop/DBus",
3475 "org.freedesktop.DBus",
3477 get_name_owner_handler
,
3481 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3485 log_unit_debug(u
, "Watching D-Bus name '%s'.", name
);
3489 int unit_watch_bus_name(Unit
*u
, const char *name
) {
3495 /* Watch a specific name on the bus. We only support one unit
3496 * watching each name for now. */
3498 if (u
->manager
->api_bus
) {
3499 /* If the bus is already available, install the match directly.
3500 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
3501 r
= unit_install_bus_match(u
, u
->manager
->api_bus
, name
);
3503 return log_warning_errno(r
, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name
);
3506 r
= hashmap_put(u
->manager
->watch_bus
, name
, u
);
3508 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3509 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3510 return log_warning_errno(r
, "Failed to put bus name to hashmap: %m");
3516 void unit_unwatch_bus_name(Unit
*u
, const char *name
) {
3520 (void) hashmap_remove_value(u
->manager
->watch_bus
, name
, u
);
3521 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
3522 u
->get_name_owner_slot
= sd_bus_slot_unref(u
->get_name_owner_slot
);
3525 bool unit_can_serialize(Unit
*u
) {
3528 return UNIT_VTABLE(u
)->serialize
&& UNIT_VTABLE(u
)->deserialize_item
;
3531 static int serialize_cgroup_mask(FILE *f
, const char *key
, CGroupMask mask
) {
3532 _cleanup_free_
char *s
= NULL
;
3541 r
= cg_mask_to_string(mask
, &s
);
3543 return log_error_errno(r
, "Failed to format cgroup mask: %m");
3545 return serialize_item(f
, key
, s
);
3548 static const char *const ip_accounting_metric_field
[_CGROUP_IP_ACCOUNTING_METRIC_MAX
] = {
3549 [CGROUP_IP_INGRESS_BYTES
] = "ip-accounting-ingress-bytes",
3550 [CGROUP_IP_INGRESS_PACKETS
] = "ip-accounting-ingress-packets",
3551 [CGROUP_IP_EGRESS_BYTES
] = "ip-accounting-egress-bytes",
3552 [CGROUP_IP_EGRESS_PACKETS
] = "ip-accounting-egress-packets",
3555 static const char *const io_accounting_metric_field_base
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
3556 [CGROUP_IO_READ_BYTES
] = "io-accounting-read-bytes-base",
3557 [CGROUP_IO_WRITE_BYTES
] = "io-accounting-write-bytes-base",
3558 [CGROUP_IO_READ_OPERATIONS
] = "io-accounting-read-operations-base",
3559 [CGROUP_IO_WRITE_OPERATIONS
] = "io-accounting-write-operations-base",
3562 static const char *const io_accounting_metric_field_last
[_CGROUP_IO_ACCOUNTING_METRIC_MAX
] = {
3563 [CGROUP_IO_READ_BYTES
] = "io-accounting-read-bytes-last",
3564 [CGROUP_IO_WRITE_BYTES
] = "io-accounting-write-bytes-last",
3565 [CGROUP_IO_READ_OPERATIONS
] = "io-accounting-read-operations-last",
3566 [CGROUP_IO_WRITE_OPERATIONS
] = "io-accounting-write-operations-last",
3569 int unit_serialize(Unit
*u
, FILE *f
, FDSet
*fds
, bool serialize_jobs
) {
3576 if (unit_can_serialize(u
)) {
3577 r
= UNIT_VTABLE(u
)->serialize(u
, f
, fds
);
3582 (void) serialize_dual_timestamp(f
, "state-change-timestamp", &u
->state_change_timestamp
);
3584 (void) serialize_dual_timestamp(f
, "inactive-exit-timestamp", &u
->inactive_exit_timestamp
);
3585 (void) serialize_dual_timestamp(f
, "active-enter-timestamp", &u
->active_enter_timestamp
);
3586 (void) serialize_dual_timestamp(f
, "active-exit-timestamp", &u
->active_exit_timestamp
);
3587 (void) serialize_dual_timestamp(f
, "inactive-enter-timestamp", &u
->inactive_enter_timestamp
);
3589 (void) serialize_dual_timestamp(f
, "condition-timestamp", &u
->condition_timestamp
);
3590 (void) serialize_dual_timestamp(f
, "assert-timestamp", &u
->assert_timestamp
);
3592 if (dual_timestamp_is_set(&u
->condition_timestamp
))
3593 (void) serialize_bool(f
, "condition-result", u
->condition_result
);
3595 if (dual_timestamp_is_set(&u
->assert_timestamp
))
3596 (void) serialize_bool(f
, "assert-result", u
->assert_result
);
3598 (void) serialize_bool(f
, "transient", u
->transient
);
3599 (void) serialize_bool(f
, "in-audit", u
->in_audit
);
3601 (void) serialize_bool(f
, "exported-invocation-id", u
->exported_invocation_id
);
3602 (void) serialize_bool(f
, "exported-log-level-max", u
->exported_log_level_max
);
3603 (void) serialize_bool(f
, "exported-log-extra-fields", u
->exported_log_extra_fields
);
3604 (void) serialize_bool(f
, "exported-log-rate-limit-interval", u
->exported_log_ratelimit_interval
);
3605 (void) serialize_bool(f
, "exported-log-rate-limit-burst", u
->exported_log_ratelimit_burst
);
3607 (void) serialize_item_format(f
, "cpu-usage-base", "%" PRIu64
, u
->cpu_usage_base
);
3608 if (u
->cpu_usage_last
!= NSEC_INFINITY
)
3609 (void) serialize_item_format(f
, "cpu-usage-last", "%" PRIu64
, u
->cpu_usage_last
);
3611 if (u
->managed_oom_kill_last
> 0)
3612 (void) serialize_item_format(f
, "managed-oom-kill-last", "%" PRIu64
, u
->managed_oom_kill_last
);
3614 if (u
->oom_kill_last
> 0)
3615 (void) serialize_item_format(f
, "oom-kill-last", "%" PRIu64
, u
->oom_kill_last
);
3617 for (CGroupIOAccountingMetric im
= 0; im
< _CGROUP_IO_ACCOUNTING_METRIC_MAX
; im
++) {
3618 (void) serialize_item_format(f
, io_accounting_metric_field_base
[im
], "%" PRIu64
, u
->io_accounting_base
[im
]);
3620 if (u
->io_accounting_last
[im
] != UINT64_MAX
)
3621 (void) serialize_item_format(f
, io_accounting_metric_field_last
[im
], "%" PRIu64
, u
->io_accounting_last
[im
]);
3625 (void) serialize_item(f
, "cgroup", u
->cgroup_path
);
3627 (void) serialize_bool(f
, "cgroup-realized", u
->cgroup_realized
);
3628 (void) serialize_cgroup_mask(f
, "cgroup-realized-mask", u
->cgroup_realized_mask
);
3629 (void) serialize_cgroup_mask(f
, "cgroup-enabled-mask", u
->cgroup_enabled_mask
);
3630 (void) serialize_cgroup_mask(f
, "cgroup-invalidated-mask", u
->cgroup_invalidated_mask
);
3632 if (uid_is_valid(u
->ref_uid
))
3633 (void) serialize_item_format(f
, "ref-uid", UID_FMT
, u
->ref_uid
);
3634 if (gid_is_valid(u
->ref_gid
))
3635 (void) serialize_item_format(f
, "ref-gid", GID_FMT
, u
->ref_gid
);
3637 if (!sd_id128_is_null(u
->invocation_id
))
3638 (void) serialize_item_format(f
, "invocation-id", SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(u
->invocation_id
));
3640 (void) serialize_item_format(f
, "freezer-state", "%s", freezer_state_to_string(unit_freezer_state(u
)));
3642 bus_track_serialize(u
->bus_track
, f
, "ref");
3644 for (CGroupIPAccountingMetric m
= 0; m
< _CGROUP_IP_ACCOUNTING_METRIC_MAX
; m
++) {
3647 r
= unit_get_ip_accounting(u
, m
, &v
);
3649 (void) serialize_item_format(f
, ip_accounting_metric_field
[m
], "%" PRIu64
, v
);
3652 if (serialize_jobs
) {
3655 job_serialize(u
->job
, f
);
3660 job_serialize(u
->nop_job
, f
);
3669 static int unit_deserialize_job(Unit
*u
, FILE *f
) {
3670 _cleanup_(job_freep
) Job
*j
= NULL
;
3680 r
= job_deserialize(j
, f
);
3684 r
= job_install_deserialized(j
);
3692 int unit_deserialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
3700 _cleanup_free_
char *line
= NULL
;
3705 r
= read_line(f
, LONG_LINE_MAX
, &line
);
3707 return log_error_errno(r
, "Failed to read serialization line: %m");
3708 if (r
== 0) /* eof */
3712 if (isempty(l
)) /* End marker */
3715 k
= strcspn(l
, "=");
3723 if (streq(l
, "job")) {
3725 /* New-style serialized job */
3726 r
= unit_deserialize_job(u
, f
);
3729 } else /* Legacy for pre-44 */
3730 log_unit_warning(u
, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v
);
3732 } else if (streq(l
, "state-change-timestamp")) {
3733 (void) deserialize_dual_timestamp(v
, &u
->state_change_timestamp
);
3735 } else if (streq(l
, "inactive-exit-timestamp")) {
3736 (void) deserialize_dual_timestamp(v
, &u
->inactive_exit_timestamp
);
3738 } else if (streq(l
, "active-enter-timestamp")) {
3739 (void) deserialize_dual_timestamp(v
, &u
->active_enter_timestamp
);
3741 } else if (streq(l
, "active-exit-timestamp")) {
3742 (void) deserialize_dual_timestamp(v
, &u
->active_exit_timestamp
);
3744 } else if (streq(l
, "inactive-enter-timestamp")) {
3745 (void) deserialize_dual_timestamp(v
, &u
->inactive_enter_timestamp
);
3747 } else if (streq(l
, "condition-timestamp")) {
3748 (void) deserialize_dual_timestamp(v
, &u
->condition_timestamp
);
3750 } else if (streq(l
, "assert-timestamp")) {
3751 (void) deserialize_dual_timestamp(v
, &u
->assert_timestamp
);
3753 } else if (streq(l
, "condition-result")) {
3755 r
= parse_boolean(v
);
3757 log_unit_debug(u
, "Failed to parse condition result value %s, ignoring.", v
);
3759 u
->condition_result
= r
;
3763 } else if (streq(l
, "assert-result")) {
3765 r
= parse_boolean(v
);
3767 log_unit_debug(u
, "Failed to parse assert result value %s, ignoring.", v
);
3769 u
->assert_result
= r
;
3773 } else if (streq(l
, "transient")) {
3775 r
= parse_boolean(v
);
3777 log_unit_debug(u
, "Failed to parse transient bool %s, ignoring.", v
);
3783 } else if (streq(l
, "in-audit")) {
3785 r
= parse_boolean(v
);
3787 log_unit_debug(u
, "Failed to parse in-audit bool %s, ignoring.", v
);
3793 } else if (streq(l
, "exported-invocation-id")) {
3795 r
= parse_boolean(v
);
3797 log_unit_debug(u
, "Failed to parse exported invocation ID bool %s, ignoring.", v
);
3799 u
->exported_invocation_id
= r
;
3803 } else if (streq(l
, "exported-log-level-max")) {
3805 r
= parse_boolean(v
);
3807 log_unit_debug(u
, "Failed to parse exported log level max bool %s, ignoring.", v
);
3809 u
->exported_log_level_max
= r
;
3813 } else if (streq(l
, "exported-log-extra-fields")) {
3815 r
= parse_boolean(v
);
3817 log_unit_debug(u
, "Failed to parse exported log extra fields bool %s, ignoring.", v
);
3819 u
->exported_log_extra_fields
= r
;
3823 } else if (streq(l
, "exported-log-rate-limit-interval")) {
3825 r
= parse_boolean(v
);
3827 log_unit_debug(u
, "Failed to parse exported log rate limit interval %s, ignoring.", v
);
3829 u
->exported_log_ratelimit_interval
= r
;
3833 } else if (streq(l
, "exported-log-rate-limit-burst")) {
3835 r
= parse_boolean(v
);
3837 log_unit_debug(u
, "Failed to parse exported log rate limit burst %s, ignoring.", v
);
3839 u
->exported_log_ratelimit_burst
= r
;
3843 } else if (STR_IN_SET(l
, "cpu-usage-base", "cpuacct-usage-base")) {
3845 r
= safe_atou64(v
, &u
->cpu_usage_base
);
3847 log_unit_debug(u
, "Failed to parse CPU usage base %s, ignoring.", v
);
3851 } else if (streq(l
, "cpu-usage-last")) {
3853 r
= safe_atou64(v
, &u
->cpu_usage_last
);
3855 log_unit_debug(u
, "Failed to read CPU usage last %s, ignoring.", v
);
3859 } else if (streq(l
, "managed-oom-kill-last")) {
3861 r
= safe_atou64(v
, &u
->managed_oom_kill_last
);
3863 log_unit_debug(u
, "Failed to read managed OOM kill last %s, ignoring.", v
);
3867 } else if (streq(l
, "oom-kill-last")) {
3869 r
= safe_atou64(v
, &u
->oom_kill_last
);
3871 log_unit_debug(u
, "Failed to read OOM kill last %s, ignoring.", v
);
3875 } else if (streq(l
, "cgroup")) {
3877 r
= unit_set_cgroup_path(u
, v
);
3879 log_unit_debug_errno(u
, r
, "Failed to set cgroup path %s, ignoring: %m", v
);
3881 (void) unit_watch_cgroup(u
);
3882 (void) unit_watch_cgroup_memory(u
);
3885 } else if (streq(l
, "cgroup-realized")) {
3888 b
= parse_boolean(v
);
3890 log_unit_debug(u
, "Failed to parse cgroup-realized bool %s, ignoring.", v
);
3892 u
->cgroup_realized
= b
;
3896 } else if (streq(l
, "cgroup-realized-mask")) {
3898 r
= cg_mask_from_string(v
, &u
->cgroup_realized_mask
);
3900 log_unit_debug(u
, "Failed to parse cgroup-realized-mask %s, ignoring.", v
);
3903 } else if (streq(l
, "cgroup-enabled-mask")) {
3905 r
= cg_mask_from_string(v
, &u
->cgroup_enabled_mask
);
3907 log_unit_debug(u
, "Failed to parse cgroup-enabled-mask %s, ignoring.", v
);
3910 } else if (streq(l
, "cgroup-invalidated-mask")) {
3912 r
= cg_mask_from_string(v
, &u
->cgroup_invalidated_mask
);
3914 log_unit_debug(u
, "Failed to parse cgroup-invalidated-mask %s, ignoring.", v
);
3917 } else if (streq(l
, "ref-uid")) {
3920 r
= parse_uid(v
, &uid
);
3922 log_unit_debug(u
, "Failed to parse referenced UID %s, ignoring.", v
);
3924 unit_ref_uid_gid(u
, uid
, GID_INVALID
);
3928 } else if (streq(l
, "ref-gid")) {
3931 r
= parse_gid(v
, &gid
);
3933 log_unit_debug(u
, "Failed to parse referenced GID %s, ignoring.", v
);
3935 unit_ref_uid_gid(u
, UID_INVALID
, gid
);
3939 } else if (streq(l
, "ref")) {
3941 r
= strv_extend(&u
->deserialized_refs
, v
);
3946 } else if (streq(l
, "invocation-id")) {
3949 r
= sd_id128_from_string(v
, &id
);
3951 log_unit_debug(u
, "Failed to parse invocation id %s, ignoring.", v
);
3953 r
= unit_set_invocation_id(u
, id
);
3955 log_unit_warning_errno(u
, r
, "Failed to set invocation ID for unit: %m");
3959 } else if (streq(l
, "freezer-state")) {
3962 s
= freezer_state_from_string(v
);
3964 log_unit_debug(u
, "Failed to deserialize freezer-state '%s', ignoring.", v
);
3966 u
->freezer_state
= s
;
3971 /* Check if this is an IP accounting metric serialization field */
3972 m
= string_table_lookup(ip_accounting_metric_field
, ELEMENTSOF(ip_accounting_metric_field
), l
);
3976 r
= safe_atou64(v
, &c
);
3978 log_unit_debug(u
, "Failed to parse IP accounting value %s, ignoring.", v
);
3980 u
->ip_accounting_extra
[m
] = c
;
3984 m
= string_table_lookup(io_accounting_metric_field_base
, ELEMENTSOF(io_accounting_metric_field_base
), l
);
3988 r
= safe_atou64(v
, &c
);
3990 log_unit_debug(u
, "Failed to parse IO accounting base value %s, ignoring.", v
);
3992 u
->io_accounting_base
[m
] = c
;
3996 m
= string_table_lookup(io_accounting_metric_field_last
, ELEMENTSOF(io_accounting_metric_field_last
), l
);
4000 r
= safe_atou64(v
, &c
);
4002 log_unit_debug(u
, "Failed to parse IO accounting last value %s, ignoring.", v
);
4004 u
->io_accounting_last
[m
] = c
;
4008 if (unit_can_serialize(u
)) {
4009 r
= exec_runtime_deserialize_compat(u
, l
, v
, fds
);
4011 log_unit_warning(u
, "Failed to deserialize runtime parameter '%s', ignoring.", l
);
4015 /* Returns positive if key was handled by the call */
4019 r
= UNIT_VTABLE(u
)->deserialize_item(u
, l
, v
, fds
);
4021 log_unit_warning(u
, "Failed to deserialize unit parameter '%s', ignoring.", l
);
4025 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
4026 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
4027 * before 228 where the base for timeouts was not persistent across reboots. */
4029 if (!dual_timestamp_is_set(&u
->state_change_timestamp
))
4030 dual_timestamp_get(&u
->state_change_timestamp
);
4032 /* Let's make sure that everything that is deserialized also gets any potential new cgroup settings applied
4033 * after we are done. For that we invalidate anything already realized, so that we can realize it again. */
4034 unit_invalidate_cgroup(u
, _CGROUP_MASK_ALL
);
4035 unit_invalidate_cgroup_bpf(u
);
4040 int unit_deserialize_skip(FILE *f
) {
4044 /* Skip serialized data for this unit. We don't know what it is. */
4047 _cleanup_free_
char *line
= NULL
;
4050 r
= read_line(f
, LONG_LINE_MAX
, &line
);
4052 return log_error_errno(r
, "Failed to read serialization line: %m");
4064 int unit_add_node_dependency(Unit
*u
, const char *what
, UnitDependency dep
, UnitDependencyMask mask
) {
4065 _cleanup_free_
char *e
= NULL
;
4071 /* Adds in links to the device node that this unit is based on */
4075 if (!is_device_path(what
))
4078 /* When device units aren't supported (such as in a container), don't create dependencies on them. */
4079 if (!unit_type_supported(UNIT_DEVICE
))
4082 r
= unit_name_from_path(what
, ".device", &e
);
4086 r
= manager_load_unit(u
->manager
, e
, NULL
, NULL
, &device
);
4090 if (dep
== UNIT_REQUIRES
&& device_shall_be_bound_by(device
, u
))
4091 dep
= UNIT_BINDS_TO
;
4093 return unit_add_two_dependencies(u
, UNIT_AFTER
,
4094 MANAGER_IS_SYSTEM(u
->manager
) ? dep
: UNIT_WANTS
,
4095 device
, true, mask
);
4098 int unit_add_blockdev_dependency(Unit
*u
, const char *what
, UnitDependencyMask mask
) {
4099 _cleanup_free_
char *escaped
= NULL
, *target
= NULL
;
4107 if (!path_startswith(what
, "/dev/"))
4110 /* If we don't support devices, then also don't bother with blockdev@.target */
4111 if (!unit_type_supported(UNIT_DEVICE
))
4114 r
= unit_name_path_escape(what
, &escaped
);
4118 r
= unit_name_build("blockdev", escaped
, ".target", &target
);
4122 return unit_add_dependency_by_name(u
, UNIT_AFTER
, target
, true, mask
);
4125 int unit_coldplug(Unit
*u
) {
4132 /* Make sure we don't enter a loop, when coldplugging recursively. */
4136 u
->coldplugged
= true;
4138 STRV_FOREACH(i
, u
->deserialized_refs
) {
4139 q
= bus_unit_track_add_name(u
, *i
);
4140 if (q
< 0 && r
>= 0)
4143 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
4145 if (UNIT_VTABLE(u
)->coldplug
) {
4146 q
= UNIT_VTABLE(u
)->coldplug(u
);
4147 if (q
< 0 && r
>= 0)
4151 uj
= u
->job
?: u
->nop_job
;
4153 q
= job_coldplug(uj
);
4154 if (q
< 0 && r
>= 0)
4161 void unit_catchup(Unit
*u
) {
4164 if (UNIT_VTABLE(u
)->catchup
)
4165 UNIT_VTABLE(u
)->catchup(u
);
4168 static bool fragment_mtime_newer(const char *path
, usec_t mtime
, bool path_masked
) {
4174 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
4175 * are never out-of-date. */
4176 if (PATH_STARTSWITH_SET(path
, "/proc", "/sys"))
4179 if (stat(path
, &st
) < 0)
4180 /* What, cannot access this anymore? */
4184 /* For masked files check if they are still so */
4185 return !null_or_empty(&st
);
4187 /* For non-empty files check the mtime */
4188 return timespec_load(&st
.st_mtim
) > mtime
;
4193 bool unit_need_daemon_reload(Unit
*u
) {
4194 _cleanup_strv_free_
char **t
= NULL
;
4199 /* For unit files, we allow masking… */
4200 if (fragment_mtime_newer(u
->fragment_path
, u
->fragment_mtime
,
4201 u
->load_state
== UNIT_MASKED
))
4204 /* Source paths should not be masked… */
4205 if (fragment_mtime_newer(u
->source_path
, u
->source_mtime
, false))
4208 if (u
->load_state
== UNIT_LOADED
)
4209 (void) unit_find_dropin_paths(u
, &t
);
4210 if (!strv_equal(u
->dropin_paths
, t
))
4213 /* … any drop-ins that are masked are simply omitted from the list. */
4214 STRV_FOREACH(path
, u
->dropin_paths
)
4215 if (fragment_mtime_newer(*path
, u
->dropin_mtime
, false))
4221 void unit_reset_failed(Unit
*u
) {
4224 if (UNIT_VTABLE(u
)->reset_failed
)
4225 UNIT_VTABLE(u
)->reset_failed(u
);
4227 ratelimit_reset(&u
->start_ratelimit
);
4228 u
->start_limit_hit
= false;
4231 Unit
*unit_following(Unit
*u
) {
4234 if (UNIT_VTABLE(u
)->following
)
4235 return UNIT_VTABLE(u
)->following(u
);
4240 bool unit_stop_pending(Unit
*u
) {
4243 /* This call does check the current state of the unit. It's
4244 * hence useful to be called from state change calls of the
4245 * unit itself, where the state isn't updated yet. This is
4246 * different from unit_inactive_or_pending() which checks both
4247 * the current state and for a queued job. */
4249 return unit_has_job_type(u
, JOB_STOP
);
4252 bool unit_inactive_or_pending(Unit
*u
) {
4255 /* Returns true if the unit is inactive or going down */
4257 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)))
4260 if (unit_stop_pending(u
))
4266 bool unit_active_or_pending(Unit
*u
) {
4269 /* Returns true if the unit is active or going up */
4271 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)))
4275 IN_SET(u
->job
->type
, JOB_START
, JOB_RELOAD_OR_START
, JOB_RESTART
))
4281 bool unit_will_restart_default(Unit
*u
) {
4284 return unit_has_job_type(u
, JOB_START
);
4287 bool unit_will_restart(Unit
*u
) {
4290 if (!UNIT_VTABLE(u
)->will_restart
)
4293 return UNIT_VTABLE(u
)->will_restart(u
);
4296 int unit_kill(Unit
*u
, KillWho w
, int signo
, sd_bus_error
*error
) {
4298 assert(w
>= 0 && w
< _KILL_WHO_MAX
);
4299 assert(SIGNAL_VALID(signo
));
4301 if (!UNIT_VTABLE(u
)->kill
)
4304 return UNIT_VTABLE(u
)->kill(u
, w
, signo
, error
);
4307 static Set
*unit_pid_set(pid_t main_pid
, pid_t control_pid
) {
4308 _cleanup_set_free_ Set
*pid_set
= NULL
;
4311 pid_set
= set_new(NULL
);
4315 /* Exclude the main/control pids from being killed via the cgroup */
4317 r
= set_put(pid_set
, PID_TO_PTR(main_pid
));
4322 if (control_pid
> 0) {
4323 r
= set_put(pid_set
, PID_TO_PTR(control_pid
));
4328 return TAKE_PTR(pid_set
);
4331 static int kill_common_log(pid_t pid
, int signo
, void *userdata
) {
4332 _cleanup_free_
char *comm
= NULL
;
4337 (void) get_process_comm(pid
, &comm
);
4338 log_unit_info(u
, "Sending signal SIG%s to process " PID_FMT
" (%s) on client request.",
4339 signal_to_string(signo
), pid
, strna(comm
));
4344 int unit_kill_common(
4350 sd_bus_error
*error
) {
4353 bool killed
= false;
4355 /* This is the common implementation for explicit user-requested killing of unit processes, shared by
4356 * various unit types. Do not confuse with unit_kill_context(), which is what we use when we want to
4357 * stop a service ourselves. */
4359 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
)) {
4361 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no main processes", unit_type_to_string(u
->type
));
4363 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No main process to kill");
4366 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
)) {
4367 if (control_pid
< 0)
4368 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no control processes", unit_type_to_string(u
->type
));
4369 if (control_pid
== 0)
4370 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No control process to kill");
4373 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
4374 if (control_pid
> 0) {
4375 _cleanup_free_
char *comm
= NULL
;
4376 (void) get_process_comm(control_pid
, &comm
);
4378 if (kill(control_pid
, signo
) < 0) {
4379 /* Report this failure both to the logs and to the client */
4380 sd_bus_error_set_errnof(
4382 "Failed to send signal SIG%s to control process " PID_FMT
" (%s): %m",
4383 signal_to_string(signo
), control_pid
, strna(comm
));
4384 r
= log_unit_warning_errno(
4386 "Failed to send signal SIG%s to control process " PID_FMT
" (%s) on client request: %m",
4387 signal_to_string(signo
), control_pid
, strna(comm
));
4389 log_unit_info(u
, "Sent signal SIG%s to control process " PID_FMT
" (%s) on client request.",
4390 signal_to_string(signo
), control_pid
, strna(comm
));
4395 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
4397 _cleanup_free_
char *comm
= NULL
;
4398 (void) get_process_comm(main_pid
, &comm
);
4400 if (kill(main_pid
, signo
) < 0) {
4402 sd_bus_error_set_errnof(
4404 "Failed to send signal SIG%s to main process " PID_FMT
" (%s): %m",
4405 signal_to_string(signo
), main_pid
, strna(comm
));
4407 r
= log_unit_warning_errno(
4409 "Failed to send signal SIG%s to main process " PID_FMT
" (%s) on client request: %m",
4410 signal_to_string(signo
), main_pid
, strna(comm
));
4412 log_unit_info(u
, "Sent signal SIG%s to main process " PID_FMT
" (%s) on client request.",
4413 signal_to_string(signo
), main_pid
, strna(comm
));
4418 if (IN_SET(who
, KILL_ALL
, KILL_ALL_FAIL
) && u
->cgroup_path
) {
4419 _cleanup_set_free_ Set
*pid_set
= NULL
;
4422 /* Exclude the main/control pids from being killed via the cgroup */
4423 pid_set
= unit_pid_set(main_pid
, control_pid
);
4427 q
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, signo
, 0, pid_set
, kill_common_log
, u
);
4429 if (!IN_SET(q
, -ESRCH
, -ENOENT
)) {
4431 sd_bus_error_set_errnof(
4433 "Failed to send signal SIG%s to auxiliary processes: %m",
4434 signal_to_string(signo
));
4436 r
= log_unit_warning_errno(
4438 "Failed to send signal SIG%s to auxiliary processes on client request: %m",
4439 signal_to_string(signo
));
4445 /* If the "fail" versions of the operation are requested, then complain if the set of processes we killed is empty */
4446 if (r
== 0 && !killed
&& IN_SET(who
, KILL_ALL_FAIL
, KILL_CONTROL_FAIL
, KILL_MAIN_FAIL
))
4447 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No matching processes to kill");
4452 int unit_following_set(Unit
*u
, Set
**s
) {
4456 if (UNIT_VTABLE(u
)->following_set
)
4457 return UNIT_VTABLE(u
)->following_set(u
, s
);
4463 UnitFileState
unit_get_unit_file_state(Unit
*u
) {
4468 if (u
->unit_file_state
< 0 && u
->fragment_path
) {
4469 r
= unit_file_get_state(
4470 u
->manager
->unit_file_scope
,
4473 &u
->unit_file_state
);
4475 u
->unit_file_state
= UNIT_FILE_BAD
;
4478 return u
->unit_file_state
;
4481 int unit_get_unit_file_preset(Unit
*u
) {
4484 if (u
->unit_file_preset
< 0 && u
->fragment_path
)
4485 u
->unit_file_preset
= unit_file_query_preset(
4486 u
->manager
->unit_file_scope
,
4488 basename(u
->fragment_path
),
4491 return u
->unit_file_preset
;
4494 Unit
* unit_ref_set(UnitRef
*ref
, Unit
*source
, Unit
*target
) {
4500 unit_ref_unset(ref
);
4502 ref
->source
= source
;
4503 ref
->target
= target
;
4504 LIST_PREPEND(refs_by_target
, target
->refs_by_target
, ref
);
4508 void unit_ref_unset(UnitRef
*ref
) {
4514 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
4515 * be unreferenced now. */
4516 unit_add_to_gc_queue(ref
->target
);
4518 LIST_REMOVE(refs_by_target
, ref
->target
->refs_by_target
, ref
);
4519 ref
->source
= ref
->target
= NULL
;
4522 static int user_from_unit_name(Unit
*u
, char **ret
) {
4524 static const uint8_t hash_key
[] = {
4525 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
4526 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
4529 _cleanup_free_
char *n
= NULL
;
4532 r
= unit_name_to_prefix(u
->id
, &n
);
4536 if (valid_user_group_name(n
, 0)) {
4541 /* If we can't use the unit name as a user name, then let's hash it and use that */
4542 if (asprintf(ret
, "_du%016" PRIx64
, siphash24(n
, strlen(n
), hash_key
)) < 0)
4548 int unit_patch_contexts(Unit
*u
) {
4555 /* Patch in the manager defaults into the exec and cgroup
4556 * contexts, _after_ the rest of the settings have been
4559 ec
= unit_get_exec_context(u
);
4561 /* This only copies in the ones that need memory */
4562 for (unsigned i
= 0; i
< _RLIMIT_MAX
; i
++)
4563 if (u
->manager
->rlimit
[i
] && !ec
->rlimit
[i
]) {
4564 ec
->rlimit
[i
] = newdup(struct rlimit
, u
->manager
->rlimit
[i
], 1);
4569 if (MANAGER_IS_USER(u
->manager
) &&
4570 !ec
->working_directory
) {
4572 r
= get_home_dir(&ec
->working_directory
);
4576 /* Allow user services to run, even if the
4577 * home directory is missing */
4578 ec
->working_directory_missing_ok
= true;
4581 if (ec
->private_devices
)
4582 ec
->capability_bounding_set
&= ~((UINT64_C(1) << CAP_MKNOD
) | (UINT64_C(1) << CAP_SYS_RAWIO
));
4584 if (ec
->protect_kernel_modules
)
4585 ec
->capability_bounding_set
&= ~(UINT64_C(1) << CAP_SYS_MODULE
);
4587 if (ec
->protect_kernel_logs
)
4588 ec
->capability_bounding_set
&= ~(UINT64_C(1) << CAP_SYSLOG
);
4590 if (ec
->protect_clock
)
4591 ec
->capability_bounding_set
&= ~((UINT64_C(1) << CAP_SYS_TIME
) | (UINT64_C(1) << CAP_WAKE_ALARM
));
4593 if (ec
->dynamic_user
) {
4595 r
= user_from_unit_name(u
, &ec
->user
);
4601 ec
->group
= strdup(ec
->user
);
4606 /* If the dynamic user option is on, let's make sure that the unit can't leave its
4607 * UID/GID around in the file system or on IPC objects. Hence enforce a strict
4610 ec
->private_tmp
= true;
4611 ec
->remove_ipc
= true;
4612 ec
->protect_system
= PROTECT_SYSTEM_STRICT
;
4613 if (ec
->protect_home
== PROTECT_HOME_NO
)
4614 ec
->protect_home
= PROTECT_HOME_READ_ONLY
;
4616 /* Make sure this service can neither benefit from SUID/SGID binaries nor create
4618 ec
->no_new_privileges
= true;
4619 ec
->restrict_suid_sgid
= true;
4623 cc
= unit_get_cgroup_context(u
);
4626 if (ec
->private_devices
&&
4627 cc
->device_policy
== CGROUP_DEVICE_POLICY_AUTO
)
4628 cc
->device_policy
= CGROUP_DEVICE_POLICY_CLOSED
;
4630 if ((ec
->root_image
|| !LIST_IS_EMPTY(ec
->mount_images
)) &&
4631 (cc
->device_policy
!= CGROUP_DEVICE_POLICY_AUTO
|| cc
->device_allow
)) {
4634 /* When RootImage= or MountImages= is specified, the following devices are touched. */
4635 FOREACH_STRING(p
, "/dev/loop-control", "/dev/mapper/control") {
4636 r
= cgroup_add_device_allow(cc
, p
, "rw");
4640 FOREACH_STRING(p
, "block-loop", "block-blkext", "block-device-mapper") {
4641 r
= cgroup_add_device_allow(cc
, p
, "rwm");
4646 /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices.
4647 * Same for mapper and verity. */
4648 FOREACH_STRING(p
, "modprobe@loop.service", "modprobe@dm_mod.service", "modprobe@dm_verity.service") {
4649 r
= unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_WANTS
, p
, true, UNIT_DEPENDENCY_FILE
);
4655 if (ec
->protect_clock
) {
4656 r
= cgroup_add_device_allow(cc
, "char-rtc", "r");
4665 ExecContext
*unit_get_exec_context(Unit
*u
) {
4672 offset
= UNIT_VTABLE(u
)->exec_context_offset
;
4676 return (ExecContext
*) ((uint8_t*) u
+ offset
);
4679 KillContext
*unit_get_kill_context(Unit
*u
) {
4686 offset
= UNIT_VTABLE(u
)->kill_context_offset
;
4690 return (KillContext
*) ((uint8_t*) u
+ offset
);
4693 CGroupContext
*unit_get_cgroup_context(Unit
*u
) {
4699 offset
= UNIT_VTABLE(u
)->cgroup_context_offset
;
4703 return (CGroupContext
*) ((uint8_t*) u
+ offset
);
4706 ExecRuntime
*unit_get_exec_runtime(Unit
*u
) {
4712 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
4716 return *(ExecRuntime
**) ((uint8_t*) u
+ offset
);
4719 static const char* unit_drop_in_dir(Unit
*u
, UnitWriteFlags flags
) {
4722 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4725 if (u
->transient
) /* Redirect drop-ins for transient units always into the transient directory. */
4726 return u
->manager
->lookup_paths
.transient
;
4728 if (flags
& UNIT_PERSISTENT
)
4729 return u
->manager
->lookup_paths
.persistent_control
;
4731 if (flags
& UNIT_RUNTIME
)
4732 return u
->manager
->lookup_paths
.runtime_control
;
4737 char* unit_escape_setting(const char *s
, UnitWriteFlags flags
, char **buf
) {
4743 /* Escapes the input string as requested. Returns the escaped string. If 'buf' is specified then the allocated
4744 * return buffer pointer is also written to *buf, except if no escaping was necessary, in which case *buf is
4745 * set to NULL, and the input pointer is returned as-is. This means the return value always contains a properly
4746 * escaped version, but *buf when passed only contains a pointer if an allocation was necessary. If *buf is
4747 * not specified, then the return value always needs to be freed. Callers can use this to optimize memory
4750 if (flags
& UNIT_ESCAPE_SPECIFIERS
) {
4751 ret
= specifier_escape(s
);
4758 if (flags
& UNIT_ESCAPE_C
) {
4771 return ret
?: (char*) s
;
4774 return ret
?: strdup(s
);
4777 char* unit_concat_strv(char **l
, UnitWriteFlags flags
) {
4778 _cleanup_free_
char *result
= NULL
;
4779 size_t n
= 0, allocated
= 0;
4782 /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command lines in a
4783 * way suitable for ExecStart= stanzas */
4785 STRV_FOREACH(i
, l
) {
4786 _cleanup_free_
char *buf
= NULL
;
4791 p
= unit_escape_setting(*i
, flags
, &buf
);
4795 a
= (n
> 0) + 1 + strlen(p
) + 1; /* separating space + " + entry + " */
4796 if (!GREEDY_REALLOC(result
, allocated
, n
+ a
+ 1))
4810 if (!GREEDY_REALLOC(result
, allocated
, n
+ 1))
4815 return TAKE_PTR(result
);
4818 int unit_write_setting(Unit
*u
, UnitWriteFlags flags
, const char *name
, const char *data
) {
4819 _cleanup_free_
char *p
= NULL
, *q
= NULL
, *escaped
= NULL
;
4820 const char *dir
, *wrapped
;
4827 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4830 data
= unit_escape_setting(data
, flags
, &escaped
);
4834 /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
4835 * previous section header is the same */
4837 if (flags
& UNIT_PRIVATE
) {
4838 if (!UNIT_VTABLE(u
)->private_section
)
4841 if (!u
->transient_file
|| u
->last_section_private
< 0)
4842 data
= strjoina("[", UNIT_VTABLE(u
)->private_section
, "]\n", data
);
4843 else if (u
->last_section_private
== 0)
4844 data
= strjoina("\n[", UNIT_VTABLE(u
)->private_section
, "]\n", data
);
4846 if (!u
->transient_file
|| u
->last_section_private
< 0)
4847 data
= strjoina("[Unit]\n", data
);
4848 else if (u
->last_section_private
> 0)
4849 data
= strjoina("\n[Unit]\n", data
);
4852 if (u
->transient_file
) {
4853 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
4854 * write to the transient unit file. */
4855 fputs(data
, u
->transient_file
);
4857 if (!endswith(data
, "\n"))
4858 fputc('\n', u
->transient_file
);
4860 /* Remember which section we wrote this entry to */
4861 u
->last_section_private
= !!(flags
& UNIT_PRIVATE
);
4865 dir
= unit_drop_in_dir(u
, flags
);
4869 wrapped
= strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
4870 "# or an equivalent operation. Do not edit.\n",
4874 r
= drop_in_file(dir
, u
->id
, 50, name
, &p
, &q
);
4878 (void) mkdir_p_label(p
, 0755);
4880 /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
4881 * recreate the cache after every drop-in we write. */
4882 if (u
->manager
->unit_path_cache
) {
4883 r
= set_put_strdup(&u
->manager
->unit_path_cache
, p
);
4888 r
= write_string_file_atomic_label(q
, wrapped
);
4892 r
= strv_push(&u
->dropin_paths
, q
);
4897 strv_uniq(u
->dropin_paths
);
4899 u
->dropin_mtime
= now(CLOCK_REALTIME
);
4904 int unit_write_settingf(Unit
*u
, UnitWriteFlags flags
, const char *name
, const char *format
, ...) {
4905 _cleanup_free_
char *p
= NULL
;
4913 if (UNIT_WRITE_FLAGS_NOOP(flags
))
4916 va_start(ap
, format
);
4917 r
= vasprintf(&p
, format
, ap
);
4923 return unit_write_setting(u
, flags
, name
, p
);
4926 int unit_make_transient(Unit
*u
) {
4927 _cleanup_free_
char *path
= NULL
;
4932 if (!UNIT_VTABLE(u
)->can_transient
)
4935 (void) mkdir_p_label(u
->manager
->lookup_paths
.transient
, 0755);
4937 path
= path_join(u
->manager
->lookup_paths
.transient
, u
->id
);
4941 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
4942 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
4944 RUN_WITH_UMASK(0022) {
4945 f
= fopen(path
, "we");
4950 safe_fclose(u
->transient_file
);
4951 u
->transient_file
= f
;
4953 free_and_replace(u
->fragment_path
, path
);
4955 u
->source_path
= mfree(u
->source_path
);
4956 u
->dropin_paths
= strv_free(u
->dropin_paths
);
4957 u
->fragment_mtime
= u
->source_mtime
= u
->dropin_mtime
= 0;
4959 u
->load_state
= UNIT_STUB
;
4961 u
->transient
= true;
4963 unit_add_to_dbus_queue(u
);
4964 unit_add_to_gc_queue(u
);
4966 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
4972 static int log_kill(pid_t pid
, int sig
, void *userdata
) {
4973 _cleanup_free_
char *comm
= NULL
;
4975 (void) get_process_comm(pid
, &comm
);
4977 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
4978 only, like for example systemd's own PAM stub process. */
4979 if (comm
&& comm
[0] == '(')
4982 log_unit_notice(userdata
,
4983 "Killing process " PID_FMT
" (%s) with signal SIG%s.",
4986 signal_to_string(sig
));
4991 static int operation_to_signal(const KillContext
*c
, KillOperation k
, bool *noteworthy
) {
4996 case KILL_TERMINATE
:
4997 case KILL_TERMINATE_AND_LOG
:
4998 *noteworthy
= false;
4999 return c
->kill_signal
;
5002 *noteworthy
= false;
5003 return restart_kill_signal(c
);
5007 return c
->final_kill_signal
;
5011 return c
->watchdog_signal
;
5014 assert_not_reached("KillOperation unknown");
5018 int unit_kill_context(
5024 bool main_pid_alien
) {
5026 bool wait_for_exit
= false, send_sighup
;
5027 cg_kill_log_func_t log_func
= NULL
;
5033 /* Kill the processes belonging to this unit, in preparation for shutting the unit down. Returns > 0
5034 * if we killed something worth waiting for, 0 otherwise. Do not confuse with unit_kill_common()
5035 * which is used for user-requested killing of unit processes. */
5037 if (c
->kill_mode
== KILL_NONE
)
5041 sig
= operation_to_signal(c
, k
, ¬eworthy
);
5043 log_func
= log_kill
;
5047 IN_SET(k
, KILL_TERMINATE
, KILL_TERMINATE_AND_LOG
) &&
5052 log_func(main_pid
, sig
, u
);
5054 r
= kill_and_sigcont(main_pid
, sig
);
5055 if (r
< 0 && r
!= -ESRCH
) {
5056 _cleanup_free_
char *comm
= NULL
;
5057 (void) get_process_comm(main_pid
, &comm
);
5059 log_unit_warning_errno(u
, r
, "Failed to kill main process " PID_FMT
" (%s), ignoring: %m", main_pid
, strna(comm
));
5061 if (!main_pid_alien
)
5062 wait_for_exit
= true;
5064 if (r
!= -ESRCH
&& send_sighup
)
5065 (void) kill(main_pid
, SIGHUP
);
5069 if (control_pid
> 0) {
5071 log_func(control_pid
, sig
, u
);
5073 r
= kill_and_sigcont(control_pid
, sig
);
5074 if (r
< 0 && r
!= -ESRCH
) {
5075 _cleanup_free_
char *comm
= NULL
;
5076 (void) get_process_comm(control_pid
, &comm
);
5078 log_unit_warning_errno(u
, r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m", control_pid
, strna(comm
));
5080 wait_for_exit
= true;
5082 if (r
!= -ESRCH
&& send_sighup
)
5083 (void) kill(control_pid
, SIGHUP
);
5087 if (u
->cgroup_path
&&
5088 (c
->kill_mode
== KILL_CONTROL_GROUP
|| (c
->kill_mode
== KILL_MIXED
&& k
== KILL_KILL
))) {
5089 _cleanup_set_free_ Set
*pid_set
= NULL
;
5091 /* Exclude the main/control pids from being killed via the cgroup */
5092 pid_set
= unit_pid_set(main_pid
, control_pid
);
5096 r
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
5098 CGROUP_SIGCONT
|CGROUP_IGNORE_SELF
,
5102 if (!IN_SET(r
, -EAGAIN
, -ESRCH
, -ENOENT
))
5103 log_unit_warning_errno(u
, r
, "Failed to kill control group %s, ignoring: %m", u
->cgroup_path
);
5107 /* FIXME: For now, on the legacy hierarchy, we will not wait for the cgroup members to die if
5108 * we are running in a container or if this is a delegation unit, simply because cgroup
5109 * notification is unreliable in these cases. It doesn't work at all in containers, and outside
5110 * of containers it can be confused easily by left-over directories in the cgroup — which
5111 * however should not exist in non-delegated units. On the unified hierarchy that's different,
5112 * there we get proper events. Hence rely on them. */
5114 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0 ||
5115 (detect_container() == 0 && !unit_cgroup_delegate(u
)))
5116 wait_for_exit
= true;
5121 pid_set
= unit_pid_set(main_pid
, control_pid
);
5125 (void) cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
5134 return wait_for_exit
;
5137 int unit_require_mounts_for(Unit
*u
, const char *path
, UnitDependencyMask mask
) {
5138 _cleanup_free_
char *p
= NULL
;
5139 UnitDependencyInfo di
;
5145 /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these paths in
5146 * the unit (from the path to the UnitDependencyInfo structure indicating how to the dependency came to
5147 * be). However, we build a prefix table for all possible prefixes so that new appearing mount units can easily
5148 * determine which units to make themselves a dependency of. */
5150 if (!path_is_absolute(path
))
5153 r
= hashmap_ensure_allocated(&u
->requires_mounts_for
, &path_hash_ops
);
5161 path
= path_simplify(p
, true);
5163 if (!path_is_normalized(path
))
5166 if (hashmap_contains(u
->requires_mounts_for
, path
))
5169 di
= (UnitDependencyInfo
) {
5173 r
= hashmap_put(u
->requires_mounts_for
, path
, di
.data
);
5178 char prefix
[strlen(path
) + 1];
5179 PATH_FOREACH_PREFIX_MORE(prefix
, path
) {
5182 x
= hashmap_get(u
->manager
->units_requiring_mounts_for
, prefix
);
5184 _cleanup_free_
char *q
= NULL
;
5186 r
= hashmap_ensure_allocated(&u
->manager
->units_requiring_mounts_for
, &path_hash_ops
);
5198 r
= hashmap_put(u
->manager
->units_requiring_mounts_for
, q
, x
);
5214 int unit_setup_exec_runtime(Unit
*u
) {
5221 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
5224 /* Check if there already is an ExecRuntime for this unit? */
5225 rt
= (ExecRuntime
**) ((uint8_t*) u
+ offset
);
5229 /* Try to get it from somebody else */
5230 HASHMAP_FOREACH_KEY(v
, other
, u
->dependencies
[UNIT_JOINS_NAMESPACE_OF
]) {
5231 r
= exec_runtime_acquire(u
->manager
, NULL
, other
->id
, false, rt
);
5236 return exec_runtime_acquire(u
->manager
, unit_get_exec_context(u
), u
->id
, true, rt
);
5239 int unit_setup_dynamic_creds(Unit
*u
) {
5241 DynamicCreds
*dcreds
;
5246 offset
= UNIT_VTABLE(u
)->dynamic_creds_offset
;
5248 dcreds
= (DynamicCreds
*) ((uint8_t*) u
+ offset
);
5250 ec
= unit_get_exec_context(u
);
5253 if (!ec
->dynamic_user
)
5256 return dynamic_creds_acquire(dcreds
, u
->manager
, ec
->user
, ec
->group
);
5259 bool unit_type_supported(UnitType t
) {
5260 if (_unlikely_(t
< 0))
5262 if (_unlikely_(t
>= _UNIT_TYPE_MAX
))
5265 if (!unit_vtable
[t
]->supported
)
5268 return unit_vtable
[t
]->supported();
5271 void unit_warn_if_dir_nonempty(Unit
*u
, const char* where
) {
5277 r
= dir_is_empty(where
);
5278 if (r
> 0 || r
== -ENOTDIR
)
5281 log_unit_warning_errno(u
, r
, "Failed to check directory %s: %m", where
);
5285 log_struct(LOG_NOTICE
,
5286 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
5288 LOG_UNIT_INVOCATION_ID(u
),
5289 LOG_UNIT_MESSAGE(u
, "Directory %s to mount over is not empty, mounting anyway.", where
),
5293 int unit_fail_if_noncanonical(Unit
*u
, const char* where
) {
5294 _cleanup_free_
char *canonical_where
= NULL
;
5300 r
= chase_symlinks(where
, NULL
, CHASE_NONEXISTENT
, &canonical_where
, NULL
);
5302 log_unit_debug_errno(u
, r
, "Failed to check %s for symlinks, ignoring: %m", where
);
5306 /* We will happily ignore a trailing slash (or any redundant slashes) */
5307 if (path_equal(where
, canonical_where
))
5310 /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
5312 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
5314 LOG_UNIT_INVOCATION_ID(u
),
5315 LOG_UNIT_MESSAGE(u
, "Mount path %s is not canonical (contains a symlink).", where
),
5321 bool unit_is_pristine(Unit
*u
) {
5324 /* Check if the unit already exists or is already around,
5325 * in a number of different ways. Note that to cater for unit
5326 * types such as slice, we are generally fine with units that
5327 * are marked UNIT_LOADED even though nothing was actually
5328 * loaded, as those unit types don't require a file on disk. */
5330 return !(!IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_LOADED
) ||
5333 !strv_isempty(u
->dropin_paths
) ||
5338 pid_t
unit_control_pid(Unit
*u
) {
5341 if (UNIT_VTABLE(u
)->control_pid
)
5342 return UNIT_VTABLE(u
)->control_pid(u
);
5347 pid_t
unit_main_pid(Unit
*u
) {
5350 if (UNIT_VTABLE(u
)->main_pid
)
5351 return UNIT_VTABLE(u
)->main_pid(u
);
5356 static void unit_unref_uid_internal(
5360 void (*_manager_unref_uid
)(Manager
*m
, uid_t uid
, bool destroy_now
)) {
5364 assert(_manager_unref_uid
);
5366 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
5367 * gid_t are actually the same time, with the same validity rules.
5369 * Drops a reference to UID/GID from a unit. */
5371 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
5372 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
5374 if (!uid_is_valid(*ref_uid
))
5377 _manager_unref_uid(u
->manager
, *ref_uid
, destroy_now
);
5378 *ref_uid
= UID_INVALID
;
5381 static void unit_unref_uid(Unit
*u
, bool destroy_now
) {
5382 unit_unref_uid_internal(u
, &u
->ref_uid
, destroy_now
, manager_unref_uid
);
5385 static void unit_unref_gid(Unit
*u
, bool destroy_now
) {
5386 unit_unref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, destroy_now
, manager_unref_gid
);
5389 void unit_unref_uid_gid(Unit
*u
, bool destroy_now
) {
5392 unit_unref_uid(u
, destroy_now
);
5393 unit_unref_gid(u
, destroy_now
);
5396 static int unit_ref_uid_internal(
5401 int (*_manager_ref_uid
)(Manager
*m
, uid_t uid
, bool clean_ipc
)) {
5407 assert(uid_is_valid(uid
));
5408 assert(_manager_ref_uid
);
5410 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
5411 * are actually the same type, and have the same validity rules.
5413 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
5414 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
5417 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
5418 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
5420 if (*ref_uid
== uid
)
5423 if (uid_is_valid(*ref_uid
)) /* Already set? */
5426 r
= _manager_ref_uid(u
->manager
, uid
, clean_ipc
);
5434 static int unit_ref_uid(Unit
*u
, uid_t uid
, bool clean_ipc
) {
5435 return unit_ref_uid_internal(u
, &u
->ref_uid
, uid
, clean_ipc
, manager_ref_uid
);
5438 static int unit_ref_gid(Unit
*u
, gid_t gid
, bool clean_ipc
) {
5439 return unit_ref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, (uid_t
) gid
, clean_ipc
, manager_ref_gid
);
5442 static int unit_ref_uid_gid_internal(Unit
*u
, uid_t uid
, gid_t gid
, bool clean_ipc
) {
5447 /* Reference both a UID and a GID in one go. Either references both, or neither. */
5449 if (uid_is_valid(uid
)) {
5450 r
= unit_ref_uid(u
, uid
, clean_ipc
);
5455 if (gid_is_valid(gid
)) {
5456 q
= unit_ref_gid(u
, gid
, clean_ipc
);
5459 unit_unref_uid(u
, false);
5465 return r
> 0 || q
> 0;
5468 int unit_ref_uid_gid(Unit
*u
, uid_t uid
, gid_t gid
) {
5474 c
= unit_get_exec_context(u
);
5476 r
= unit_ref_uid_gid_internal(u
, uid
, gid
, c
? c
->remove_ipc
: false);
5478 return log_unit_warning_errno(u
, r
, "Couldn't add UID/GID reference to unit, proceeding without: %m");
5483 void unit_notify_user_lookup(Unit
*u
, uid_t uid
, gid_t gid
) {
5488 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
5489 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
5490 * objects when no service references the UID/GID anymore. */
5492 r
= unit_ref_uid_gid(u
, uid
, gid
);
5494 unit_add_to_dbus_queue(u
);
5497 int unit_acquire_invocation_id(Unit
*u
) {
5503 r
= sd_id128_randomize(&id
);
5505 return log_unit_error_errno(u
, r
, "Failed to generate invocation ID for unit: %m");
5507 r
= unit_set_invocation_id(u
, id
);
5509 return log_unit_error_errno(u
, r
, "Failed to set invocation ID for unit: %m");
5511 unit_add_to_dbus_queue(u
);
5515 int unit_set_exec_params(Unit
*u
, ExecParameters
*p
) {
5521 /* Copy parameters from manager */
5522 r
= manager_get_effective_environment(u
->manager
, &p
->environment
);
5526 p
->confirm_spawn
= manager_get_confirm_spawn(u
->manager
);
5527 p
->cgroup_supported
= u
->manager
->cgroup_supported
;
5528 p
->prefix
= u
->manager
->prefix
;
5529 SET_FLAG(p
->flags
, EXEC_PASS_LOG_UNIT
|EXEC_CHOWN_DIRECTORIES
, MANAGER_IS_SYSTEM(u
->manager
));
5531 /* Copy parameters from unit */
5532 p
->cgroup_path
= u
->cgroup_path
;
5533 SET_FLAG(p
->flags
, EXEC_CGROUP_DELEGATE
, unit_cgroup_delegate(u
));
5535 p
->received_credentials
= u
->manager
->received_credentials
;
5540 int unit_fork_helper_process(Unit
*u
, const char *name
, pid_t
*ret
) {
5546 /* Forks off a helper process and makes sure it is a member of the unit's cgroup. Returns == 0 in the child,
5547 * and > 0 in the parent. The pid parameter is always filled in with the child's PID. */
5549 (void) unit_realize_cgroup(u
);
5551 r
= safe_fork(name
, FORK_REOPEN_LOG
, ret
);
5555 (void) default_signals(SIGNALS_CRASH_HANDLER
, SIGNALS_IGNORE
, -1);
5556 (void) ignore_signals(SIGPIPE
, -1);
5558 (void) prctl(PR_SET_PDEATHSIG
, SIGTERM
);
5560 if (u
->cgroup_path
) {
5561 r
= cg_attach_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, 0, NULL
, NULL
);
5563 log_unit_error_errno(u
, r
, "Failed to join unit cgroup %s: %m", u
->cgroup_path
);
5571 int unit_fork_and_watch_rm_rf(Unit
*u
, char **paths
, pid_t
*ret_pid
) {
5578 r
= unit_fork_helper_process(u
, "(sd-rmrf)", &pid
);
5582 int ret
= EXIT_SUCCESS
;
5585 STRV_FOREACH(i
, paths
) {
5586 r
= rm_rf(*i
, REMOVE_ROOT
|REMOVE_PHYSICAL
|REMOVE_MISSING_OK
);
5588 log_error_errno(r
, "Failed to remove '%s': %m", *i
);
5596 r
= unit_watch_pid(u
, pid
, true);
5604 static void unit_update_dependency_mask(Unit
*u
, UnitDependency d
, Unit
*other
, UnitDependencyInfo di
) {
5607 assert(d
< _UNIT_DEPENDENCY_MAX
);
5610 if (di
.origin_mask
== 0 && di
.destination_mask
== 0) {
5611 /* No bit set anymore, let's drop the whole entry */
5612 assert_se(hashmap_remove(u
->dependencies
[d
], other
));
5613 log_unit_debug(u
, "lost dependency %s=%s", unit_dependency_to_string(d
), other
->id
);
5615 /* Mask was reduced, let's update the entry */
5616 assert_se(hashmap_update(u
->dependencies
[d
], other
, di
.data
) == 0);
5619 void unit_remove_dependencies(Unit
*u
, UnitDependencyMask mask
) {
5622 /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
5627 for (UnitDependency d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
5631 UnitDependencyInfo di
;
5636 HASHMAP_FOREACH_KEY(di
.data
, other
, u
->dependencies
[d
]) {
5637 if (FLAGS_SET(~mask
, di
.origin_mask
))
5639 di
.origin_mask
&= ~mask
;
5640 unit_update_dependency_mask(u
, d
, other
, di
);
5642 /* We updated the dependency from our unit to the other unit now. But most dependencies
5643 * imply a reverse dependency. Hence, let's delete that one too. For that we go through
5644 * all dependency types on the other unit and delete all those which point to us and
5645 * have the right mask set. */
5647 for (UnitDependency q
= 0; q
< _UNIT_DEPENDENCY_MAX
; q
++) {
5648 UnitDependencyInfo dj
;
5650 dj
.data
= hashmap_get(other
->dependencies
[q
], u
);
5651 if (FLAGS_SET(~mask
, dj
.destination_mask
))
5653 dj
.destination_mask
&= ~mask
;
5655 unit_update_dependency_mask(other
, q
, u
, dj
);
5658 unit_add_to_gc_queue(other
);
5668 static int unit_get_invocation_path(Unit
*u
, char **ret
) {
5675 if (MANAGER_IS_SYSTEM(u
->manager
))
5676 p
= strjoin("/run/systemd/units/invocation:", u
->id
);
5678 _cleanup_free_
char *user_path
= NULL
;
5679 r
= xdg_user_runtime_dir(&user_path
, "/systemd/units/invocation:");
5682 p
= strjoin(user_path
, u
->id
);
5692 static int unit_export_invocation_id(Unit
*u
) {
5693 _cleanup_free_
char *p
= NULL
;
5698 if (u
->exported_invocation_id
)
5701 if (sd_id128_is_null(u
->invocation_id
))
5704 r
= unit_get_invocation_path(u
, &p
);
5706 return log_unit_debug_errno(u
, r
, "Failed to get invocation path: %m");
5708 r
= symlink_atomic_label(u
->invocation_id_string
, p
);
5710 return log_unit_debug_errno(u
, r
, "Failed to create invocation ID symlink %s: %m", p
);
5712 u
->exported_invocation_id
= true;
5716 static int unit_export_log_level_max(Unit
*u
, const ExecContext
*c
) {
5724 if (u
->exported_log_level_max
)
5727 if (c
->log_level_max
< 0)
5730 assert(c
->log_level_max
<= 7);
5732 buf
[0] = '0' + c
->log_level_max
;
5735 p
= strjoina("/run/systemd/units/log-level-max:", u
->id
);
5736 r
= symlink_atomic(buf
, p
);
5738 return log_unit_debug_errno(u
, r
, "Failed to create maximum log level symlink %s: %m", p
);
5740 u
->exported_log_level_max
= true;
5744 static int unit_export_log_extra_fields(Unit
*u
, const ExecContext
*c
) {
5745 _cleanup_close_
int fd
= -1;
5746 struct iovec
*iovec
;
5753 if (u
->exported_log_extra_fields
)
5756 if (c
->n_log_extra_fields
<= 0)
5759 sizes
= newa(le64_t
, c
->n_log_extra_fields
);
5760 iovec
= newa(struct iovec
, c
->n_log_extra_fields
* 2);
5762 for (size_t i
= 0; i
< c
->n_log_extra_fields
; i
++) {
5763 sizes
[i
] = htole64(c
->log_extra_fields
[i
].iov_len
);
5765 iovec
[i
*2] = IOVEC_MAKE(sizes
+ i
, sizeof(le64_t
));
5766 iovec
[i
*2+1] = c
->log_extra_fields
[i
];
5769 p
= strjoina("/run/systemd/units/log-extra-fields:", u
->id
);
5770 pattern
= strjoina(p
, ".XXXXXX");
5772 fd
= mkostemp_safe(pattern
);
5774 return log_unit_debug_errno(u
, fd
, "Failed to create extra fields file %s: %m", p
);
5776 n
= writev(fd
, iovec
, c
->n_log_extra_fields
*2);
5778 r
= log_unit_debug_errno(u
, errno
, "Failed to write extra fields: %m");
5782 (void) fchmod(fd
, 0644);
5784 if (rename(pattern
, p
) < 0) {
5785 r
= log_unit_debug_errno(u
, errno
, "Failed to rename extra fields file: %m");
5789 u
->exported_log_extra_fields
= true;
5793 (void) unlink(pattern
);
5797 static int unit_export_log_ratelimit_interval(Unit
*u
, const ExecContext
*c
) {
5798 _cleanup_free_
char *buf
= NULL
;
5805 if (u
->exported_log_ratelimit_interval
)
5808 if (c
->log_ratelimit_interval_usec
== 0)
5811 p
= strjoina("/run/systemd/units/log-rate-limit-interval:", u
->id
);
5813 if (asprintf(&buf
, "%" PRIu64
, c
->log_ratelimit_interval_usec
) < 0)
5816 r
= symlink_atomic(buf
, p
);
5818 return log_unit_debug_errno(u
, r
, "Failed to create log rate limit interval symlink %s: %m", p
);
5820 u
->exported_log_ratelimit_interval
= true;
5824 static int unit_export_log_ratelimit_burst(Unit
*u
, const ExecContext
*c
) {
5825 _cleanup_free_
char *buf
= NULL
;
5832 if (u
->exported_log_ratelimit_burst
)
5835 if (c
->log_ratelimit_burst
== 0)
5838 p
= strjoina("/run/systemd/units/log-rate-limit-burst:", u
->id
);
5840 if (asprintf(&buf
, "%u", c
->log_ratelimit_burst
) < 0)
5843 r
= symlink_atomic(buf
, p
);
5845 return log_unit_debug_errno(u
, r
, "Failed to create log rate limit burst symlink %s: %m", p
);
5847 u
->exported_log_ratelimit_burst
= true;
5851 void unit_export_state_files(Unit
*u
) {
5852 const ExecContext
*c
;
5859 if (MANAGER_IS_TEST_RUN(u
->manager
))
5862 /* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
5863 * from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
5864 * the IPC system itself and PID 1 also log to the journal.
5866 * Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
5867 * IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
5868 * apply to communication between the journal and systemd, as we assume that these two daemons live in the same
5869 * namespace at least.
5871 * Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
5872 * better for storing small bits of data, in particular as we can write them with two system calls, and read
5875 (void) unit_export_invocation_id(u
);
5877 if (!MANAGER_IS_SYSTEM(u
->manager
))
5880 c
= unit_get_exec_context(u
);
5882 (void) unit_export_log_level_max(u
, c
);
5883 (void) unit_export_log_extra_fields(u
, c
);
5884 (void) unit_export_log_ratelimit_interval(u
, c
);
5885 (void) unit_export_log_ratelimit_burst(u
, c
);
5889 void unit_unlink_state_files(Unit
*u
) {
5897 /* Undoes the effect of unit_export_state() */
5899 if (u
->exported_invocation_id
) {
5900 _cleanup_free_
char *invocation_path
= NULL
;
5901 int r
= unit_get_invocation_path(u
, &invocation_path
);
5903 (void) unlink(invocation_path
);
5904 u
->exported_invocation_id
= false;
5908 if (!MANAGER_IS_SYSTEM(u
->manager
))
5911 if (u
->exported_log_level_max
) {
5912 p
= strjoina("/run/systemd/units/log-level-max:", u
->id
);
5915 u
->exported_log_level_max
= false;
5918 if (u
->exported_log_extra_fields
) {
5919 p
= strjoina("/run/systemd/units/extra-fields:", u
->id
);
5922 u
->exported_log_extra_fields
= false;
5925 if (u
->exported_log_ratelimit_interval
) {
5926 p
= strjoina("/run/systemd/units/log-rate-limit-interval:", u
->id
);
5929 u
->exported_log_ratelimit_interval
= false;
5932 if (u
->exported_log_ratelimit_burst
) {
5933 p
= strjoina("/run/systemd/units/log-rate-limit-burst:", u
->id
);
5936 u
->exported_log_ratelimit_burst
= false;
5940 int unit_prepare_exec(Unit
*u
) {
5945 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
5946 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
5947 r
= bpf_firewall_load_custom(u
);
5951 /* Prepares everything so that we can fork of a process for this unit */
5953 (void) unit_realize_cgroup(u
);
5955 if (u
->reset_accounting
) {
5956 (void) unit_reset_accounting(u
);
5957 u
->reset_accounting
= false;
5960 unit_export_state_files(u
);
5962 r
= unit_setup_exec_runtime(u
);
5966 r
= unit_setup_dynamic_creds(u
);
5973 static bool ignore_leftover_process(const char *comm
) {
5974 return comm
&& comm
[0] == '('; /* Most likely our own helper process (PAM?), ignore */
5977 int unit_log_leftover_process_start(pid_t pid
, int sig
, void *userdata
) {
5978 _cleanup_free_
char *comm
= NULL
;
5980 (void) get_process_comm(pid
, &comm
);
5982 if (ignore_leftover_process(comm
))
5985 /* During start we print a warning */
5987 log_unit_warning(userdata
,
5988 "Found left-over process " PID_FMT
" (%s) in control group while starting unit. Ignoring.\n"
5989 "This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
5995 int unit_log_leftover_process_stop(pid_t pid
, int sig
, void *userdata
) {
5996 _cleanup_free_
char *comm
= NULL
;
5998 (void) get_process_comm(pid
, &comm
);
6000 if (ignore_leftover_process(comm
))
6003 /* During stop we only print an informational message */
6005 log_unit_info(userdata
,
6006 "Unit process " PID_FMT
" (%s) remains running after unit stopped.",
6012 int unit_warn_leftover_processes(Unit
*u
, cg_kill_log_func_t log_func
) {
6015 (void) unit_pick_cgroup_path(u
);
6017 if (!u
->cgroup_path
)
6020 return cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, 0, 0, NULL
, log_func
, u
);
6023 bool unit_needs_console(Unit
*u
) {
6025 UnitActiveState state
;
6029 state
= unit_active_state(u
);
6031 if (UNIT_IS_INACTIVE_OR_FAILED(state
))
6034 if (UNIT_VTABLE(u
)->needs_console
)
6035 return UNIT_VTABLE(u
)->needs_console(u
);
6037 /* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
6038 ec
= unit_get_exec_context(u
);
6042 return exec_context_may_touch_console(ec
);
6045 const char *unit_label_path(const Unit
*u
) {
6050 /* Returns the file system path to use for MAC access decisions, i.e. the file to read the SELinux label off
6051 * when validating access checks. */
6053 p
= u
->source_path
?: u
->fragment_path
;
6057 /* If a unit is masked, then don't read the SELinux label of /dev/null, as that really makes no sense */
6058 if (null_or_empty_path(p
) > 0)
6064 int unit_pid_attachable(Unit
*u
, pid_t pid
, sd_bus_error
*error
) {
6069 /* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
6070 * and not a kernel thread either */
6072 /* First, a simple range check */
6073 if (!pid_is_valid(pid
))
6074 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process identifier " PID_FMT
" is not valid.", pid
);
6076 /* Some extra safety check */
6077 if (pid
== 1 || pid
== getpid_cached())
6078 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process " PID_FMT
" is a manager process, refusing.", pid
);
6080 /* Don't even begin to bother with kernel threads */
6081 r
= is_kernel_thread(pid
);
6083 return sd_bus_error_setf(error
, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN
, "Process with ID " PID_FMT
" does not exist.", pid
);
6085 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether process " PID_FMT
" is a kernel thread: %m", pid
);
6087 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Process " PID_FMT
" is a kernel thread, refusing.", pid
);
6092 void unit_log_success(Unit
*u
) {
6095 log_struct(LOG_INFO
,
6096 "MESSAGE_ID=" SD_MESSAGE_UNIT_SUCCESS_STR
,
6098 LOG_UNIT_INVOCATION_ID(u
),
6099 LOG_UNIT_MESSAGE(u
, "Succeeded."));
6102 void unit_log_failure(Unit
*u
, const char *result
) {
6106 log_struct(LOG_WARNING
,
6107 "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILURE_RESULT_STR
,
6109 LOG_UNIT_INVOCATION_ID(u
),
6110 LOG_UNIT_MESSAGE(u
, "Failed with result '%s'.", result
),
6111 "UNIT_RESULT=%s", result
);
6114 void unit_log_skip(Unit
*u
, const char *result
) {
6118 log_struct(LOG_INFO
,
6119 "MESSAGE_ID=" SD_MESSAGE_UNIT_SKIPPED_STR
,
6121 LOG_UNIT_INVOCATION_ID(u
),
6122 LOG_UNIT_MESSAGE(u
, "Skipped due to '%s'.", result
),
6123 "UNIT_RESULT=%s", result
);
6126 void unit_log_process_exit(
6129 const char *command
,
6139 /* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
6140 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
6141 * that the service already logged the reason at a higher log level on its own. Otherwise, make it a
6145 else if (code
== CLD_EXITED
)
6148 level
= LOG_WARNING
;
6151 "MESSAGE_ID=" SD_MESSAGE_UNIT_PROCESS_EXIT_STR
,
6152 LOG_UNIT_MESSAGE(u
, "%s exited, code=%s, status=%i/%s",
6154 sigchld_code_to_string(code
), status
,
6155 strna(code
== CLD_EXITED
6156 ? exit_status_to_string(status
, EXIT_STATUS_FULL
)
6157 : signal_to_string(status
))),
6158 "EXIT_CODE=%s", sigchld_code_to_string(code
),
6159 "EXIT_STATUS=%i", status
,
6160 "COMMAND=%s", strna(command
),
6162 LOG_UNIT_INVOCATION_ID(u
));
6165 int unit_exit_status(Unit
*u
) {
6168 /* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
6169 * 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
6170 * if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
6171 * service process has exited abnormally (signal/coredump). */
6173 if (!UNIT_VTABLE(u
)->exit_status
)
6176 return UNIT_VTABLE(u
)->exit_status(u
);
6179 int unit_failure_action_exit_status(Unit
*u
) {
6184 /* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
6186 if (u
->failure_action_exit_status
>= 0)
6187 return u
->failure_action_exit_status
;
6189 r
= unit_exit_status(u
);
6190 if (r
== -EBADE
) /* Exited, but not cleanly (i.e. by signal or such) */
6196 int unit_success_action_exit_status(Unit
*u
) {
6201 /* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
6203 if (u
->success_action_exit_status
>= 0)
6204 return u
->success_action_exit_status
;
6206 r
= unit_exit_status(u
);
6207 if (r
== -EBADE
) /* Exited, but not cleanly (i.e. by signal or such) */
6213 int unit_test_trigger_loaded(Unit
*u
) {
6216 /* Tests whether the unit to trigger is loaded */
6218 trigger
= UNIT_TRIGGER(u
);
6220 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
6221 "Refusing to start, no unit to trigger.");
6222 if (trigger
->load_state
!= UNIT_LOADED
)
6223 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
6224 "Refusing to start, unit %s to trigger not loaded.", trigger
->id
);
6229 void unit_destroy_runtime_data(Unit
*u
, const ExecContext
*context
) {
6233 if (context
->runtime_directory_preserve_mode
== EXEC_PRESERVE_NO
||
6234 (context
->runtime_directory_preserve_mode
== EXEC_PRESERVE_RESTART
&& !unit_will_restart(u
)))
6235 exec_context_destroy_runtime_directory(context
, u
->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
6237 exec_context_destroy_credentials(context
, u
->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
], u
->id
);
6240 int unit_clean(Unit
*u
, ExecCleanMask mask
) {
6241 UnitActiveState state
;
6245 /* Special return values:
6247 * -EOPNOTSUPP → cleaning not supported for this unit type
6248 * -EUNATCH → cleaning not defined for this resource type
6249 * -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
6250 * a job queued or similar
6253 if (!UNIT_VTABLE(u
)->clean
)
6259 if (u
->load_state
!= UNIT_LOADED
)
6265 state
= unit_active_state(u
);
6266 if (!IN_SET(state
, UNIT_INACTIVE
))
6269 return UNIT_VTABLE(u
)->clean(u
, mask
);
6272 int unit_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
6275 if (!UNIT_VTABLE(u
)->clean
||
6276 u
->load_state
!= UNIT_LOADED
) {
6281 /* When the clean() method is set, can_clean() really should be set too */
6282 assert(UNIT_VTABLE(u
)->can_clean
);
6284 return UNIT_VTABLE(u
)->can_clean(u
, ret
);
6287 bool unit_can_freeze(Unit
*u
) {
6290 if (UNIT_VTABLE(u
)->can_freeze
)
6291 return UNIT_VTABLE(u
)->can_freeze(u
);
6293 return UNIT_VTABLE(u
)->freeze
;
6296 void unit_frozen(Unit
*u
) {
6299 u
->freezer_state
= FREEZER_FROZEN
;
6301 bus_unit_send_pending_freezer_message(u
);
6304 void unit_thawed(Unit
*u
) {
6307 u
->freezer_state
= FREEZER_RUNNING
;
6309 bus_unit_send_pending_freezer_message(u
);
6312 static int unit_freezer_action(Unit
*u
, FreezerAction action
) {
6314 int (*method
)(Unit
*);
6318 assert(IN_SET(action
, FREEZER_FREEZE
, FREEZER_THAW
));
6320 method
= action
== FREEZER_FREEZE
? UNIT_VTABLE(u
)->freeze
: UNIT_VTABLE(u
)->thaw
;
6321 if (!method
|| !cg_freezer_supported())
6327 if (u
->load_state
!= UNIT_LOADED
)
6330 s
= unit_active_state(u
);
6331 if (s
!= UNIT_ACTIVE
)
6334 if (IN_SET(u
->freezer_state
, FREEZER_FREEZING
, FREEZER_THAWING
))
6344 int unit_freeze(Unit
*u
) {
6345 return unit_freezer_action(u
, FREEZER_FREEZE
);
6348 int unit_thaw(Unit
*u
) {
6349 return unit_freezer_action(u
, FREEZER_THAW
);
6352 /* Wrappers around low-level cgroup freezer operations common for service and scope units */
6353 int unit_freeze_vtable_common(Unit
*u
) {
6354 return unit_cgroup_freezer_action(u
, FREEZER_FREEZE
);
6357 int unit_thaw_vtable_common(Unit
*u
) {
6358 return unit_cgroup_freezer_action(u
, FREEZER_THAW
);
6361 static const char* const collect_mode_table
[_COLLECT_MODE_MAX
] = {
6362 [COLLECT_INACTIVE
] = "inactive",
6363 [COLLECT_INACTIVE_OR_FAILED
] = "inactive-or-failed",
6366 DEFINE_STRING_TABLE_LOOKUP(collect_mode
, CollectMode
);