podup 3.5.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
//! `ps` — list this project's containers as a table or JSON. Split out of the
//! query root so each file stays within the source line limit.

use crate::compose::types::ComposeFile;
use crate::error::{ComposeError, Result};
use crate::libpod::types::container::{ContainerListEntry, ContainerPort};
use crate::libpod::{urlencoded, API_PREFIX};

use super::Engine;
use crate::units::{format_duration, DurationFormat};

/// Options for [`Engine::ps_with_options`], mirroring `docker compose ps`.
#[derive(Default)]
pub struct PsOptions {
	/// Include stopped containers, `-a/--all` (default: running only).
	pub all: bool,
	/// Print only container IDs, `-q/--quiet`.
	pub quiet: bool,
	/// Emit JSON instead of the table, `--format json`.
	pub json: bool,
}

/// Service/status/name filters for [`Engine::ps_filtered`] (`docker compose ps`
/// `--services`, `[SERVICE...]`, `--status`, `--filter`). Kept off the frozen
/// [`PsOptions`] struct so the published library API stays stable across minors.
#[derive(Default)]
pub struct PsFilterOptions {
	/// Print the service names instead of the container table, `--services`.
	pub services_only: bool,
	/// Restrict to these services' containers (positional `SERVICE` filter).
	pub services: Vec<String>,
	/// Status filters, `--status` (e.g. running, exited); OR-combined.
	pub status: Vec<String>,
	/// Generic `KEY=VALUE` predicates, `--filter` (supports status= and name=).
	pub filters: Vec<String>,
}

/// Human-readable status for `ps`. Podman's libpod list endpoint leaves
/// `Status` empty and reports the machine state in `State`, so fall back to it
/// rather than rendering a blank column.
fn display_status(c: &ContainerListEntry) -> &str {
	if c.status.is_empty() {
		&c.state
	} else {
		&c.status
	}
}

/// How `ps` renders a span: the shared default, three components.
const SPAN_FORMAT: DurationFormat = DurationFormat::default_parts();

/// Table STATUS cell, as of `now` (Unix seconds).
///
/// A running container says how long it has been up, which is what both
/// reference tools do and what podup did not: `podman ps` renders `Up 13 hours
/// (healthy)` and `docker compose ps` renders `Up 2 minutes`, while podup
/// rendered the bare word `running`. The state alone answers "is it on"; the
/// span answers "did it just restart", which is the question someone runs `ps`
/// to settle.
///
/// The health suffix only appears when the container has a healthcheck —
/// libpod leaves `Status` empty otherwise, measured on Podman 5.7.0, so there is
/// nothing to append rather than an unknown to invent.
///
/// Podman's list endpoint reports an exited container with a bare `exited` state
/// and no code, which is indistinguishable from a clean exit; surface the exit
/// code the way `docker compose ps` does (`Exited (0)` / `Exited (7)`).
///
/// `now` is a parameter rather than a clock read so the rendering is pure and
/// its tests are deterministic.
fn table_status(c: &ContainerListEntry, now: i64) -> String {
	let status = display_status(c);
	let exited = c.state.eq_ignore_ascii_case("exited") || c.state.eq_ignore_ascii_case("dead");
	// Only synthesize when the status text doesn't already carry the code, so a
	// richer Docker-style `Exited (7) 4 seconds ago` is left untouched.
	if exited && !status.contains("Exited (") {
		return format!("Exited ({})", c.exit_code.unwrap_or(0));
	}
	if !c.state.eq_ignore_ascii_case("running") {
		return status.to_string();
	}
	let Some(uptime) = span_since(c.started_at, now) else {
		return status.to_string();
	};
	// `health_from_status` answers with an empty string when the container has
	// no healthcheck, which is the same case as libpod sending an empty
	// `Status` — nothing to append rather than an unknown to invent.
	match health_from_status(status) {
		"" => format!("Up {uptime}"),
		health => format!("Up {uptime} ({health})"),
	}
}

