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