2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include "sd-messages.h"
29 #include "alloc-util.h"
30 #include "bus-common-errors.h"
32 #include "cgroup-util.h"
33 #include "dbus-unit.h"
39 #include "fileio-label.h"
40 #include "format-util.h"
41 #include "id128-util.h"
42 #include "load-dropin.h"
43 #include "load-fragment.h"
48 #include "parse-util.h"
49 #include "path-util.h"
50 #include "process-util.h"
52 #include "signal-util.h"
54 #include "stat-util.h"
55 #include "stdio-util.h"
56 #include "string-util.h"
58 #include "umask-util.h"
59 #include "unit-name.h"
61 #include "user-util.h"
64 const UnitVTable
* const unit_vtable
[_UNIT_TYPE_MAX
] = {
65 [UNIT_SERVICE
] = &service_vtable
,
66 [UNIT_SOCKET
] = &socket_vtable
,
67 [UNIT_TARGET
] = &target_vtable
,
68 [UNIT_DEVICE
] = &device_vtable
,
69 [UNIT_MOUNT
] = &mount_vtable
,
70 [UNIT_AUTOMOUNT
] = &automount_vtable
,
71 [UNIT_SWAP
] = &swap_vtable
,
72 [UNIT_TIMER
] = &timer_vtable
,
73 [UNIT_PATH
] = &path_vtable
,
74 [UNIT_SLICE
] = &slice_vtable
,
75 [UNIT_SCOPE
] = &scope_vtable
78 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
);
80 Unit
*unit_new(Manager
*m
, size_t size
) {
84 assert(size
>= sizeof(Unit
));
90 u
->names
= set_new(&string_hash_ops
);
95 u
->type
= _UNIT_TYPE_INVALID
;
96 u
->default_dependencies
= true;
97 u
->unit_file_state
= _UNIT_FILE_STATE_INVALID
;
98 u
->unit_file_preset
= -1;
99 u
->on_failure_job_mode
= JOB_REPLACE
;
100 u
->cgroup_inotify_wd
= -1;
101 u
->job_timeout
= USEC_INFINITY
;
102 u
->job_running_timeout
= USEC_INFINITY
;
103 u
->ref_uid
= UID_INVALID
;
104 u
->ref_gid
= GID_INVALID
;
105 u
->cpu_usage_last
= NSEC_INFINITY
;
107 u
->ip_accounting_ingress_map_fd
= -1;
108 u
->ip_accounting_egress_map_fd
= -1;
109 u
->ipv4_allow_map_fd
= -1;
110 u
->ipv6_allow_map_fd
= -1;
111 u
->ipv4_deny_map_fd
= -1;
112 u
->ipv6_deny_map_fd
= -1;
114 RATELIMIT_INIT(u
->start_limit
, m
->default_start_limit_interval
, m
->default_start_limit_burst
);
115 RATELIMIT_INIT(u
->auto_stop_ratelimit
, 10 * USEC_PER_SEC
, 16);
120 int unit_new_for_name(Manager
*m
, size_t size
, const char *name
, Unit
**ret
) {
124 u
= unit_new(m
, size
);
128 r
= unit_add_name(u
, name
);
138 bool unit_has_name(Unit
*u
, const char *name
) {
142 return set_contains(u
->names
, (char*) name
);
145 static void unit_init(Unit
*u
) {
152 assert(u
->type
>= 0);
154 cc
= unit_get_cgroup_context(u
);
156 cgroup_context_init(cc
);
158 /* Copy in the manager defaults into the cgroup
159 * context, _before_ the rest of the settings have
160 * been initialized */
162 cc
->cpu_accounting
= u
->manager
->default_cpu_accounting
;
163 cc
->io_accounting
= u
->manager
->default_io_accounting
;
164 cc
->ip_accounting
= u
->manager
->default_ip_accounting
;
165 cc
->blockio_accounting
= u
->manager
->default_blockio_accounting
;
166 cc
->memory_accounting
= u
->manager
->default_memory_accounting
;
167 cc
->tasks_accounting
= u
->manager
->default_tasks_accounting
;
168 cc
->ip_accounting
= u
->manager
->default_ip_accounting
;
170 if (u
->type
!= UNIT_SLICE
)
171 cc
->tasks_max
= u
->manager
->default_tasks_max
;
174 ec
= unit_get_exec_context(u
);
176 exec_context_init(ec
);
178 ec
->keyring_mode
= MANAGER_IS_SYSTEM(u
->manager
) ?
179 EXEC_KEYRING_PRIVATE
: EXEC_KEYRING_INHERIT
;
182 kc
= unit_get_kill_context(u
);
184 kill_context_init(kc
);
186 if (UNIT_VTABLE(u
)->init
)
187 UNIT_VTABLE(u
)->init(u
);
190 int unit_add_name(Unit
*u
, const char *text
) {
191 _cleanup_free_
char *s
= NULL
, *i
= NULL
;
198 if (unit_name_is_valid(text
, UNIT_NAME_TEMPLATE
)) {
203 r
= unit_name_replace_instance(text
, u
->instance
, &s
);
212 if (set_contains(u
->names
, s
))
214 if (hashmap_contains(u
->manager
->units
, s
))
217 if (!unit_name_is_valid(s
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
220 t
= unit_name_to_type(s
);
224 if (u
->type
!= _UNIT_TYPE_INVALID
&& t
!= u
->type
)
227 r
= unit_name_to_instance(s
, &i
);
231 if (i
&& !unit_type_may_template(t
))
234 /* Ensure that this unit is either instanced or not instanced,
235 * but not both. Note that we do allow names with different
236 * instance names however! */
237 if (u
->type
!= _UNIT_TYPE_INVALID
&& !u
->instance
!= !i
)
240 if (!unit_type_may_alias(t
) && !set_isempty(u
->names
))
243 if (hashmap_size(u
->manager
->units
) >= MANAGER_MAX_NAMES
)
246 r
= set_put(u
->names
, s
);
251 r
= hashmap_put(u
->manager
->units
, s
, u
);
253 (void) set_remove(u
->names
, s
);
257 if (u
->type
== _UNIT_TYPE_INVALID
) {
262 LIST_PREPEND(units_by_type
, u
->manager
->units_by_type
[t
], u
);
271 unit_add_to_dbus_queue(u
);
275 int unit_choose_id(Unit
*u
, const char *name
) {
276 _cleanup_free_
char *t
= NULL
;
283 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
288 r
= unit_name_replace_instance(name
, u
->instance
, &t
);
295 /* Selects one of the names of this unit as the id */
296 s
= set_get(u
->names
, (char*) name
);
300 /* Determine the new instance from the new id */
301 r
= unit_name_to_instance(s
, &i
);
310 unit_add_to_dbus_queue(u
);
315 int unit_set_description(Unit
*u
, const char *description
) {
320 if (isempty(description
))
323 s
= strdup(description
);
328 free(u
->description
);
331 unit_add_to_dbus_queue(u
);
335 bool unit_check_gc(Unit
*u
) {
336 UnitActiveState state
;
346 state
= unit_active_state(u
);
347 inactive
= state
== UNIT_INACTIVE
;
349 /* If the unit is inactive and failed and no job is queued for
350 * it, then release its runtime resources */
351 if (UNIT_IS_INACTIVE_OR_FAILED(state
) &&
352 UNIT_VTABLE(u
)->release_resources
)
353 UNIT_VTABLE(u
)->release_resources(u
, inactive
);
355 /* But we keep the unit object around for longer when it is
356 * referenced or configured to not be gc'ed */
366 if (sd_bus_track_count(u
->bus_track
) > 0)
369 if (UNIT_VTABLE(u
)->check_gc
)
370 if (UNIT_VTABLE(u
)->check_gc(u
))
376 void unit_add_to_load_queue(Unit
*u
) {
378 assert(u
->type
!= _UNIT_TYPE_INVALID
);
380 if (u
->load_state
!= UNIT_STUB
|| u
->in_load_queue
)
383 LIST_PREPEND(load_queue
, u
->manager
->load_queue
, u
);
384 u
->in_load_queue
= true;
387 void unit_add_to_cleanup_queue(Unit
*u
) {
390 if (u
->in_cleanup_queue
)
393 LIST_PREPEND(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
394 u
->in_cleanup_queue
= true;
397 void unit_add_to_gc_queue(Unit
*u
) {
400 if (u
->in_gc_queue
|| u
->in_cleanup_queue
)
403 if (unit_check_gc(u
))
406 LIST_PREPEND(gc_queue
, u
->manager
->gc_unit_queue
, u
);
407 u
->in_gc_queue
= true;
410 void unit_add_to_dbus_queue(Unit
*u
) {
412 assert(u
->type
!= _UNIT_TYPE_INVALID
);
414 if (u
->load_state
== UNIT_STUB
|| u
->in_dbus_queue
)
417 /* Shortcut things if nobody cares */
418 if (sd_bus_track_count(u
->manager
->subscribed
) <= 0 &&
419 sd_bus_track_count(u
->bus_track
) <= 0 &&
420 set_isempty(u
->manager
->private_buses
)) {
421 u
->sent_dbus_new_signal
= true;
425 LIST_PREPEND(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
426 u
->in_dbus_queue
= true;
429 static void bidi_set_free(Unit
*u
, Set
*s
) {
435 /* Frees the set and makes sure we are dropped from the
436 * inverse pointers */
438 SET_FOREACH(other
, s
, i
) {
441 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
442 set_remove(other
->dependencies
[d
], u
);
444 unit_add_to_gc_queue(other
);
450 static void unit_remove_transient(Unit
*u
) {
458 if (u
->fragment_path
)
459 (void) unlink(u
->fragment_path
);
461 STRV_FOREACH(i
, u
->dropin_paths
) {
462 _cleanup_free_
char *p
= NULL
, *pp
= NULL
;
464 p
= dirname_malloc(*i
); /* Get the drop-in directory from the drop-in file */
468 pp
= dirname_malloc(p
); /* Get the config directory from the drop-in directory */
472 /* Only drop transient drop-ins */
473 if (!path_equal(u
->manager
->lookup_paths
.transient
, pp
))
481 static void unit_free_requires_mounts_for(Unit
*u
) {
484 STRV_FOREACH(j
, u
->requires_mounts_for
) {
485 char s
[strlen(*j
) + 1];
487 PATH_FOREACH_PREFIX_MORE(s
, *j
) {
491 x
= hashmap_get2(u
->manager
->units_requiring_mounts_for
, s
, (void**) &y
);
497 if (set_isempty(x
)) {
498 hashmap_remove(u
->manager
->units_requiring_mounts_for
, y
);
505 u
->requires_mounts_for
= strv_free(u
->requires_mounts_for
);
508 static void unit_done(Unit
*u
) {
517 if (UNIT_VTABLE(u
)->done
)
518 UNIT_VTABLE(u
)->done(u
);
520 ec
= unit_get_exec_context(u
);
522 exec_context_done(ec
);
524 cc
= unit_get_cgroup_context(u
);
526 cgroup_context_done(cc
);
529 void unit_free(Unit
*u
) {
537 if (u
->transient_file
)
538 fclose(u
->transient_file
);
540 if (!MANAGER_IS_RELOADING(u
->manager
))
541 unit_remove_transient(u
);
543 bus_unit_send_removed_signal(u
);
547 sd_bus_slot_unref(u
->match_bus_slot
);
549 sd_bus_track_unref(u
->bus_track
);
550 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
552 unit_free_requires_mounts_for(u
);
554 SET_FOREACH(t
, u
->names
, i
)
555 hashmap_remove_value(u
->manager
->units
, t
, u
);
557 if (!sd_id128_is_null(u
->invocation_id
))
558 hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
572 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
573 bidi_set_free(u
, u
->dependencies
[d
]);
575 if (u
->type
!= _UNIT_TYPE_INVALID
)
576 LIST_REMOVE(units_by_type
, u
->manager
->units_by_type
[u
->type
], u
);
578 if (u
->in_load_queue
)
579 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
581 if (u
->in_dbus_queue
)
582 LIST_REMOVE(dbus_queue
, u
->manager
->dbus_unit_queue
, u
);
584 if (u
->in_cleanup_queue
)
585 LIST_REMOVE(cleanup_queue
, u
->manager
->cleanup_queue
, u
);
588 LIST_REMOVE(gc_queue
, u
->manager
->gc_unit_queue
, u
);
590 if (u
->in_cgroup_queue
)
591 LIST_REMOVE(cgroup_queue
, u
->manager
->cgroup_queue
, u
);
593 unit_release_cgroup(u
);
595 unit_unref_uid_gid(u
, false);
597 (void) manager_update_failed_units(u
->manager
, u
, false);
598 set_remove(u
->manager
->startup_units
, u
);
600 free(u
->description
);
601 strv_free(u
->documentation
);
602 free(u
->fragment_path
);
603 free(u
->source_path
);
604 strv_free(u
->dropin_paths
);
607 free(u
->job_timeout_reboot_arg
);
609 set_free_free(u
->names
);
611 unit_unwatch_all_pids(u
);
613 condition_free_list(u
->conditions
);
614 condition_free_list(u
->asserts
);
618 unit_ref_unset(&u
->slice
);
621 unit_ref_unset(u
->refs
);
623 safe_close(u
->ip_accounting_ingress_map_fd
);
624 safe_close(u
->ip_accounting_egress_map_fd
);
626 safe_close(u
->ipv4_allow_map_fd
);
627 safe_close(u
->ipv6_allow_map_fd
);
628 safe_close(u
->ipv4_deny_map_fd
);
629 safe_close(u
->ipv6_deny_map_fd
);
631 bpf_program_unref(u
->ip_bpf_ingress
);
632 bpf_program_unref(u
->ip_bpf_egress
);
637 UnitActiveState
unit_active_state(Unit
*u
) {
640 if (u
->load_state
== UNIT_MERGED
)
641 return unit_active_state(unit_follow_merge(u
));
643 /* After a reload it might happen that a unit is not correctly
644 * loaded but still has a process around. That's why we won't
645 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
647 return UNIT_VTABLE(u
)->active_state(u
);
650 const char* unit_sub_state_to_string(Unit
*u
) {
653 return UNIT_VTABLE(u
)->sub_state_to_string(u
);
656 static int complete_move(Set
**s
, Set
**other
) {
666 r
= set_move(*s
, *other
);
677 static int merge_names(Unit
*u
, Unit
*other
) {
685 r
= complete_move(&u
->names
, &other
->names
);
689 set_free_free(other
->names
);
693 SET_FOREACH(t
, u
->names
, i
)
694 assert_se(hashmap_replace(u
->manager
->units
, t
, u
) == 0);
699 static int reserve_dependencies(Unit
*u
, Unit
*other
, UnitDependency d
) {
704 assert(d
< _UNIT_DEPENDENCY_MAX
);
707 * If u does not have this dependency set allocated, there is no need
708 * to reserve anything. In that case other's set will be transferred
709 * as a whole to u by complete_move().
711 if (!u
->dependencies
[d
])
714 /* merge_dependencies() will skip a u-on-u dependency */
715 n_reserve
= set_size(other
->dependencies
[d
]) - !!set_get(other
->dependencies
[d
], u
);
717 return set_reserve(u
->dependencies
[d
], n_reserve
);
720 static void merge_dependencies(Unit
*u
, Unit
*other
, const char *other_id
, UnitDependency d
) {
727 assert(d
< _UNIT_DEPENDENCY_MAX
);
729 /* Fix backwards pointers */
730 SET_FOREACH(back
, other
->dependencies
[d
], i
) {
733 for (k
= 0; k
< _UNIT_DEPENDENCY_MAX
; k
++) {
734 /* Do not add dependencies between u and itself */
736 if (set_remove(back
->dependencies
[k
], other
))
737 maybe_warn_about_dependency(u
, other_id
, k
);
739 r
= set_remove_and_put(back
->dependencies
[k
], other
, u
);
741 set_remove(back
->dependencies
[k
], other
);
743 assert(r
>= 0 || r
== -ENOENT
);
748 /* Also do not move dependencies on u to itself */
749 back
= set_remove(other
->dependencies
[d
], u
);
751 maybe_warn_about_dependency(u
, other_id
, d
);
753 /* The move cannot fail. The caller must have performed a reservation. */
754 assert_se(complete_move(&u
->dependencies
[d
], &other
->dependencies
[d
]) == 0);
756 other
->dependencies
[d
] = set_free(other
->dependencies
[d
]);
759 int unit_merge(Unit
*u
, Unit
*other
) {
761 const char *other_id
= NULL
;
766 assert(u
->manager
== other
->manager
);
767 assert(u
->type
!= _UNIT_TYPE_INVALID
);
769 other
= unit_follow_merge(other
);
774 if (u
->type
!= other
->type
)
777 if (!u
->instance
!= !other
->instance
)
780 if (!unit_type_may_alias(u
->type
)) /* Merging only applies to unit names that support aliases */
783 if (other
->load_state
!= UNIT_STUB
&&
784 other
->load_state
!= UNIT_NOT_FOUND
)
793 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
797 other_id
= strdupa(other
->id
);
799 /* Make reservations to ensure merge_dependencies() won't fail */
800 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
801 r
= reserve_dependencies(u
, other
, d
);
803 * We don't rollback reservations if we fail. We don't have
804 * a way to undo reservations. A reservation is not a leak.
811 r
= merge_names(u
, other
);
815 /* Redirect all references */
817 unit_ref_set(other
->refs
, u
);
819 /* Merge dependencies */
820 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++)
821 merge_dependencies(u
, other
, other_id
, d
);
823 other
->load_state
= UNIT_MERGED
;
824 other
->merged_into
= u
;
826 /* If there is still some data attached to the other node, we
827 * don't need it anymore, and can free it. */
828 if (other
->load_state
!= UNIT_STUB
)
829 if (UNIT_VTABLE(other
)->done
)
830 UNIT_VTABLE(other
)->done(other
);
832 unit_add_to_dbus_queue(u
);
833 unit_add_to_cleanup_queue(other
);
838 int unit_merge_by_name(Unit
*u
, const char *name
) {
839 _cleanup_free_
char *s
= NULL
;
846 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
850 r
= unit_name_replace_instance(name
, u
->instance
, &s
);
857 other
= manager_get_unit(u
->manager
, name
);
859 return unit_merge(u
, other
);
861 return unit_add_name(u
, name
);
864 Unit
* unit_follow_merge(Unit
*u
) {
867 while (u
->load_state
== UNIT_MERGED
)
868 assert_se(u
= u
->merged_into
);
873 int unit_add_exec_dependencies(Unit
*u
, ExecContext
*c
) {
874 ExecDirectoryType dt
;
881 if (c
->working_directory
) {
882 r
= unit_require_mounts_for(u
, c
->working_directory
);
887 if (c
->root_directory
) {
888 r
= unit_require_mounts_for(u
, c
->root_directory
);
894 r
= unit_require_mounts_for(u
, c
->root_image
);
899 for (dt
= 0; dt
< _EXEC_DIRECTORY_MAX
; dt
++) {
900 if (!u
->manager
->prefix
[dt
])
903 STRV_FOREACH(dp
, c
->directories
[dt
].paths
) {
904 _cleanup_free_
char *p
;
906 p
= strjoin(u
->manager
->prefix
[dt
], "/", *dp
);
910 r
= unit_require_mounts_for(u
, p
);
916 if (!MANAGER_IS_SYSTEM(u
->manager
))
919 if (c
->private_tmp
) {
922 FOREACH_STRING(p
, "/tmp", "/var/tmp") {
923 r
= unit_require_mounts_for(u
, p
);
928 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_TMPFILES_SETUP_SERVICE
, NULL
, true);
933 if (!IN_SET(c
->std_output
,
934 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
935 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
,
936 EXEC_OUTPUT_SYSLOG
, EXEC_OUTPUT_SYSLOG_AND_CONSOLE
) &&
937 !IN_SET(c
->std_error
,
938 EXEC_OUTPUT_JOURNAL
, EXEC_OUTPUT_JOURNAL_AND_CONSOLE
,
939 EXEC_OUTPUT_KMSG
, EXEC_OUTPUT_KMSG_AND_CONSOLE
,
940 EXEC_OUTPUT_SYSLOG
, EXEC_OUTPUT_SYSLOG_AND_CONSOLE
))
943 /* If syslog or kernel logging is requested, make sure our own
944 * logging daemon is run first. */
946 r
= unit_add_dependency_by_name(u
, UNIT_AFTER
, SPECIAL_JOURNALD_SOCKET
, NULL
, true);
953 const char *unit_description(Unit
*u
) {
957 return u
->description
;
962 void unit_dump(Unit
*u
, FILE *f
, const char *prefix
) {
968 timestamp0
[FORMAT_TIMESTAMP_MAX
],
969 timestamp1
[FORMAT_TIMESTAMP_MAX
],
970 timestamp2
[FORMAT_TIMESTAMP_MAX
],
971 timestamp3
[FORMAT_TIMESTAMP_MAX
],
972 timestamp4
[FORMAT_TIMESTAMP_MAX
],
973 timespan
[FORMAT_TIMESPAN_MAX
];
975 _cleanup_set_free_ Set
*following_set
= NULL
;
980 assert(u
->type
>= 0);
982 prefix
= strempty(prefix
);
983 prefix2
= strjoina(prefix
, "\t");
987 "%s\tDescription: %s\n"
989 "%s\tUnit Load State: %s\n"
990 "%s\tUnit Active State: %s\n"
991 "%s\tState Change Timestamp: %s\n"
992 "%s\tInactive Exit Timestamp: %s\n"
993 "%s\tActive Enter Timestamp: %s\n"
994 "%s\tActive Exit Timestamp: %s\n"
995 "%s\tInactive Enter Timestamp: %s\n"
996 "%s\tGC Check Good: %s\n"
997 "%s\tNeed Daemon Reload: %s\n"
998 "%s\tTransient: %s\n"
999 "%s\tPerpetual: %s\n"
1002 "%s\tCGroup realized: %s\n",
1004 prefix
, unit_description(u
),
1005 prefix
, strna(u
->instance
),
1006 prefix
, unit_load_state_to_string(u
->load_state
),
1007 prefix
, unit_active_state_to_string(unit_active_state(u
)),
1008 prefix
, strna(format_timestamp(timestamp0
, sizeof(timestamp0
), u
->state_change_timestamp
.realtime
)),
1009 prefix
, strna(format_timestamp(timestamp1
, sizeof(timestamp1
), u
->inactive_exit_timestamp
.realtime
)),
1010 prefix
, strna(format_timestamp(timestamp2
, sizeof(timestamp2
), u
->active_enter_timestamp
.realtime
)),
1011 prefix
, strna(format_timestamp(timestamp3
, sizeof(timestamp3
), u
->active_exit_timestamp
.realtime
)),
1012 prefix
, strna(format_timestamp(timestamp4
, sizeof(timestamp4
), u
->inactive_enter_timestamp
.realtime
)),
1013 prefix
, yes_no(unit_check_gc(u
)),
1014 prefix
, yes_no(unit_need_daemon_reload(u
)),
1015 prefix
, yes_no(u
->transient
),
1016 prefix
, yes_no(u
->perpetual
),
1017 prefix
, strna(unit_slice_name(u
)),
1018 prefix
, strna(u
->cgroup_path
),
1019 prefix
, yes_no(u
->cgroup_realized
));
1021 if (u
->cgroup_realized_mask
!= 0) {
1022 _cleanup_free_
char *s
= NULL
;
1023 (void) cg_mask_to_string(u
->cgroup_realized_mask
, &s
);
1024 fprintf(f
, "%s\tCGroup mask: %s\n", prefix
, strnull(s
));
1026 if (u
->cgroup_members_mask
!= 0) {
1027 _cleanup_free_
char *s
= NULL
;
1028 (void) cg_mask_to_string(u
->cgroup_members_mask
, &s
);
1029 fprintf(f
, "%s\tCGroup members mask: %s\n", prefix
, strnull(s
));
1032 SET_FOREACH(t
, u
->names
, i
)
1033 fprintf(f
, "%s\tName: %s\n", prefix
, t
);
1035 if (!sd_id128_is_null(u
->invocation_id
))
1036 fprintf(f
, "%s\tInvocation ID: " SD_ID128_FORMAT_STR
"\n",
1037 prefix
, SD_ID128_FORMAT_VAL(u
->invocation_id
));
1039 STRV_FOREACH(j
, u
->documentation
)
1040 fprintf(f
, "%s\tDocumentation: %s\n", prefix
, *j
);
1042 following
= unit_following(u
);
1044 fprintf(f
, "%s\tFollowing: %s\n", prefix
, following
->id
);
1046 r
= unit_following_set(u
, &following_set
);
1050 SET_FOREACH(other
, following_set
, i
)
1051 fprintf(f
, "%s\tFollowing Set Member: %s\n", prefix
, other
->id
);
1054 if (u
->fragment_path
)
1055 fprintf(f
, "%s\tFragment Path: %s\n", prefix
, u
->fragment_path
);
1058 fprintf(f
, "%s\tSource Path: %s\n", prefix
, u
->source_path
);
1060 STRV_FOREACH(j
, u
->dropin_paths
)
1061 fprintf(f
, "%s\tDropIn Path: %s\n", prefix
, *j
);
1063 if (u
->job_timeout
!= USEC_INFINITY
)
1064 fprintf(f
, "%s\tJob Timeout: %s\n", prefix
, format_timespan(timespan
, sizeof(timespan
), u
->job_timeout
, 0));
1066 if (u
->job_timeout_action
!= EMERGENCY_ACTION_NONE
)
1067 fprintf(f
, "%s\tJob Timeout Action: %s\n", prefix
, emergency_action_to_string(u
->job_timeout_action
));
1069 if (u
->job_timeout_reboot_arg
)
1070 fprintf(f
, "%s\tJob Timeout Reboot Argument: %s\n", prefix
, u
->job_timeout_reboot_arg
);
1072 condition_dump_list(u
->conditions
, f
, prefix
, condition_type_to_string
);
1073 condition_dump_list(u
->asserts
, f
, prefix
, assert_type_to_string
);
1075 if (dual_timestamp_is_set(&u
->condition_timestamp
))
1077 "%s\tCondition Timestamp: %s\n"
1078 "%s\tCondition Result: %s\n",
1079 prefix
, strna(format_timestamp(timestamp1
, sizeof(timestamp1
), u
->condition_timestamp
.realtime
)),
1080 prefix
, yes_no(u
->condition_result
));
1082 if (dual_timestamp_is_set(&u
->assert_timestamp
))
1084 "%s\tAssert Timestamp: %s\n"
1085 "%s\tAssert Result: %s\n",
1086 prefix
, strna(format_timestamp(timestamp1
, sizeof(timestamp1
), u
->assert_timestamp
.realtime
)),
1087 prefix
, yes_no(u
->assert_result
));
1089 for (d
= 0; d
< _UNIT_DEPENDENCY_MAX
; d
++) {
1092 SET_FOREACH(other
, u
->dependencies
[d
], i
)
1093 fprintf(f
, "%s\t%s: %s\n", prefix
, unit_dependency_to_string(d
), other
->id
);
1096 if (!strv_isempty(u
->requires_mounts_for
)) {
1098 "%s\tRequiresMountsFor:", prefix
);
1100 STRV_FOREACH(j
, u
->requires_mounts_for
)
1101 fprintf(f
, " %s", *j
);
1106 if (u
->load_state
== UNIT_LOADED
) {
1109 "%s\tStopWhenUnneeded: %s\n"
1110 "%s\tRefuseManualStart: %s\n"
1111 "%s\tRefuseManualStop: %s\n"
1112 "%s\tDefaultDependencies: %s\n"
1113 "%s\tOnFailureJobMode: %s\n"
1114 "%s\tIgnoreOnIsolate: %s\n",
1115 prefix
, yes_no(u
->stop_when_unneeded
),
1116 prefix
, yes_no(u
->refuse_manual_start
),
1117 prefix
, yes_no(u
->refuse_manual_stop
),
1118 prefix
, yes_no(u
->default_dependencies
),
1119 prefix
, job_mode_to_string(u
->on_failure_job_mode
),
1120 prefix
, yes_no(u
->ignore_on_isolate
));
1122 if (UNIT_VTABLE(u
)->dump
)
1123 UNIT_VTABLE(u
)->dump(u
, f
, prefix2
);
1125 } else if (u
->load_state
== UNIT_MERGED
)
1127 "%s\tMerged into: %s\n",
1128 prefix
, u
->merged_into
->id
);
1129 else if (u
->load_state
== UNIT_ERROR
)
1130 fprintf(f
, "%s\tLoad Error Code: %s\n", prefix
, strerror(-u
->load_error
));
1132 for (n
= sd_bus_track_first(u
->bus_track
); n
; n
= sd_bus_track_next(u
->bus_track
))
1133 fprintf(f
, "%s\tBus Ref: %s\n", prefix
, n
);
1136 job_dump(u
->job
, f
, prefix2
);
1139 job_dump(u
->nop_job
, f
, prefix2
);
1142 /* Common implementation for multiple backends */
1143 int unit_load_fragment_and_dropin(Unit
*u
) {
1148 /* Load a .{service,socket,...} file */
1149 r
= unit_load_fragment(u
);
1153 if (u
->load_state
== UNIT_STUB
)
1156 /* Load drop-in directory data. If u is an alias, we might be reloading the
1157 * target unit needlessly. But we cannot be sure which drops-ins have already
1158 * been loaded and which not, at least without doing complicated book-keeping,
1159 * so let's always reread all drop-ins. */
1160 return unit_load_dropin(unit_follow_merge(u
));
1163 /* Common implementation for multiple backends */
1164 int unit_load_fragment_and_dropin_optional(Unit
*u
) {
1169 /* Same as unit_load_fragment_and_dropin(), but whether
1170 * something can be loaded or not doesn't matter. */
1172 /* Load a .service file */
1173 r
= unit_load_fragment(u
);
1177 if (u
->load_state
== UNIT_STUB
)
1178 u
->load_state
= UNIT_LOADED
;
1180 /* Load drop-in directory data */
1181 return unit_load_dropin(unit_follow_merge(u
));
1184 int unit_add_default_target_dependency(Unit
*u
, Unit
*target
) {
1188 if (target
->type
!= UNIT_TARGET
)
1191 /* Only add the dependency if both units are loaded, so that
1192 * that loop check below is reliable */
1193 if (u
->load_state
!= UNIT_LOADED
||
1194 target
->load_state
!= UNIT_LOADED
)
1197 /* If either side wants no automatic dependencies, then let's
1199 if (!u
->default_dependencies
||
1200 !target
->default_dependencies
)
1203 /* Don't create loops */
1204 if (set_get(target
->dependencies
[UNIT_BEFORE
], u
))
1207 return unit_add_dependency(target
, UNIT_AFTER
, u
, true);
1210 static int unit_add_target_dependencies(Unit
*u
) {
1212 static const UnitDependency deps
[] = {
1226 for (k
= 0; k
< ELEMENTSOF(deps
); k
++)
1227 SET_FOREACH(target
, u
->dependencies
[deps
[k
]], i
) {
1228 r
= unit_add_default_target_dependency(u
, target
);
1236 static int unit_add_slice_dependencies(Unit
*u
) {
1239 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1242 if (UNIT_ISSET(u
->slice
))
1243 return unit_add_two_dependencies(u
, UNIT_AFTER
, UNIT_REQUIRES
, UNIT_DEREF(u
->slice
), true);
1245 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1248 return unit_add_two_dependencies_by_name(u
, UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_ROOT_SLICE
, NULL
, true);
1251 static int unit_add_mount_dependencies(Unit
*u
) {
1257 STRV_FOREACH(i
, u
->requires_mounts_for
) {
1258 char prefix
[strlen(*i
) + 1];
1260 PATH_FOREACH_PREFIX_MORE(prefix
, *i
) {
1261 _cleanup_free_
char *p
= NULL
;
1264 r
= unit_name_from_path(prefix
, ".mount", &p
);
1268 m
= manager_get_unit(u
->manager
, p
);
1270 /* Make sure to load the mount unit if
1271 * it exists. If so the dependencies
1272 * on this unit will be added later
1273 * during the loading of the mount
1275 (void) manager_load_unit_prepare(u
->manager
, p
, NULL
, NULL
, &m
);
1281 if (m
->load_state
!= UNIT_LOADED
)
1284 r
= unit_add_dependency(u
, UNIT_AFTER
, m
, true);
1288 if (m
->fragment_path
) {
1289 r
= unit_add_dependency(u
, UNIT_REQUIRES
, m
, true);
1299 static int unit_add_startup_units(Unit
*u
) {
1303 c
= unit_get_cgroup_context(u
);
1307 if (c
->startup_cpu_shares
== CGROUP_CPU_SHARES_INVALID
&&
1308 c
->startup_io_weight
== CGROUP_WEIGHT_INVALID
&&
1309 c
->startup_blockio_weight
== CGROUP_BLKIO_WEIGHT_INVALID
)
1312 r
= set_ensure_allocated(&u
->manager
->startup_units
, NULL
);
1316 return set_put(u
->manager
->startup_units
, u
);
1319 int unit_load(Unit
*u
) {
1324 if (u
->in_load_queue
) {
1325 LIST_REMOVE(load_queue
, u
->manager
->load_queue
, u
);
1326 u
->in_load_queue
= false;
1329 if (u
->type
== _UNIT_TYPE_INVALID
)
1332 if (u
->load_state
!= UNIT_STUB
)
1335 if (u
->transient_file
) {
1336 r
= fflush_and_check(u
->transient_file
);
1340 fclose(u
->transient_file
);
1341 u
->transient_file
= NULL
;
1343 u
->fragment_mtime
= now(CLOCK_REALTIME
);
1346 if (UNIT_VTABLE(u
)->load
) {
1347 r
= UNIT_VTABLE(u
)->load(u
);
1352 if (u
->load_state
== UNIT_STUB
) {
1357 if (u
->load_state
== UNIT_LOADED
) {
1359 r
= unit_add_target_dependencies(u
);
1363 r
= unit_add_slice_dependencies(u
);
1367 r
= unit_add_mount_dependencies(u
);
1371 r
= unit_add_startup_units(u
);
1375 if (u
->on_failure_job_mode
== JOB_ISOLATE
&& set_size(u
->dependencies
[UNIT_ON_FAILURE
]) > 1) {
1376 log_unit_error(u
, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
1381 if (u
->job_running_timeout
!= USEC_INFINITY
&& u
->job_running_timeout
> u
->job_timeout
)
1382 log_unit_warning(u
, "JobRunningTimeoutSec= is greater than JobTimeoutSec=, it has no effect.");
1384 unit_update_cgroup_members_masks(u
);
1387 assert((u
->load_state
!= UNIT_MERGED
) == !u
->merged_into
);
1389 unit_add_to_dbus_queue(unit_follow_merge(u
));
1390 unit_add_to_gc_queue(u
);
1395 u
->load_state
= u
->load_state
== UNIT_STUB
? UNIT_NOT_FOUND
: UNIT_ERROR
;
1397 unit_add_to_dbus_queue(u
);
1398 unit_add_to_gc_queue(u
);
1400 log_unit_debug_errno(u
, r
, "Failed to load configuration: %m");
1405 static bool unit_condition_test_list(Unit
*u
, Condition
*first
, const char *(*to_string
)(ConditionType t
)) {
1412 /* If the condition list is empty, then it is true */
1416 /* Otherwise, if all of the non-trigger conditions apply and
1417 * if any of the trigger conditions apply (unless there are
1418 * none) we return true */
1419 LIST_FOREACH(conditions
, c
, first
) {
1422 r
= condition_test(c
);
1425 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1427 c
->trigger
? "|" : "",
1428 c
->negate
? "!" : "",
1434 c
->trigger
? "|" : "",
1435 c
->negate
? "!" : "",
1437 condition_result_to_string(c
->result
));
1439 if (!c
->trigger
&& r
<= 0)
1442 if (c
->trigger
&& triggered
<= 0)
1446 return triggered
!= 0;
1449 static bool unit_condition_test(Unit
*u
) {
1452 dual_timestamp_get(&u
->condition_timestamp
);
1453 u
->condition_result
= unit_condition_test_list(u
, u
->conditions
, condition_type_to_string
);
1455 return u
->condition_result
;
1458 static bool unit_assert_test(Unit
*u
) {
1461 dual_timestamp_get(&u
->assert_timestamp
);
1462 u
->assert_result
= unit_condition_test_list(u
, u
->asserts
, assert_type_to_string
);
1464 return u
->assert_result
;
1467 void unit_status_printf(Unit
*u
, const char *status
, const char *unit_status_msg_format
) {
1468 DISABLE_WARNING_FORMAT_NONLITERAL
;
1469 manager_status_printf(u
->manager
, STATUS_TYPE_NORMAL
, status
, unit_status_msg_format
, unit_description(u
));
1473 _pure_
static const char* unit_get_status_message_format(Unit
*u
, JobType t
) {
1475 const UnitStatusMessageFormats
*format_table
;
1478 assert(IN_SET(t
, JOB_START
, JOB_STOP
, JOB_RELOAD
));
1480 if (t
!= JOB_RELOAD
) {
1481 format_table
= &UNIT_VTABLE(u
)->status_message_formats
;
1483 format
= format_table
->starting_stopping
[t
== JOB_STOP
];
1489 /* Return generic strings */
1491 return "Starting %s.";
1492 else if (t
== JOB_STOP
)
1493 return "Stopping %s.";
1495 return "Reloading %s.";
1498 static void unit_status_print_starting_stopping(Unit
*u
, JobType t
) {
1503 /* Reload status messages have traditionally not been printed to console. */
1504 if (!IN_SET(t
, JOB_START
, JOB_STOP
))
1507 format
= unit_get_status_message_format(u
, t
);
1509 DISABLE_WARNING_FORMAT_NONLITERAL
;
1510 unit_status_printf(u
, "", format
);
1514 static void unit_status_log_starting_stopping_reloading(Unit
*u
, JobType t
) {
1515 const char *format
, *mid
;
1520 if (!IN_SET(t
, JOB_START
, JOB_STOP
, JOB_RELOAD
))
1523 if (log_on_console())
1526 /* We log status messages for all units and all operations. */
1528 format
= unit_get_status_message_format(u
, t
);
1530 DISABLE_WARNING_FORMAT_NONLITERAL
;
1531 snprintf(buf
, sizeof buf
, format
, unit_description(u
));
1534 mid
= t
== JOB_START
? "MESSAGE_ID=" SD_MESSAGE_UNIT_STARTING_STR
:
1535 t
== JOB_STOP
? "MESSAGE_ID=" SD_MESSAGE_UNIT_STOPPING_STR
:
1536 "MESSAGE_ID=" SD_MESSAGE_UNIT_RELOADING_STR
;
1538 /* Note that we deliberately use LOG_MESSAGE() instead of
1539 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
1540 * closely what is written to screen using the status output,
1541 * which is supposed the highest level, friendliest output
1542 * possible, which means we should avoid the low-level unit
1544 log_struct(LOG_INFO
,
1545 LOG_MESSAGE("%s", buf
),
1551 void unit_status_emit_starting_stopping_reloading(Unit
*u
, JobType t
) {
1554 assert(t
< _JOB_TYPE_MAX
);
1556 unit_status_log_starting_stopping_reloading(u
, t
);
1557 unit_status_print_starting_stopping(u
, t
);
1560 int unit_start_limit_test(Unit
*u
) {
1563 if (ratelimit_test(&u
->start_limit
)) {
1564 u
->start_limit_hit
= false;
1568 log_unit_warning(u
, "Start request repeated too quickly.");
1569 u
->start_limit_hit
= true;
1571 return emergency_action(u
->manager
, u
->start_limit_action
, u
->reboot_arg
, "unit failed");
1574 bool unit_shall_confirm_spawn(Unit
*u
) {
1577 if (manager_is_confirm_spawn_disabled(u
->manager
))
1580 /* For some reasons units remaining in the same process group
1581 * as PID 1 fail to acquire the console even if it's not used
1582 * by any process. So skip the confirmation question for them. */
1583 return !unit_get_exec_context(u
)->same_pgrp
;
1586 static bool unit_verify_deps(Unit
*u
) {
1592 /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined with
1593 * After=. We do not check Requires= or Requisite= here as they only should have an effect on the job
1594 * processing, but do not have any effect afterwards. We don't check BindsTo= dependencies that are not used in
1595 * conjunction with After= as for them any such check would make things entirely racy. */
1597 SET_FOREACH(other
, u
->dependencies
[UNIT_BINDS_TO
], j
) {
1599 if (!set_contains(u
->dependencies
[UNIT_AFTER
], other
))
1602 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other
))) {
1603 log_unit_notice(u
, "Bound to unit %s, but unit isn't active.", other
->id
);
1612 * -EBADR: This unit type does not support starting.
1613 * -EALREADY: Unit is already started.
1614 * -EAGAIN: An operation is already in progress. Retry later.
1615 * -ECANCELED: Too many requests for now.
1616 * -EPROTO: Assert failed
1617 * -EINVAL: Unit not loaded
1618 * -EOPNOTSUPP: Unit type not supported
1619 * -ENOLINK: The necessary dependencies are not fulfilled.
1621 int unit_start(Unit
*u
) {
1622 UnitActiveState state
;
1627 /* If this is already started, then this will succeed. Note
1628 * that this will even succeed if this unit is not startable
1629 * by the user. This is relied on to detect when we need to
1630 * wait for units and when waiting is finished. */
1631 state
= unit_active_state(u
);
1632 if (UNIT_IS_ACTIVE_OR_RELOADING(state
))
1635 /* Units that aren't loaded cannot be started */
1636 if (u
->load_state
!= UNIT_LOADED
)
1639 /* If the conditions failed, don't do anything at all. If we
1640 * already are activating this call might still be useful to
1641 * speed up activation in case there is some hold-off time,
1642 * but we don't want to recheck the condition in that case. */
1643 if (state
!= UNIT_ACTIVATING
&&
1644 !unit_condition_test(u
)) {
1645 log_unit_debug(u
, "Starting requested but condition failed. Not starting unit.");
1649 /* If the asserts failed, fail the entire job */
1650 if (state
!= UNIT_ACTIVATING
&&
1651 !unit_assert_test(u
)) {
1652 log_unit_notice(u
, "Starting requested but asserts failed.");
1656 /* Units of types that aren't supported cannot be
1657 * started. Note that we do this test only after the condition
1658 * checks, so that we rather return condition check errors
1659 * (which are usually not considered a true failure) than "not
1660 * supported" errors (which are considered a failure).
1662 if (!unit_supported(u
))
1665 /* Let's make sure that the deps really are in order before we start this. Normally the job engine should have
1666 * taken care of this already, but let's check this here again. After all, our dependencies might not be in
1667 * effect anymore, due to a reload or due to a failed condition. */
1668 if (!unit_verify_deps(u
))
1671 /* Forward to the main object, if we aren't it. */
1672 following
= unit_following(u
);
1674 log_unit_debug(u
, "Redirecting start request from %s to %s.", u
->id
, following
->id
);
1675 return unit_start(following
);
1678 /* If it is stopped, but we cannot start it, then fail */
1679 if (!UNIT_VTABLE(u
)->start
)
1682 /* We don't suppress calls to ->start() here when we are
1683 * already starting, to allow this request to be used as a
1684 * "hurry up" call, for example when the unit is in some "auto
1685 * restart" state where it waits for a holdoff timer to elapse
1686 * before it will start again. */
1688 unit_add_to_dbus_queue(u
);
1690 return UNIT_VTABLE(u
)->start(u
);
1693 bool unit_can_start(Unit
*u
) {
1696 if (u
->load_state
!= UNIT_LOADED
)
1699 if (!unit_supported(u
))
1702 return !!UNIT_VTABLE(u
)->start
;
1705 bool unit_can_isolate(Unit
*u
) {
1708 return unit_can_start(u
) &&
1713 * -EBADR: This unit type does not support stopping.
1714 * -EALREADY: Unit is already stopped.
1715 * -EAGAIN: An operation is already in progress. Retry later.
1717 int unit_stop(Unit
*u
) {
1718 UnitActiveState state
;
1723 state
= unit_active_state(u
);
1724 if (UNIT_IS_INACTIVE_OR_FAILED(state
))
1727 following
= unit_following(u
);
1729 log_unit_debug(u
, "Redirecting stop request from %s to %s.", u
->id
, following
->id
);
1730 return unit_stop(following
);
1733 if (!UNIT_VTABLE(u
)->stop
)
1736 unit_add_to_dbus_queue(u
);
1738 return UNIT_VTABLE(u
)->stop(u
);
1741 bool unit_can_stop(Unit
*u
) {
1744 if (!unit_supported(u
))
1750 return !!UNIT_VTABLE(u
)->stop
;
1754 * -EBADR: This unit type does not support reloading.
1755 * -ENOEXEC: Unit is not started.
1756 * -EAGAIN: An operation is already in progress. Retry later.
1758 int unit_reload(Unit
*u
) {
1759 UnitActiveState state
;
1764 if (u
->load_state
!= UNIT_LOADED
)
1767 if (!unit_can_reload(u
))
1770 state
= unit_active_state(u
);
1771 if (state
== UNIT_RELOADING
)
1774 if (state
!= UNIT_ACTIVE
) {
1775 log_unit_warning(u
, "Unit cannot be reloaded because it is inactive.");
1779 following
= unit_following(u
);
1781 log_unit_debug(u
, "Redirecting reload request from %s to %s.", u
->id
, following
->id
);
1782 return unit_reload(following
);
1785 unit_add_to_dbus_queue(u
);
1787 if (!UNIT_VTABLE(u
)->reload
) {
1788 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
1789 unit_notify(u
, unit_active_state(u
), unit_active_state(u
), true);
1793 return UNIT_VTABLE(u
)->reload(u
);
1796 bool unit_can_reload(Unit
*u
) {
1799 if (UNIT_VTABLE(u
)->can_reload
)
1800 return UNIT_VTABLE(u
)->can_reload(u
);
1802 if (!set_isempty(u
->dependencies
[UNIT_PROPAGATES_RELOAD_TO
]))
1805 return UNIT_VTABLE(u
)->reload
;
1808 static void unit_check_unneeded(Unit
*u
) {
1810 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1812 static const UnitDependency needed_dependencies
[] = {
1826 /* If this service shall be shut down when unneeded then do
1829 if (!u
->stop_when_unneeded
)
1832 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)))
1835 for (j
= 0; j
< ELEMENTSOF(needed_dependencies
); j
++)
1836 SET_FOREACH(other
, u
->dependencies
[needed_dependencies
[j
]], i
)
1837 if (unit_active_or_pending(other
))
1840 /* If stopping a unit fails continuously we might enter a stop
1841 * loop here, hence stop acting on the service being
1842 * unnecessary after a while. */
1843 if (!ratelimit_test(&u
->auto_stop_ratelimit
)) {
1844 log_unit_warning(u
, "Unit not needed anymore, but not stopping since we tried this too often recently.");
1848 log_unit_info(u
, "Unit not needed anymore. Stopping.");
1850 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1851 r
= manager_add_job(u
->manager
, JOB_STOP
, u
, JOB_FAIL
, &error
, NULL
);
1853 log_unit_warning_errno(u
, r
, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error
, r
));
1856 static void unit_check_binds_to(Unit
*u
) {
1857 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1868 if (unit_active_state(u
) != UNIT_ACTIVE
)
1871 SET_FOREACH(other
, u
->dependencies
[UNIT_BINDS_TO
], i
) {
1875 if (!other
->coldplugged
)
1876 /* We might yet create a job for the other unit… */
1879 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
)))
1889 /* If stopping a unit fails continuously we might enter a stop
1890 * loop here, hence stop acting on the service being
1891 * unnecessary after a while. */
1892 if (!ratelimit_test(&u
->auto_stop_ratelimit
)) {
1893 log_unit_warning(u
, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other
->id
);
1898 log_unit_info(u
, "Unit is bound to inactive unit %s. Stopping, too.", other
->id
);
1900 /* A unit we need to run is gone. Sniff. Let's stop this. */
1901 r
= manager_add_job(u
->manager
, JOB_STOP
, u
, JOB_FAIL
, &error
, NULL
);
1903 log_unit_warning_errno(u
, r
, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error
, r
));
1906 static void retroactively_start_dependencies(Unit
*u
) {
1911 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)));
1913 SET_FOREACH(other
, u
->dependencies
[UNIT_REQUIRES
], i
)
1914 if (!set_get(u
->dependencies
[UNIT_AFTER
], other
) &&
1915 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
1916 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
);
1918 SET_FOREACH(other
, u
->dependencies
[UNIT_BINDS_TO
], i
)
1919 if (!set_get(u
->dependencies
[UNIT_AFTER
], other
) &&
1920 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
1921 manager_add_job(u
->manager
, JOB_START
, other
, JOB_REPLACE
, NULL
, NULL
);
1923 SET_FOREACH(other
, u
->dependencies
[UNIT_WANTS
], i
)
1924 if (!set_get(u
->dependencies
[UNIT_AFTER
], other
) &&
1925 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other
)))
1926 manager_add_job(u
->manager
, JOB_START
, other
, JOB_FAIL
, NULL
, NULL
);
1928 SET_FOREACH(other
, u
->dependencies
[UNIT_CONFLICTS
], i
)
1929 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1930 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
);
1932 SET_FOREACH(other
, u
->dependencies
[UNIT_CONFLICTED_BY
], i
)
1933 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1934 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
);
1937 static void retroactively_stop_dependencies(Unit
*u
) {
1942 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)));
1944 /* Pull down units which are bound to us recursively if enabled */
1945 SET_FOREACH(other
, u
->dependencies
[UNIT_BOUND_BY
], i
)
1946 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1947 manager_add_job(u
->manager
, JOB_STOP
, other
, JOB_REPLACE
, NULL
, NULL
);
1950 static void check_unneeded_dependencies(Unit
*u
) {
1955 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)));
1957 /* Garbage collect services that might not be needed anymore, if enabled */
1958 SET_FOREACH(other
, u
->dependencies
[UNIT_REQUIRES
], i
)
1959 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1960 unit_check_unneeded(other
);
1961 SET_FOREACH(other
, u
->dependencies
[UNIT_WANTS
], i
)
1962 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1963 unit_check_unneeded(other
);
1964 SET_FOREACH(other
, u
->dependencies
[UNIT_REQUISITE
], i
)
1965 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1966 unit_check_unneeded(other
);
1967 SET_FOREACH(other
, u
->dependencies
[UNIT_BINDS_TO
], i
)
1968 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other
)))
1969 unit_check_unneeded(other
);
1972 void unit_start_on_failure(Unit
*u
) {
1978 if (set_size(u
->dependencies
[UNIT_ON_FAILURE
]) <= 0)
1981 log_unit_info(u
, "Triggering OnFailure= dependencies.");
1983 SET_FOREACH(other
, u
->dependencies
[UNIT_ON_FAILURE
], i
) {
1986 r
= manager_add_job(u
->manager
, JOB_START
, other
, u
->on_failure_job_mode
, NULL
, NULL
);
1988 log_unit_error_errno(u
, r
, "Failed to enqueue OnFailure= job: %m");
1992 void unit_trigger_notify(Unit
*u
) {
1998 SET_FOREACH(other
, u
->dependencies
[UNIT_TRIGGERED_BY
], i
)
1999 if (UNIT_VTABLE(other
)->trigger_notify
)
2000 UNIT_VTABLE(other
)->trigger_notify(other
, u
);
2003 void unit_notify(Unit
*u
, UnitActiveState os
, UnitActiveState ns
, bool reload_success
) {
2008 assert(os
< _UNIT_ACTIVE_STATE_MAX
);
2009 assert(ns
< _UNIT_ACTIVE_STATE_MAX
);
2011 /* Note that this is called for all low-level state changes,
2012 * even if they might map to the same high-level
2013 * UnitActiveState! That means that ns == os is an expected
2014 * behavior here. For example: if a mount point is remounted
2015 * this function will be called too! */
2019 /* Update timestamps for state changes */
2020 if (!MANAGER_IS_RELOADING(m
)) {
2021 dual_timestamp_get(&u
->state_change_timestamp
);
2023 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && !UNIT_IS_INACTIVE_OR_FAILED(ns
))
2024 u
->inactive_exit_timestamp
= u
->state_change_timestamp
;
2025 else if (!UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_INACTIVE_OR_FAILED(ns
))
2026 u
->inactive_enter_timestamp
= u
->state_change_timestamp
;
2028 if (!UNIT_IS_ACTIVE_OR_RELOADING(os
) && UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2029 u
->active_enter_timestamp
= u
->state_change_timestamp
;
2030 else if (UNIT_IS_ACTIVE_OR_RELOADING(os
) && !UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2031 u
->active_exit_timestamp
= u
->state_change_timestamp
;
2034 /* Keep track of failed units */
2035 (void) manager_update_failed_units(u
->manager
, u
, ns
== UNIT_FAILED
);
2037 /* Make sure the cgroup is always removed when we become inactive */
2038 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2039 unit_prune_cgroup(u
);
2041 /* Note that this doesn't apply to RemainAfterExit services exiting
2042 * successfully, since there's no change of state in that case. Which is
2043 * why it is handled in service_set_state() */
2044 if (UNIT_IS_INACTIVE_OR_FAILED(os
) != UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2047 ec
= unit_get_exec_context(u
);
2048 if (ec
&& exec_context_may_touch_console(ec
)) {
2049 if (UNIT_IS_INACTIVE_OR_FAILED(ns
)) {
2052 if (m
->n_on_console
== 0)
2053 /* unset no_console_output flag, since the console is free */
2054 m
->no_console_output
= false;
2063 if (u
->job
->state
== JOB_WAITING
)
2065 /* So we reached a different state for this
2066 * job. Let's see if we can run it now if it
2067 * failed previously due to EAGAIN. */
2068 job_add_to_run_queue(u
->job
);
2070 /* Let's check whether this state change constitutes a
2071 * finished job, or maybe contradicts a running job and
2072 * hence needs to invalidate jobs. */
2074 switch (u
->job
->type
) {
2077 case JOB_VERIFY_ACTIVE
:
2079 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
))
2080 job_finish_and_invalidate(u
->job
, JOB_DONE
, true, false);
2081 else if (u
->job
->state
== JOB_RUNNING
&& ns
!= UNIT_ACTIVATING
) {
2084 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2085 job_finish_and_invalidate(u
->job
, ns
== UNIT_FAILED
? JOB_FAILED
: JOB_DONE
, true, false);
2091 case JOB_RELOAD_OR_START
:
2092 case JOB_TRY_RELOAD
:
2094 if (u
->job
->state
== JOB_RUNNING
) {
2095 if (ns
== UNIT_ACTIVE
)
2096 job_finish_and_invalidate(u
->job
, reload_success
? JOB_DONE
: JOB_FAILED
, true, false);
2097 else if (ns
!= UNIT_ACTIVATING
&& ns
!= UNIT_RELOADING
) {
2100 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2101 job_finish_and_invalidate(u
->job
, ns
== UNIT_FAILED
? JOB_FAILED
: JOB_DONE
, true, false);
2109 case JOB_TRY_RESTART
:
2111 if (UNIT_IS_INACTIVE_OR_FAILED(ns
))
2112 job_finish_and_invalidate(u
->job
, JOB_DONE
, true, false);
2113 else if (u
->job
->state
== JOB_RUNNING
&& ns
!= UNIT_DEACTIVATING
) {
2115 job_finish_and_invalidate(u
->job
, JOB_FAILED
, true, false);
2121 assert_not_reached("Job type unknown");
2127 if (!MANAGER_IS_RELOADING(m
)) {
2129 /* If this state change happened without being
2130 * requested by a job, then let's retroactively start
2131 * or stop dependencies. We skip that step when
2132 * deserializing, since we don't want to create any
2133 * additional jobs just because something is already
2137 if (UNIT_IS_INACTIVE_OR_FAILED(os
) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns
))
2138 retroactively_start_dependencies(u
);
2139 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os
) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns
))
2140 retroactively_stop_dependencies(u
);
2143 /* stop unneeded units regardless if going down was expected or not */
2144 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns
))
2145 check_unneeded_dependencies(u
);
2147 if (ns
!= os
&& ns
== UNIT_FAILED
) {
2148 log_unit_notice(u
, "Unit entered failed state.");
2149 unit_start_on_failure(u
);
2153 /* Some names are special */
2154 if (UNIT_IS_ACTIVE_OR_RELOADING(ns
)) {
2156 if (unit_has_name(u
, SPECIAL_DBUS_SERVICE
))
2157 /* The bus might have just become available,
2158 * hence try to connect to it, if we aren't
2162 if (u
->type
== UNIT_SERVICE
&&
2163 !UNIT_IS_ACTIVE_OR_RELOADING(os
) &&
2164 !MANAGER_IS_RELOADING(m
)) {
2165 /* Write audit record if we have just finished starting up */
2166 manager_send_unit_audit(m
, u
, AUDIT_SERVICE_START
, true);
2170 if (!UNIT_IS_ACTIVE_OR_RELOADING(os
))
2171 manager_send_unit_plymouth(m
, u
);
2175 /* We don't care about D-Bus here, since we'll get an
2176 * asynchronous notification for it anyway. */
2178 if (u
->type
== UNIT_SERVICE
&&
2179 UNIT_IS_INACTIVE_OR_FAILED(ns
) &&
2180 !UNIT_IS_INACTIVE_OR_FAILED(os
) &&
2181 !MANAGER_IS_RELOADING(m
)) {
2183 /* Hmm, if there was no start record written
2184 * write it now, so that we always have a nice
2187 manager_send_unit_audit(m
, u
, AUDIT_SERVICE_START
, ns
== UNIT_INACTIVE
);
2189 if (ns
== UNIT_INACTIVE
)
2190 manager_send_unit_audit(m
, u
, AUDIT_SERVICE_STOP
, true);
2192 /* Write audit record if we have just finished shutting down */
2193 manager_send_unit_audit(m
, u
, AUDIT_SERVICE_STOP
, ns
== UNIT_INACTIVE
);
2195 u
->in_audit
= false;
2199 manager_recheck_journal(m
);
2200 unit_trigger_notify(u
);
2202 if (!MANAGER_IS_RELOADING(u
->manager
)) {
2203 /* Maybe we finished startup and are now ready for
2204 * being stopped because unneeded? */
2205 unit_check_unneeded(u
);
2207 /* Maybe we finished startup, but something we needed
2208 * has vanished? Let's die then. (This happens when
2209 * something BindsTo= to a Type=oneshot unit, as these
2210 * units go directly from starting to inactive,
2211 * without ever entering started.) */
2212 unit_check_binds_to(u
);
2215 unit_add_to_dbus_queue(u
);
2216 unit_add_to_gc_queue(u
);
2219 int unit_watch_pid(Unit
*u
, pid_t pid
) {
2225 /* Watch a specific PID. We only support one or two units
2226 * watching each PID for now, not more. */
2228 r
= set_ensure_allocated(&u
->pids
, NULL
);
2232 r
= hashmap_ensure_allocated(&u
->manager
->watch_pids1
, NULL
);
2236 r
= hashmap_put(u
->manager
->watch_pids1
, PID_TO_PTR(pid
), u
);
2238 r
= hashmap_ensure_allocated(&u
->manager
->watch_pids2
, NULL
);
2242 r
= hashmap_put(u
->manager
->watch_pids2
, PID_TO_PTR(pid
), u
);
2245 q
= set_put(u
->pids
, PID_TO_PTR(pid
));
2252 void unit_unwatch_pid(Unit
*u
, pid_t pid
) {
2256 (void) hashmap_remove_value(u
->manager
->watch_pids1
, PID_TO_PTR(pid
), u
);
2257 (void) hashmap_remove_value(u
->manager
->watch_pids2
, PID_TO_PTR(pid
), u
);
2258 (void) set_remove(u
->pids
, PID_TO_PTR(pid
));
2261 void unit_unwatch_all_pids(Unit
*u
) {
2264 while (!set_isempty(u
->pids
))
2265 unit_unwatch_pid(u
, PTR_TO_PID(set_first(u
->pids
)));
2267 u
->pids
= set_free(u
->pids
);
2270 void unit_tidy_watch_pids(Unit
*u
, pid_t except1
, pid_t except2
) {
2276 /* Cleans dead PIDs from our list */
2278 SET_FOREACH(e
, u
->pids
, i
) {
2279 pid_t pid
= PTR_TO_PID(e
);
2281 if (pid
== except1
|| pid
== except2
)
2284 if (!pid_is_unwaited(pid
))
2285 unit_unwatch_pid(u
, pid
);
2289 bool unit_job_is_applicable(Unit
*u
, JobType j
) {
2291 assert(j
>= 0 && j
< _JOB_TYPE_MAX
);
2295 case JOB_VERIFY_ACTIVE
:
2298 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
2299 * startable by us but may appear due to external events, and it thus makes sense to permit enqueing
2304 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
2305 * external events), hence it makes no sense to permit enqueing such a request either. */
2306 return !u
->perpetual
;
2309 case JOB_TRY_RESTART
:
2310 return unit_can_stop(u
) && unit_can_start(u
);
2313 case JOB_TRY_RELOAD
:
2314 return unit_can_reload(u
);
2316 case JOB_RELOAD_OR_START
:
2317 return unit_can_reload(u
) && unit_can_start(u
);
2320 assert_not_reached("Invalid job type");
2324 static void maybe_warn_about_dependency(Unit
*u
, const char *other
, UnitDependency dependency
) {
2327 /* Only warn about some unit types */
2328 if (!IN_SET(dependency
, UNIT_CONFLICTS
, UNIT_CONFLICTED_BY
, UNIT_BEFORE
, UNIT_AFTER
, UNIT_ON_FAILURE
, UNIT_TRIGGERS
, UNIT_TRIGGERED_BY
))
2331 if (streq_ptr(u
->id
, other
))
2332 log_unit_warning(u
, "Dependency %s=%s dropped", unit_dependency_to_string(dependency
), u
->id
);
2334 log_unit_warning(u
, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency
), strna(other
), u
->id
);
2337 int unit_add_dependency(Unit
*u
, UnitDependency d
, Unit
*other
, bool add_reference
) {
2339 static const UnitDependency inverse_table
[_UNIT_DEPENDENCY_MAX
] = {
2340 [UNIT_REQUIRES
] = UNIT_REQUIRED_BY
,
2341 [UNIT_WANTS
] = UNIT_WANTED_BY
,
2342 [UNIT_REQUISITE
] = UNIT_REQUISITE_OF
,
2343 [UNIT_BINDS_TO
] = UNIT_BOUND_BY
,
2344 [UNIT_PART_OF
] = UNIT_CONSISTS_OF
,
2345 [UNIT_REQUIRED_BY
] = UNIT_REQUIRES
,
2346 [UNIT_REQUISITE_OF
] = UNIT_REQUISITE
,
2347 [UNIT_WANTED_BY
] = UNIT_WANTS
,
2348 [UNIT_BOUND_BY
] = UNIT_BINDS_TO
,
2349 [UNIT_CONSISTS_OF
] = UNIT_PART_OF
,
2350 [UNIT_CONFLICTS
] = UNIT_CONFLICTED_BY
,
2351 [UNIT_CONFLICTED_BY
] = UNIT_CONFLICTS
,
2352 [UNIT_BEFORE
] = UNIT_AFTER
,
2353 [UNIT_AFTER
] = UNIT_BEFORE
,
2354 [UNIT_ON_FAILURE
] = _UNIT_DEPENDENCY_INVALID
,
2355 [UNIT_REFERENCES
] = UNIT_REFERENCED_BY
,
2356 [UNIT_REFERENCED_BY
] = UNIT_REFERENCES
,
2357 [UNIT_TRIGGERS
] = UNIT_TRIGGERED_BY
,
2358 [UNIT_TRIGGERED_BY
] = UNIT_TRIGGERS
,
2359 [UNIT_PROPAGATES_RELOAD_TO
] = UNIT_RELOAD_PROPAGATED_FROM
,
2360 [UNIT_RELOAD_PROPAGATED_FROM
] = UNIT_PROPAGATES_RELOAD_TO
,
2361 [UNIT_JOINS_NAMESPACE_OF
] = UNIT_JOINS_NAMESPACE_OF
,
2363 int r
, q
= 0, v
= 0, w
= 0;
2364 Unit
*orig_u
= u
, *orig_other
= other
;
2367 assert(d
>= 0 && d
< _UNIT_DEPENDENCY_MAX
);
2370 u
= unit_follow_merge(u
);
2371 other
= unit_follow_merge(other
);
2373 /* We won't allow dependencies on ourselves. We will not
2374 * consider them an error however. */
2376 maybe_warn_about_dependency(orig_u
, orig_other
->id
, d
);
2380 if (d
== UNIT_BEFORE
&& other
->type
== UNIT_DEVICE
) {
2381 log_unit_warning(u
, "Dependency Before=%s ignored (.device units cannot be delayed)", other
->id
);
2385 r
= set_ensure_allocated(&u
->dependencies
[d
], NULL
);
2389 if (inverse_table
[d
] != _UNIT_DEPENDENCY_INVALID
) {
2390 r
= set_ensure_allocated(&other
->dependencies
[inverse_table
[d
]], NULL
);
2395 if (add_reference
) {
2396 r
= set_ensure_allocated(&u
->dependencies
[UNIT_REFERENCES
], NULL
);
2400 r
= set_ensure_allocated(&other
->dependencies
[UNIT_REFERENCED_BY
], NULL
);
2405 q
= set_put(u
->dependencies
[d
], other
);
2409 if (inverse_table
[d
] != _UNIT_DEPENDENCY_INVALID
&& inverse_table
[d
] != d
) {
2410 v
= set_put(other
->dependencies
[inverse_table
[d
]], u
);
2417 if (add_reference
) {
2418 w
= set_put(u
->dependencies
[UNIT_REFERENCES
], other
);
2424 r
= set_put(other
->dependencies
[UNIT_REFERENCED_BY
], u
);
2429 unit_add_to_dbus_queue(u
);
2434 set_remove(u
->dependencies
[d
], other
);
2437 set_remove(other
->dependencies
[inverse_table
[d
]], u
);
2440 set_remove(u
->dependencies
[UNIT_REFERENCES
], other
);
2445 int unit_add_two_dependencies(Unit
*u
, UnitDependency d
, UnitDependency e
, Unit
*other
, bool add_reference
) {
2450 r
= unit_add_dependency(u
, d
, other
, add_reference
);
2454 return unit_add_dependency(u
, e
, other
, add_reference
);
2457 static int resolve_template(Unit
*u
, const char *name
, const char*path
, char **buf
, const char **ret
) {
2461 assert(name
|| path
);
2466 name
= basename(path
);
2468 if (!unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
2475 r
= unit_name_replace_instance(name
, u
->instance
, buf
);
2477 _cleanup_free_
char *i
= NULL
;
2479 r
= unit_name_to_prefix(u
->id
, &i
);
2483 r
= unit_name_replace_instance(name
, i
, buf
);
2492 int unit_add_dependency_by_name(Unit
*u
, UnitDependency d
, const char *name
, const char *path
, bool add_reference
) {
2493 _cleanup_free_
char *buf
= NULL
;
2498 assert(name
|| path
);
2500 r
= resolve_template(u
, name
, path
, &buf
, &name
);
2504 r
= manager_load_unit(u
->manager
, name
, path
, NULL
, &other
);
2508 return unit_add_dependency(u
, d
, other
, add_reference
);
2511 int unit_add_two_dependencies_by_name(Unit
*u
, UnitDependency d
, UnitDependency e
, const char *name
, const char *path
, bool add_reference
) {
2512 _cleanup_free_
char *buf
= NULL
;
2517 assert(name
|| path
);
2519 r
= resolve_template(u
, name
, path
, &buf
, &name
);
2523 r
= manager_load_unit(u
->manager
, name
, path
, NULL
, &other
);
2527 return unit_add_two_dependencies(u
, d
, e
, other
, add_reference
);
2530 int set_unit_path(const char *p
) {
2531 /* This is mostly for debug purposes */
2532 if (setenv("SYSTEMD_UNIT_PATH", p
, 1) < 0)
2538 char *unit_dbus_path(Unit
*u
) {
2544 return unit_dbus_path_from_name(u
->id
);
2547 char *unit_dbus_path_invocation_id(Unit
*u
) {
2550 if (sd_id128_is_null(u
->invocation_id
))
2553 return unit_dbus_path_from_name(u
->invocation_id_string
);
2556 int unit_set_slice(Unit
*u
, Unit
*slice
) {
2560 /* Sets the unit slice if it has not been set before. Is extra
2561 * careful, to only allow this for units that actually have a
2562 * cgroup context. Also, we don't allow to set this for slices
2563 * (since the parent slice is derived from the name). Make
2564 * sure the unit we set is actually a slice. */
2566 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2569 if (u
->type
== UNIT_SLICE
)
2572 if (unit_active_state(u
) != UNIT_INACTIVE
)
2575 if (slice
->type
!= UNIT_SLICE
)
2578 if (unit_has_name(u
, SPECIAL_INIT_SCOPE
) &&
2579 !unit_has_name(slice
, SPECIAL_ROOT_SLICE
))
2582 if (UNIT_DEREF(u
->slice
) == slice
)
2585 /* Disallow slice changes if @u is already bound to cgroups */
2586 if (UNIT_ISSET(u
->slice
) && u
->cgroup_realized
)
2589 unit_ref_unset(&u
->slice
);
2590 unit_ref_set(&u
->slice
, slice
);
2594 int unit_set_default_slice(Unit
*u
) {
2595 _cleanup_free_
char *b
= NULL
;
2596 const char *slice_name
;
2602 if (UNIT_ISSET(u
->slice
))
2606 _cleanup_free_
char *prefix
= NULL
, *escaped
= NULL
;
2608 /* Implicitly place all instantiated units in their
2609 * own per-template slice */
2611 r
= unit_name_to_prefix(u
->id
, &prefix
);
2615 /* The prefix is already escaped, but it might include
2616 * "-" which has a special meaning for slice units,
2617 * hence escape it here extra. */
2618 escaped
= unit_name_escape(prefix
);
2622 if (MANAGER_IS_SYSTEM(u
->manager
))
2623 b
= strjoin("system-", escaped
, ".slice");
2625 b
= strappend(escaped
, ".slice");
2632 MANAGER_IS_SYSTEM(u
->manager
) && !unit_has_name(u
, SPECIAL_INIT_SCOPE
)
2633 ? SPECIAL_SYSTEM_SLICE
2634 : SPECIAL_ROOT_SLICE
;
2636 r
= manager_load_unit(u
->manager
, slice_name
, NULL
, NULL
, &slice
);
2640 return unit_set_slice(u
, slice
);
2643 const char *unit_slice_name(Unit
*u
) {
2646 if (!UNIT_ISSET(u
->slice
))
2649 return UNIT_DEREF(u
->slice
)->id
;
2652 int unit_load_related_unit(Unit
*u
, const char *type
, Unit
**_found
) {
2653 _cleanup_free_
char *t
= NULL
;
2660 r
= unit_name_change_suffix(u
->id
, type
, &t
);
2663 if (unit_has_name(u
, t
))
2666 r
= manager_load_unit(u
->manager
, t
, NULL
, NULL
, _found
);
2667 assert(r
< 0 || *_found
!= u
);
2671 static int signal_name_owner_changed(sd_bus_message
*message
, void *userdata
, sd_bus_error
*error
) {
2672 const char *name
, *old_owner
, *new_owner
;
2679 r
= sd_bus_message_read(message
, "sss", &name
, &old_owner
, &new_owner
);
2681 bus_log_parse_error(r
);
2685 old_owner
= isempty(old_owner
) ? NULL
: old_owner
;
2686 new_owner
= isempty(new_owner
) ? NULL
: new_owner
;
2688 if (UNIT_VTABLE(u
)->bus_name_owner_change
)
2689 UNIT_VTABLE(u
)->bus_name_owner_change(u
, name
, old_owner
, new_owner
);
2694 int unit_install_bus_match(Unit
*u
, sd_bus
*bus
, const char *name
) {
2701 if (u
->match_bus_slot
)
2704 match
= strjoina("type='signal',"
2705 "sender='org.freedesktop.DBus',"
2706 "path='/org/freedesktop/DBus',"
2707 "interface='org.freedesktop.DBus',"
2708 "member='NameOwnerChanged',"
2709 "arg0='", name
, "'");
2711 return sd_bus_add_match(bus
, &u
->match_bus_slot
, match
, signal_name_owner_changed
, u
);
2714 int unit_watch_bus_name(Unit
*u
, const char *name
) {
2720 /* Watch a specific name on the bus. We only support one unit
2721 * watching each name for now. */
2723 if (u
->manager
->api_bus
) {
2724 /* If the bus is already available, install the match directly.
2725 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
2726 r
= unit_install_bus_match(u
, u
->manager
->api_bus
, name
);
2728 return log_warning_errno(r
, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name
);
2731 r
= hashmap_put(u
->manager
->watch_bus
, name
, u
);
2733 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
2734 return log_warning_errno(r
, "Failed to put bus name to hashmap: %m");
2740 void unit_unwatch_bus_name(Unit
*u
, const char *name
) {
2744 (void) hashmap_remove_value(u
->manager
->watch_bus
, name
, u
);
2745 u
->match_bus_slot
= sd_bus_slot_unref(u
->match_bus_slot
);
2748 bool unit_can_serialize(Unit
*u
) {
2751 return UNIT_VTABLE(u
)->serialize
&& UNIT_VTABLE(u
)->deserialize_item
;
2754 static int unit_serialize_cgroup_mask(FILE *f
, const char *key
, CGroupMask mask
) {
2755 _cleanup_free_
char *s
= NULL
;
2762 r
= cg_mask_to_string(mask
, &s
);
2773 int unit_serialize(Unit
*u
, FILE *f
, FDSet
*fds
, bool serialize_jobs
) {
2780 if (unit_can_serialize(u
)) {
2783 r
= UNIT_VTABLE(u
)->serialize(u
, f
, fds
);
2787 rt
= unit_get_exec_runtime(u
);
2789 r
= exec_runtime_serialize(u
, rt
, f
, fds
);
2795 dual_timestamp_serialize(f
, "state-change-timestamp", &u
->state_change_timestamp
);
2797 dual_timestamp_serialize(f
, "inactive-exit-timestamp", &u
->inactive_exit_timestamp
);
2798 dual_timestamp_serialize(f
, "active-enter-timestamp", &u
->active_enter_timestamp
);
2799 dual_timestamp_serialize(f
, "active-exit-timestamp", &u
->active_exit_timestamp
);
2800 dual_timestamp_serialize(f
, "inactive-enter-timestamp", &u
->inactive_enter_timestamp
);
2802 dual_timestamp_serialize(f
, "condition-timestamp", &u
->condition_timestamp
);
2803 dual_timestamp_serialize(f
, "assert-timestamp", &u
->assert_timestamp
);
2805 if (dual_timestamp_is_set(&u
->condition_timestamp
))
2806 unit_serialize_item(u
, f
, "condition-result", yes_no(u
->condition_result
));
2808 if (dual_timestamp_is_set(&u
->assert_timestamp
))
2809 unit_serialize_item(u
, f
, "assert-result", yes_no(u
->assert_result
));
2811 unit_serialize_item(u
, f
, "transient", yes_no(u
->transient
));
2813 unit_serialize_item_format(u
, f
, "cpu-usage-base", "%" PRIu64
, u
->cpu_usage_base
);
2814 if (u
->cpu_usage_last
!= NSEC_INFINITY
)
2815 unit_serialize_item_format(u
, f
, "cpu-usage-last", "%" PRIu64
, u
->cpu_usage_last
);
2818 unit_serialize_item(u
, f
, "cgroup", u
->cgroup_path
);
2819 unit_serialize_item(u
, f
, "cgroup-realized", yes_no(u
->cgroup_realized
));
2820 (void) unit_serialize_cgroup_mask(f
, "cgroup-realized-mask", u
->cgroup_realized_mask
);
2821 (void) unit_serialize_cgroup_mask(f
, "cgroup-enabled-mask", u
->cgroup_enabled_mask
);
2822 unit_serialize_item_format(u
, f
, "cgroup-bpf-realized", "%i", u
->cgroup_bpf_state
);
2824 if (uid_is_valid(u
->ref_uid
))
2825 unit_serialize_item_format(u
, f
, "ref-uid", UID_FMT
, u
->ref_uid
);
2826 if (gid_is_valid(u
->ref_gid
))
2827 unit_serialize_item_format(u
, f
, "ref-gid", GID_FMT
, u
->ref_gid
);
2829 if (!sd_id128_is_null(u
->invocation_id
))
2830 unit_serialize_item_format(u
, f
, "invocation-id", SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(u
->invocation_id
));
2832 bus_track_serialize(u
->bus_track
, f
, "ref");
2834 if (serialize_jobs
) {
2836 fprintf(f
, "job\n");
2837 job_serialize(u
->job
, f
);
2841 fprintf(f
, "job\n");
2842 job_serialize(u
->nop_job
, f
);
2851 int unit_serialize_item(Unit
*u
, FILE *f
, const char *key
, const char *value
) {
2867 int unit_serialize_item_escaped(Unit
*u
, FILE *f
, const char *key
, const char *value
) {
2868 _cleanup_free_
char *c
= NULL
;
2889 int unit_serialize_item_fd(Unit
*u
, FILE *f
, FDSet
*fds
, const char *key
, int fd
) {
2899 copy
= fdset_put_dup(fds
, fd
);
2903 fprintf(f
, "%s=%i\n", key
, copy
);
2907 void unit_serialize_item_format(Unit
*u
, FILE *f
, const char *key
, const char *format
, ...) {
2918 va_start(ap
, format
);
2919 vfprintf(f
, format
, ap
);
2925 int unit_deserialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2926 ExecRuntime
**rt
= NULL
;
2934 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
2936 rt
= (ExecRuntime
**) ((uint8_t*) u
+ offset
);
2939 char line
[LINE_MAX
], *l
, *v
;
2942 if (!fgets(line
, sizeof(line
), f
)) {
2955 k
= strcspn(l
, "=");
2963 if (streq(l
, "job")) {
2965 /* new-style serialized job */
2972 r
= job_deserialize(j
, f
);
2978 r
= hashmap_put(u
->manager
->jobs
, UINT32_TO_PTR(j
->id
), j
);
2984 r
= job_install_deserialized(j
);
2986 hashmap_remove(u
->manager
->jobs
, UINT32_TO_PTR(j
->id
));
2990 } else /* legacy for pre-44 */
2991 log_unit_warning(u
, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v
);
2993 } else if (streq(l
, "state-change-timestamp")) {
2994 dual_timestamp_deserialize(v
, &u
->state_change_timestamp
);
2996 } else if (streq(l
, "inactive-exit-timestamp")) {
2997 dual_timestamp_deserialize(v
, &u
->inactive_exit_timestamp
);
2999 } else if (streq(l
, "active-enter-timestamp")) {
3000 dual_timestamp_deserialize(v
, &u
->active_enter_timestamp
);
3002 } else if (streq(l
, "active-exit-timestamp")) {
3003 dual_timestamp_deserialize(v
, &u
->active_exit_timestamp
);
3005 } else if (streq(l
, "inactive-enter-timestamp")) {
3006 dual_timestamp_deserialize(v
, &u
->inactive_enter_timestamp
);
3008 } else if (streq(l
, "condition-timestamp")) {
3009 dual_timestamp_deserialize(v
, &u
->condition_timestamp
);
3011 } else if (streq(l
, "assert-timestamp")) {
3012 dual_timestamp_deserialize(v
, &u
->assert_timestamp
);
3014 } else if (streq(l
, "condition-result")) {
3016 r
= parse_boolean(v
);
3018 log_unit_debug(u
, "Failed to parse condition result value %s, ignoring.", v
);
3020 u
->condition_result
= r
;
3024 } else if (streq(l
, "assert-result")) {
3026 r
= parse_boolean(v
);
3028 log_unit_debug(u
, "Failed to parse assert result value %s, ignoring.", v
);
3030 u
->assert_result
= r
;
3034 } else if (streq(l
, "transient")) {
3036 r
= parse_boolean(v
);
3038 log_unit_debug(u
, "Failed to parse transient bool %s, ignoring.", v
);
3044 } else if (STR_IN_SET(l
, "cpu-usage-base", "cpuacct-usage-base")) {
3046 r
= safe_atou64(v
, &u
->cpu_usage_base
);
3048 log_unit_debug(u
, "Failed to parse CPU usage base %s, ignoring.", v
);
3052 } else if (streq(l
, "cpu-usage-last")) {
3054 r
= safe_atou64(v
, &u
->cpu_usage_last
);
3056 log_unit_debug(u
, "Failed to read CPU usage last %s, ignoring.", v
);
3060 } else if (streq(l
, "cgroup")) {
3062 r
= unit_set_cgroup_path(u
, v
);
3064 log_unit_debug_errno(u
, r
, "Failed to set cgroup path %s, ignoring: %m", v
);
3066 (void) unit_watch_cgroup(u
);
3069 } else if (streq(l
, "cgroup-realized")) {
3072 b
= parse_boolean(v
);
3074 log_unit_debug(u
, "Failed to parse cgroup-realized bool %s, ignoring.", v
);
3076 u
->cgroup_realized
= b
;
3080 } else if (streq(l
, "cgroup-realized-mask")) {
3082 r
= cg_mask_from_string(v
, &u
->cgroup_realized_mask
);
3084 log_unit_debug(u
, "Failed to parse cgroup-realized-mask %s, ignoring.", v
);
3087 } else if (streq(l
, "cgroup-enabled-mask")) {
3089 r
= cg_mask_from_string(v
, &u
->cgroup_enabled_mask
);
3091 log_unit_debug(u
, "Failed to parse cgroup-enabled-mask %s, ignoring.", v
);
3094 } else if (streq(l
, "cgroup-bpf-realized")) {
3097 r
= safe_atoi(v
, &i
);
3099 log_unit_debug(u
, "Failed to parse cgroup BPF state %s, ignoring.", v
);
3101 u
->cgroup_bpf_state
=
3102 i
< 0 ? UNIT_CGROUP_BPF_INVALIDATED
:
3103 i
> 0 ? UNIT_CGROUP_BPF_ON
:
3104 UNIT_CGROUP_BPF_OFF
;
3108 } else if (streq(l
, "ref-uid")) {
3111 r
= parse_uid(v
, &uid
);
3113 log_unit_debug(u
, "Failed to parse referenced UID %s, ignoring.", v
);
3115 unit_ref_uid_gid(u
, uid
, GID_INVALID
);
3119 } else if (streq(l
, "ref-gid")) {
3122 r
= parse_gid(v
, &gid
);
3124 log_unit_debug(u
, "Failed to parse referenced GID %s, ignoring.", v
);
3126 unit_ref_uid_gid(u
, UID_INVALID
, gid
);
3128 } else if (streq(l
, "ref")) {
3130 r
= strv_extend(&u
->deserialized_refs
, v
);
3135 } else if (streq(l
, "invocation-id")) {
3138 r
= sd_id128_from_string(v
, &id
);
3140 log_unit_debug(u
, "Failed to parse invocation id %s, ignoring.", v
);
3142 r
= unit_set_invocation_id(u
, id
);
3144 log_unit_warning_errno(u
, r
, "Failed to set invocation ID for unit: %m");
3150 if (unit_can_serialize(u
)) {
3152 r
= exec_runtime_deserialize_item(u
, rt
, l
, v
, fds
);
3154 log_unit_warning(u
, "Failed to deserialize runtime parameter '%s', ignoring.", l
);
3158 /* Returns positive if key was handled by the call */
3163 r
= UNIT_VTABLE(u
)->deserialize_item(u
, l
, v
, fds
);
3165 log_unit_warning(u
, "Failed to deserialize unit parameter '%s', ignoring.", l
);
3169 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
3170 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
3171 * before 228 where the base for timeouts was not persistent across reboots. */
3173 if (!dual_timestamp_is_set(&u
->state_change_timestamp
))
3174 dual_timestamp_get(&u
->state_change_timestamp
);
3179 void unit_deserialize_skip(FILE *f
) {
3182 /* Skip serialized data for this unit. We don't know what it is. */
3185 char line
[LINE_MAX
], *l
;
3187 if (!fgets(line
, sizeof line
, f
))
3200 int unit_add_node_link(Unit
*u
, const char *what
, bool wants
, UnitDependency dep
) {
3202 _cleanup_free_
char *e
= NULL
;
3207 /* Adds in links to the device node that this unit is based on */
3211 if (!is_device_path(what
))
3214 /* When device units aren't supported (such as in a
3215 * container), don't create dependencies on them. */
3216 if (!unit_type_supported(UNIT_DEVICE
))
3219 r
= unit_name_from_path(what
, ".device", &e
);
3223 r
= manager_load_unit(u
->manager
, e
, NULL
, NULL
, &device
);
3227 if (dep
== UNIT_REQUIRES
&& device_shall_be_bound_by(device
, u
))
3228 dep
= UNIT_BINDS_TO
;
3230 r
= unit_add_two_dependencies(u
, UNIT_AFTER
,
3231 MANAGER_IS_SYSTEM(u
->manager
) ? dep
: UNIT_WANTS
,
3237 r
= unit_add_dependency(device
, UNIT_WANTS
, u
, false);
3245 int unit_coldplug(Unit
*u
) {
3251 /* Make sure we don't enter a loop, when coldplugging
3256 u
->coldplugged
= true;
3258 STRV_FOREACH(i
, u
->deserialized_refs
) {
3259 q
= bus_unit_track_add_name(u
, *i
);
3260 if (q
< 0 && r
>= 0)
3263 u
->deserialized_refs
= strv_free(u
->deserialized_refs
);
3265 if (UNIT_VTABLE(u
)->coldplug
) {
3266 q
= UNIT_VTABLE(u
)->coldplug(u
);
3267 if (q
< 0 && r
>= 0)
3272 q
= job_coldplug(u
->job
);
3273 if (q
< 0 && r
>= 0)
3280 static bool fragment_mtime_newer(const char *path
, usec_t mtime
, bool path_masked
) {
3286 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
3287 * are never out-of-date. */
3288 if (PATH_STARTSWITH_SET(path
, "/proc", "/sys"))
3291 if (stat(path
, &st
) < 0)
3292 /* What, cannot access this anymore? */
3296 /* For masked files check if they are still so */
3297 return !null_or_empty(&st
);
3299 /* For non-empty files check the mtime */
3300 return timespec_load(&st
.st_mtim
) > mtime
;
3305 bool unit_need_daemon_reload(Unit
*u
) {
3306 _cleanup_strv_free_
char **t
= NULL
;
3311 /* For unit files, we allow masking… */
3312 if (fragment_mtime_newer(u
->fragment_path
, u
->fragment_mtime
,
3313 u
->load_state
== UNIT_MASKED
))
3316 /* Source paths should not be masked… */
3317 if (fragment_mtime_newer(u
->source_path
, u
->source_mtime
, false))
3320 (void) unit_find_dropin_paths(u
, &t
);
3321 if (!strv_equal(u
->dropin_paths
, t
))
3324 /* … any drop-ins that are masked are simply omitted from the list. */
3325 STRV_FOREACH(path
, u
->dropin_paths
)
3326 if (fragment_mtime_newer(*path
, u
->dropin_mtime
, false))
3332 void unit_reset_failed(Unit
*u
) {
3335 if (UNIT_VTABLE(u
)->reset_failed
)
3336 UNIT_VTABLE(u
)->reset_failed(u
);
3338 RATELIMIT_RESET(u
->start_limit
);
3339 u
->start_limit_hit
= false;
3342 Unit
*unit_following(Unit
*u
) {
3345 if (UNIT_VTABLE(u
)->following
)
3346 return UNIT_VTABLE(u
)->following(u
);
3351 bool unit_stop_pending(Unit
*u
) {
3354 /* This call does check the current state of the unit. It's
3355 * hence useful to be called from state change calls of the
3356 * unit itself, where the state isn't updated yet. This is
3357 * different from unit_inactive_or_pending() which checks both
3358 * the current state and for a queued job. */
3360 return u
->job
&& u
->job
->type
== JOB_STOP
;
3363 bool unit_inactive_or_pending(Unit
*u
) {
3366 /* Returns true if the unit is inactive or going down */
3368 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u
)))
3371 if (unit_stop_pending(u
))
3377 bool unit_active_or_pending(Unit
*u
) {
3380 /* Returns true if the unit is active or going up */
3382 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u
)))
3386 (u
->job
->type
== JOB_START
||
3387 u
->job
->type
== JOB_RELOAD_OR_START
||
3388 u
->job
->type
== JOB_RESTART
))
3394 int unit_kill(Unit
*u
, KillWho w
, int signo
, sd_bus_error
*error
) {
3396 assert(w
>= 0 && w
< _KILL_WHO_MAX
);
3397 assert(SIGNAL_VALID(signo
));
3399 if (!UNIT_VTABLE(u
)->kill
)
3402 return UNIT_VTABLE(u
)->kill(u
, w
, signo
, error
);
3405 static Set
*unit_pid_set(pid_t main_pid
, pid_t control_pid
) {
3409 pid_set
= set_new(NULL
);
3413 /* Exclude the main/control pids from being killed via the cgroup */
3415 r
= set_put(pid_set
, PID_TO_PTR(main_pid
));
3420 if (control_pid
> 0) {
3421 r
= set_put(pid_set
, PID_TO_PTR(control_pid
));
3433 int unit_kill_common(
3439 sd_bus_error
*error
) {
3442 bool killed
= false;
3444 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
)) {
3446 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no main processes", unit_type_to_string(u
->type
));
3447 else if (main_pid
== 0)
3448 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No main process to kill");
3451 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
)) {
3452 if (control_pid
< 0)
3453 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_PROCESS
, "%s units have no control processes", unit_type_to_string(u
->type
));
3454 else if (control_pid
== 0)
3455 return sd_bus_error_set_const(error
, BUS_ERROR_NO_SUCH_PROCESS
, "No control process to kill");
3458 if (IN_SET(who
, KILL_CONTROL
, KILL_CONTROL_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
3459 if (control_pid
> 0) {
3460 if (kill(control_pid
, signo
) < 0)
3466 if (IN_SET(who
, KILL_MAIN
, KILL_MAIN_FAIL
, KILL_ALL
, KILL_ALL_FAIL
))
3468 if (kill(main_pid
, signo
) < 0)
3474 if (IN_SET(who
, KILL_ALL
, KILL_ALL_FAIL
) && u
->cgroup_path
) {
3475 _cleanup_set_free_ Set
*pid_set
= NULL
;
3478 /* Exclude the main/control pids from being killed via the cgroup */
3479 pid_set
= unit_pid_set(main_pid
, control_pid
);
3483 q
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, signo
, 0, pid_set
, NULL
, NULL
);
3484 if (q
< 0 && q
!= -EAGAIN
&& q
!= -ESRCH
&& q
!= -ENOENT
)
3490 if (r
== 0 && !killed
&& IN_SET(who
, KILL_ALL_FAIL
, KILL_CONTROL_FAIL
))
3496 int unit_following_set(Unit
*u
, Set
**s
) {
3500 if (UNIT_VTABLE(u
)->following_set
)
3501 return UNIT_VTABLE(u
)->following_set(u
, s
);
3507 UnitFileState
unit_get_unit_file_state(Unit
*u
) {
3512 if (u
->unit_file_state
< 0 && u
->fragment_path
) {
3513 r
= unit_file_get_state(
3514 u
->manager
->unit_file_scope
,
3516 basename(u
->fragment_path
),
3517 &u
->unit_file_state
);
3519 u
->unit_file_state
= UNIT_FILE_BAD
;
3522 return u
->unit_file_state
;
3525 int unit_get_unit_file_preset(Unit
*u
) {
3528 if (u
->unit_file_preset
< 0 && u
->fragment_path
)
3529 u
->unit_file_preset
= unit_file_query_preset(
3530 u
->manager
->unit_file_scope
,
3532 basename(u
->fragment_path
));
3534 return u
->unit_file_preset
;
3537 Unit
* unit_ref_set(UnitRef
*ref
, Unit
*u
) {
3542 unit_ref_unset(ref
);
3545 LIST_PREPEND(refs
, u
->refs
, ref
);
3549 void unit_ref_unset(UnitRef
*ref
) {
3555 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
3556 * be unreferenced now. */
3557 unit_add_to_gc_queue(ref
->unit
);
3559 LIST_REMOVE(refs
, ref
->unit
->refs
, ref
);
3563 static int user_from_unit_name(Unit
*u
, char **ret
) {
3565 static const uint8_t hash_key
[] = {
3566 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
3567 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
3570 _cleanup_free_
char *n
= NULL
;
3573 r
= unit_name_to_prefix(u
->id
, &n
);
3577 if (valid_user_group_name(n
)) {
3583 /* If we can't use the unit name as a user name, then let's hash it and use that */
3584 if (asprintf(ret
, "_du%016" PRIx64
, siphash24(n
, strlen(n
), hash_key
)) < 0)
3590 int unit_patch_contexts(Unit
*u
) {
3598 /* Patch in the manager defaults into the exec and cgroup
3599 * contexts, _after_ the rest of the settings have been
3602 ec
= unit_get_exec_context(u
);
3604 /* This only copies in the ones that need memory */
3605 for (i
= 0; i
< _RLIMIT_MAX
; i
++)
3606 if (u
->manager
->rlimit
[i
] && !ec
->rlimit
[i
]) {
3607 ec
->rlimit
[i
] = newdup(struct rlimit
, u
->manager
->rlimit
[i
], 1);
3612 if (MANAGER_IS_USER(u
->manager
) &&
3613 !ec
->working_directory
) {
3615 r
= get_home_dir(&ec
->working_directory
);
3619 /* Allow user services to run, even if the
3620 * home directory is missing */
3621 ec
->working_directory_missing_ok
= true;
3624 if (ec
->private_devices
)
3625 ec
->capability_bounding_set
&= ~((UINT64_C(1) << CAP_MKNOD
) | (UINT64_C(1) << CAP_SYS_RAWIO
));
3627 if (ec
->protect_kernel_modules
)
3628 ec
->capability_bounding_set
&= ~(UINT64_C(1) << CAP_SYS_MODULE
);
3630 if (ec
->dynamic_user
) {
3632 r
= user_from_unit_name(u
, &ec
->user
);
3638 ec
->group
= strdup(ec
->user
);
3643 /* If the dynamic user option is on, let's make sure that the unit can't leave its UID/GID
3644 * around in the file system or on IPC objects. Hence enforce a strict sandbox. */
3646 ec
->private_tmp
= true;
3647 ec
->remove_ipc
= true;
3648 ec
->protect_system
= PROTECT_SYSTEM_STRICT
;
3649 if (ec
->protect_home
== PROTECT_HOME_NO
)
3650 ec
->protect_home
= PROTECT_HOME_READ_ONLY
;
3654 cc
= unit_get_cgroup_context(u
);
3658 ec
->private_devices
&&
3659 cc
->device_policy
== CGROUP_AUTO
)
3660 cc
->device_policy
= CGROUP_CLOSED
;
3666 ExecContext
*unit_get_exec_context(Unit
*u
) {
3673 offset
= UNIT_VTABLE(u
)->exec_context_offset
;
3677 return (ExecContext
*) ((uint8_t*) u
+ offset
);
3680 KillContext
*unit_get_kill_context(Unit
*u
) {
3687 offset
= UNIT_VTABLE(u
)->kill_context_offset
;
3691 return (KillContext
*) ((uint8_t*) u
+ offset
);
3694 CGroupContext
*unit_get_cgroup_context(Unit
*u
) {
3700 offset
= UNIT_VTABLE(u
)->cgroup_context_offset
;
3704 return (CGroupContext
*) ((uint8_t*) u
+ offset
);
3707 ExecRuntime
*unit_get_exec_runtime(Unit
*u
) {
3713 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
3717 return *(ExecRuntime
**) ((uint8_t*) u
+ offset
);
3720 static const char* unit_drop_in_dir(Unit
*u
, UnitSetPropertiesMode mode
) {
3723 if (!IN_SET(mode
, UNIT_RUNTIME
, UNIT_PERSISTENT
))
3726 if (u
->transient
) /* Redirect drop-ins for transient units always into the transient directory. */
3727 return u
->manager
->lookup_paths
.transient
;
3729 if (mode
== UNIT_RUNTIME
)
3730 return u
->manager
->lookup_paths
.runtime_control
;
3732 if (mode
== UNIT_PERSISTENT
)
3733 return u
->manager
->lookup_paths
.persistent_control
;
3738 int unit_write_drop_in(Unit
*u
, UnitSetPropertiesMode mode
, const char *name
, const char *data
) {
3739 _cleanup_free_
char *p
= NULL
, *q
= NULL
;
3740 const char *dir
, *wrapped
;
3745 if (u
->transient_file
) {
3746 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
3747 * write to the transient unit file. */
3748 fputs(data
, u
->transient_file
);
3749 fputc('\n', u
->transient_file
);
3753 if (!IN_SET(mode
, UNIT_PERSISTENT
, UNIT_RUNTIME
))
3756 dir
= unit_drop_in_dir(u
, mode
);
3760 wrapped
= strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
3761 "# or an equivalent operation. Do not edit.\n",
3765 r
= drop_in_file(dir
, u
->id
, 50, name
, &p
, &q
);
3769 (void) mkdir_p(p
, 0755);
3770 r
= write_string_file_atomic_label(q
, wrapped
);
3774 r
= strv_push(&u
->dropin_paths
, q
);
3779 strv_uniq(u
->dropin_paths
);
3781 u
->dropin_mtime
= now(CLOCK_REALTIME
);
3786 int unit_write_drop_in_format(Unit
*u
, UnitSetPropertiesMode mode
, const char *name
, const char *format
, ...) {
3787 _cleanup_free_
char *p
= NULL
;
3795 if (!IN_SET(mode
, UNIT_PERSISTENT
, UNIT_RUNTIME
))
3798 va_start(ap
, format
);
3799 r
= vasprintf(&p
, format
, ap
);
3805 return unit_write_drop_in(u
, mode
, name
, p
);
3808 int unit_write_drop_in_private(Unit
*u
, UnitSetPropertiesMode mode
, const char *name
, const char *data
) {
3815 if (!UNIT_VTABLE(u
)->private_section
)
3818 if (!IN_SET(mode
, UNIT_PERSISTENT
, UNIT_RUNTIME
))
3821 ndata
= strjoina("[", UNIT_VTABLE(u
)->private_section
, "]\n", data
);
3823 return unit_write_drop_in(u
, mode
, name
, ndata
);
3826 int unit_write_drop_in_private_format(Unit
*u
, UnitSetPropertiesMode mode
, const char *name
, const char *format
, ...) {
3827 _cleanup_free_
char *p
= NULL
;
3835 if (!IN_SET(mode
, UNIT_PERSISTENT
, UNIT_RUNTIME
))
3838 va_start(ap
, format
);
3839 r
= vasprintf(&p
, format
, ap
);
3845 return unit_write_drop_in_private(u
, mode
, name
, p
);
3848 int unit_make_transient(Unit
*u
) {
3854 if (!UNIT_VTABLE(u
)->can_transient
)
3857 path
= strjoin(u
->manager
->lookup_paths
.transient
, "/", u
->id
);
3861 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
3862 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
3864 RUN_WITH_UMASK(0022) {
3865 f
= fopen(path
, "we");
3872 if (u
->transient_file
)
3873 fclose(u
->transient_file
);
3874 u
->transient_file
= f
;
3876 free(u
->fragment_path
);
3877 u
->fragment_path
= path
;
3879 u
->source_path
= mfree(u
->source_path
);
3880 u
->dropin_paths
= strv_free(u
->dropin_paths
);
3881 u
->fragment_mtime
= u
->source_mtime
= u
->dropin_mtime
= 0;
3883 u
->load_state
= UNIT_STUB
;
3885 u
->transient
= true;
3887 unit_add_to_dbus_queue(u
);
3888 unit_add_to_gc_queue(u
);
3890 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
3896 static void log_kill(pid_t pid
, int sig
, void *userdata
) {
3897 _cleanup_free_
char *comm
= NULL
;
3899 (void) get_process_comm(pid
, &comm
);
3901 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
3902 only, like for example systemd's own PAM stub process. */
3903 if (comm
&& comm
[0] == '(')
3906 log_unit_notice(userdata
,
3907 "Killing process " PID_FMT
" (%s) with signal SIG%s.",
3910 signal_to_string(sig
));
3913 static int operation_to_signal(KillContext
*c
, KillOperation k
) {
3918 case KILL_TERMINATE
:
3919 case KILL_TERMINATE_AND_LOG
:
3920 return c
->kill_signal
;
3929 assert_not_reached("KillOperation unknown");
3933 int unit_kill_context(
3939 bool main_pid_alien
) {
3941 bool wait_for_exit
= false, send_sighup
;
3942 cg_kill_log_func_t log_func
= NULL
;
3948 /* Kill the processes belonging to this unit, in preparation for shutting the unit down.
3949 * Returns > 0 if we killed something worth waiting for, 0 otherwise. */
3951 if (c
->kill_mode
== KILL_NONE
)
3954 sig
= operation_to_signal(c
, k
);
3958 IN_SET(k
, KILL_TERMINATE
, KILL_TERMINATE_AND_LOG
) &&
3961 if (k
!= KILL_TERMINATE
|| IN_SET(sig
, SIGKILL
, SIGABRT
))
3962 log_func
= log_kill
;
3966 log_func(main_pid
, sig
, u
);
3968 r
= kill_and_sigcont(main_pid
, sig
);
3969 if (r
< 0 && r
!= -ESRCH
) {
3970 _cleanup_free_
char *comm
= NULL
;
3971 (void) get_process_comm(main_pid
, &comm
);
3973 log_unit_warning_errno(u
, r
, "Failed to kill main process " PID_FMT
" (%s), ignoring: %m", main_pid
, strna(comm
));
3975 if (!main_pid_alien
)
3976 wait_for_exit
= true;
3978 if (r
!= -ESRCH
&& send_sighup
)
3979 (void) kill(main_pid
, SIGHUP
);
3983 if (control_pid
> 0) {
3985 log_func(control_pid
, sig
, u
);
3987 r
= kill_and_sigcont(control_pid
, sig
);
3988 if (r
< 0 && r
!= -ESRCH
) {
3989 _cleanup_free_
char *comm
= NULL
;
3990 (void) get_process_comm(control_pid
, &comm
);
3992 log_unit_warning_errno(u
, r
, "Failed to kill control process " PID_FMT
" (%s), ignoring: %m", control_pid
, strna(comm
));
3994 wait_for_exit
= true;
3996 if (r
!= -ESRCH
&& send_sighup
)
3997 (void) kill(control_pid
, SIGHUP
);
4001 if (u
->cgroup_path
&&
4002 (c
->kill_mode
== KILL_CONTROL_GROUP
|| (c
->kill_mode
== KILL_MIXED
&& k
== KILL_KILL
))) {
4003 _cleanup_set_free_ Set
*pid_set
= NULL
;
4005 /* Exclude the main/control pids from being killed via the cgroup */
4006 pid_set
= unit_pid_set(main_pid
, control_pid
);
4010 r
= cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
4012 CGROUP_SIGCONT
|CGROUP_IGNORE_SELF
,
4016 if (r
!= -EAGAIN
&& r
!= -ESRCH
&& r
!= -ENOENT
)
4017 log_unit_warning_errno(u
, r
, "Failed to kill control group %s, ignoring: %m", u
->cgroup_path
);
4021 /* FIXME: For now, on the legacy hierarchy, we
4022 * will not wait for the cgroup members to die
4023 * if we are running in a container or if this
4024 * is a delegation unit, simply because cgroup
4025 * notification is unreliable in these
4026 * cases. It doesn't work at all in
4027 * containers, and outside of containers it
4028 * can be confused easily by left-over
4029 * directories in the cgroup — which however
4030 * should not exist in non-delegated units. On
4031 * the unified hierarchy that's different,
4032 * there we get proper events. Hence rely on
4035 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
) > 0 ||
4036 (detect_container() == 0 && !unit_cgroup_delegate(u
)))
4037 wait_for_exit
= true;
4042 pid_set
= unit_pid_set(main_pid
, control_pid
);
4046 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
4055 return wait_for_exit
;
4058 int unit_require_mounts_for(Unit
*u
, const char *path
) {
4059 char prefix
[strlen(path
) + 1], *p
;
4065 /* Registers a unit for requiring a certain path and all its
4066 * prefixes. We keep a simple array of these paths in the
4067 * unit, since its usually short. However, we build a prefix
4068 * table for all possible prefixes so that new appearing mount
4069 * units can easily determine which units to make themselves a
4072 if (!path_is_absolute(path
))
4079 path_kill_slashes(p
);
4081 if (!path_is_safe(p
)) {
4086 if (strv_contains(u
->requires_mounts_for
, p
)) {
4091 r
= strv_consume(&u
->requires_mounts_for
, p
);
4095 PATH_FOREACH_PREFIX_MORE(prefix
, p
) {
4098 x
= hashmap_get(u
->manager
->units_requiring_mounts_for
, prefix
);
4102 r
= hashmap_ensure_allocated(&u
->manager
->units_requiring_mounts_for
, &string_hash_ops
);
4116 r
= hashmap_put(u
->manager
->units_requiring_mounts_for
, q
, x
);
4132 int unit_setup_exec_runtime(Unit
*u
) {
4138 offset
= UNIT_VTABLE(u
)->exec_runtime_offset
;
4141 /* Check if there already is an ExecRuntime for this unit? */
4142 rt
= (ExecRuntime
**) ((uint8_t*) u
+ offset
);
4146 /* Try to get it from somebody else */
4147 SET_FOREACH(other
, u
->dependencies
[UNIT_JOINS_NAMESPACE_OF
], i
) {
4149 *rt
= unit_get_exec_runtime(other
);
4151 exec_runtime_ref(*rt
);
4156 return exec_runtime_make(rt
, unit_get_exec_context(u
), u
->id
);
4159 int unit_setup_dynamic_creds(Unit
*u
) {
4161 DynamicCreds
*dcreds
;
4166 offset
= UNIT_VTABLE(u
)->dynamic_creds_offset
;
4168 dcreds
= (DynamicCreds
*) ((uint8_t*) u
+ offset
);
4170 ec
= unit_get_exec_context(u
);
4173 if (!ec
->dynamic_user
)
4176 return dynamic_creds_acquire(dcreds
, u
->manager
, ec
->user
, ec
->group
);
4179 bool unit_type_supported(UnitType t
) {
4180 if (_unlikely_(t
< 0))
4182 if (_unlikely_(t
>= _UNIT_TYPE_MAX
))
4185 if (!unit_vtable
[t
]->supported
)
4188 return unit_vtable
[t
]->supported();
4191 void unit_warn_if_dir_nonempty(Unit
*u
, const char* where
) {
4197 r
= dir_is_empty(where
);
4201 log_unit_warning_errno(u
, r
, "Failed to check directory %s: %m", where
);
4205 log_struct(LOG_NOTICE
,
4206 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
4208 LOG_UNIT_MESSAGE(u
, "Directory %s to mount over is not empty, mounting anyway.", where
),
4213 int unit_fail_if_symlink(Unit
*u
, const char* where
) {
4219 r
= is_symlink(where
);
4221 log_unit_debug_errno(u
, r
, "Failed to check symlink %s, ignoring: %m", where
);
4228 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR
,
4230 LOG_UNIT_MESSAGE(u
, "Mount on symlink %s not allowed.", where
),
4237 bool unit_is_pristine(Unit
*u
) {
4240 /* Check if the unit already exists or is already around,
4241 * in a number of different ways. Note that to cater for unit
4242 * types such as slice, we are generally fine with units that
4243 * are marked UNIT_LOADED even though nothing was
4244 * actually loaded, as those unit types don't require a file
4245 * on disk to validly load. */
4247 return !(!IN_SET(u
->load_state
, UNIT_NOT_FOUND
, UNIT_LOADED
) ||
4250 !strv_isempty(u
->dropin_paths
) ||
4255 pid_t
unit_control_pid(Unit
*u
) {
4258 if (UNIT_VTABLE(u
)->control_pid
)
4259 return UNIT_VTABLE(u
)->control_pid(u
);
4264 pid_t
unit_main_pid(Unit
*u
) {
4267 if (UNIT_VTABLE(u
)->main_pid
)
4268 return UNIT_VTABLE(u
)->main_pid(u
);
4273 static void unit_unref_uid_internal(
4277 void (*_manager_unref_uid
)(Manager
*m
, uid_t uid
, bool destroy_now
)) {
4281 assert(_manager_unref_uid
);
4283 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
4284 * gid_t are actually the same time, with the same validity rules.
4286 * Drops a reference to UID/GID from a unit. */
4288 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
4289 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
4291 if (!uid_is_valid(*ref_uid
))
4294 _manager_unref_uid(u
->manager
, *ref_uid
, destroy_now
);
4295 *ref_uid
= UID_INVALID
;
4298 void unit_unref_uid(Unit
*u
, bool destroy_now
) {
4299 unit_unref_uid_internal(u
, &u
->ref_uid
, destroy_now
, manager_unref_uid
);
4302 void unit_unref_gid(Unit
*u
, bool destroy_now
) {
4303 unit_unref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, destroy_now
, manager_unref_gid
);
4306 static int unit_ref_uid_internal(
4311 int (*_manager_ref_uid
)(Manager
*m
, uid_t uid
, bool clean_ipc
)) {
4317 assert(uid_is_valid(uid
));
4318 assert(_manager_ref_uid
);
4320 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
4321 * are actually the same type, and have the same validity rules.
4323 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
4324 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
4327 assert_cc(sizeof(uid_t
) == sizeof(gid_t
));
4328 assert_cc(UID_INVALID
== (uid_t
) GID_INVALID
);
4330 if (*ref_uid
== uid
)
4333 if (uid_is_valid(*ref_uid
)) /* Already set? */
4336 r
= _manager_ref_uid(u
->manager
, uid
, clean_ipc
);
4344 int unit_ref_uid(Unit
*u
, uid_t uid
, bool clean_ipc
) {
4345 return unit_ref_uid_internal(u
, &u
->ref_uid
, uid
, clean_ipc
, manager_ref_uid
);
4348 int unit_ref_gid(Unit
*u
, gid_t gid
, bool clean_ipc
) {
4349 return unit_ref_uid_internal(u
, (uid_t
*) &u
->ref_gid
, (uid_t
) gid
, clean_ipc
, manager_ref_gid
);
4352 static int unit_ref_uid_gid_internal(Unit
*u
, uid_t uid
, gid_t gid
, bool clean_ipc
) {
4357 /* Reference both a UID and a GID in one go. Either references both, or neither. */
4359 if (uid_is_valid(uid
)) {
4360 r
= unit_ref_uid(u
, uid
, clean_ipc
);
4365 if (gid_is_valid(gid
)) {
4366 q
= unit_ref_gid(u
, gid
, clean_ipc
);
4369 unit_unref_uid(u
, false);
4375 return r
> 0 || q
> 0;
4378 int unit_ref_uid_gid(Unit
*u
, uid_t uid
, gid_t gid
) {
4384 c
= unit_get_exec_context(u
);
4386 r
= unit_ref_uid_gid_internal(u
, uid
, gid
, c
? c
->remove_ipc
: false);
4388 return log_unit_warning_errno(u
, r
, "Couldn't add UID/GID reference to unit, proceeding without: %m");
4393 void unit_unref_uid_gid(Unit
*u
, bool destroy_now
) {
4396 unit_unref_uid(u
, destroy_now
);
4397 unit_unref_gid(u
, destroy_now
);
4400 void unit_notify_user_lookup(Unit
*u
, uid_t uid
, gid_t gid
) {
4405 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
4406 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
4407 * objects when no service references the UID/GID anymore. */
4409 r
= unit_ref_uid_gid(u
, uid
, gid
);
4411 bus_unit_send_change_signal(u
);
4414 int unit_set_invocation_id(Unit
*u
, sd_id128_t id
) {
4419 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
4421 if (sd_id128_equal(u
->invocation_id
, id
))
4424 if (!sd_id128_is_null(u
->invocation_id
))
4425 (void) hashmap_remove_value(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
4427 if (sd_id128_is_null(id
)) {
4432 r
= hashmap_ensure_allocated(&u
->manager
->units_by_invocation_id
, &id128_hash_ops
);
4436 u
->invocation_id
= id
;
4437 sd_id128_to_string(id
, u
->invocation_id_string
);
4439 r
= hashmap_put(u
->manager
->units_by_invocation_id
, &u
->invocation_id
, u
);
4446 u
->invocation_id
= SD_ID128_NULL
;
4447 u
->invocation_id_string
[0] = 0;
4451 int unit_acquire_invocation_id(Unit
*u
) {
4457 r
= sd_id128_randomize(&id
);
4459 return log_unit_error_errno(u
, r
, "Failed to generate invocation ID for unit: %m");
4461 r
= unit_set_invocation_id(u
, id
);
4463 return log_unit_error_errno(u
, r
, "Failed to set invocation ID for unit: %m");
4468 void unit_set_exec_params(Unit
*s
, ExecParameters
*p
) {
4474 p
->cgroup_path
= s
->cgroup_path
;
4476 c
= unit_get_cgroup_context(s
);
4477 SET_FLAG(p
->flags
, EXEC_CGROUP_DELEGATE
, c
&& c
->delegate
);