hermit-run 0.5.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! `hermit oci` — discover and run OCI images from the local image store.
//!
//! `hermit run --image <ref>` already materializes an image rootfs, and because
//! `buildah` and `podman` share one containers/storage graph root it has always
//! read the *same* store podman writes. What was missing was a way to see what
//! is in that store, to ask what hermit would do with a reference, and — most
//! importantly — to resolve a reference to a stable image **identity** before
//! anything is keyed against it.
//!
//! `hermit oci run` is deliberately a thin front over the existing `--image`
//! path. The new behavior is the resolution step: a tag is a mutable pointer, so
//! running (and caching) against the resolved image id is what makes "the file
//! inputs are pinned" true rather than aspirational.

use clap::Parser;
use hermit::Error;
use hermit::ExitStatus;

use crate::global_opts::GlobalOpts;
use crate::podman_store::PodmanStore;
use crate::podman_store::ResolvedImage;
use crate::run::RunOpts;

#[derive(Debug, Parser)]
pub struct OciOpts {
    #[clap(subcommand)]
    command: OciSubcommand,
}

#[derive(Debug, Parser)]
enum OciSubcommand {
    /// List OCI images available in the local image store.
    #[clap(name = "ls")]
    Ls(LsOpts),

    /// Show what hermit would do with an image reference.
    #[clap(name = "inspect")]
    Inspect(InspectOpts),

    /// Download an image into the local store (the only networked subcommand).
    #[clap(name = "pull")]
    Pull(PullOpts),

    /// Run a program deterministically against an image's filesystem.
    #[clap(name = "run", trailing_var_arg = true)]
    Run(Box<OciRunOpts>),
}

#[derive(Debug, Parser)]
struct LsOpts {
    /// Include untagged intermediate images.
    #[clap(long, short = 'a')]
    all: bool,
}

#[derive(Debug, Parser)]
struct InspectOpts {
    /// Image reference: a tag, a short or full image id, or `name@sha256:...`.
    image: String,
}

#[derive(Debug, Parser)]
struct PullOpts {
    /// Image reference to download.
    image: String,
}

#[derive(Debug, Parser)]
struct OciRunOpts {
    /// Image reference to run against. Must already be in the local store
    /// unless `--pull` is given.
    #[clap(value_name = "IMAGE")]
    image_ref: String,

    /// Download the image first if it is not already present locally.
    #[clap(long)]
    pull: bool,

    /// Options forwarded to `hermit run`, followed by the guest program.
    #[clap(flatten)]
    run: RunOpts,
}

/// Obtain the local store, turning "no podman" into an actionable error.
///
/// `hermit oci` is *about* the local store, so unlike `hermit run --image` there
/// is no meaningful fallback: say plainly what is missing.
fn require_store() -> Result<PodmanStore, Error> {
    PodmanStore::probe()?.ok_or_else(|| {
        Error::msg(
            "No local OCI image store found. `hermit oci` reads the \
             containers/storage store that podman and buildah share, so it \
             needs a rootless `podman` on PATH.",
        )
    })
}

impl OciOpts {
    /// The embedded run participates in the outer invocation's verdict stamp.
    pub(crate) fn verify_json_path(&self) -> Option<&std::path::Path> {
        match &self.command {
            OciSubcommand::Run(opts) => opts.run.verify_json_path(),
            _ => None,
        }
    }

    /// Refuse pending runtime integration before host probes or image access.
    pub(crate) fn refuse_unready_exec_stop(&self) -> Result<(), Error> {
        if let OciSubcommand::Run(opts) = &self.command {
            opts.run.refuse_unready_exec_stop()?;
        }
        Ok(())
    }

    /// Preserve the embedded run's explicit maximum separately from its default.
    pub(crate) fn capture_max_timeslice_source(&mut self, matches: &clap::ArgMatches) {
        if let OciSubcommand::Run(opts) = &mut self.command {
            opts.run.capture_max_timeslice_source(matches);
        }
    }

    /// Whether this `hermit oci` subcommand starts a guest.
    pub(crate) fn starts_guest(&self) -> bool {
        matches!(self.command, OciSubcommand::Run(_))
    }

    /// Resolve the embedded run's omitted epoch at the same outer process
    /// boundary as a top-level `hermit run` invocation.
    pub(crate) fn capture_default_run_epoch(
        &mut self,
        capture_now: impl FnOnce() -> std::time::SystemTime,
    ) {
        if let OciSubcommand::Run(opts) = &mut self.command {
            opts.run.capture_default_epoch(capture_now);
        }
    }

    #[cfg(test)]
    pub(crate) fn run_epoch_capture_for_test(&self) -> (String, bool, bool) {
        let OciSubcommand::Run(opts) = &self.command else {
            panic!("expected oci run")
        };
        let (epoch, captured) = opts.run.epoch_capture_for_test();
        (epoch, captured, opts.run.reports_virtual_epoch_for_test())
    }

