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