podbox-cli 0.6.7

Declarative Podman-native container environment manager. Define an environment as a TOML file and let systemd own its lifecycle.
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
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use nix::fcntl::{Flock, FlockArg};

use crate::codegen::quadlet;
use crate::config::{self, Config};
use crate::env::HostEnv;
use crate::podman::{PodmanVersion, podman_version};
use crate::systemd;
use crate::xdg::ResolvedXdgDirs;

/// Directory for user Quadlet source files.
pub fn quadlet_dir() -> PathBuf {
    dirs::config_dir()
        .unwrap_or_else(|| config::expand_tilde("~/.config"))
        .join("containers/systemd")
}

/// Flat install path: `~/.config/containers/systemd/<name>.container`.
pub fn flat_container_path(name: &str) -> PathBuf {
    quadlet_dir().join(format!("{name}.container"))
}

/// Application-scoped install path (Podman 6 directory/`--application` layout):
/// `~/.config/containers/systemd/<name>/<name>.container`.
pub fn application_container_path(name: &str) -> PathBuf {
    quadlet_dir().join(name).join(format!("{name}.container"))
}

/// True if a `.container` Quadlet exists in either flat or application layout.
pub fn is_installed(name: &str) -> bool {
    container_unit_path(name).is_some()
}

/// Path to the installed `.container` unit, if any (flat preferred, then app dir).
pub fn container_unit_path(name: &str) -> Option<PathBuf> {
    let flat = flat_container_path(name);
    if flat.exists() {
        return Some(flat);
    }
    let app = application_container_path(name);
    if app.exists() {
        return Some(app);
    }
    None
}

/// Names of installed `.container` units under the Quadlet dir (flat + one app level).
pub fn list_installed_names() -> Vec<String> {
    let qdir = quadlet_dir();
    let mut names = Vec::new();

    let Ok(entries) = std::fs::read_dir(&qdir) else {
        return names;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().is_some_and(|e| e == "container") {
            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                names.push(stem.to_string());
            }
            continue;
        }
        // Application subdir: <name>/<name>.container
        if path.is_dir() {
            let Some(dir_name) = path.file_name().and_then(|s| s.to_str()) else {
                continue;
            };
            let nested = path.join(format!("{dir_name}.container"));
            if nested.exists() {
                names.push(dir_name.to_string());
            }
        }
    }

    names.sort();
    names.dedup();
    names
}

/// Directory for user systemd unit files.
fn systemd_user_dir() -> PathBuf {
    dirs::config_dir()
        .unwrap_or_else(|| config::expand_tilde("~/.config"))
        .join("systemd/user")
}

/// Write custom systemd units (socket, host-service, optional dbus-proxy
/// and compositor) to sdir.
fn write_custom_units(
    name: &str,
    sdir: &Path,
    socket_content: &str,
    host_service_content: &str,
    dbus_proxy_content: Option<&str>,
    compositor_service_content: Option<&str>,
) -> Result<()> {
    std::fs::create_dir_all(sdir)?;
    std::fs::write(sdir.join(format!("{}.socket", name)), socket_content)?;
    std::fs::write(
        sdir.join(format!("{}-host.service", name)),
        host_service_content,
    )?;
    if let Some(proxy) = dbus_proxy_content {
        std::fs::write(sdir.join(format!("{}-proxy.service", name)), proxy)?;
    }
    if let Some(comp) = compositor_service_content {
        std::fs::write(sdir.join(format!("{}-compositor.service", name)), comp)?;
    }
    write_clean_stop_dropin(name, sdir)?;
    Ok(())
}

