podup 3.2.0

Translate and run docker-compose files on rootless Podman
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! `podup autostart` service mode: a single rootless `systemctl --user` unit that
//! brings a compose stack up at boot.
//!
//! Everything here is user-scope only — the unit lives under
//! `${XDG_CONFIG_HOME:-~/.config}/systemd/user/` and every action goes through
//! `systemctl --user` / `loginctl`. No root, no `sudo`, nothing under `/etc` or
//! the system systemd. External-command calls go through the `SystemCtl` seam so
//! the install/uninstall/status logic is unit-testable without a live systemd.

mod quadlet;
mod service;

pub use quadlet::{install_quadlet, rebuild_quadlet, uninstall_quadlet};
pub use service::{render_service_unit, ServiceUnitOpts};

use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use crate::ComposeError;

/// Seam over the external `systemctl --user` / `loginctl` commands. The real impl
/// shells out; tests substitute a fake that records the argument vectors and
/// returns canned output, so install/uninstall/status are exercised without
/// touching the host's systemd.
pub trait SystemCtl {
	/// Run `systemctl --user <args>`.
	fn systemctl(&self, args: &[&str]) -> io::Result<Output>;
	/// Run `loginctl <args>`.
	fn loginctl(&self, args: &[&str]) -> io::Result<Output>;
}

/// The production [`SystemCtl`]: invokes the real `systemctl --user` and
/// `loginctl` binaries.
pub struct RealSystemCtl;

impl SystemCtl for RealSystemCtl {
	fn systemctl(&self, args: &[&str]) -> io::Result<Output> {
		Command::new("systemctl").arg("--user").args(args).output()
	}

	fn loginctl(&self, args: &[&str]) -> io::Result<Output> {
		Command::new("loginctl").args(args).output()
	}
}

/// The longest `stop_grace_period` across a compose file's services, in seconds.
///
/// systemd bounds `ExecStop` independently of what runs inside it, and its
/// default `DefaultTimeoutStopUSec` is 90s. `podup stop` honours each
/// container's own grace period, so a stack whose slowest container needs more
/// than that stops cleanly when a human runs it and gets killed mid-stop at
/// reboot — the difference only shows up during an unattended shutdown, which
/// is the worst version of it.
///
/// `None` when no service sets one, or when none parses, so the unit simply
/// omits `TimeoutStopSec=` and keeps systemd's default. An unparseable duration
/// is skipped rather than defaulted: the value is validated elsewhere, and
/// guessing a timeout from a malformed one would be worse than not setting it.
pub fn max_stop_grace_secs(file: &crate::compose::types::ComposeFile) -> Option<u64> {
	file.services
		.values()
		.filter_map(|s| s.stop_grace_period.as_deref())
		.filter_map(crate::size::parse_duration_secs)
		.max()
}

/// Options for [`install`].
///
/// `#[non_exhaustive]`: see [`ServiceUnitOpts`] — same reason, same construction
/// pattern.
#[non_exhaustive]
#[derive(Default)]
pub struct InstallOptions {
	/// The unit to render and install.
	pub unit: ServiceUnitOpts,
	/// Install the unit but do not `enable --now` it (no immediate start).
	pub no_start: bool,
	/// Print the unit and the actions that would run, but change nothing.
	pub dry_run: bool,
}

impl InstallOptions {
	/// Install `unit` with the default flags (start it, really write it).
	pub fn new(unit: ServiceUnitOpts) -> Self {
		Self {
			unit,
			no_start: false,
			dry_run: false,
		}
	}

	/// Install the unit but do not `enable --now` it. Builder-style.
	pub fn with_no_start(mut self, no_start: bool) -> Self {
		self.no_start = no_start;
		self
	}

	/// Print what would happen and change nothing. Builder-style.
	pub fn with_dry_run(mut self, dry_run: bool) -> Self {
		self.dry_run = dry_run;
		self
	}
}

/// `${XDG_CONFIG_HOME:-~/.config}`. Falls back to `$HOME/.config`, then `.config`
/// in the working directory if even `HOME` is unset (so a path is always formed).
fn config_home() -> PathBuf {
	if let Some(x) = std::env::var_os("XDG_CONFIG_HOME").filter(|s| !s.is_empty()) {
		return PathBuf::from(x);
	}
	match std::env::var_os("HOME").filter(|s| !s.is_empty()) {
		Some(home) => PathBuf::from(home).join(".config"),
		None => PathBuf::from(".config"),
	}
}

/// Directory that holds `systemctl --user` unit files.
fn unit_dir() -> PathBuf {
	config_home().join("systemd").join("user")
}

