]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/unit.h
core: introduce unit_main_pid_full() which optionally provides if the PID is alien...
[thirdparty/systemd.git] / src / core / unit.h
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
c2f1db8f 2#pragma once
87f0e418 3
9e615fa3 4#include <errno.h>
87f0e418
LP
5#include <stdbool.h>
6#include <stdlib.h>
84ebe6f0 7#include <sys/socket.h>
bbc9006e 8#include <unistd.h>
87f0e418 9
2d3b784d
ZJS
10#include "sd-id128.h"
11
9e615fa3
LB
12/* Circular dependency with manager.h, needs to be defined before local includes */
13typedef enum UnitMountDependencyType {
14 UNIT_MOUNT_WANTS,
15 UNIT_MOUNT_REQUIRES,
16 _UNIT_MOUNT_DEPENDENCY_TYPE_MAX,
17 _UNIT_MOUNT_DEPENDENCY_TYPE_INVALID = -EINVAL,
18} UnitMountDependencyType;
19
6a48d82f 20#include "bpf-program.h"
7901288a 21#include "cgroup.h"
134e56dc 22#include "condition.h"
87a47f99 23#include "emergency-action.h"
e77e07f6 24#include "install.h"
71d35b6b 25#include "list.h"
7901288a 26#include "pidref.h"
fab34748 27#include "set.h"
7901288a 28#include "show-status.h"
5cfa33e0 29#include "unit-file.h"
87f0e418 30
57b7a260
FS
31typedef struct UnitRef UnitRef;
32
db2cb23b
UTL
33typedef enum KillOperation {
34 KILL_TERMINATE,
1d98fef1 35 KILL_TERMINATE_AND_LOG,
a232ebcc 36 KILL_RESTART,
db2cb23b 37 KILL_KILL,
c87700a1 38 KILL_WATCHDOG,
4940c0b0 39 _KILL_OPERATION_MAX,
2d93c20e 40 _KILL_OPERATION_INVALID = -EINVAL,
db2cb23b
UTL
41} KillOperation;
42
5afe510c
LP
43typedef enum CollectMode {
44 COLLECT_INACTIVE,
45 COLLECT_INACTIVE_OR_FAILED,
46 _COLLECT_MODE_MAX,
2d93c20e 47 _COLLECT_MODE_INVALID = -EINVAL,
5afe510c
LP
48} CollectMode;
49
87f0e418 50static inline bool UNIT_IS_ACTIVE_OR_RELOADING(UnitActiveState t) {
3742095b 51 return IN_SET(t, UNIT_ACTIVE, UNIT_RELOADING);
87f0e418
LP
52}
53
54static inline bool UNIT_IS_ACTIVE_OR_ACTIVATING(UnitActiveState t) {
3742095b 55 return IN_SET(t, UNIT_ACTIVE, UNIT_ACTIVATING, UNIT_RELOADING);
87f0e418
LP
56}
57
58static inline bool UNIT_IS_INACTIVE_OR_DEACTIVATING(UnitActiveState t) {
3742095b 59 return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED, UNIT_DEACTIVATING);
6124958c
LP
60}
61
fdf20a31 62static inline bool UNIT_IS_INACTIVE_OR_FAILED(UnitActiveState t) {
3742095b 63 return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED);
87f0e418
LP
64}
65
0377cd29
LP
66static inline bool UNIT_IS_LOAD_COMPLETE(UnitLoadState t) {
67 return t >= 0 && t < _UNIT_LOAD_STATE_MAX && t != UNIT_STUB && t != UNIT_MERGED;
68}
69
eef85c4a
LP
70/* Stores the 'reason' a dependency was created as a bit mask, i.e. due to which configuration source it came to be. We
71 * use this so that we can selectively flush out parts of dependencies again. Note that the same dependency might be
72 * created as a result of multiple "reasons", hence the bitmask. */
73typedef enum UnitDependencyMask {
5238e957 74 /* Configured directly by the unit file, .wants/.requires symlink or drop-in, or as an immediate result of a
eef85c4a
LP
75 * non-dependency option configured that way. */
76 UNIT_DEPENDENCY_FILE = 1 << 0,
77
78 /* As unconditional implicit dependency (not affected by unit configuration — except by the unit name and
79 * type) */
80 UNIT_DEPENDENCY_IMPLICIT = 1 << 1,
81
82 /* A dependency effected by DefaultDependencies=yes. Note that dependencies marked this way are conceptually
83 * just a subset of UNIT_DEPENDENCY_FILE, as DefaultDependencies= is itself a unit file setting that can only
84 * be set in unit files. We make this two separate bits only to help debugging how dependencies came to be. */
85 UNIT_DEPENDENCY_DEFAULT = 1 << 2,
86
87 /* A dependency created from udev rules */
88 UNIT_DEPENDENCY_UDEV = 1 << 3,
89
90 /* A dependency created because of some unit's RequiresMountsFor= setting */
91 UNIT_DEPENDENCY_PATH = 1 << 4,
92
87c734ee
FB
93 /* A dependency initially configured from the mount unit file however the dependency will be updated
94 * from /proc/self/mountinfo as soon as the kernel will make the entry for that mount available in
95 * the /proc file */
96 UNIT_DEPENDENCY_MOUNT_FILE = 1 << 5,
97
98 /* A dependency created or updated because of data read from /proc/self/mountinfo */
99 UNIT_DEPENDENCY_MOUNTINFO = 1 << 6,
49267b1b 100
eef85c4a 101 /* A dependency created because of data read from /proc/swaps and no other configuration source */
87c734ee 102 UNIT_DEPENDENCY_PROC_SWAP = 1 << 7,
eef85c4a 103
899acf5c 104 /* A dependency for units in slices assigned by directly setting Slice= */
87c734ee 105 UNIT_DEPENDENCY_SLICE_PROPERTY = 1 << 8,
899acf5c 106
87c734ee 107 _UNIT_DEPENDENCY_MASK_FULL = (1 << 9) - 1,
eef85c4a
LP
108} UnitDependencyMask;
109
110/* The Unit's dependencies[] hashmaps use this structure as value. It has the same size as a void pointer, and thus can
111 * be stored directly as hashmap value, without any indirection. Note that this stores two masks, as both the origin
112 * and the destination of a dependency might have created it. */
113typedef union UnitDependencyInfo {
114 void *data;
115 struct {
116 UnitDependencyMask origin_mask:16;
117 UnitDependencyMask destination_mask:16;
118 } _packed_;
119} UnitDependencyInfo;
120
48b92b37
LB
121/* Store information about why a unit was activated.
122 * We start with trigger units (.path/.timer), eventually it will be expanded to include more metadata. */
123typedef struct ActivationDetails {
124 unsigned n_ref;
125 UnitType trigger_unit_type;
126 char *trigger_unit_name;
127} ActivationDetails;
128
129/* For casting an activation event into the various unit-specific types */
130#define DEFINE_ACTIVATION_DETAILS_CAST(UPPERCASE, MixedCase, UNIT_TYPE) \
131 static inline MixedCase* UPPERCASE(ActivationDetails *a) { \
132 if (_unlikely_(!a || a->trigger_unit_type != UNIT_##UNIT_TYPE)) \
133 return NULL; \
134 \
135 return (MixedCase*) a; \
136 }
137
138/* For casting the various unit types into a unit */
139#define ACTIVATION_DETAILS(u) \
140 ({ \
141 typeof(u) _u_ = (u); \
142 ActivationDetails *_w_ = _u_ ? &(_u_)->meta : NULL; \
143 _w_; \
144 })
145
146ActivationDetails *activation_details_new(Unit *trigger_unit);
147ActivationDetails *activation_details_ref(ActivationDetails *p);
148ActivationDetails *activation_details_unref(ActivationDetails *p);
149void activation_details_serialize(ActivationDetails *p, FILE *f);
150int activation_details_deserialize(const char *key, const char *value, ActivationDetails **info);
151int activation_details_append_env(ActivationDetails *info, char ***strv);
152int activation_details_append_pair(ActivationDetails *info, char ***strv);
153DEFINE_TRIVIAL_CLEANUP_FUNC(ActivationDetails*, activation_details_unref);
154
155typedef struct ActivationDetailsVTable {
156 /* How much memory does an object of this activation type need */
157 size_t object_size;
158
159 /* This should reset all type-specific variables. This should not allocate memory, and is called
160 * with zero-initialized data. It should hence only initialize variables that need to be set != 0. */
161 void (*init)(ActivationDetails *info, Unit *trigger_unit);
162
163 /* This should free all type-specific variables. It should be idempotent. */
164 void (*done)(ActivationDetails *info);
165
166 /* This should serialize all type-specific variables. */
167 void (*serialize)(ActivationDetails *info, FILE *f);
168
169 /* This should deserialize all type-specific variables, one at a time. */
170 int (*deserialize)(const char *key, const char *value, ActivationDetails **info);
171
172 /* This should format the type-specific variables for the env block of the spawned service,
173 * and return the number of added items. */
174 int (*append_env)(ActivationDetails *info, char ***strv);
175
176 /* This should append type-specific variables as key/value pairs for the D-Bus property of the job,
177 * and return the number of added pairs. */
178 int (*append_pair)(ActivationDetails *info, char ***strv);
179} ActivationDetailsVTable;
180
181extern const ActivationDetailsVTable * const activation_details_vtable[_UNIT_TYPE_MAX];
182
183static inline const ActivationDetailsVTable* ACTIVATION_DETAILS_VTABLE(const ActivationDetails *a) {
184 assert(a);
185 assert(a->trigger_unit_type < _UNIT_TYPE_MAX);
186
187 return activation_details_vtable[a->trigger_unit_type];
188}
189
15ed3c3a
LP
190/* Newer LLVM versions don't like implicit casts from large pointer types to smaller enums, hence let's add
191 * explicit type-safe helpers for that. */
192static inline UnitDependency UNIT_DEPENDENCY_FROM_PTR(const void *p) {
193 return PTR_TO_INT(p);
194}
195
196static inline void* UNIT_DEPENDENCY_TO_PTR(UnitDependency d) {
197 return INT_TO_PTR(d);
198}
199
ef734fd6
LP
200#include "job.h"
201
a016b922
LP
202struct UnitRef {
203 /* Keeps tracks of references to a unit. This is useful so
204 * that we can merge two units if necessary and correct all
205 * references to them */
206
7f7d01ed
ZJS
207 Unit *source, *target;
208 LIST_FIELDS(UnitRef, refs_by_target);
a016b922
LP
209};
210
57b7a260 211typedef struct Unit {
87f0e418 212 Manager *manager;
23a177ef 213
87f0e418
LP
214 UnitType type;
215 UnitLoadState load_state;
23a177ef 216 Unit *merged_into;
87f0e418 217
4562c355 218 char *id; /* The one special name that we use for identification */
9e2f7c11 219 char *instance;
87f0e418 220
4562c355 221 Set *aliases; /* All the other names. */
87f0e418 222
15ed3c3a
LP
223 /* For each dependency type we can look up another Hashmap with this, whose key is a Unit* object,
224 * and whose value encodes why the dependency exists, using the UnitDependencyInfo type. i.e. a
225 * Hashmap(UnitDependency → Hashmap(Unit* → UnitDependencyInfo)) */
226 Hashmap *dependencies;
eef85c4a 227
9e615fa3
LB
228 /* Similar, for RequiresMountsFor= and WantsMountsFor= path dependencies. The key is the path, the
229 * value the UnitDependencyInfo type */
230 Hashmap *mounts_for[_UNIT_MOUNT_DEPENDENCY_TYPE_MAX];
7c8fa05c 231
87f0e418 232 char *description;
49dbfa7b 233 char **documentation;
faf919f1 234
23e9a7dd
LP
235 /* The SELinux context used for checking access to this unit read off the unit file at load time (do
236 * not confuse with the selinux_context field in ExecContext which is the SELinux context we'll set
237 * for processes) */
238 char *access_selinux_context;
239
6be1e7d5 240 char *fragment_path; /* if loaded from a config file this is the primary path to it */
1b64d026 241 char *source_path; /* if converted, the source file */
ae7a7182 242 char **dropin_paths;
f78f265f 243
c2911d48 244 usec_t fragment_not_found_timestamp_hash;
45fb0699 245 usec_t fragment_mtime;
1b64d026 246 usec_t source_mtime;
ae7a7182 247 usec_t dropin_mtime;
87f0e418 248
4f4afc88
LP
249 /* If this is a transient unit we are currently writing, this is where we are writing it to */
250 FILE *transient_file;
251
8c2524c7 252 /* Freezer state */
af1e3365 253 sd_bus_message *pending_freezer_invocation;
8c2524c7
ZJS
254 FreezerState freezer_state;
255
256 /* Job timeout and action to take */
257 EmergencyAction job_timeout_action;
258 usec_t job_timeout;
259 usec_t job_running_timeout;
260 char *job_timeout_reboot_arg;
261
e0209d83 262 /* If there is something to do with this unit, then this is the installed job for it */
87f0e418
LP
263 Job *job;
264
e0209d83
MS
265 /* JOB_NOP jobs are special and can be installed without disturbing the real job. */
266 Job *nop_job;
267
bbc29086
DM
268 /* The slot used for watching NameOwnerChanged signals */
269 sd_bus_slot *match_bus_slot;
a5a8776a 270 sd_bus_slot *get_name_owner_slot;
bbc29086 271
05a98afd
LP
272 /* References to this unit from clients */
273 sd_bus_track *bus_track;
274 char **deserialized_refs;
275
57020a3a 276 /* References to this */
7f7d01ed 277 LIST_HEAD(UnitRef, refs_by_target);
57020a3a 278
52661efd
LP
279 /* Conditions to check */
280 LIST_HEAD(Condition, conditions);
59fccdc5 281 LIST_HEAD(Condition, asserts);
52661efd 282
90bbc946 283 dual_timestamp condition_timestamp;
59fccdc5 284 dual_timestamp assert_timestamp;
90bbc946 285
a483fb59
LP
286 /* Updated whenever the low-level state changes */
287 dual_timestamp state_change_timestamp;
288
289 /* Updated whenever the (high-level) active state enters or leaves the active or inactive states */
63983207
LP
290 dual_timestamp inactive_exit_timestamp;
291 dual_timestamp active_enter_timestamp;
292 dual_timestamp active_exit_timestamp;
293 dual_timestamp inactive_enter_timestamp;
87f0e418 294
ef734fd6 295 /* Per type list */
ac155bb8 296 LIST_FIELDS(Unit, units_by_type);
c1e1601e 297
701cc384 298 /* Load queue */
ac155bb8 299 LIST_FIELDS(Unit, load_queue);
701cc384 300
c1e1601e 301 /* D-Bus queue */
ac155bb8 302 LIST_FIELDS(Unit, dbus_queue);
23a177ef
LP
303
304 /* Cleanup queue */
ac155bb8 305 LIST_FIELDS(Unit, cleanup_queue);
9d58f1db 306
701cc384 307 /* GC queue */
ac155bb8 308 LIST_FIELDS(Unit, gc_queue);
701cc384 309
4ad49000 310 /* CGroup realize members queue */
91a6073e 311 LIST_FIELDS(Unit, cgroup_realize_queue);
4ad49000 312
09e24654
LP
313 /* cgroup empty queue */
314 LIST_FIELDS(Unit, cgroup_empty_queue);
315
afcfaa69
LP
316 /* cgroup OOM queue */
317 LIST_FIELDS(Unit, cgroup_oom_queue);
318
19496554
MS
319 /* Target dependencies queue */
320 LIST_FIELDS(Unit, target_deps_queue);
321
0bc488c9 322 /* Queue of units with StopWhenUnneeded= set that shall be checked for clean-up. */
a3c1168a
LP
323 LIST_FIELDS(Unit, stop_when_unneeded_queue);
324
0bc488c9
LP
325 /* Queue of units that have an Uphold= dependency from some other unit, and should be checked for starting */
326 LIST_FIELDS(Unit, start_when_upheld_queue);
327
56c59592
LP
328 /* Queue of units that have a BindTo= dependency on some other unit, and should possibly be shut down */
329 LIST_FIELDS(Unit, stop_when_bound_queue);
330
6ac62d61
LP
331 /* Queue of units that should be checked if they can release resources now */
332 LIST_FIELDS(Unit, release_resources_queue);
333
495e75ed
LP
334 /* PIDs we keep an eye on. Note that a unit might have many more, but these are the ones we care
335 * enough about to process SIGCHLD for */
336 Set *pids; /* → PidRef* */
a911bb9a 337
62a76913
LP
338 /* Used in SIGCHLD and sd_notify() message event invocation logic to avoid that we dispatch the same event
339 * multiple times on the same unit. */
340 unsigned sigchldgen;
341 unsigned notifygen;
36f20ae3 342
701cc384 343 /* Used during GC sweeps */
eced69b3 344 unsigned gc_marker;
701cc384 345
8821a00f
LP
346 /* Error code when we didn't manage to load the unit (negative) */
347 int load_error;
348
6bf0f408 349 /* Put a ratelimit on unit starting */
7bf081a1 350 RateLimit start_ratelimit;
87a47f99 351 EmergencyAction start_limit_action;
53c35a76 352
ff68472a
ZJS
353 /* The unit has been marked for reload, restart, etc. Stored as 1u << marker1 | 1u << marker2. */
354 unsigned markers;
355
7af67e9a
LP
356 /* What to do on failure or success */
357 EmergencyAction success_action, failure_action;
358 int success_action_exit_status, failure_action_exit_status;
6bf0f408
LP
359 char *reboot_arg;
360
0bc488c9
LP
361 /* Make sure we never enter endless loops with the StopWhenUnneeded=, BindsTo=, Uphold= logic */
362 RateLimit auto_start_stop_ratelimit;
7223d500 363 sd_event_source *auto_start_stop_event_source;
bea355da 364
00d9ef85
LP
365 /* Reference to a specific UID/GID */
366 uid_t ref_uid;
367 gid_t ref_gid;
368
d2dc52db 369 /* Cached unit file state and preset */
a4375746 370 UnitFileState unit_file_state;
e77e07f6 371 PresetAction unit_file_preset;
a4375746 372
66ebf6c0
TH
373 /* Where the cpu.stat or cpuacct.usage was at the time the unit was started */
374 nsec_t cpu_usage_base;
fe700f46 375 nsec_t cpu_usage_last; /* the most recently read value */
5ad096b3 376
9824ab1f
MY
377 /* Most recently read value of memory accounting metrics */
378 uint64_t memory_accounting_last[_CGROUP_MEMORY_ACCOUNTING_METRIC_CACHED_LAST + 1];
aac3384e 379
38c41427 380 /* The current counter of OOM kills initiated by systemd-oomd */
fe8d22fb
AZ
381 uint64_t managed_oom_kill_last;
382
383 /* The current counter of the oom_kill field in the memory.events cgroup attribute */
afcfaa69
LP
384 uint64_t oom_kill_last;
385
fbe14fc9
LP
386 /* Where the io.stat data was at the time the unit was started */
387 uint64_t io_accounting_base[_CGROUP_IO_ACCOUNTING_METRIC_MAX];
388 uint64_t io_accounting_last[_CGROUP_IO_ACCOUNTING_METRIC_MAX]; /* the most recently read value */
389
7c52a17b
ZJS
390 /* Counterparts in the cgroup filesystem */
391 char *cgroup_path;
184b4f78 392 uint64_t cgroup_id;
4e1dfa45
CD
393 CGroupMask cgroup_realized_mask; /* In which hierarchies does this unit's cgroup exist? (only relevant on cgroup v1) */
394 CGroupMask cgroup_enabled_mask; /* Which controllers are enabled (or more correctly: enabled for the children) for this unit's cgroup? (only relevant on cgroup v2) */
5238e957 395 CGroupMask cgroup_invalidated_mask; /* A mask specifying controllers which shall be considered invalidated, and require re-realization */
5a62e5e2 396 CGroupMask cgroup_members_mask; /* A cache for the controllers required by all children of this cgroup (only relevant for slice units) */
afcfaa69
LP
397
398 /* Inotify watch descriptors for watching cgroup.events and memory.events on cgroupv2 */
0bb814c2 399 int cgroup_control_inotify_wd;
afcfaa69 400 int cgroup_memory_inotify_wd;
7c52a17b 401
084c7007
RG
402 /* Device Controller BPF program */
403 BPFProgram *bpf_device_control_installed;
404
6a48d82f
DM
405 /* IP BPF Firewalling/accounting */
406 int ip_accounting_ingress_map_fd;
407 int ip_accounting_egress_map_fd;
0fd9c28c 408 uint64_t ip_accounting_extra[_CGROUP_IP_ACCOUNTING_METRIC_MAX];
6a48d82f
DM
409
410 int ipv4_allow_map_fd;
411 int ipv6_allow_map_fd;
412 int ipv4_deny_map_fd;
413 int ipv6_deny_map_fd;
aa2b6f1d
LP
414 BPFProgram *ip_bpf_ingress, *ip_bpf_ingress_installed;
415 BPFProgram *ip_bpf_egress, *ip_bpf_egress_installed;
0fd9c28c 416
fab34748
KL
417 Set *ip_bpf_custom_ingress;
418 Set *ip_bpf_custom_ingress_installed;
419 Set *ip_bpf_custom_egress;
420 Set *ip_bpf_custom_egress_installed;
6a48d82f 421
5f8ba20d
JK
422 /* BPF programs managed (e.g. loaded to kernel) by an entity external to systemd,
423 * attached to unit cgroup by provided program fd and attach type. */
424 Hashmap *bpf_foreign_by_key;
425
3d027d4d 426 FDSet *initial_socket_bind_link_fds;
91ce91c7
JK
427#if BPF_FRAMEWORK
428 /* BPF links to BPF programs attached to cgroup/bind{4|6} hooks and
429 * responsible for allowing or denying a unit to bind(2) to a socket
430 * address. */
431 struct bpf_link *ipv4_socket_bind_link;
432 struct bpf_link *ipv6_socket_bind_link;
433#endif
434
6f50d4f7
MV
435 FDSet *initial_restric_ifaces_link_fds;
436#if BPF_FRAMEWORK
437 struct bpf_link *restrict_ifaces_ingress_bpf_link;
438 struct bpf_link *restrict_ifaces_egress_bpf_link;
439#endif
440
50be4f4a
LP
441 /* Low-priority event source which is used to remove watched PIDs that have gone away, and subscribe to any new
442 * ones which might have appeared. */
443 sd_event_source *rewatch_pids_event_source;
444
294446dc
LP
445 /* How to start OnSuccess=/OnFailure= units */
446 JobMode on_success_job_mode;
7c52a17b
ZJS
447 JobMode on_failure_job_mode;
448
48b92b37
LB
449 /* If the job had a specific trigger that needs to be advertised (eg: a path unit), store it. */
450 ActivationDetails *activation_details;
451
5afe510c
LP
452 /* Tweaking the GC logic */
453 CollectMode collect_mode;
454
4b58153d
LP
455 /* The current invocation ID */
456 sd_id128_t invocation_id;
457 char invocation_id_string[SD_ID128_STRING_MAX]; /* useful when logging */
458
9d58f1db
LP
459 /* Garbage collect us we nobody wants or requires us anymore */
460 bool stop_when_unneeded;
461
35b8ca3a 462 /* Create default dependencies */
a40eb732
LP
463 bool default_dependencies;
464
559214cb
LB
465 /* Configure so that the unit survives a system transition without stopping/starting. */
466 bool survive_final_kill_signal;
467
b5e9dba8
LP
468 /* Refuse manual starting, allow starting only indirectly via dependency. */
469 bool refuse_manual_start;
470
471 /* Don't allow the user to stop this unit manually, allow stopping only indirectly via dependency. */
472 bool refuse_manual_stop;
473
2528a7a6
LP
474 /* Allow isolation requests */
475 bool allow_isolate;
476
c8f4d764
LP
477 /* Ignore this unit when isolating */
478 bool ignore_on_isolate;
479
49f43d5f 480 /* Did the last condition check succeed? */
90bbc946 481 bool condition_result;
59fccdc5 482 bool assert_result;
90bbc946 483
c2756a68
LP
484 /* Is this a transient unit? */
485 bool transient;
486
f5869324
LP
487 /* Is this a unit that is always running and cannot be stopped? */
488 bool perpetual;
489
66fa4bdd 490 /* Booleans indicating membership of this unit in the various queues */
9d58f1db
LP
491 bool in_load_queue:1;
492 bool in_dbus_queue:1;
493 bool in_cleanup_queue:1;
701cc384 494 bool in_gc_queue:1;
91a6073e 495 bool in_cgroup_realize_queue:1;
09e24654 496 bool in_cgroup_empty_queue:1;
afcfaa69 497 bool in_cgroup_oom_queue:1;
19496554 498 bool in_target_deps_queue:1;
a3c1168a 499 bool in_stop_when_unneeded_queue:1;
0bc488c9 500 bool in_start_when_upheld_queue:1;
56c59592 501 bool in_stop_when_bound_queue:1;
6ac62d61 502 bool in_release_resources_queue:1;
701cc384 503
9d58f1db 504 bool sent_dbus_new_signal:1;
6c073082 505
8c2524c7
ZJS
506 bool job_running_timeout_set:1;
507
cd6d0a45 508 bool in_audit:1;
adefcf28 509 bool on_console:1;
a57f7e2c
LP
510
511 bool cgroup_realized:1;
bc432dc7 512 bool cgroup_members_mask_valid:1;
f78f265f 513
3c7416b6
LP
514 /* Reset cgroup accounting next time we fork something off */
515 bool reset_accounting:1;
516
6bf0f408
LP
517 bool start_limit_hit:1;
518
f78f265f 519 /* Did we already invoke unit_coldplug() for this unit? */
f8a30ce5 520 bool coldplugged:1;
05a98afd
LP
521
522 /* For transient units: whether to add a bus track reference after creating the unit */
523 bool bus_track_add:1;
d3070fbd
LP
524
525 /* Remember which unit state files we created */
526 bool exported_invocation_id:1;
527 bool exported_log_level_max:1;
528 bool exported_log_extra_fields:1;
5ac1530e
ZJS
529 bool exported_log_ratelimit_interval:1;
530 bool exported_log_ratelimit_burst:1;
2e59b241 531
527ede0c
FB
532 /* Whether we warned about clamping the CPU quota period */
533 bool warned_clamping_cpu_quota_period:1;
534
2e59b241
LP
535 /* When writing transient unit files, stores which section we stored last. If < 0, we didn't write any yet. If
536 * == 0 we are in the [Unit] section, if > 0 we are in the unit type-specific section. */
845d247a 537 signed int last_section_private:2;
57b7a260 538} Unit;
87f0e418 539
57b7a260 540typedef struct UnitStatusMessageFormats {
c6918296
MS
541 const char *starting_stopping[2];
542 const char *finished_start_job[_JOB_RESULT_MAX];
543 const char *finished_stop_job[_JOB_RESULT_MAX];
eda0cbf0
ZJS
544 /* If this entry is present, it'll be called to provide a context-dependent format string,
545 * or NULL to fall back to finished_{start,stop}_job; if those are NULL too, fall back to generic. */
546 const char *(*finished_job)(Unit *u, JobType t, JobResult result);
57b7a260 547} UnitStatusMessageFormats;
c6918296 548
2e59b241
LP
549/* Flags used when writing drop-in files or transient unit files */
550typedef enum UnitWriteFlags {
551 /* Write a runtime unit file or drop-in (i.e. one below /run) */
f3af6290 552 UNIT_RUNTIME = 1 << 0,
2e59b241
LP
553
554 /* Write a persistent drop-in (i.e. one below /etc) */
f3af6290 555 UNIT_PERSISTENT = 1 << 1,
2e59b241
LP
556
557 /* Place this item in the per-unit-type private section, instead of [Unit] */
f3af6290 558 UNIT_PRIVATE = 1 << 2,
2e59b241 559
f3af6290
ZJS
560 /* Apply specifier escaping */
561 UNIT_ESCAPE_SPECIFIERS = 1 << 3,
24536beb 562
f3af6290
ZJS
563 /* Escape elements of ExecStart= syntax, incl. prevention of variable expansion */
564 UNIT_ESCAPE_EXEC_SYNTAX_ENV = 1 << 4,
2e59b241 565
8c41640a
ZJS
566 /* Escape elements of ExecStart=: syntax (no variable expansion) */
567 UNIT_ESCAPE_EXEC_SYNTAX = 1 << 5,
2e59b241
LP
568
569 /* Apply C escaping before writing */
8c41640a 570 UNIT_ESCAPE_C = 1 << 6,
2e59b241
LP
571} UnitWriteFlags;
572
573/* Returns true if neither persistent, nor runtime storage is requested, i.e. this is a check invocation only */
6529ccfa
LP
574static inline bool UNIT_WRITE_FLAGS_NOOP(UnitWriteFlags flags) {
575 return (flags & (UNIT_RUNTIME|UNIT_PERSISTENT)) == 0;
576}
8e2af478 577
57b7a260
FS
578#include "kill.h"
579
580typedef struct UnitVTable {
7d17cfbc
MS
581 /* How much memory does an object of this unit type need */
582 size_t object_size;
583
3ef63c31
LP
584 /* If greater than 0, the offset into the object where
585 * ExecContext is found, if the unit type has that */
586 size_t exec_context_offset;
587
4ad49000
LP
588 /* If greater than 0, the offset into the object where
589 * CGroupContext is found, if the unit type has that */
590 size_t cgroup_context_offset;
591
718db961
LP
592 /* If greater than 0, the offset into the object where
593 * KillContext is found, if the unit type has that */
594 size_t kill_context_offset;
595
613b411c 596 /* If greater than 0, the offset into the object where the
e76506b7 597 * pointer to ExecSharedRuntime is found, if the unit type has
613b411c
LP
598 * that */
599 size_t exec_runtime_offset;
600
ee33e53a 601 /* The name of the configuration file section with the private settings of this unit */
4ad49000 602 const char *private_section;
71645aca 603
f975e971
LP
604 /* Config file sections this unit type understands, separated
605 * by NUL chars */
606 const char *sections;
607
e537352b 608 /* This should reset all type-specific variables. This should
a16e1123
LP
609 * not allocate memory, and is called with zero-initialized
610 * data. It should hence only initialize variables that need
611 * to be set != 0. */
e537352b
LP
612 void (*init)(Unit *u);
613
a16e1123
LP
614 /* This should free all type-specific variables. It should be
615 * idempotent. */
616 void (*done)(Unit *u);
617
e537352b
LP
618 /* Actually load data from disk. This may fail, and should set
619 * load_state to UNIT_LOADED, UNIT_MERGED or leave it at
620 * UNIT_STUB if no configuration could be found. */
621 int (*load)(Unit *u);
622
f0831ed2 623 /* During deserialization we only record the intended state to return to. With coldplug() we actually put the
a95c0505
LP
624 * deserialized state in effect. This is where unit_notify() should be called to start things up. Note that
625 * this callback is invoked *before* we leave the reloading state of the manager, i.e. *before* we consider the
626 * reloading to be complete. Thus, this callback should just restore the exact same state for any unit that was
627 * in effect before the reload, i.e. units should not catch up with changes happened during the reload. That's
628 * what catchup() below is for. */
be847e82 629 int (*coldplug)(Unit *u);
87f0e418 630
a95c0505
LP
631 /* This is called shortly after all units' coldplug() call was invoked, and *after* the manager left the
632 * reloading state. It's supposed to catch up with state changes due to external events we missed so far (for
633 * example because they took place while we were reloading/reexecing) */
f0831ed2
LP
634 void (*catchup)(Unit *u);
635
87f0e418
LP
636 void (*dump)(Unit *u, FILE *f, const char *prefix);
637
638 int (*start)(Unit *u);
639 int (*stop)(Unit *u);
640 int (*reload)(Unit *u);
641
380dc8b0
LP
642 /* Clear out the various runtime/state/cache/logs/configuration data */
643 int (*clean)(Unit *u, ExecCleanMask m);
644
d9e45bc3
MS
645 /* Freeze the unit */
646 int (*freeze)(Unit *u);
647 int (*thaw)(Unit *u);
648 bool (*can_freeze)(Unit *u);
649
380dc8b0
LP
650 /* Return which kind of data can be cleaned */
651 int (*can_clean)(Unit *u, ExecCleanMask *ret);
652
87f0e418
LP
653 bool (*can_reload)(Unit *u);
654
1ece068e
ZJS
655 /* Serialize state and file descriptors that should be carried over into the new
656 * instance after reexecution. */
a16e1123
LP
657 int (*serialize)(Unit *u, FILE *f, FDSet *fds);
658
659 /* Restore one item from the serialization */
660 int (*deserialize_item)(Unit *u, const char *key, const char *data, FDSet *fds);
661
01e10de3 662 /* Try to match up fds with what we need for this unit */
9ff1a6f1 663 void (*distribute_fds)(Unit *u, FDSet *fds);
01e10de3 664
87f0e418
LP
665 /* Boils down the more complex internal state of this unit to
666 * a simpler one that the engine can understand */
667 UnitActiveState (*active_state)(Unit *u);
668
10a94420
LP
669 /* Returns the substate specific to this unit type as
670 * string. This is purely information so that we can give the
35b8ca3a 671 * user a more fine grained explanation in which actual state a
10a94420
LP
672 * unit is in. */
673 const char* (*sub_state_to_string)(Unit *u);
674
deb4e708
MK
675 /* Additionally to UnitActiveState determine whether unit is to be restarted. */
676 bool (*will_restart)(Unit *u);
677
f2f725e5
ZJS
678 /* Return false when there is a reason to prevent this unit from being gc'ed
679 * even though nothing references it and it isn't active in any way. */
680 bool (*may_gc)(Unit *u);
701cc384 681
39c79477
ZJS
682 /* Return true when the unit is not controlled by the manager (e.g. extrinsic mounts). */
683 bool (*is_extrinsic)(Unit *u);
684
7eb2a8a1
LP
685 /* When the unit is not running and no job for it queued we shall release its runtime resources */
686 void (*release_resources)(Unit *u);
a354329f 687
718db961 688 /* Invoked on every child that died */
87f0e418 689 void (*sigchld_event)(Unit *u, pid_t pid, int code, int status);
7824bbeb 690
fdf20a31
MM
691 /* Reset failed state if we are in failed state */
692 void (*reset_failed)(Unit *u);
5632e374 693
afcfaa69 694 /* Called whenever any of the cgroups this unit watches for ran empty */
4ad49000 695 void (*notify_cgroup_empty)(Unit *u);
8e274523 696
afcfaa69 697 /* Called whenever an OOM kill event on this unit was seen */
38c41427 698 void (*notify_cgroup_oom)(Unit *u, bool managed_oom);
afcfaa69 699
8c47c732 700 /* Called whenever a process of this unit sends us a message */
fcee2755 701 void (*notify_message)(Unit *u, const struct ucred *ucred, char * const *tags, FDSet *fds);
8c47c732 702
00d9ef85 703 /* Called whenever a name this Unit registered for comes or goes away. */
fc67a943 704 void (*bus_name_owner_change)(Unit *u, const char *new_owner);
05e343b7 705
8e2af478 706 /* Called for each property that is being set */
2e59b241 707 int (*bus_set_property)(Unit *u, const char *name, sd_bus_message *message, UnitWriteFlags flags, sd_bus_error *error);
8e2af478
LP
708
709 /* Called after at least one property got changed to apply the necessary change */
710 int (*bus_commit_properties)(Unit *u);
711
a7f241db
LP
712 /* Return the unit this unit is following */
713 Unit *(*following)(Unit *u);
714
6210e7fc
LP
715 /* Return the set of units that are following each other */
716 int (*following_set)(Unit *u, Set **s);
717
3ecaa09b
LP
718 /* Invoked each time a unit this unit is triggering changes
719 * state or gains/loses a job */
720 void (*trigger_notify)(Unit *u, Unit *trigger);
721
8742514c
LP
722 /* Called whenever CLOCK_REALTIME made a jump */
723 void (*time_change)(Unit *u);
724
bbf5fd8e
LP
725 /* Called whenever /etc/localtime was modified */
726 void (*timezone_change)(Unit *u);
727
7a7821c8
LP
728 /* Returns the next timeout of a unit */
729 int (*get_timeout)(Unit *u, usec_t *timeout);
68db7a3b 730
f5a9d2ee 731 /* Returns the start timeout of a unit */
732 usec_t (*get_timeout_start_usec)(Unit *u);
733
291d565a 734 /* Returns the main PID if there is any defined, or 0. */
3e22239d 735 PidRef* (*main_pid)(Unit *u, bool *ret_is_alien);
291d565a 736
37eb258e
LP
737 /* Returns the control PID if there is any defined, or 0. */
738 PidRef* (*control_pid)(Unit *u);
291d565a 739
bb2c7685
LP
740 /* Returns true if the unit currently needs access to the console */
741 bool (*needs_console)(Unit *u);
742
7af67e9a
LP
743 /* Returns the exit status to propagate in case of FailureAction=exit/SuccessAction=exit; usually returns the
744 * exit code of the "main" process of the service or similar. */
745 int (*exit_status)(Unit *u);
746
5e1669ff
ZJS
747 /* Return a copy of the status string pointer. */
748 const char* (*status_text)(Unit *u);
749
04eb582a
LP
750 /* Like the enumerate() callback further down, but only enumerates the perpetual units, i.e. all units that
751 * unconditionally exist and are always active. The main reason to keep both enumeration functions separate is
752 * philosophical: the state of perpetual units should be put in place by coldplug(), while the state of those
753 * discovered through regular enumeration should be put in place by catchup(), see below. */
754 void (*enumerate_perpetual)(Manager *m);
755
f0831ed2
LP
756 /* This is called for each unit type and should be used to enumerate units already existing in the system
757 * internally and load them. However, everything that is loaded here should still stay in inactive state. It is
04eb582a 758 * the job of the catchup() call above to put the units into the discovered state. */
ba64af90 759 void (*enumerate)(Manager *m);
f50e0a01
LP
760
761 /* Type specific cleanups. */
7824bbeb 762 void (*shutdown)(Manager *m);
9d58f1db 763
cbd4a8df 764 /* If this function is set and returns false all jobs for units
0faacd47 765 * of this type will immediately fail. */
1c2e9646 766 bool (*supported)(void);
0faacd47 767
9727f242
DDM
768 /* If this function is set, it's invoked first as part of starting a unit to allow start rate
769 * limiting checks to occur before we do anything else. */
705578c3 770 int (*can_start)(Unit *u);
9727f242 771
47261967
LP
772 /* Returns > 0 if the whole subsystem is ratelimited, and new start operations should not be started
773 * for this unit type right now. */
774 int (*subsystem_ratelimited)(Manager *m);
775
718db961 776 /* The strings to print in status messages */
c6918296
MS
777 UnitStatusMessageFormats status_message_formats;
778
c2756a68 779 /* True if transient units of this type are OK */
cbd4a8df 780 bool can_transient;
c5a97ed1 781
1d9cc876 782 /* True if cgroup delegation is permissible */
cbd4a8df 783 bool can_delegate;
1d9cc876 784
c80a9a33 785 /* True if the unit type triggers other units, i.e. can have a UNIT_TRIGGERS dependency */
cbd4a8df 786 bool can_trigger;
c80a9a33
LP
787
788 /* True if the unit type knows a failure state, and thus can be source of an OnFailure= dependency */
cbd4a8df 789 bool can_fail;
c80a9a33 790
d4fd1cf2 791 /* True if units of this type shall be startable only once and then never again */
cbd4a8df 792 bool once_only;
d4fd1cf2 793
755021d4
ZJS
794 /* Do not serialize this unit when preparing for root switch */
795 bool exclude_from_switch_root_serialization;
796
c5a97ed1 797 /* True if queued jobs of this type should be GC'ed if no other job needs them anymore */
cbd4a8df 798 bool gc_jobs;
4d824a4e 799
0923b425 800 /* True if systemd-oomd can monitor and act on this unit's recursive children's cgroups */
cbd4a8df 801 bool can_set_managed_oom;
d52b8493 802
b2bfd121
LP
803 /* If true, we'll notify plymouth about this unit */
804 bool notify_plymouth;
805
d52b8493
LP
806 /* The audit events to generate on start + stop (or 0 if none shall be generated) */
807 int audit_start_message_type;
808 int audit_stop_message_type;
57b7a260 809} UnitVTable;
87f0e418
LP
810
811extern const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX];
812
c2503e35 813static inline const UnitVTable* UNIT_VTABLE(const Unit *u) {
6529ccfa
LP
814 return unit_vtable[u->type];
815}
87f0e418
LP
816
817/* For casting a unit into the various unit types */
818#define DEFINE_CAST(UPPERCASE, MixedCase) \
819 static inline MixedCase* UPPERCASE(Unit *u) { \
ac155bb8 820 if (_unlikely_(!u || u->type != UNIT_##UPPERCASE)) \
87f0e418
LP
821 return NULL; \
822 \
823 return (MixedCase*) u; \
824 }
825
826/* For casting the various unit types into a unit */
bbf11206
LP
827#define UNIT(u) \
828 ({ \
829 typeof(u) _u_ = (u); \
830 Unit *_w_ = _u_ ? &(_u_)->meta : NULL; \
831 _w_; \
832 })
87f0e418 833
35b7ff80
LP
834#define UNIT_HAS_EXEC_CONTEXT(u) (UNIT_VTABLE(u)->exec_context_offset > 0)
835#define UNIT_HAS_CGROUP_CONTEXT(u) (UNIT_VTABLE(u)->cgroup_context_offset > 0)
836#define UNIT_HAS_KILL_CONTEXT(u) (UNIT_VTABLE(u)->kill_context_offset > 0)
837
15ed3c3a
LP
838Unit* unit_has_dependency(const Unit *u, UnitDependencyAtom atom, Unit *other);
839int unit_get_dependency_array(const Unit *u, UnitDependencyAtom atom, Unit ***ret_array);
83123a44 840int unit_get_transitive_dependency_set(Unit *u, UnitDependencyAtom atom, Set **ret);
15ed3c3a
LP
841
842static inline Hashmap* unit_get_dependencies(Unit *u, UnitDependency d) {
843 return hashmap_get(u->dependencies, UNIT_DEPENDENCY_TO_PTR(d));
844}
845
6529ccfa 846static inline Unit* UNIT_TRIGGER(Unit *u) {
15ed3c3a 847 return unit_has_dependency(u, UNIT_ATOM_TRIGGERS, NULL);
6529ccfa 848}
3ecaa09b 849
12f64221 850static inline Unit* UNIT_GET_SLICE(const Unit *u) {
d219a2b0 851 return unit_has_dependency(u, UNIT_ATOM_IN_SLICE, NULL);
12f64221
LP
852}
853
75db809a
ZJS
854Unit* unit_new(Manager *m, size_t size);
855Unit* unit_free(Unit *u);
dc409696 856DEFINE_TRIVIAL_CLEANUP_FUNC(Unit *, unit_free);
87f0e418 857
a581e45a 858int unit_new_for_name(Manager *m, size_t size, const char *name, Unit **ret);
87f0e418 859int unit_add_name(Unit *u, const char *name);
9e2f7c11 860
eef85c4a
LP
861int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference, UnitDependencyMask mask);
862int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask);
2c966c03 863
35d8c19a 864int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask);
5a724170 865int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask);
2c966c03 866
23a177ef
LP
867int unit_add_exec_dependencies(Unit *u, ExecContext *c);
868
0ae97ec1 869int unit_choose_id(Unit *u, const char *name);
f50e0a01 870int unit_set_description(Unit *u, const char *description);
87f0e418 871
6ac62d61
LP
872void unit_release_resources(Unit *u);
873
f2f725e5 874bool unit_may_gc(Unit *u);
701cc384 875
39c79477
ZJS
876static inline bool unit_is_extrinsic(Unit *u) {
877 return u->perpetual ||
878 (UNIT_VTABLE(u)->is_extrinsic && UNIT_VTABLE(u)->is_extrinsic(u));
879}
880
5e1669ff
ZJS
881static inline const char* unit_status_text(Unit *u) {
882 if (u && UNIT_VTABLE(u)->status_text)
883 return UNIT_VTABLE(u)->status_text(u);
884 return NULL;
885}
886
87f0e418 887void unit_add_to_load_queue(Unit *u);
c1e1601e 888void unit_add_to_dbus_queue(Unit *u);
23a177ef 889void unit_add_to_cleanup_queue(Unit *u);
701cc384 890void unit_add_to_gc_queue(Unit *u);
19496554 891void unit_add_to_target_deps_queue(Unit *u);
fda09318 892void unit_submit_to_stop_when_unneeded_queue(Unit *u);
0bc488c9 893void unit_submit_to_start_when_upheld_queue(Unit *u);
56c59592 894void unit_submit_to_stop_when_bound_queue(Unit *u);
6ac62d61 895void unit_submit_to_release_resources_queue(Unit *u);
87f0e418
LP
896
897int unit_merge(Unit *u, Unit *other);
23a177ef
LP
898int unit_merge_by_name(Unit *u, const char *other);
899
44a6b1b6 900Unit *unit_follow_merge(Unit *u) _pure_;
87f0e418 901
c3620770 902int unit_load_fragment_and_dropin(Unit *u, bool fragment_required);
87f0e418
LP
903int unit_load(Unit *unit);
904
899acf5c 905int unit_set_slice(Unit *u, Unit *slice);
d79200e2 906int unit_set_default_slice(Unit *u);
a016b922 907
44a6b1b6 908const char *unit_description(Unit *u) _pure_;
04d232d8 909const char *unit_status_string(Unit *u, char **combined);
87f0e418 910
303ee601 911bool unit_has_name(const Unit *u, const char *name);
f278026d 912
87f0e418 913UnitActiveState unit_active_state(Unit *u);
d9e45bc3
MS
914FreezerState unit_freezer_state(Unit *u);
915int unit_freezer_state_kernel(Unit *u, FreezerState *ret);
87f0e418 916
10a94420
LP
917const char* unit_sub_state_to_string(Unit *u);
918
44a6b1b6
ZJS
919bool unit_can_reload(Unit *u) _pure_;
920bool unit_can_start(Unit *u) _pure_;
f5869324 921bool unit_can_stop(Unit *u) _pure_;
44a6b1b6 922bool unit_can_isolate(Unit *u) _pure_;
87f0e418 923
48b92b37 924int unit_start(Unit *u, ActivationDetails *details);
87f0e418
LP
925int unit_stop(Unit *u);
926int unit_reload(Unit *u);
927
a721cd00 928int unit_kill(Unit *u, KillWho w, int signo, int code, int value, sd_bus_error *error);
8a0867d6 929
38c41427
NK
930void unit_notify_cgroup_oom(Unit *u, bool managed_oom);
931
96b09de5 932void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success);
87f0e418 933
d70dfe1b 934int unit_watch_pidref(Unit *u, const PidRef *pid, bool exclusive);
f75f613d 935int unit_watch_pid(Unit *u, pid_t pid, bool exclusive);
d70dfe1b 936void unit_unwatch_pidref(Unit *u, const PidRef *pid);
87f0e418 937void unit_unwatch_pid(Unit *u, pid_t pid);
a911bb9a
LP
938void unit_unwatch_all_pids(Unit *u);
939
50be4f4a
LP
940int unit_enqueue_rewatch_pids(Unit *u);
941void unit_dequeue_rewatch_pids(Unit *u);
87f0e418 942
9806e87d 943int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name);
05e343b7
LP
944int unit_watch_bus_name(Unit *u, const char *name);
945void unit_unwatch_bus_name(Unit *u, const char *name);
946
87f0e418
LP
947bool unit_job_is_applicable(Unit *u, JobType j);
948
0301abf4
LP
949int set_unit_path(const char *p);
950
50159e6a 951char *unit_dbus_path(Unit *u);
4b58153d 952char *unit_dbus_path_invocation_id(Unit *u);
50159e6a 953
f6ff8c29
LP
954int unit_load_related_unit(Unit *u, const char *type, Unit **_found);
955
d336ba9f 956int unit_add_node_dependency(Unit *u, const char *what, UnitDependency d, UnitDependencyMask mask);
44b0d1fd 957int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask);
6e2ef85b 958
be847e82 959int unit_coldplug(Unit *u);
f0831ed2 960void unit_catchup(Unit *u);
cca098b0 961
04d232d8 962void unit_status_printf(Unit *u, StatusType status_type, const char *status, const char *format, const char *ident) _printf_(4, 0);
9e58ff9c 963
45fb0699
LP
964bool unit_need_daemon_reload(Unit *u);
965
fdf20a31 966void unit_reset_failed(Unit *u);
5632e374 967
a7f241db 968Unit *unit_following(Unit *u);
eeaedb7c 969int unit_following_set(Unit *u, Set **s);
a7f241db 970
9444b1f2
LP
971const char *unit_slice_name(Unit *u);
972
44a6b1b6
ZJS
973bool unit_stop_pending(Unit *u) _pure_;
974bool unit_inactive_or_pending(Unit *u) _pure_;
31afa0a4 975bool unit_active_or_pending(Unit *u);
52a12341 976bool unit_will_restart_default(Unit *u);
deb4e708 977bool unit_will_restart(Unit *u);
18ffdfda 978
bba34eed
LP
979int unit_add_default_target_dependency(Unit *u, Unit *target);
980
294446dc 981void unit_start_on_failure(Unit *u, const char *dependency_name, UnitDependencyAtom atom, JobMode job_mode);
3ecaa09b 982void unit_trigger_notify(Unit *u);
c0daa706 983
a4375746 984UnitFileState unit_get_unit_file_state(Unit *u);
e77e07f6 985PresetAction unit_get_unit_file_preset(Unit *u);
a4375746 986
7f7d01ed 987Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target);
57020a3a
LP
988void unit_ref_unset(UnitRef *ref);
989
7f7d01ed
ZJS
990#define UNIT_DEREF(ref) ((ref).target)
991#define UNIT_ISSET(ref) (!!(ref).target)
57020a3a 992
598459ce 993int unit_patch_contexts(Unit *u);
e06c73cc 994
c2503e35 995ExecContext *unit_get_exec_context(const Unit *u) _pure_;
718db961 996KillContext *unit_get_kill_context(Unit *u) _pure_;
4ad49000 997CGroupContext *unit_get_cgroup_context(Unit *u) _pure_;
598459ce 998
28135da3 999ExecRuntime *unit_get_exec_runtime(Unit *u) _pure_;
613b411c
LP
1000
1001int unit_setup_exec_runtime(Unit *u);
3ef63c31 1002
68ecb48b 1003const char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf);
2e59b241 1004char* unit_concat_strv(char **l, UnitWriteFlags flags);
b9ec9359 1005
2e59b241
LP
1006int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data);
1007int unit_write_settingf(Unit *u, UnitWriteFlags mode, const char *name, const char *format, ...) _printf_(4,5);
b9ec9359 1008
7901288a 1009int unit_kill_context(Unit *u, KillContext *c, KillOperation k, PidRef *main_pid, PidRef *control_pid, bool main_pid_alien);
cd2086fe 1010
c2756a68
LP
1011int unit_make_transient(Unit *u);
1012
9e615fa3 1013int unit_add_mounts_for(Unit *u, const char *path, UnitDependencyMask mask, UnitMountDependencyType type);
a57f7e2c 1014
1c2e9646
LP
1015bool unit_type_supported(UnitType t);
1016
0f13f3bd
LP
1017bool unit_is_pristine(Unit *u);
1018
a3c1168a 1019bool unit_is_unneeded(Unit *u);
0bc488c9 1020bool unit_is_upheld_by_active(Unit *u, Unit **ret_culprit);
56c59592 1021bool unit_is_bound_by_inactive(Unit *u, Unit **ret_culprit);
a3c1168a 1022
37eb258e 1023PidRef* unit_control_pid(Unit *u);
3e22239d
YW
1024PidRef* unit_main_pid_full(Unit *u, bool *ret_is_alien);
1025static inline PidRef* unit_main_pid(Unit *u) {
1026 return unit_main_pid_full(u, NULL);
1027}
291d565a 1028
8b4305c7 1029void unit_warn_if_dir_nonempty(Unit *u, const char* where);
25cd4964 1030int unit_fail_if_noncanonical(Unit *u, const char* where);
8b4305c7 1031
97a3f4ee 1032int unit_test_start_limit(Unit *u);
07299350 1033
00d9ef85
LP
1034int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid);
1035void unit_unref_uid_gid(Unit *u, bool destroy_now);
1036
1037void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid);
1038
2d3b784d 1039int unit_set_invocation_id(Unit *u, sd_id128_t id);
4b58153d
LP
1040int unit_acquire_invocation_id(Unit *u);
1041
1ad6e8b3 1042int unit_set_exec_params(Unit *s, ExecParameters *p);
f0d47797 1043
4775b55d
LP
1044int unit_fork_helper_process(Unit *u, const char *name, PidRef *ret);
1045int unit_fork_and_watch_rm_rf(Unit *u, char **paths, PidRef *ret);
a79279c7 1046
c999cf38
LP
1047void unit_remove_dependencies(Unit *u, UnitDependencyMask mask);
1048
d3070fbd
LP
1049void unit_export_state_files(Unit *u);
1050void unit_unlink_state_files(Unit *u);
1051
3c7416b6
LP
1052int unit_prepare_exec(Unit *u);
1053
4d1b2df1
LP
1054int unit_log_leftover_process_start(const PidRef* pid, int sig, void *userdata);
1055int unit_log_leftover_process_stop(const PidRef* pid, int sig, void *userdata);
1056
4c425434 1057int unit_warn_leftover_processes(Unit *u, cg_kill_log_func_t log_func);
a4634b21 1058
bb2c7685
LP
1059bool unit_needs_console(Unit *u);
1060
d70dfe1b 1061int unit_pid_attachable(Unit *unit, const PidRef *pid, sd_bus_error *error);
6592b975 1062
28a2dfe8
ZJS
1063static inline bool unit_has_job_type(Unit *u, JobType type) {
1064 return u && u->job && u->job->type == type;
1065}
1066
c2503e35
RH
1067static inline bool unit_log_level_test(const Unit *u, int level) {
1068 ExecContext *ec = unit_get_exec_context(u);
1069 return !ec || ec->log_level_max < 0 || ec->log_level_max >= LOG_PRI(level);
1070}
1071
31cd5f63
AZ
1072/* unit_log_skip is for cases like ExecCondition= where a unit is considered "done"
1073 * after some execution, rather than succeeded or failed. */
1074void unit_log_skip(Unit *u, const char *result);
523ee2d4 1075void unit_log_success(Unit *u);
7c047d74 1076void unit_log_failure(Unit *u, const char *result);
aac99f30
ZJS
1077static inline void unit_log_result(Unit *u, bool success, const char *result) {
1078 if (success)
1079 unit_log_success(u);
1080 else
1081 unit_log_failure(u, result);
1082}
1083
5cc2cd1c 1084void unit_log_process_exit(Unit *u, const char *kind, const char *command, bool success, int code, int status);
7c047d74 1085
7af67e9a
LP
1086int unit_exit_status(Unit *u);
1087int unit_success_action_exit_status(Unit *u);
1088int unit_failure_action_exit_status(Unit *u);
1089
a4191c9f
LP
1090int unit_test_trigger_loaded(Unit *u);
1091
bb0c0d6f 1092void unit_destroy_runtime_data(Unit *u, const ExecContext *context);
380dc8b0
LP
1093int unit_clean(Unit *u, ExecCleanMask mask);
1094int unit_can_clean(Unit *u, ExecCleanMask *ret_mask);
1095
f882c102
DDM
1096bool unit_can_start_refuse_manual(Unit *u);
1097bool unit_can_stop_refuse_manual(Unit *u);
1098bool unit_can_isolate_refuse_manual(Unit *u);
1099
d9e45bc3
MS
1100bool unit_can_freeze(Unit *u);
1101int unit_freeze(Unit *u);
1102void unit_frozen(Unit *u);
1103
1104int unit_thaw(Unit *u);
1105void unit_thawed(Unit *u);
1106
1107int unit_freeze_vtable_common(Unit *u);
1108int unit_thaw_vtable_common(Unit *u);
1109
6e548561
DDM
1110Condition *unit_find_failed_condition(Unit *u);
1111
e9276800
LP
1112int unit_arm_timer(Unit *u, sd_event_source **source, bool relative, usec_t usec, sd_event_time_handler_t handler);
1113
a8157796
LP
1114int unit_compare_priority(Unit *a, Unit *b);
1115
9e615fa3
LB
1116UnitMountDependencyType unit_mount_dependency_type_from_string(const char *s) _const_;
1117const char* unit_mount_dependency_type_to_string(UnitMountDependencyType t) _const_;
1118UnitDependency unit_mount_dependency_type_to_dependency_type(UnitMountDependencyType t) _pure_;
1119
e8e581bf
ZJS
1120/* Macros which append UNIT= or USER_UNIT= to the message */
1121
ac513634 1122#define log_unit_full_errno_zerook(unit, level, error, ...) \
f2341e0a 1123 ({ \
8dec4a9d 1124 const Unit *_u = (unit); \
c2503e35 1125 const int _l = (level); \
1092e82b
LB
1126 bool _do_log = !(log_get_max_level() < LOG_PRI(_l) || \
1127 (_u && !unit_log_level_test(_u, _l))); \
1128 const ExecContext *_c = _do_log && _u ? \
1129 unit_get_exec_context(_u) : NULL; \
1130 LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL, \
1131 _c ? _c->n_log_extra_fields : 0); \
1132 !_do_log ? -ERRNO_VALUE(error) : \
c2503e35
RH
1133 _u ? log_object_internal(_l, error, PROJECT_FILE, __LINE__, __func__, _u->manager->unit_log_field, _u->id, _u->manager->invocation_log_field, _u->invocation_id_string, ##__VA_ARGS__) : \
1134 log_internal(_l, error, PROJECT_FILE, __LINE__, __func__, ##__VA_ARGS__); \
f2341e0a
LP
1135 })
1136
ac513634
YW
1137#define log_unit_full_errno(unit, level, error, ...) \
1138 ({ \
1139 int _error = (error); \
1140 ASSERT_NON_ZERO(_error); \
1141 log_unit_full_errno_zerook(unit, level, _error, ##__VA_ARGS__); \
1142 })
1143
1144#define log_unit_full(unit, level, ...) (void) log_unit_full_errno_zerook(unit, level, 0, __VA_ARGS__)
8ed6f81b 1145
ac513634 1146#define log_unit_debug(unit, ...) log_unit_full(unit, LOG_DEBUG, __VA_ARGS__)
8ed6f81b
YW
1147#define log_unit_info(unit, ...) log_unit_full(unit, LOG_INFO, __VA_ARGS__)
1148#define log_unit_notice(unit, ...) log_unit_full(unit, LOG_NOTICE, __VA_ARGS__)
1149#define log_unit_warning(unit, ...) log_unit_full(unit, LOG_WARNING, __VA_ARGS__)
1150#define log_unit_error(unit, ...) log_unit_full(unit, LOG_ERR, __VA_ARGS__)
1151
1152#define log_unit_debug_errno(unit, error, ...) log_unit_full_errno(unit, LOG_DEBUG, error, __VA_ARGS__)
1153#define log_unit_info_errno(unit, error, ...) log_unit_full_errno(unit, LOG_INFO, error, __VA_ARGS__)
1154#define log_unit_notice_errno(unit, error, ...) log_unit_full_errno(unit, LOG_NOTICE, error, __VA_ARGS__)
1155#define log_unit_warning_errno(unit, error, ...) log_unit_full_errno(unit, LOG_WARNING, error, __VA_ARGS__)
1156#define log_unit_error_errno(unit, error, ...) log_unit_full_errno(unit, LOG_ERR, error, __VA_ARGS__)
f2341e0a 1157
556b6f4e
DDM
1158#if LOG_TRACE
1159# define log_unit_trace(...) log_unit_debug(__VA_ARGS__)
1160# define log_unit_trace_errno(...) log_unit_debug_errno(__VA_ARGS__)
1161#else
1162# define log_unit_trace(...) do {} while (0)
1163# define log_unit_trace_errno(e, ...) (-ERRNO_VALUE(e))
1164#endif
1165
c2503e35
RH
1166#define log_unit_struct_errno(unit, level, error, ...) \
1167 ({ \
1168 const Unit *_u = (unit); \
1169 const int _l = (level); \
1092e82b
LB
1170 bool _do_log = unit_log_level_test(_u, _l); \
1171 const ExecContext *_c = _do_log && _u ? \
1172 unit_get_exec_context(_u) : NULL; \
1173 LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL, \
1174 _c ? _c->n_log_extra_fields : 0); \
1175 _do_log ? \
c2503e35
RH
1176 log_struct_errno(_l, error, __VA_ARGS__, LOG_UNIT_ID(_u)) : \
1177 -ERRNO_VALUE(error); \
1178 })
1179
1180#define log_unit_struct(unit, level, ...) log_unit_struct_errno(unit, level, 0, __VA_ARGS__)
1181
1182#define log_unit_struct_iovec_errno(unit, level, error, iovec, n_iovec) \
1183 ({ \
1092e82b 1184 const Unit *_u = (unit); \
c2503e35 1185 const int _l = (level); \
1092e82b
LB
1186 bool _do_log = unit_log_level_test(_u, _l); \
1187 const ExecContext *_c = _do_log && _u ? \
1188 unit_get_exec_context(_u) : NULL; \
1189 LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL, \
1190 _c ? _c->n_log_extra_fields : 0); \
1191 _do_log ? \
c2503e35
RH
1192 log_struct_iovec_errno(_l, error, iovec, n_iovec) : \
1193 -ERRNO_VALUE(error); \
1194 })
1195
1196#define log_unit_struct_iovec(unit, level, iovec, n_iovec) log_unit_struct_iovec_errno(unit, level, 0, iovec, n_iovec)
1197
b9ce5cf9
ZJS
1198/* Like LOG_MESSAGE(), but with the unit name prefixed. */
1199#define LOG_UNIT_MESSAGE(unit, fmt, ...) LOG_MESSAGE("%s: " fmt, (unit)->id, ##__VA_ARGS__)
f2341e0a 1200#define LOG_UNIT_ID(unit) (unit)->manager->unit_log_format_string, (unit)->id
f1c50bec 1201#define LOG_UNIT_INVOCATION_ID(unit) (unit)->manager->invocation_log_format_string, (unit)->invocation_id_string
5afe510c
LP
1202
1203const char* collect_mode_to_string(CollectMode m) _const_;
1204CollectMode collect_mode_from_string(const char *s) _pure_;
15ed3c3a
LP
1205
1206typedef struct UnitForEachDependencyData {
1207 /* Stores state for the FOREACH macro below for iterating through all deps that have any of the
1208 * specified dependency atom bits set */
1209 UnitDependencyAtom match_atom;
1210 Hashmap *by_type, *by_unit;
1211 void *current_type;
1212 Iterator by_type_iterator, by_unit_iterator;
1213 Unit **current_unit;
1214} UnitForEachDependencyData;
1215
1216/* Iterates through all dependencies that have a specific atom in the dependency type set. This tries to be
1217 * smart: if the atom is unique, we'll directly go to right entry. Otherwise we'll iterate through the
1218 * per-dependency type hashmap and match all dep that have the right atom set. */
1219#define _UNIT_FOREACH_DEPENDENCY(other, u, ma, data) \
1220 for (UnitForEachDependencyData data = { \
1221 .match_atom = (ma), \
1222 .by_type = (u)->dependencies, \
1223 .by_type_iterator = ITERATOR_FIRST, \
1224 .current_unit = &(other), \
1225 }; \
1226 ({ \
1227 UnitDependency _dt = _UNIT_DEPENDENCY_INVALID; \
1228 bool _found; \
1229 \
1230 if (data.by_type && ITERATOR_IS_FIRST(data.by_type_iterator)) { \
1231 _dt = unit_dependency_from_unique_atom(data.match_atom); \
1232 if (_dt >= 0) { \
1233 data.by_unit = hashmap_get(data.by_type, UNIT_DEPENDENCY_TO_PTR(_dt)); \
1234 data.current_type = UNIT_DEPENDENCY_TO_PTR(_dt); \
1235 data.by_type = NULL; \
1236 _found = !!data.by_unit; \
1237 } \
1238 } \
1239 if (_dt < 0) \
1240 _found = hashmap_iterate(data.by_type, \
1241 &data.by_type_iterator, \
1242 (void**)&(data.by_unit), \
1243 (const void**) &(data.current_type)); \
1244 _found; \
1245 }); ) \
1246 if ((unit_dependency_to_atom(UNIT_DEPENDENCY_FROM_PTR(data.current_type)) & data.match_atom) != 0) \
1247 for (data.by_unit_iterator = ITERATOR_FIRST; \
1248 hashmap_iterate(data.by_unit, \
1249 &data.by_unit_iterator, \
1250 NULL, \
1251 (const void**) data.current_unit); )
1252
1253/* Note: this matches deps that have *any* of the atoms specified in match_atom set */
1254#define UNIT_FOREACH_DEPENDENCY(other, u, match_atom) \
1255 _UNIT_FOREACH_DEPENDENCY(other, u, match_atom, UNIQ_T(data, UNIQ))
4b2af439
DDM
1256
1257#define _LOG_CONTEXT_PUSH_UNIT(unit, u, c) \
1258 const Unit *u = (unit); \
1259 const ExecContext *c = unit_get_exec_context(u); \
1260 LOG_CONTEXT_PUSH_KEY_VALUE(u->manager->unit_log_field, u->id); \
1261 LOG_CONTEXT_PUSH_KEY_VALUE(u->manager->invocation_log_field, u->invocation_id_string); \
1262 LOG_CONTEXT_PUSH_IOV(c ? c->log_extra_fields : NULL, c ? c->n_log_extra_fields : 0)
1263
1264#define LOG_CONTEXT_PUSH_UNIT(unit) \
1265 _LOG_CONTEXT_PUSH_UNIT(unit, UNIQ_T(u, UNIQ), UNIQ_T(c, UNIQ))