podup 1.7.1

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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Container orchestration engine.
//!
//! Translates a parsed [`ComposeFile`](crate::compose::types::ComposeFile) into Podman API calls via the libpod REST API.

mod build;
mod container;
mod copy;
mod events;
pub use events::EventsOptions;
mod image;
pub use build::{BuildOptions, PullOptions, PushOptions};
pub use copy::CpOptions;
pub use image::{resolve_image_digests, CommitOptions};
pub use lifecycle::{validate_stop_timeout, RunOptions, RunOverrides};
pub use lock::ProjectLock;
pub use query::{ExecOptions, ImagesOptions, LogsDisplay, LogsOptions, PsFilterOptions, PsOptions};
mod container_config;
mod health;
mod lifecycle;
mod lock;
mod names;
mod network;
mod profiles;
pub use profiles::{retain_active_profiles, retain_active_profiles_with_targets};
mod projects;
pub use projects::{list_projects, list_projects_filtered, LsOptions};
mod query;
mod secrets;
mod staging;
mod stats;
pub use staging::is_safe_project_name;
pub use stats::StatsOptions;
mod volume;
pub use volume::VolumesOptions;
mod volume_mounts;
#[cfg(feature = "watch")]
mod watch;

use std::io::Write;
use std::path::PathBuf;

use futures_util::StreamExt;

use crate::compose::types::{LifecycleHook, Service};
use crate::error::{ComposeError, Result};
use crate::libpod::types::exec::{ExecCreateConfig, ExecStartConfig};
use crate::libpod::{Client, LogOutput, API_PREFIX};

// ---------------------------------------------------------------------------
// Engine
// ---------------------------------------------------------------------------

/// Handle through which all Podman operations for a project are dispatched.
pub struct Engine {
	pub(super) client: Client,
	pub(super) project: String,
	pub(super) base_dir: PathBuf,
	/// Optional CLI `-t/--timeout` override (seconds) for container shutdown
	/// grace; when set it takes precedence over each service's
	/// `stop_grace_period`. `None` falls back to the per-service value.
	pub(super) stop_timeout: Option<i32>,
	/// CLI `--scale SERVICE=N` overrides (from `up --scale` and the `scale`
	/// subcommand); when a service is present it takes precedence over the
	/// compose `scale:`/`deploy.replicas` value. Empty falls back to compose.
	pub(super) scale_overrides: std::collections::HashMap<String, u32>,
	/// CLI `up --pull <policy>` override; takes precedence over each service's
	/// `pull_policy`. `None` falls back to the per-service value.
	pub(super) pull_policy_override: Option<String>,
	/// CLI `up --no-build`: never build images, even for services with a
	/// `build:` section (they fall back to pulling/using an existing image).
	pub(super) no_build: bool,
	/// CLI `up --quiet-pull`: suppress image-pull progress output.
	pub(super) quiet_pull: bool,
	/// CLI `run`-only flag overrides (user/workdir/entrypoint/volume/publish/
	/// interactive/no-deps); empty by default.
	pub(super) run_overrides: lifecycle::RunOverrides,
	/// Global `--env-file` paths that double as `docker compose run --env-file`:
	/// their contents seed a one-off `run` container's environment at the lowest
	/// precedence (env-file < service `environment:` < `-e`). Resolved relative
	/// to `base_dir`; empty by default. Kept off the frozen public
	/// [`lifecycle::RunOverrides`] struct so the library API stays stable.
	pub(super) run_env_files: Vec<String>,
	/// CLI `docker compose run -l/--label KEY=VAL` ad-hoc labels for the one-off
	/// `run` container; empty by default. Kept off the frozen public
	/// [`lifecycle::RunOverrides`] struct so the library API stays stable.
	pub(super) run_labels: Vec<String>,
	/// CLI `up -V/--renew-anon-volumes`: when recreating a container, also remove
	/// its old anonymous volumes instead of leaving them orphaned.
	pub(super) renew_anon_volumes: bool,
}

impl Engine {
	/// Create an engine for `project_name` using the working directory as the base path for relative volume mounts.
	pub fn new(client: Client, project: String) -> Self {
		Self {
			client,
			project,
			base_dir: std::env::current_dir().unwrap_or_default(),
			stop_timeout: None,
			scale_overrides: std::collections::HashMap::new(),
			pull_policy_override: None,
			no_build: false,
			quiet_pull: false,
			run_overrides: lifecycle::RunOverrides::default(),
			run_env_files: Vec::new(),
			run_labels: Vec::new(),
			renew_anon_volumes: false,
		}
	}