/// The unit's file name: `podup-<project>.service`. The project name is validated
/// as a safe path component before reaching here, so it cannot escape `unit_dir`.
fn unit_file_name(project: &str) -> String {
	format!("podup-{project}.service")
}

/// Full path to the unit file for a project.
fn unit_path(project: &str) -> PathBuf {
	unit_dir().join(unit_file_name(project))
}

/// The current login user, for `loginctl` and linger queries. Read from the
/// environment to avoid an `unsafe` `getuid` FFI call.
fn current_user() -> Option<String> {
	std::env::var("USER")
		.ok()
		.or_else(|| std::env::var("LOGNAME").ok())
		.filter(|s| !s.is_empty())
}

/// Quadlet autostart units for this project, if any exist on disk. Service mode
/// and Quadlet mode would both try to start the same stack at boot, so an
/// existing Quadlet install is a conflict to surface, not to silently overwrite.
/// Looks for `<project>-*.container` under
/// `${XDG_CONFIG_HOME:-~/.config}/containers/systemd/`.
fn quadlet_units_present(project: &str) -> Vec<PathBuf> {
	let dir = config_home().join("containers").join("systemd");
	let prefix = format!("{project}-");
	let mut found = Vec::new();
	if let Ok(entries) = std::fs::read_dir(&dir) {
		for entry in entries.flatten() {
			let name = entry.file_name();
			let name = name.to_string_lossy();
			if name.starts_with(&prefix) && name.ends_with(".container") {
				found.push(entry.path());
			}
		}
	}
	found.sort();
	found
}

/// Whether linger is enabled for `user` (so the user manager — and the stack —
/// survives logout and starts at boot). Parses `loginctl show-user <user>
/// --value --property=Linger`, treating any error/unexpected output as "off".
fn linger_enabled<S: SystemCtl>(sc: &S, user: &str) -> bool {
	match sc.loginctl(&["show-user", user, "--value", "--property=Linger"]) {
		Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout)
			.trim()
			.eq_ignore_ascii_case("yes"),
		_ => false,
	}
}

/// Advisory when linger is off: without it the user manager is not started at
/// boot, so the unit will not bring the stack up until first login. Returns the
/// message to print, or `None` when linger is already enabled.
fn linger_warning<S: SystemCtl>(sc: &S) -> Option<String> {
	let user = current_user()?;
	if linger_enabled(sc, &user) {
		return None;
	}
	Some(format!(
		"linger is not enabled for {user}; the stack will not start at boot until you run:\n    \
		 loginctl enable-linger {user}"
	))
}

/// Advisory when `XDG_RUNTIME_DIR` is unset: `systemctl --user` needs a live user
/// session bus, which is otherwise missing (so the calls below will likely fail).
/// Returns the message to print, or `None` when the variable is set.
fn runtime_dir_warning() -> Option<String> {
	let present = std::env::var_os("XDG_RUNTIME_DIR").is_some_and(|s| !s.is_empty());
	if present {
		return None;
	}
	Some(
		"XDG_RUNTIME_DIR is not set; `systemctl --user` needs an active user session. \
		 Open one (e.g. `machinectl shell <user>@`) or export XDG_RUNTIME_DIR before retrying."
			.to_string(),
	)
}

/// Print the linger and runtime-dir advisories to stderr (warn, never fail).
fn emit_guards<S: SystemCtl>(sc: &S) {
	for warning in [linger_warning(sc), runtime_dir_warning()]
		.into_iter()
		.flatten()
	{
		tracing::warn!("{warning}");
	}
}

/// Turn a `systemctl` invocation result into a `Result`, mapping a launch failure
/// or a non-zero exit into a clear autostart error naming the action.
fn checked(res: io::Result<Output>, what: &str) -> crate::Result<()> {
	let out = res.map_err(|e| {
		ComposeError::Autostart(format!("failed to run `systemctl --user {what}`: {e}"))
	})?;
	if out.status.success() {
		return Ok(());
	}
	let stderr = String::from_utf8_lossy(&out.stderr);
	Err(ComposeError::Autostart(format!(
		"`systemctl --user {what}` failed: {}",
		stderr.trim()
	)))
}