/// Container service units are generated by Quadlet, which cannot express
/// `SuccessExitStatus`. When the guest's idle timer fires, the host stops the
/// unit via `systemctl stop`; systemd SIGTERMs the container, the main process
/// exits 143, and the unit would otherwise land in `failed`. A drop-in marks
/// SIGTERM (and a graceful 0 exit) as a clean stop so idle shutdown settles in
/// `inactive` instead of `failed`.
fn write_clean_stop_dropin(name: &str, sdir: &Path) -> Result<()> {
    let dir = sdir.join(format!("{}.service.d", name));
    std::fs::create_dir_all(&dir)?;
    std::fs::write(
        dir.join("99-podbox-clean-stop.conf"),
        "[Service]\nSuccessExitStatus=0 143 SIGTERM SIGINT\n",
    )?;
    Ok(())
}

/// Activate custom units after Quadlet files are in place.
fn finalize_units(
    name: &str,
    sdir: &Path,
    socket_content: &str,
    host_service_content: &str,
    dbus_proxy_content: Option<&str>,
    compositor_service_content: Option<&str>,
    use_wayland_proxy: bool,
) -> Result<()> {
    write_custom_units(
        name,
        sdir,
        socket_content,
        host_service_content,
        dbus_proxy_content,
        compositor_service_content,
    )?;
    println!("Systemd units installed to {}", sdir.display());

    systemd::daemon_reload()?;
    systemd::reset_failed(name)?;
    systemd::stop_socket_and_host(name)?;
    if use_wayland_proxy {
        systemd::stop_compositor(name)?;
    }
    systemd::enable_now_socket(name)?;
    Ok(())
}

/// Install `.container` (+ optional `.build`) via `podman quadlet install` using
/// **file** arguments, not a directory.
///
/// Keeps the flat layout (`…/systemd/<name>.container`) for Podman 5.6–5.x.
fn podman_quadlet_install_files(
    name: &str,
    container_content: &str,
    build_content: Option<&str>,
) -> Result<()> {
    let tmp = std::env::temp_dir().join(format!("podbox-install-{name}"));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp)?;

    let container_path = tmp.join(format!("{name}.container"));
    std::fs::write(&container_path, container_content)?;

    let mut args: Vec<std::ffi::OsString> = vec![
        "quadlet".into(),
        "install".into(),
        "--replace".into(),
        container_path.into(),
    ];

    if let Some(bc) = build_content {
        let build_path = tmp.join(format!("{name}.build"));
        std::fs::write(&build_path, bc)?;
        args.push(build_path.into());
    }

    let output = crate::process::run_piped("podman", &args)?;
    let _ = std::fs::remove_dir_all(&tmp);
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("podman quadlet install failed: {stderr}");
    }
    println!("Quadlet files installed via podman quadlet install.");
    Ok(())
}

/// Install `.container` (+ optional `.build`) via `podman quadlet install` using
/// **directory** arguments with `--application` for Podman 6.x.
///
/// Podman 6 requires `--application` when the source is a directory. The units
/// end up at `…/systemd/<name>/<name>.container`.
fn podman_quadlet_install_application(
    name: &str,
    container_content: &str,
    build_content: Option<&str>,
) -> Result<()> {
    let tmp = std::env::temp_dir().join(format!("podbox-install-{name}"));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp)?;

    std::fs::write(tmp.join(format!("{name}.container")), container_content)?;
    if let Some(bc) = build_content {
        std::fs::write(tmp.join(format!("{name}.build")), bc)?;
    }

    let args: Vec<std::ffi::OsString> = vec![
        "quadlet".into(),
        "install".into(),
        "--replace".into(),
        "--application".into(),
        name.into(),
        tmp.into(),
    ];

    let output = crate::process::run_piped("podman", &args)?;
    let _ = std::fs::remove_dir_all(std::env::temp_dir().join(format!("podbox-install-{name}")));
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("podman quadlet install --application failed: {stderr}");
    }
    println!("Quadlet files installed via podman quadlet install --application {name}.");
    Ok(())
}