    pub fn main(&mut self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
        match &mut self.command {
            OciSubcommand::Ls(opts) => opts.main(),
            OciSubcommand::Inspect(opts) => opts.main(),
            OciSubcommand::Pull(opts) => opts.main(),
            OciSubcommand::Run(opts) => opts.main(global),
        }
    }
}

impl LsOpts {
    fn main(&self) -> Result<ExitStatus, Error> {
        let store = require_store()?;
        let images = store.list(self.all)?;
        if images.is_empty() {
            // An empty store is a legitimate state, not a failure. Say where we
            // looked so the user can tell "empty" from "wrong store".
            println!("No images in the local store at {}", store.graph_root());
            return Ok(ExitStatus::SUCCESS);
        }
        println!("{:<14}  {:<48}  {:>10}", "IMAGE ID", "NAME", "SIZE");
        for image in &images {
            println!(
                "{:<14}  {:<48}  {:>10}",
                short_id(&image.id),
                image.display_name(),
                human_size(image.size),
            );
        }
        Ok(ExitStatus::SUCCESS)
    }
}

impl InspectOpts {
    fn main(&self) -> Result<ExitStatus, Error> {
        let store = require_store()?;
        let image = store.resolve(&self.image)?;
        report(&store, &image)?;
        Ok(ExitStatus::SUCCESS)
    }
}

impl PullOpts {
    fn main(&self) -> Result<ExitStatus, Error> {
        let store = require_store()?;
        let image = store.pull(&self.image)?;
        report(&store, &image)?;
        Ok(ExitStatus::SUCCESS)
    }
}

/// Print the resolution result and the parts of the image config that change
/// how hermit runs the guest.
fn report(store: &PodmanStore, image: &ResolvedImage) -> Result<(), Error> {
    println!("reference:  {}", image.reference);
    println!("image id:   {}", image.id);
    // A locally built image has no manifest digest until it is pushed or
    // pulled. Distinguish that from "we failed to look it up".
    println!(
        "digest:     {}",
        image
            .digest
            .as_deref()
            .unwrap_or("<none> (locally built; not pushed or pulled)")
    );
    println!("store:      {}", store.graph_root());

    let config = store.config(image)?;
    println!(
        "workdir:    {}",
        config
            .workdir
            .as_deref()
            .unwrap_or("/ (image declares none)")
    );
    if config.env.is_empty() {
        println!("env:        <none declared>");
    } else {
        println!("env:");
        for (key, value) in &config.env {
            println!("  {key}={value}");
        }
    }
    if !config.entrypoint.is_empty() {
        println!("entrypoint: {:?}", config.entrypoint);
    }
    if !config.cmd.is_empty() {
        // hermit always requires an explicit guest program, so say so rather
        // than let the reader assume `hermit oci run <ref>` would use this.
        println!(
            "cmd:        {:?}  (informational; hermit requires an explicit program)",
            config.cmd
        );
    }

    match store.overlay_dirs(image) {
        Ok(dirs) => {
            println!("layers:     {} (topmost first)", dirs.len());
            for dir in &dirs {
                println!("  {dir}");
            }
        }
        Err(e) => println!("layers:     <unavailable> ({e})"),
    }
    Ok(())
}

impl OciRunOpts {
    fn main(&mut self, global: &GlobalOpts) -> Result<ExitStatus, Error> {
        self.run.refuse_unready_exec_stop()?;
        // `hermit oci run` takes its image as a positional; the inherited
        // `--image` flag would be a second, unresolved way to say the same
        // thing. Reject the ambiguity rather than silently picking one.
        if let Some(flag) = self.run.image() {
            return Err(Error::msg(format!(
                "`hermit oci run` takes the image as a positional argument; drop \
                 `--image {flag}` and pass {:?} once. `--image` on `hermit run` \
                 bypasses reference resolution, which is what `hermit oci run` \
                 exists to do.",
                self.image_ref
            )));
        }
        // A run config records a `hermit run` command line, and this run's
        // image is resolved from the store rather than given as an option, so
        // a saved config could not reproduce it.
        if let Some(option) = self.run.run_config_option() {
            return Err(Error::msg(format!(
                "`hermit oci run` does not accept {option}: run configs are read and written \
                 only by `hermit run`. Resolve the image id with `hermit oci inspect {:?}` and \
                 run `hermit run --image <ID> {option} ...` instead.",
                self.image_ref
            )));
        }
        let store = require_store()?;
        // Resolution never contacts a registry unless --pull was asked for, so
        // an ordinary `hermit oci run` cannot silently download.
        let image = if self.pull {
            store.pull(&self.image_ref)?
        } else {
            store.resolve(&self.image_ref)?
        };
        tracing::info!(
            "Resolved OCI reference {} to image id {}",
            image.reference,
            image.id
        );
        // Hand the *resolved id* to the existing --image path. Passing the raw
        // reference would let a moved tag alias an older rootfs.
        self.run.set_image(image.id.clone());
        self.run.main(global)
    }
}