	/// Create an engine with an explicit base directory — use when the compose file is not in the working directory.
	pub fn with_base_dir(client: Client, project: String, base_dir: PathBuf) -> Self {
		Self {
			client,
			project,
			base_dir,
			stop_timeout: None,
			scale_overrides: std::collections::HashMap::new(),
			pull_policy_override: None,
			no_build: false,
			quiet_pull: false,
			run_overrides: lifecycle::RunOverrides::default(),
			run_env_files: Vec::new(),
			run_labels: Vec::new(),
			renew_anon_volumes: false,
		}
	}

	/// Set the CLI `-t/--timeout` shutdown-grace override (seconds). Builder-style.
	pub fn with_stop_timeout(mut self, timeout: Option<i32>) -> Self {
		self.stop_timeout = timeout;
		self
	}

	/// Set the CLI `--scale SERVICE=N` replica overrides. Builder-style.
	pub fn with_scale_overrides(
		mut self,
		overrides: std::collections::HashMap<String, u32>,
	) -> Self {
		self.scale_overrides = overrides;
		self
	}

	/// Set the CLI `up` image-acquisition overrides: `--pull <policy>`,
	/// `--no-build`, and `--quiet-pull`. Builder-style.
	pub fn with_up_overrides(
		mut self,
		pull_policy: Option<String>,
		no_build: bool,
		quiet_pull: bool,
	) -> Self {
		self.pull_policy_override = pull_policy;
		self.no_build = no_build;
		self.quiet_pull = quiet_pull;
		self
	}

	/// Set the CLI `run`-only flag overrides (`-u/-w/--entrypoint/-v/-p/-i/
	/// --no-deps`). Builder-style; consumed by [`Engine::run`].
	pub fn with_run_overrides(mut self, overrides: RunOverrides) -> Self {
		self.run_overrides = overrides;
		self
	}

	/// Set the global `--env-file` paths that also seed a one-off `run`
	/// container's environment (`docker compose run --env-file`: env-file <
	/// service `environment:` < `-e`). Builder-style; consumed by
	/// [`Engine::run`]. Resolved relative to the engine's base dir.
	pub fn with_run_env_files(mut self, env_files: Vec<String>) -> Self {
		self.run_env_files = env_files;
		self
	}

	/// Set the CLI `docker compose run -l/--label KEY=VAL` ad-hoc labels for the
	/// one-off `run` container. Builder-style; consumed by [`Engine::run`].
	pub fn with_run_labels(mut self, labels: Vec<String>) -> Self {
		self.run_labels = labels;
		self
	}

	/// Set the CLI `up -V/--renew-anon-volumes` flag. Builder-style; when set,
	/// recreating a container also removes its old anonymous volumes.
	pub fn with_renew_anon_volumes(mut self, renew: bool) -> Self {
		self.renew_anon_volumes = renew;
		self
	}

	/// Resolve the replica count for a service: a CLI `--scale` override wins,
	/// else the compose `scale:`, else `deploy.replicas`, else 1. The single
	/// source of truth so `up`, naming, and teardown never drift.
	pub(super) fn resolve_replicas(&self, service_name: &str, service: &Service) -> usize {
		if let Some(&n) = self.scale_overrides.get(service_name) {
			return n as usize;
		}
		service
			.scale
			.or(service.deploy.as_ref().and_then(|d| d.replicas))
			.unwrap_or(1) as usize
	}