/// Best-effort removal of leftover flat unit files (`.container`, `.build`).
///
/// Called before a `--application` install to avoid dual installs from old
/// flat layouts.
fn remove_flat_units(name: &str) {
    let qdir = quadlet_dir();
    for ext in ["container", "build"] {
        let path = qdir.join(format!("{name}.{ext}"));
        if !path.exists() {
            continue;
        }
        // Best-effort podman quadlet rm first, then manual delete as fallback.
        let args: Vec<std::ffi::OsString> = vec![
            "quadlet".into(),
            "rm".into(),
            format!("{name}.{ext}").into(),
        ];
        let _ = crate::process::run_piped("podman", &args);
        // Manual fallback in case podman rm failed.
        let _ = std::fs::remove_file(&path);
    }
}

/// Best-effort removal of leftover application-scoped install dirs.
fn remove_application_dir(name: &str) {
    let app_dir = quadlet_dir().join(name);
    if app_dir.is_dir() {
        let _ = std::fs::remove_dir_all(&app_dir);
    }
}

/// Validate that mount paths referenced in extra mounts exist on the host.
fn preflight_check(config: &Config) -> Result<()> {
    let name = &config.container.name;

    // Check home directory
    if !config.container.home.exists() {
        eprintln!(
            "  Note: home directory '{}' will be created (does not exist yet).",
            config.container.home.display()
        );
    }

    // Parse extra mounts and check host paths
    for mount in &config.container.mounts.extra {
        let host_path = match mount.split_once(':') {
            Some((host, _)) => host,
            None => mount,
        };
        let path = std::path::Path::new(host_path);
        if !path.exists() {
            if crate::codegen::distros::is_tty() {
                let prompt = format!(
                    "Mount path '{}' does not exist on the host. Create it?",
                    path.display()
                );
                let create =
                    dialoguer::Confirm::with_theme(&dialoguer::theme::ColorfulTheme::default())
                        .with_prompt(prompt)
                        .default(true)
                        .interact_opt()?;
                if create == Some(true) {
                    std::fs::create_dir_all(path).with_context(|| {
                        format!("failed to create mount directory '{}'", path.display())
                    })?;
                    println!("✓ Directory '{}' created.", path.display());
                } else {
                    eprintln!(
                        "Warning: mount path '{}' does not exist on the host. This may cause the container to fail to load.",
                        path.display()
                    );
                }
            } else {
                eprintln!(
                    "Warning: mount path '{}' does not exist on the host (container '{}').",
                    path.display(),
                    name
                );
            }
        }
    }

    // Intelligently check if container is running
    let is_running = crate::podman::query_state(name)
        .map(|state| state == crate::podman::ContainerState::Running)
        .unwrap_or(false);

    // Only run port bind tests if the container is stopped
    if is_running {
        println!(
            "  Note: container '{}' is running. Skipping port conflict checks for upgrade.",
            name
        );
        return Ok(());
    }

    // Check for port conflicts (IPv4 + IPv6, TCP + UDP)
    let conflicts = crate::ports::check_host_ports(&config.network.ports);
    if !conflicts.is_empty() {
        let listed = conflicts
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(", ");
        anyhow::bail!(
            "Port conflict: already in use on the host — {listed}. \
             Find the process with: `ss -ltnp 'sport = :<port>'`"
        );
    }

    // Check admin cap_preset
    if config.security.cap_preset == crate::config::CapPreset::Admin {
        if crate::codegen::distros::is_tty() {
            let caps = config.security.cap_preset.caps().join(", ");
            let confirmed = dialoguer::Confirm::with_theme(
                &dialoguer::theme::ColorfulTheme::default(),
            )
            .with_prompt(format!(
                "WARNING: CapPreset::Admin grants {caps}. Only proceed if you fully trust this container. Continue?"
            ))
            .default(false)
            .interact()?;
            if !confirmed {
                anyhow::bail!(
                    "Aborted — set cap_preset to a lower level or use cap_add for specific caps"
                );
            }
        } else {
            let caps = config.security.cap_preset.caps().join(", ");
            eprintln!(
                "Note: cap_preset = \"admin\" grants {caps}. Non-interactive mode, continuing without confirmation."
            );
        }
    }

    Ok(())
}