fn short_id(id: &str) -> &str {
    // podman's own display width for an image id.
    id.get(..12).unwrap_or(id)
}

/// Human-readable byte count, matching the decimal (MB = 10^6) convention
/// podman uses so the two tools' listings agree.
fn human_size(bytes: u64) -> String {
    const UNITS: [(&str, u64); 4] = [
        ("GB", 1_000_000_000),
        ("MB", 1_000_000),
        ("kB", 1_000),
        ("B", 1),
    ];
    for (suffix, scale) in UNITS {
        if bytes >= scale {
            return if scale == 1 {
                format!("{bytes} {suffix}")
            } else {
                format!("{:.1} {suffix}", bytes as f64 / scale as f64)
            };
        }
    }
    "0 B".to_string()
}

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

    #[test]
    fn short_id_truncates_to_podman_width_without_panicking() {
        let id = "1ee23df5e47b5b7331304af929f5461f9f516f5c166c3031832d2adfd22f323c";
        assert_eq!(short_id(id), "1ee23df5e47b");
        // Never panic on an unexpectedly short id.
        assert_eq!(short_id("abc"), "abc");
        assert_eq!(short_id(""), "");
    }

    #[test]
    fn human_size_uses_the_decimal_convention_podman_prints() {
        assert_eq!(human_size(0), "0 B");
        assert_eq!(human_size(512), "512 B");
        assert_eq!(human_size(1_500), "1.5 kB");
        assert_eq!(human_size(80_659_122), "80.7 MB");
        assert_eq!(human_size(2_500_000_000), "2.5 GB");
    }

    // `hermit oci run` must accept the same trailing guest command shape as
    // `hermit run`, with the image reference first.
    #[test]
    fn oci_run_parses_image_then_forwarded_run_args() {
        let opts = OciOpts::try_parse_from([
            "oci",
            "run",
            "restored-ubuntu:24.04",
            "--strict",
            "--",
            "/bin/echo",
            "hi",
        ])
        .expect("oci run should parse an image followed by run options");
        match opts.command {
            OciSubcommand::Run(run) => {
                assert_eq!(run.image_ref, "restored-ubuntu:24.04");
                assert!(!run.pull, "--pull must default off so run never downloads");
            }
            other => panic!("expected the run subcommand, got {other:?}"),
        }
    }

    #[test]
    fn oci_run_forwards_maximum_source_to_timerless_config_validation() {
        use clap::CommandFactory;

        for (maximum, refuses) in [
            (None, false),
            (Some("--max-timeslice=disabled"), false),
            (Some("--max-timeslice=200000000"), true),
        ] {
            let mut argv = vec![
                "hermit",
                "--backend=dbt",
                "oci",
                "run",
                "example.invalid/image:tag",
                "--epoch=2000-12-31T23:59:59Z",
            ];
            argv.extend(maximum);
            argv.extend(["--", "/nonexistent-oci-preemption-guest"]);
            let matches = crate::Args::command().try_get_matches_from(argv).unwrap();
            let args = crate::args_from_matches_with_clock(&matches, || {
                panic!("an explicit epoch must not sample the host clock")
            })
            .unwrap();
            let crate::Subcommand::Oci(oci) = args.command else {
                panic!("expected oci subcommand");
            };
            let OciSubcommand::Run(mut options) = oci.command else {
                panic!("expected embedded run subcommand");
            };
            // Use the same global selection RunOpts::main installs, without
            // resolving an OCI store or claiming this backend supports images.
            options.run.set_backend(args.global.backend);
            assert_eq!(options.run.global_backend_arg(), " --backend=dbt");
            let result = options.run.validate_args();
            if refuses {
                let error = result.unwrap_err();
                let message = format!("{error:#}");
                assert!(
                    error
                        .downcast_ref::<crate::container::PolicyRefusal>()
                        .is_some(),
                    "{message}"
                );
                assert!(
                    message
                        .contains("unsupported_preemption: --backend=dbt refuses --max-timeslice"),
                    "{message}"
                );
                assert_eq!(
                    options.run.det_opts.det_config.max_timeslice.map(u64::from),
                    Some(200_000_000)
                );
            } else {
                result.unwrap();
                assert_eq!(
                    options.run.det_opts.det_config.max_timeslice.map(u64::from),
                    if maximum.is_none() {
                        Some(200_000_000)
                    } else {
                        None
                    }
                );
            }
        }
    }

    #[test]
    fn oci_ls_defaults_to_hiding_intermediate_images() {
        let opts = OciOpts::try_parse_from(["oci", "ls"]).expect("oci ls should parse");
        match opts.command {
            OciSubcommand::Ls(ls) => assert!(!ls.all),
            other => panic!("expected the ls subcommand, got {other:?}"),
        }
        let opts = OciOpts::try_parse_from(["oci", "ls", "--all"]).expect("oci ls --all");
        match opts.command {
            OciSubcommand::Ls(ls) => assert!(ls.all),
            other => panic!("expected the ls subcommand, got {other:?}"),
        }
    }
}