	pub(super) async fn run_lifecycle_hook(
		&self,
		container_name: &str,
		hook: &LifecycleHook,
	) -> Result<()> {
		let cmd = hook.command.to_exec();
		let env: Vec<String> = {
			let m = hook.environment.to_map();
			m.into_iter()
				.filter_map(|(k, v)| v.map(|v| format!("{k}={v}")))
				.collect()
		};

		let exec_cfg = ExecCreateConfig {
			cmd: Some(cmd),
			user: hook.user.clone(),
			privileged: hook.privileged,
			working_dir: hook.working_dir.clone(),
			env: if env.is_empty() { None } else { Some(env) },
			attach_stdout: Some(true),
			attach_stderr: Some(true),
			..Default::default()
		};

		let path = format!(
			"{API_PREFIX}/containers/{}/exec",
			crate::libpod::urlencoded(container_name)
		);
		let resp: crate::libpod::types::exec::ExecCreateResponse = self
			.client
			.post_json(&path, &exec_cfg)
			.await
			.map_err(ComposeError::Podman)?;
		let exec_id = resp.id;

		let start_cfg = ExecStartConfig {
			detach: false,
			tty: false,
		};
		let start_path = format!(
			"{API_PREFIX}/exec/{}/start",
			crate::libpod::urlencoded(&exec_id)
		);
		let resp = self
			.client
			.post_json_stream(&start_path, &start_cfg)
			.await
			.map_err(ComposeError::Podman)?;

		let mut stream = crate::libpod::parse_multiplexed(resp.into_body());
		// Lock stdout once for the whole stream instead of re-acquiring the lock
		// (and issuing a syscall) per frame; stdout is ours exclusively on this
		// path. stderr is locked per frame because the tracing subscriber also
		// writes there: holding its lock across the await loop would starve
		// concurrent log emissions. Flush after each frame so output stays prompt.
		let mut out = std::io::stdout().lock();
		while let Some(msg) = stream.next().await {
			match msg.map_err(ComposeError::Podman)? {
				LogOutput::StdOut { message } => {
					let _ = out.write_all(String::from_utf8_lossy(&message).as_bytes());
					let _ = out.flush();
				}
				LogOutput::StdErr { message } => {
					let mut err = std::io::stderr().lock();
					let _ = err.write_all(String::from_utf8_lossy(&message).as_bytes());
					let _ = err.flush();
				}
			}
		}

		// A hook that exits non-zero must surface as an error (matching
		// `Engine::run`): otherwise a failing `post_start` readiness/init step is
		// silently treated as success and dependents start against a container
		// that never initialised. `pre_stop` callers deliberately ignore the Err.
		let inspect_path = format!(
			"{API_PREFIX}/exec/{}/json",
			crate::libpod::urlencoded(&exec_id)
		);
		let inspect: crate::libpod::types::exec::ExecInspect = self
			.client
			.get_json(&inspect_path)
			.await
			.map_err(ComposeError::Podman)?;
		if let Some(code) = inspect.exit_code {
			if code != 0 {
				return Err(ComposeError::Build(format!(
					"lifecycle hook exited with status {code}"
				)));
			}
		}

		Ok(())
	}

	pub(super) fn container_name(&self, service_name: &str, service: &Service) -> String {
		service
			.container_name
			.clone()
			.unwrap_or_else(|| format!("{}-{}", self.project, service_name))
	}

	pub(super) fn replica_names(&self, service_name: &str, service: &Service) -> Vec<String> {
		let replicas = self.resolve_replicas(service_name, service);
		let base = self.container_name(service_name, service);
		if replicas <= 1 {
			vec![base]
		} else {
			(1..=replicas).map(|i| format!("{base}-{i}")).collect()
		}
	}

	pub(super) fn first_replica_name(&self, service_name: &str, service: &Service) -> String {
		let replicas = self.resolve_replicas(service_name, service);
		let base = self.container_name(service_name, service);
		if replicas <= 1 {
			base
		} else {
			format!("{base}-1")
		}
	}

	/// Resolve the container name for a service replica from the statically
	/// derived names: the 1-based `--index` when given (erroring if out of
	/// range), else the first replica.
	///
	/// Prefer [`Engine::live_replica_name_at`] for the replica-targeting
	/// commands (`exec`, `cp`): the static names reflect only the compose
	/// `scale:`/`deploy.replicas` (plus a `--scale` on the *current* invocation),
	/// so a later `cp`/`exec` would not see replicas created by a prior
	/// `up --scale`. This variant stays for callers that cannot await.
	pub(super) fn replica_name_at(
		&self,
		service_name: &str,
		service: &Service,
		index: Option<u32>,
	) -> Result<String> {
		let names = self.replica_names(service_name, service);
		let base = self.container_name(service_name, service);
		resolve_replica_name(service_name, &base, &names, index)
	}

	/// Resolve the container name for a service replica against the *running*
	/// scale: the replicas Podman actually has (matched by the `podup.service`
	/// label), falling back to the statically derived names before anything is
	/// created. `--index n` therefore targets replica `n` even when it was
	/// created by an earlier `up --scale`/`scale` rather than the current
	/// invocation, matching `docker compose cp/exec --index`. Shared by the
	/// replica-targeting commands (`exec`, `cp`).
	pub(super) async fn live_replica_name_at(
		&self,
		service_name: &str,
		service: &Service,
		index: Option<u32>,
	) -> Result<String> {
		let names = self.live_replica_names(service_name, service).await?;
		let base = self.container_name(service_name, service);
		resolve_replica_name(service_name, &base, &names, index)
	}