/// Table CREATED cell, as of `now`: how long ago the container was created.
///
/// Empty when libpod sent no timestamp or one this cannot parse. A blank cell
/// says podup could not tell; a cell holding a plausible wrong age does not, and
/// the wrong age is the one a reader acts on.
fn table_created(c: &ContainerListEntry, now: i64) -> String {
	crate::timestamp::parse_rfc3339(&c.created)
		.and_then(|created| span_since(created, now))
		.unwrap_or_default()
}

/// Render the span from `then` to `now`, or `None` when there is nothing to
/// render.
///
/// A zero `then` means the field was absent, not that the instant was the epoch.
/// A `then` in the future is clock skew between this process and the server —
/// clamped to zero rather than rendered as a negative age, since `Up 0s` on a
/// container that just started is right and `Up -3s` is never right.
fn span_since(then: i64, now: i64) -> Option<String> {
	if then <= 0 {
		return None;
	}
	let elapsed = now.saturating_sub(then).max(0);
	Some(format_duration(
		std::time::Duration::from_secs(elapsed as u64),
		&SPAN_FORMAT,
	))
}

/// The wall clock as Unix seconds, for the cells that render an age.
///
/// Before the epoch is not a state this can reach on any host that boots, so a
/// failure floors at zero and every cell renders blank rather than the call
/// site handling an error it cannot act on.
pub(super) fn now_unix() -> i64 {
	std::time::SystemTime::now()
		.duration_since(std::time::UNIX_EPOCH)
		.map(|d| d.as_secs() as i64)
		.unwrap_or(0)
}

/// The container's display name (leading slash stripped).
fn name_of(c: &ContainerListEntry) -> String {
	c.names.join(", ").trim_start_matches('/').to_string()
}

/// Whether a container status/state word satisfies a `--status`/`status=` filter.
/// Each wanted value matches case-insensitively as a prefix of the status word
/// (so `running` matches `running` and `up`-style strings via the state). An
/// empty `wanted` matches everything. Pure so the predicate is unit-tested.
fn status_matches(status: &str, wanted: &[String]) -> bool {
	if wanted.is_empty() {
		return true;
	}
	let s = status.trim().to_ascii_lowercase();
	wanted.iter().any(|w| {
		let w = w.trim().to_ascii_lowercase();
		!w.is_empty() && (s == w || s.starts_with(&w))
	})
}

/// Split `--filter KEY=VALUE` predicates into the supported buckets: extra
/// `status=` values are folded into the status filter, `name=` values into the
/// name-substring filter, and anything else is returned as `unknown` so the
/// caller can warn. Pure so it is unit-tested.
fn split_ps_filters(filters: &[String]) -> (Vec<String>, Vec<String>, Vec<String>) {
	let (mut status, mut names, mut unknown) = (Vec::new(), Vec::new(), Vec::new());
	for f in filters {
		match f.split_once('=') {
			Some(("status", v)) => status.push(v.to_string()),
			Some(("name", v)) => names.push(v.to_string()),
			_ => unknown.push(f.clone()),
		}
	}
	(status, names, unknown)
}

/// The health word embedded in a human status string (`Up 2 minutes (healthy)`),
/// or `""` when absent. The libpod list endpoint carries no separate health
/// field, so `ps` derives it from the status text the way `docker ps` shows it.
fn health_from_status(status: &str) -> &'static str {
	let s = status.to_ascii_lowercase();
	if s.contains("unhealthy") {
		"unhealthy"
	} else if s.contains("healthy") {
		"healthy"
	} else if s.contains("health: starting") {
		"starting"
	} else {
		""
	}
}

/// Number of consecutive ports a record covers (`range`, at least 1).
fn span_len(p: &ContainerPort) -> u16 {
	p.range.filter(|&r| r > 0).unwrap_or(1)
}

/// `base + offset` widened to `u32` before adding. `host_port`,
/// `container_port` and `range` all come straight off libpod's JSON — untrusted
/// input a hostile or buggy daemon could set to any `u16` value — so a plain
/// `u16 + u16` (e.g. `host_port: 65535` with a `range` of 2) can overflow: it
/// wraps silently in a release build and panics under overflow-checks. Doing
/// the addition in `u32` keeps every legitimate port value identical while a
/// pathological one renders as the (larger) real number instead of wrapping.
fn widen_add(base: u16, offset: u16) -> u32 {
	u32::from(base) + u32::from(offset)
}