/// Install (and, unless `no_start`, enable + start) the service-mode autostart
/// unit. Writes only under `${XDG_CONFIG_HOME:-~/.config}/systemd/user/`.
pub fn install<S: SystemCtl>(sc: &S, opts: &InstallOptions) -> crate::Result<()> {
	let project = &opts.unit.project;
	let path = unit_path(project);

	// Refuse to stack service mode on top of an existing Quadlet autostart install
	// for the same project — both would start the stack at boot.
	let quadlet = quadlet_units_present(project);
	if !quadlet.is_empty() {
		let names: Vec<String> = quadlet.iter().map(|p| p.display().to_string()).collect();
		return Err(ComposeError::Autostart(format!(
			"quadlet autostart units for project '{project}' already exist:\n    {}\n\
			 remove them before installing service mode (quadlet autostart is tracked by #993).",
			names.join("\n    ")
		)));
	}

	// Fail closed on values a unit line cannot represent (control characters
	// would inject directives via the literal `WorkingDirectory=` line).
	service::validate_unit_opts(&opts.unit).map_err(ComposeError::Autostart)?;

	let unit_text = render_service_unit(&opts.unit);
	let unit_name = unit_file_name(project);

	// Surface the linger / session guards before acting (or previewing).
	emit_guards(sc);

	if opts.dry_run {
		print!("{unit_text}");
		println!("\n# would write {}", path.display());
		println!("# would run: systemctl --user daemon-reload");
		if opts.no_start {
			println!("# (--no-start) would not enable or start the unit");
		} else {
			println!("# would run: systemctl --user enable --now {unit_name}");
		}
		return Ok(());
	}

	let dir = unit_dir();
	std::fs::create_dir_all(&dir)
		.map_err(|e| ComposeError::Autostart(format!("cannot create {}: {e}", dir.display())))?;
	std::fs::write(&path, unit_text.as_bytes())
		.map_err(|e| ComposeError::Autostart(format!("cannot write {}: {e}", path.display())))?;
	eprintln!("podup: wrote {}", path.display());

	checked(sc.systemctl(&["daemon-reload"]), "daemon-reload")?;
	if opts.no_start {
		eprintln!("podup: installed {unit_name} (not enabled; --no-start)");
	} else {
		checked(
			sc.systemctl(&["enable", "--now", &unit_name]),
			&format!("enable --now {unit_name}"),
		)?;
		eprintln!("podup: enabled and started {unit_name}");
	}
	Ok(())
}

/// Whether systemd knows anything about `unit` — loaded, enabled, running, or
/// merely present as a fragment.
///
/// `systemctl is-active` exits **4** for a unit it has never heard of and
/// something else for every other state (0 active, 3 inactive/failed/activating).
/// That numeric 4 is the only reliable "there is nothing here" signal: the
/// message text is localised, and the *fragment file* is not a proxy for it —
/// measured, a unit whose file is deleted out of band stays loaded, enabled and
/// running, and `disable --now` still exits 0, removes its `.wants/` symlink and
/// stops it. Gating on the file would delete the only way out of that state.
///
/// A probe that cannot even be spawned returns `true`: the right response to
/// "I could not ask" is to attempt the disable anyway and let `checked` report
/// whatever happens, never to assume there is nothing to do.
fn unit_is_known<S: SystemCtl>(sc: &S, unit: &str) -> bool {
	sc.systemctl(&["is-active", "--quiet", unit])
		.map(|o| o.status.code() != Some(4))
		.unwrap_or(true)
}

/// Uninstall the service-mode autostart unit: disable + stop it, remove the unit
/// file, and reload the user manager.
///
/// Idempotent — uninstalling when nothing is installed is a quiet no-op — but a
/// `disable` that genuinely fails is reported rather than swallowed, so the
/// command cannot claim success while the service is still enabled and running.
pub fn uninstall<S: SystemCtl>(sc: &S, project: &str) -> crate::Result<()> {
	let unit_name = unit_file_name(project);
	let path = unit_path(project);

	// Disable whenever systemd knows the unit, whether or not its file is still
	// there. `disable --now` is idempotent across every state it can be in
	// (enabled, never enabled, running, stopped, fragment deleted out of band),
	// so the only case worth skipping is the one where systemd has never heard
	// of it — which is exactly what `unit_is_known` answers.
	if unit_is_known(sc, &unit_name) {
		checked(
			sc.systemctl(&["disable", "--now", &unit_name]),
			"disable --now",
		)?;
	}

	if path.exists() {
		std::fs::remove_file(&path).map_err(|e| {
			ComposeError::Autostart(format!("cannot remove {}: {e}", path.display()))
		})?;
		eprintln!("podup: removed {}", path.display());
	} else {
		eprintln!(
			"podup: no unit file at {} (already removed)",
			path.display()
		);
	}

	checked(sc.systemctl(&["daemon-reload"]), "daemon-reload")?;
	Ok(())
}