	/// Watch for file changes and apply the service's `develop.watch` rules. Returns an error when the `watch` feature is disabled.
	#[cfg(not(feature = "watch"))]
	pub async fn watch(&self, _file: &crate::compose::types::ComposeFile) -> Result<()> {
		Err(crate::error::ComposeError::Unsupported(
			"watch requires the 'watch' feature".into(),
		))
	}
}

// ---------------------------------------------------------------------------
// Replica resolution helpers
// ---------------------------------------------------------------------------

/// Resolve a replica container name from the set of names that exist for a
/// service (the running replicas, or the statically derived names before
/// anything is created) and a 1-based `--index`. Each name is either the
/// unsuffixed base (the sole replica) or `{base}-{n}`.
///
/// `--index n` targets the replica numbered `n` — by name, not by position —
/// so it stays correct after a runtime `scale`/`up --scale` and regardless of
/// the order Podman lists containers; `0` is rejected (indexes are 1-based);
/// `None` picks the lowest-numbered replica. Pure so it is unit-testable
/// without a Podman socket.
fn resolve_replica_name(
	service_name: &str,
	base: &str,
	names: &[String],
	index: Option<u32>,
) -> Result<String> {
	match index {
		Some(0) => Err(ComposeError::ReplicaIndex {
			service: service_name.to_string(),
			index: 0,
		}),
		Some(i) => {
			let suffixed = format!("{base}-{i}");
			if names.iter().any(|n| n == &suffixed) {
				return Ok(suffixed);
			}
			// A single, unsuffixed replica answers to index 1 only.
			if i == 1 && names.iter().any(|n| n == base) {
				return Ok(base.to_string());
			}
			Err(ComposeError::ReplicaIndex {
				service: service_name.to_string(),
				index: i,
			})
		}
		None => order_replicas(base, names)
			.into_iter()
			.next()
			.ok_or_else(|| ComposeError::ServiceNotFound(service_name.into())),
	}
}

/// Order replica container names by their 1-based replica number so callers can
/// pick the lowest-numbered one independently of Podman's listing order. A name
/// is the unsuffixed base (the sole replica → number 1) or `{base}-{n}`; names
/// matching neither are dropped.
fn order_replicas(base: &str, names: &[String]) -> Vec<String> {
	let prefix = format!("{base}-");
	let mut numbered: Vec<(usize, String)> = names
		.iter()
		.filter_map(|name| {
			if name == base {
				Some((1, name.clone()))
			} else {
				name.strip_prefix(&prefix)
					.and_then(|s| s.parse::<usize>().ok())
					.map(|n| (n, name.clone()))
			}
		})
		.collect();
	numbered.sort_by_key(|(n, _)| *n);
	numbered.into_iter().map(|(_, name)| name).collect()
}

// ---------------------------------------------------------------------------
// Filesystem helpers
// ---------------------------------------------------------------------------

fn walk_dir(root: &std::path::Path) -> std::io::Result<Vec<PathBuf>> {
	let mut out = Vec::new();
	walk_collect(root, &mut out)?;
	Ok(out)
}