/// Host IP for display: an unset/empty value means all interfaces (`0.0.0.0`),
/// matching Docker/Podman output (libpod commonly omits it).
fn display_host_ip(p: &ContainerPort) -> &str {
	p.host_ip
		.as_deref()
		.filter(|s| !s.is_empty())
		.unwrap_or("0.0.0.0")
}

/// Render one port record the way `docker compose ps` does. A collapsed range
/// (`range > 1`) is rendered as `host_start-host_end->cont_start-cont_end` so the
/// whole range is shown rather than only its first mapping.
fn format_port_record(p: &ContainerPort) -> String {
	let proto = p
		.protocol
		.as_deref()
		.map(|proto| format!("/{proto}"))
		.unwrap_or_default();
	let host_ip = display_host_ip(p);
	let hp = p.host_port.unwrap_or(0);
	let n = span_len(p);
	if n > 1 {
		format!(
			"{host_ip}:{hp}-{}->{}-{}{proto}",
			widen_add(hp, n - 1),
			p.container_port,
			widen_add(p.container_port, n - 1),
		)
	} else {
		format!("{host_ip}:{hp}->{}{proto}", p.container_port)
	}
}

/// Render a container's published ports as a comma-joined `ps` PORTS cell.
fn format_ports(ports: &[ContainerPort]) -> String {
	ports
		.iter()
		.map(format_port_record)
		.collect::<Vec<_>>()
		.join(", ")
}

/// Structured publishers for `ps --format json`, one object per published port
/// (a collapsed range is expanded so every port appears), mirroring the
/// `Publishers` array docker compose emits.
fn publishers(ports: &[ContainerPort]) -> Vec<serde_json::Value> {
	let mut out = Vec::new();
	for p in ports {
		let n = span_len(p);
		for i in 0..n {
			out.push(serde_json::json!({
				"URL": display_host_ip(p),
				"TargetPort": widen_add(p.container_port, i),
				"PublishedPort": p.host_port.map(|hp| widen_add(hp, i)),
				"Protocol": p.protocol.as_deref().unwrap_or("tcp"),
			}));
		}
	}
	out
}

/// Build one `ps --format json` row, surfacing the fields docker compose
/// machine consumers expect (Service/State/Health/ExitCode/Publishers) in
/// addition to Name/Image/Status/ID. Pure so it can be unit-tested.
fn ps_json_row(c: &ContainerListEntry) -> serde_json::Value {
	serde_json::json!({
		"Name": name_of(c),
		"Image": c.image,
		"Project": c.labels.get("podup.project").cloned().unwrap_or_default(),
		"Service": c.labels.get("podup.service").cloned().unwrap_or_default(),
		"State": c.state,
		"Status": display_status(c),
		"Health": health_from_status(display_status(c)),
		"ExitCode": c.exit_code.unwrap_or(0),
		"Publishers": publishers(&c.ports),
		// The raw wire values, not a rendering. `docker compose ps --format
		// json` passes the RFC 3339 string through too, and a machine consumer
		// wants an instant it can compute with rather than `2mo 1d`.
		"Created": c.created,
		"StartedAt": c.started_at,
		"ID": c.id,
	})
}

impl Engine {
	/// List running containers for this project as a table (default options).
	pub async fn ps(&self, file: &ComposeFile) -> Result<()> {
		self.ps_with_options(file, PsOptions::default()).await
	}

	/// List containers with `docker compose ps`-style options (`-a/--all`,
	/// `-q/--quiet`, `--format`). For the `--services`/`[SERVICE...]`/`--status`/
	/// `--filter` predicates use [`Engine::ps_filtered`].
	pub async fn ps_with_options(&self, file: &ComposeFile, opts: PsOptions) -> Result<()> {
		self.ps_filtered(file, opts, PsFilterOptions::default())
			.await
	}