/// Which autostart mode, if any, is installed for a project. Service and quadlet
/// mode cannot coexist — each install refuses the other — so at most one is present.
/// `uninstall` uses this to remove whichever is there without the caller naming a
/// mode (and mistakenly no-op'ing against the wrong one).
pub enum InstalledMode {
	/// The service-mode `podup-<project>.service` unit is present.
	Service,
	/// Quadlet `<project>-*.container` units are present.
	Quadlet,
	/// Neither — nothing is installed.
	None,
}

/// Detect the installed autostart mode for `project` from what is on disk.
pub fn installed_mode(project: &str) -> InstalledMode {
	if unit_path(project).exists() {
		InstalledMode::Service
	} else if !quadlet_units_present(project).is_empty() {
		InstalledMode::Quadlet
	} else {
		InstalledMode::None
	}
}

/// A snapshot of the autostart unit's state, gathered for `status`.
pub struct StatusReport {
	/// Absolute path to where the unit file would live.
	pub unit_path: PathBuf,
	/// Whether the unit file exists on disk.
	pub unit_exists: bool,
	/// The unit file's permission bits (Unix only), when it exists.
	pub unit_mode: Option<u32>,
	/// `systemctl --user is-active` output (e.g. `active`, `inactive`, `failed`).
	pub is_active: String,
	/// `systemctl --user is-enabled` output (e.g. `enabled`, `disabled`).
	pub is_enabled: String,
	/// Whether linger is enabled for the current user.
	pub linger: bool,
	/// Whether `XDG_RUNTIME_DIR` is set (a user session is present).
	pub runtime_dir: bool,
}

/// Read the unit file's permission bits, on Unix. Other platforms have no POSIX
/// mode, so this is always `None` there.
#[cfg(unix)]
fn file_mode(path: &Path) -> Option<u32> {
	use std::os::unix::fs::PermissionsExt;
	std::fs::metadata(path).ok().map(|m| m.permissions().mode())
}

#[cfg(not(unix))]
fn file_mode(_path: &Path) -> Option<u32> {
	None
}

/// Run a `systemctl --user` query that reports state through its stdout (e.g.
/// `is-active`, `is-enabled`); these exit non-zero for the negative answer, so
/// the trimmed stdout is the report regardless of exit status.
fn query<S: SystemCtl>(sc: &S, arg: &str, unit_name: &str) -> String {
	match sc.systemctl(&[arg, unit_name]) {
		Ok(out) => {
			let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
			if s.is_empty() {
				"unknown".to_string()
			} else {
				s
			}
		}
		Err(e) => format!("unknown ({e})"),
	}
}

/// Gather the autostart status for a project, going through the [`SystemCtl`] seam
/// so it is testable without a live systemd.
pub fn collect_status<S: SystemCtl>(sc: &S, project: &str) -> StatusReport {
	let unit_name = unit_file_name(project);
	let path = unit_path(project);
	let unit_exists = path.exists();
	StatusReport {
		unit_mode: if unit_exists { file_mode(&path) } else { None },
		unit_exists,
		unit_path: path,
		is_active: query(sc, "is-active", &unit_name),
		is_enabled: query(sc, "is-enabled", &unit_name),
		linger: current_user().is_some_and(|u| linger_enabled(sc, &u)),
		runtime_dir: std::env::var_os("XDG_RUNTIME_DIR").is_some_and(|s| !s.is_empty()),
	}
}

/// Print the autostart status for a project.
pub fn status<S: SystemCtl>(sc: &S, project: &str) -> crate::Result<()> {
	let r = collect_status(sc, project);
	// Every line here is a yes/no an operator is scanning for, and the whole
	// screen was one colour — so "is it actually running?" meant reading six
	// labels to find the one word that answers it. The label is scaffolding
	// (dimmed); the value carries the meaning (tinted by what it says).
	let row = |label: &str, value: &str| {
		crate::ui::print_labelled(label, value);
	};
	row("unit", &r.unit_path.display().to_string());
	row("installed", if r.unit_exists { "yes" } else { "no" });
	if let Some(mode) = r.unit_mode {
		row("mode", &format!("{:04o}", mode & 0o7777));
	}
	row("active", &r.is_active);
	row("enabled", &r.is_enabled);
	row("linger", if r.linger { "enabled" } else { "disabled" });
	// Prose, not a state word, so the meaning is stated rather than inferred.
	crate::ui::print_labelled_with(
		"session",
		if r.runtime_dir {
			"XDG_RUNTIME_DIR set"
		} else {
			"XDG_RUNTIME_DIR unset (systemctl --user needs a user session)"
		},
		Some(r.runtime_dir),
	);
	Ok(())
}

#[cfg(all(test, unix))]
mod tests;