fn walk_collect(dir: &std::path::Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
	let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<std::io::Result<Vec<_>>>()?;
	entries.sort_by_key(|e| e.file_name());
	for entry in entries {
		let path = entry.path();
		let file_type = entry.file_type()?;
		out.push(path.clone());
		if file_type.is_dir() {
			walk_collect(&path, out)?;
		}
	}
	Ok(())
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
	use super::*;
	use crate::libpod::Client;

	fn engine(project: &str) -> Engine {
		Engine::with_base_dir(
			Client::new("/nonexistent.sock"),
			project.into(),
			std::env::temp_dir(),
		)
	}

	fn scaled_service(replicas: u32) -> Service {
		Service {
			scale: Some(replicas),
			..Service::default()
		}
	}

	#[test]
	fn replica_name_at_index_zero_is_rejected() {
		// `--index` is 1-based; index 0 must be an error, never replica 1.
		let e = engine("proj");
		let svc = scaled_service(3);
		let err = e
			.replica_name_at("web", &svc, Some(0))
			.expect_err("index 0 must be rejected");
		assert!(
			matches!(err, ComposeError::ReplicaIndex { index: 0, ref service } if service == "web"),
			"unexpected error: {err:?}"
		);
		// The index hint renders outside the quoted service name.
		let msg = err.to_string();
		assert!(
			msg.contains("'web'") && msg.contains("1-based"),
			"got {msg:?}"
		);
	}

	#[test]
	fn replica_name_at_index_one_is_first_replica() {
		let e = engine("proj");
		let svc = scaled_service(3);
		assert_eq!(
			e.replica_name_at("web", &svc, Some(1)).unwrap(),
			"proj-web-1"
		);
	}

	#[test]
	fn replica_name_at_index_n_is_nth_replica() {
		let e = engine("proj");
		let svc = scaled_service(3);
		assert_eq!(
			e.replica_name_at("web", &svc, Some(3)).unwrap(),
			"proj-web-3"
		);
	}

	#[test]
	fn replica_name_at_out_of_range_is_rejected() {
		let e = engine("proj");
		let svc = scaled_service(3);
		assert!(e.replica_name_at("web", &svc, Some(4)).is_err());
	}

	#[test]
	fn replica_name_at_none_is_first_replica() {
		let e = engine("proj");
		// Single replica: the unsuffixed container name.
		assert_eq!(
			e.replica_name_at("web", &Service::default(), None).unwrap(),
			"proj-web"
		);
		// Multiple replicas: the first suffixed name.
		assert_eq!(
			e.replica_name_at("web", &scaled_service(3), None).unwrap(),
			"proj-web-1"
		);
	}

	fn names(list: &[&str]) -> Vec<String> {
		list.iter().map(|s| s.to_string()).collect()
	}

	#[test]
	fn resolve_replica_targets_running_scale_not_compose_default() {
		// The regression: a later `cp`/`exec` has no `--scale` (empty overrides),
		// so the static count is the compose default (1). But the service was
		// scaled up earlier and three replicas are running — `--index 2` must
		// address the running `proj-web-2`, not fall back to the base name.
		let live = names(&["proj-web-1", "proj-web-2", "proj-web-3"]);
		assert_eq!(
			resolve_replica_name("web", "proj-web", &live, Some(2)).unwrap(),
			"proj-web-2"
		);
		assert_eq!(
			resolve_replica_name("web", "proj-web", &live, Some(3)).unwrap(),
			"proj-web-3"
		);
	}

	#[test]
	fn resolve_replica_is_order_independent() {
		// Podman does not guarantee a listing order; `--index n` targets replica
		// `n` by name, and `None` picks the lowest-numbered replica regardless.
		let live = names(&["proj-web-3", "proj-web-1", "proj-web-2"]);
		assert_eq!(
			resolve_replica_name("web", "proj-web", &live, Some(1)).unwrap(),
			"proj-web-1"
		);
		assert_eq!(
			resolve_replica_name("web", "proj-web", &live, None).unwrap(),
			"proj-web-1"
		);
	}

	#[test]
	fn resolve_replica_out_of_range_against_running_scale() {
		// Only two replicas running: index 3 is out of range, not a stale base.
		let live = names(&["proj-web-1", "proj-web-2"]);
		assert!(resolve_replica_name("web", "proj-web", &live, Some(3)).is_err());
	}

	#[test]
	fn resolve_replica_index_zero_is_rejected() {
		let live = names(&["proj-web-1", "proj-web-2"]);
		let err = resolve_replica_name("web", "proj-web", &live, Some(0))
			.expect_err("index 0 must be rejected");
		assert!(
			matches!(err, ComposeError::ReplicaIndex { index: 0, ref service } if service == "web"),
			"unexpected error: {err:?}"
		);
	}

	#[test]
	fn resolve_replica_single_unsuffixed_base() {
		// A single, unsuffixed replica answers to index 1 (and None), never index 2.
		let live = names(&["proj-web"]);
		assert_eq!(
			resolve_replica_name("web", "proj-web", &live, None).unwrap(),
			"proj-web"
		);
		assert_eq!(
			resolve_replica_name("web", "proj-web", &live, Some(1)).unwrap(),
			"proj-web"
		);
		assert!(resolve_replica_name("web", "proj-web", &live, Some(2)).is_err());
	}

	#[test]
	fn order_replicas_sorts_by_replica_number() {
		let live = names(&["proj-web-10", "proj-web-2", "proj-web-1"]);
		assert_eq!(
			order_replicas("proj-web", &live),
			names(&["proj-web-1", "proj-web-2", "proj-web-10"])
		);
	}
}