	/// List containers with `docker compose ps`-style options: `-a/--all`
	/// (include stopped), `-q/--quiet` (full IDs only), `--format`
	/// (table | json), `--services` (service-name list), a positional `SERVICE`
	/// filter, and `--status`/`--filter` predicates.
	pub async fn ps_filtered(
		&self,
		file: &ComposeFile,
		opts: PsOptions,
		filters: PsFilterOptions,
	) -> Result<()> {
		for name in &filters.services {
			if !file.services.contains_key(name) {
				return Err(ComposeError::ServiceNotFound(name.clone()));
			}
		}

		// `--services` lists the (optionally filtered) configured service names,
		// one per line, instead of the container table.
		if filters.services_only {
			for name in file.services.keys() {
				if filters.services.is_empty() || filters.services.iter().any(|s| s == name) {
					println!("{name}");
				}
			}
			return Ok(());
		}

		// Fold `--status` and any `status=`/`name=` from `--filter` together. An
		// unsupported key is an error, not a warning: a dropped predicate means
		// the command answers a question the caller did not ask, and a script
		// filtering for a condition reads the unfiltered set back as a match.
		// docker compose errors here too.
		let (mut status_filter, name_filter, unknown) = split_ps_filters(&filters.filters);
		if let Some(u) = unknown.first() {
			return Err(ComposeError::Unsupported(format!(
				"unsupported ps filter {u:?}: expected name=<NAME> or status=<STATE>"
			)));
		}
		status_filter.extend(filters.status.iter().cloned());

		// A positional `SERVICE` filter restricts to those services' container
		// names (across replicas).
		let allowed_names: Option<std::collections::HashSet<String>> =
			if filters.services.is_empty() {
				None
			} else {
				Some(
					filters
						.services
						.iter()
						.filter_map(|n| file.services.get(n).map(|s| (n, s)))
						.flat_map(|(n, s)| self.replica_names(n, s))
						.collect(),
				)
			};

		// A status filter (`--status exited`, `--filter status=exited`) implies
		// querying every container regardless of state: libpod's list endpoint
		// with `all=false` returns only running containers, so `ps --status
		// exited` without `-a` would always come back empty. `status_matches`
		// below still narrows the result to the requested status(es); this only
		// widens what libpod itself is asked for.
		let all = opts.all || !status_filter.is_empty();
		let label = format!("podup.project={}", self.project);
		let filters = serde_json::json!({ "label": [label] });
		let path = format!(
			"{API_PREFIX}/containers/json?all={}&filters={}",
			all,
			urlencoded(&filters.to_string()),
		);

		let all_containers = self
			.client
			.get_json::<Vec<ContainerListEntry>>(&path)
			.await
			.map_err(ComposeError::Podman)?;

		let containers: Vec<ContainerListEntry> = all_containers
			.into_iter()
			.filter(|c| {
				let name = name_of(c);
				allowed_names.as_ref().is_none_or(|set| {
					c.names
						.iter()
						.any(|n| set.contains(n.trim_start_matches('/')))
				}) && (status_matches(&c.state, &status_filter)
					|| status_matches(&c.status, &status_filter))
					&& (name_filter.is_empty() || name_filter.iter().any(|nf| name.contains(nf)))
			})
			.collect();

		if opts.quiet {
			// Full 64-char IDs, like `docker compose ps -q` (and podup's JSON),
			// so scripts consuming the IDs are not handed truncated values.
			for c in &containers {
				println!("{}", c.id);
			}
			return Ok(());
		}

		if opts.json {
			let rows: Vec<_> = containers.iter().map(ps_json_row).collect();
			println!(
				"{}",
				serde_json::to_string_pretty(&rows).unwrap_or_default()
			);
			return Ok(());
		}

		// One clock read for the whole table, so two rows created in the same
		// second cannot render different ages.
		let now = now_unix();
		let mut table = crate::ui::Table::new(&["NAME", "IMAGE", "CREATED", "STATUS", "PORTS"])
			.cap(0, 48)
			.cap(1, 48)
			.status_col(3)
			.identity_col(0);
		for c in &containers {
			table.push(vec![
				name_of(c),
				c.image.clone(),
				table_created(c, now),
				table_status(c, now),
				format_ports(&c.ports),
			]);
		}
		table.print();

		Ok(())
	}
}

#[cfg(test)]
mod tests;