/// Install systemd service and socket files for a container.
pub fn install(config: &Config, env: &HostEnv, xdg: &ResolvedXdgDirs, dry_run: bool) -> Result<()> {
    let name = &config.container.name;
    let ver = podman_version().unwrap_or(PodmanVersion {
        major: 5,
        minor: 5,
        patch: 0,
    });
    let qdir = quadlet_dir();
    let sdir = systemd_user_dir();
    let context_dir = crate::build::build_context_dir(name);
    let containerfile_path = context_dir.join("Containerfile");

    let socket_content = quadlet::generate_socket(config);
    let container_content = quadlet::generate_container(config, env, xdg);
    let host_service_content = quadlet::generate_host_service(name);
    let dbus_proxy_content = quadlet::generate_dbus_proxy_service(name, config);
    let compositor_service_content = quadlet::generate_compositor_service(name, config);

    let build_content = if !config.image.source().is_prebuilt() {
        Some(quadlet::generate_build(config, &containerfile_path))
    } else {
        None
    };

    if dry_run {
        if let Some(ref bc) = build_content {
            println!("=== {}.build ===", name);
            println!("{}", bc);
            println!();
        }
        println!("=== {}.socket ===", name);
        println!("{}", socket_content);
        println!();
        println!("=== {}.container ===", name);
        println!("{}", container_content);
        println!();
        println!("=== {}-host.service ===", name);
        println!("{}", host_service_content);
        if let Some(ref proxy) = dbus_proxy_content {
            println!();
            println!("=== {}-proxy.service ===", name);
            println!("{}", proxy);
        }
        if let Some(ref comp) = compositor_service_content {
            println!();
            println!("=== {}-compositor.service ===", name);
            println!("{}", comp);
        }
        return Ok(());
    }

    // Acquire exclusive install lock (auto-releases on panic/crash via kernel flock)
    let _install_lock = {
        let lock_path = context_dir.join(".install.lock");
        let _ = std::fs::create_dir_all(&context_dir);
        let file = std::fs::File::create(&lock_path).with_context(|| {
            format!("failed to create install lock at '{}'", lock_path.display())
        })?;
        Flock::lock(file, FlockArg::LockExclusive).map_err(|(_, e)| e)?
    };

    // Ensure .flatpak-info is written to the host build directory
    let _ = std::fs::create_dir_all(&context_dir);
    std::fs::write(
        context_dir.join(".flatpak-info"),
        "[Application]\nname=podbox\n",
    )?;

    // Pre-flight validation
    preflight_check(config)?;

    // Ensure home and runtime dirs exist
    std::fs::create_dir_all(&config.container.home).with_context(|| {
        format!(
            "failed to create home dir '{}'",
            config.container.home.display()
        )
    })?;

    if ver.at_least(6, 0) {
        // 6.0+: use --application with directory install.
        remove_flat_units(name);
        podman_quadlet_install_application(name, &container_content, build_content.as_deref())?;
    } else if ver.at_least(5, 6) {
        // 5.6–5.x: install individual files for flat layout.
        remove_application_dir(name);
        podman_quadlet_install_files(name, &container_content, build_content.as_deref())?;
    } else {
        // 5.5 fallback: copy files manually
        std::fs::create_dir_all(&qdir)?;
        if let Some(ref bc) = build_content {
            std::fs::write(qdir.join(format!("{name}.build")), bc)?;
        }
        std::fs::write(qdir.join(format!("{name}.container")), container_content)?;
        println!("Quadlet files installed to {}", qdir.display());
    }

    finalize_units(
        name,
        &sdir,
        &socket_content,
        &host_service_content,
        dbus_proxy_content.as_deref(),
        compositor_service_content.as_deref(),
        config.use_wayland_proxy(),
    )?;

    // Auto-export apps and bins
    for app in &config.integration.export.apps {
        if let Err(e) = crate::export::export_app(name, app) {
            eprintln!("Warning: auto-export app '{}' failed: {}", app, e);
        }
    }
    for bin in &config.integration.export.bins {
        if let Err(e) = crate::export::export_bin(name, bin) {
            eprintln!("Warning: auto-export bin '{}' failed: {}", bin, e);
        }
    }

    if config.lifecycle.autostart {
        systemd::enable_linger()?;
    }

    Ok(())
}

