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
//! `podup` — docker-compose to Podman translator CLI.
// The binary carries no `unsafe`; deny it so any future addition is caught.
#![deny(unsafe_code)]
use std::process;
#[cfg(feature = "completions")]
use clap::CommandFactory;
mod cli;
mod dispatch;
mod generate;
mod resolve;
mod startup;
use cli::*;
use generate::write_quadlet;
use resolve::*;
use startup::{init_tracing, internal_error_notice, is_mutating, parse_cli};
fn main() {
// Replace the default panic output (a raw Rust backtrace) with a `podup:`
// internal-error notice that tells the user what to report and where, plus
// the reminder to redact secrets first.
std::panic::set_hook(Box::new(|info| {
eprintln!("podup: internal error: {info}");
eprintln!("{}", internal_error_notice());
}));
// Drive the runtime on a worker thread with a large stack. Clap's
// command-building (debug builds especially) is stack-heavy and overflows
// Windows' 1 MiB main-thread stack as the subcommand surface grows; an 8 MiB
// matches Linux's default and leaves ample headroom.
std::thread::Builder::new()
.stack_size(8 * 1024 * 1024)
.name("podup".into())
.spawn(run_to_exit)
.expect("spawn podup worker thread")
.join()
.expect("podup worker thread panicked");
}
/// Build the Tokio runtime and drive [`run`], mapping its result onto the
/// process exit status. Runs on the large-stack worker thread spawned by `main`.
fn run_to_exit() {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("build Tokio runtime");
match runtime.block_on(run()) {
Ok(()) => {}
Err(podup::ComposeError::RunExited(code)) => process::exit(code as i32),
#[cfg(feature = "update")]
Err(e @ podup::ComposeError::Update(_)) => {
eprintln!("podup: error: {e}");
process::exit(podup::update::exit_code(&e));
}
Err(e) => {
eprintln!("podup: error: {e}");
process::exit(1);
}
}
}
/// Orchestrate one CLI invocation: parse args, then short-circuit the commands
/// that need neither a compose file nor (for some) Podman — `completions`,
/// `update`, `ls`, and `config`. Otherwise resolve and parse the compose
/// file(s), settle the project name and base directory (validating the name at
/// the trust boundary), acquire the per-project lock, and dispatch the
/// remaining commands.
async fn run() -> podup::Result<()> {
let cli = parse_cli();
// `watch` is an interactive, long-running command; surface its per-action
// progress (synced/rebuilt/restarted) by defaulting to INFO instead of the
// quiet WARN floor. `RUST_LOG` always overrides.
let log_floor = if matches!(cli.command, Commands::Watch) {
"info"
} else {
"warn"
};
init_tracing(log_floor);
// `completions` derives entirely from the static CLI definition; it neither
// parses a compose file nor contacts Podman. Print to stdout for piping.
#[cfg(feature = "completions")]
if let Commands::Completions { shell } = cli.command {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
// Render into a buffer first: clap_complete panics if the writer errors,
// which aborts (SIGABRT) when stdout is a closed pipe such as
// `podup completions bash | head`. A `Vec` write never fails; then send
// it to stdout and treat a broken pipe as a clean exit, like a normal
// Unix tool.
let mut buf = Vec::new();
clap_complete::generate(shell, &mut cmd, name, &mut buf);
match std::io::Write::write_all(&mut std::io::stdout(), &buf) {
Ok(()) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => return Ok(()),
Err(e) => return Err(e.into()),
}
}
// `update` operates on the binary itself, not a compose project, so it runs
// before any compose file is parsed or Podman is contacted. The network and
// filesystem work is blocking; keep it off the async path entirely.
#[cfg(feature = "update")]
if let Commands::Update { check, force } = cli.command {
let opts = podup::update::UpdateOptions {
check_only: check,
force,
};
return tokio::task::spawn_blocking(move || podup::update::run(opts))
.await
.map_err(|e| podup::ComposeError::Update(format!("update task failed: {e}")))?;
}
// `ls` discovers projects across the host by container label; it needs a
// Podman connection but no compose file, so handle it before parsing one.
if let Commands::Ls { all, quiet, format } = &cli.command {
let client = podup::podman::connect(cli.socket.as_deref())?;
return podup::list_projects(
&client,
podup::LsOptions {
all: *all,
quiet: *quiet,
json: *format == OutputFormat::Json,
},
)
.await;
}
let compose_files = resolve_compose_files(&cli.file);
let file = podup::parse_files_with_env_files(&compose_files, &cli.env_file)?;
if let Commands::Config {
format,
services,
quiet,
no_interpolate,
resolve_image_digests,
} = &cli.command
{
// `--no-interpolate` re-parses with substitution disabled; `file` (already
// parsed with interpolation) is used otherwise.
let parsed = if *no_interpolate {
podup::parse_files_with_env_files_interp(&compose_files, &cli.env_file, false)?
} else {
file
};
// `--resolve-image-digests` pins each image to its registry digest, which
// needs a Podman connection to inspect images.
let resolved = if *resolve_image_digests {
let client = podup::podman::connect(cli.socket.as_deref())?;
podup::resolve_image_digests(&client, &parsed).await?
} else {
parsed
};
return startup::render_config(&resolved, format, *services, *quiet);
}
let base_dir = resolve_base_dir(cli.project_directory.as_deref(), &compose_files[0]);
let project = resolve_project_name(cli.project, file.name.as_deref(), &base_dir);
// Validate the resolved project name at the trust boundary, before it reaches
// any code path that builds a filesystem path from it (staging, lock files,
// quadlet generation). Explicit `-p`/`COMPOSE_PROJECT_NAME` values and the
// compose `name:` field are otherwise taken verbatim; rejecting an unsafe
// name here fails closed regardless of which command runs next.
if !podup::is_safe_project_name(&project) {
return Err(podup::ComposeError::Unsupported(format!(
"project name {project:?} is not a safe path component: use only ASCII \
letters, digits, '-', '_', '.', not starting with '.', max 128 chars"
)));
}
// `generate` produces declarative artifacts from the compose file alone; it
// neither contacts Podman nor mutates project state.
if let Commands::Generate {
kind: GenerateCommands::Quadlet { output },
} = &cli.command
{
return write_quadlet(&file, &project, output.as_deref());
}
let client = podup::podman::connect(cli.socket.as_deref())?;
// The `-t/--timeout` shutdown-grace override applies to every command that
// stops containers (up recreate, down, stop, restart).
let stop_timeout = match &cli.command {
Commands::Up { timeout, .. }
| Commands::Down { timeout, .. }
| Commands::Stop { timeout, .. }
| Commands::Restart { timeout, .. } => *timeout,
_ => None,
};
// `--scale SERVICE=N` (on `up`) and the `scale` subcommand both feed the
// engine's replica overrides so `resolve_replicas` reports the target count.
let scale_overrides: std::collections::HashMap<String, u32> = match &cli.command {
Commands::Up { scale, .. } => scale.iter().cloned().collect(),
Commands::Scale { pairs } => pairs.iter().cloned().collect(),
_ => std::collections::HashMap::new(),
};
// `up` image-acquisition overrides: `--pull`, `--no-build`, `--quiet-pull`.
let (pull_override, no_build, quiet_pull) = match &cli.command {
Commands::Up {
pull,
no_build,
quiet_pull,
..
} => (pull.clone(), *no_build, *quiet_pull),
Commands::Pull { quiet, policy, .. } => (policy.clone(), false, *quiet),
_ => (None, false, false),
};
// `up -V/--renew-anon-volumes`: recreate anonymous volumes on container
// recreation instead of leaving the old ones orphaned.
let renew_anon_volumes = matches!(
&cli.command,
Commands::Up {
renew_anon_volumes: true,
..
}
);
let engine = podup::Engine::with_base_dir(client, project, base_dir)
.with_stop_timeout(stop_timeout)
.with_scale_overrides(scale_overrides)
.with_up_overrides(pull_override, no_build, quiet_pull)
.with_run_overrides(startup::run_overrides_for(&cli.command))
.with_renew_anon_volumes(renew_anon_volumes);
// Serialize mutating lifecycle commands against concurrent `podup` runs on
// the same project. Read-only / follow commands (ps, logs, top, port,
// images, exec, pull, cp, config, watch) take no lock so they don't block
// or get blocked. The guard is held until `run` returns.
let _lock = if is_mutating(&cli.command) {
Some(engine.lock_project()?)
} else {
None
};
dispatch::dispatch(&engine, &file, cli.command, &cli.profile).await
}