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