/// Remove Quadlet and systemd files for a container.
pub fn uninstall(name: &str) -> Result<()> {
    let ver = podman_version().unwrap_or(PodmanVersion {
        major: 5,
        minor: 5,
        patch: 0,
    });
    let qdir = quadlet_dir();
    let sdir = systemd_user_dir();

    if ver.at_least(5, 6) {
        let mut removed_via_podman = false;

        // Flat units: only call rm when the file exists (avoids needing --ignore).
        for ext in ["container", "build"] {
            let path = qdir.join(format!("{name}.{ext}"));
            if !path.exists() {
                continue;
            }
            let args: Vec<std::ffi::OsString> = vec![
                "quadlet".into(),
                "rm".into(),
                format!("{name}.{ext}").into(),
            ];
            let output = crate::process::run_piped("podman", &args)?;
            if output.status.success() {
                removed_via_podman = true;
            } else {
                // Fall through to manual delete below.
                let stderr = String::from_utf8_lossy(&output.stderr);
                eprintln!("Warning: podman quadlet rm {name}.{ext} failed: {stderr}");
            }
        }

        // Application-scoped leftovers (directory install / --application).
        let app_dir = qdir.join(name);
        if app_dir.is_dir() {
            if ver.at_least(6, 0) {
                let args: Vec<std::ffi::OsString> = vec![
                    "quadlet".into(),
                    "rm".into(),
                    "--recursive".into(),
                    name.into(),
                ];
                let output = crate::process::run_piped("podman", &args)?;
                if output.status.success() {
                    removed_via_podman = true;
                } else {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    eprintln!("Warning: podman quadlet rm --recursive {name} failed: {stderr}");
                }
            }
            remove_application_dir(name);
        }

        // Manual cleanup of any remaining flat files.
        for ext in ["build", "container"] {
            let path = qdir.join(format!("{name}.{ext}"));
            if path.exists() {
                std::fs::remove_file(&path)?;
            }
        }

        if removed_via_podman {
            println!("Quadlet files removed via podman quadlet rm.");
        }
    } else {
        // 5.5 fallback: remove files manually
        for ext in ["build", "container"] {
            let path = qdir.join(format!("{name}.{ext}"));
            if path.exists() {
                std::fs::remove_file(&path)?;
            }
        }
        remove_application_dir(name);
    }

    // Remove custom systemd units
    for unit in [
        "socket",
        "host.service",
        "proxy.service",
        "compositor.service",
    ] {
        let path = sdir.join(format!("{name}.{unit}"));
        if path.exists() {
            std::fs::remove_file(&path)?;
        }
    }

    // Remove the clean-stop drop-in directory for the generated container unit.
    let dropin_dir = sdir.join(format!("{name}.service.d"));
    if dropin_dir.is_dir() {
        std::fs::remove_dir_all(&dropin_dir)?;
    }

    systemd::daemon_reload()?;
    println!("Files for '{name}' removed.");

    Ok(())
}

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

    #[test]
    fn flat_and_application_paths_differ() {
        let flat = flat_container_path("myenv");
        let app = application_container_path("myenv");
        assert!(flat.to_string_lossy().ends_with("myenv.container"));
        assert!(
            app.to_string_lossy().ends_with("myenv/myenv.container")
                || app.to_string_lossy().ends_with("myenv\\myenv.container")
        );
        assert_ne!(flat, app);
    }
}