Skip to main content

bsdkrun_sdk/
sandbox.rs

1//! The [`Sandbox`] handle — a running (or stopped) bsdkrun microVM — and the
2//! fluent builders that boot one.
3//!
4//! ```no_run
5//! use bsdkrun_sdk::Sandbox;
6//!
7//! let boxx = Sandbox::linux("alpine")
8//!     .cpus(2)
9//!     .mem(1024)
10//!     .port("8080:80")
11//!     .command(["sleep", "300"])
12//!     .create()?;
13//! println!("{}", boxx.exec(["uname", "-a"])?.text());
14//! boxx.stop()?;
15//! # Ok::<(), bsdkrun_sdk::Error>(())
16//! ```
17
18use serde_json::Value;
19
20use crate::args::{build_create_args, strvec, CreateOpts, Kind};
21use crate::error::{Error, Result};
22use crate::process::{checked, run_full, spawn};
23use crate::types::{ExecResult, SandboxInfo};
24
25/// A machine id as the CLI prints it: lowercase hex, at least six digits, on a
26/// line of its own.
27fn looks_like_machine_id(line: &str) -> bool {
28    line.len() >= 6
29        && line
30            .chars()
31            .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
32}
33
34/// The host SSH port from the boot banner's `ssh -p <port>` hint, if any.
35fn parse_ssh_port(stderr: &str) -> Option<u16> {
36    let idx = stderr.find("ssh -p ")?;
37    let digits: String = stderr[idx + "ssh -p ".len()..]
38        .chars()
39        .take_while(|c| c.is_ascii_digit())
40        .collect();
41    digits.parse().ok()
42}
43
44/// A handle to a running (or stopped) bsdkrun microVM.
45///
46/// Create one with the per-kind builders ([`Sandbox::linux`],
47/// [`Sandbox::freebsd`], ...), reconnect with [`Sandbox::get`], or enumerate
48/// with [`Sandbox::list`].
49#[derive(Debug, Clone)]
50pub struct Sandbox {
51    id: String,
52    ssh_port: Option<u16>,
53}
54
55// -- shared setter macros -----------------------------------------------------
56//
57// Each create builder wraps the same `CreateOpts`; these macros stamp the
58// option groups (net/name/vm, disks) into each builder's impl so the groups
59// cannot drift between kinds — the same reason args.py factors them into
60// _net_args/_vm_args/_disk_args.
61
62macro_rules! common_setters {
63    () => {
64        /// Name the machine (`--name`).
65        pub fn name(mut self, name: impl Into<String>) -> Self {
66            self.opts.name = Some(name.into());
67            self
68        }
69
70        /// vCPU count (`--cpus`).
71        pub fn cpus(mut self, cpus: u32) -> Self {
72            self.opts.cpus = Some(cpus);
73            self
74        }
75
76        /// Guest RAM in MiB (`--mem`).
77        pub fn mem(mut self, mib: u32) -> Self {
78            self.opts.mem = Some(mib);
79            self
80        }
81
82        /// Add a host->guest TCP port forward, `"HOST:GUEST"`.
83        pub fn port(mut self, forward: impl Into<String>) -> Self {
84            self.opts.net.touched = true;
85            self.opts.net.ports.push(forward.into());
86            self
87        }
88
89        /// Add a port forward from numbers instead of a string.
90        pub fn forward(self, host: u16, guest: u16) -> Self {
91            self.port(format!("{host}:{guest}"))
92        }
93
94        /// Pin the guest MAC address (`--mac`).
95        pub fn mac(mut self, mac: impl Into<String>) -> Self {
96            self.opts.net.touched = true;
97            self.opts.net.mac = Some(mac.into());
98            self
99        }
100
101        /// Join a global network (`--network`).
102        pub fn network(mut self, network: impl Into<String>) -> Self {
103            self.opts.net.touched = true;
104            self.opts.net.network = Some(network.into());
105            self
106        }
107
108        /// Disable guest networking entirely (`--no-net`).
109        pub fn no_net(mut self) -> Self {
110            self.opts.net.touched = true;
111            self.opts.net.no_net = true;
112            self
113        }
114
115        /// bsdkrun's global `--log-level` for the create call (default 1, so
116        /// boot diagnostics land in the error when a boot fails).
117        pub fn log_level(mut self, level: u32) -> Self {
118            self.opts.log_level = Some(level);
119            self
120        }
121
122        /// The exact argv `create()` will run (minus the binary and global
123        /// flags) — for inspection and tests.
124        pub fn to_args(&self) -> Vec<String> {
125            build_create_args(self.kind, &self.opts)
126        }
127
128        /// Boot the machine (detached) and return a handle to it.
129        pub fn create(self) -> Result<Sandbox> {
130            Sandbox::create_with(self.kind, self.opts)
131        }
132    };
133}
134
135macro_rules! disk_setters {
136    () => {
137        /// Keep the root disk across `rm` (`--persist`).
138        pub fn persist(mut self) -> Self {
139            self.opts.persist = true;
140            self
141        }
142
143        /// Use a persistent CoW volume as the root disk (`-v`).
144        pub fn volume(mut self, name: impl Into<String>) -> Self {
145            self.opts.volume = Some(name.into());
146            self
147        }
148
149        /// Attach an extra raw disk, `"PATH"` or `"PATH:ro"` (`--attach-disk`).
150        pub fn attach_disk(mut self, disk: impl Into<String>) -> Self {
151            self.opts.attach_disk.push(disk.into());
152            self
153        }
154    };
155}
156
157macro_rules! define_builder {
158    ($(#[$doc:meta])* $name:ident) => {
159        $(#[$doc])*
160        #[derive(Debug, Clone)]
161        pub struct $name {
162            kind: Kind,
163            opts: CreateOpts,
164        }
165    };
166}
167
168define_builder!(
169    /// Boots an OCI image as a Linux microVM (`bsdkrun linux`).
170    LinuxBuilder
171);
172define_builder!(
173    /// Boots FreeBSD (`bsdkrun freebsd`).
174    FreebsdBuilder
175);
176define_builder!(
177    /// Boots NetBSD (`bsdkrun netbsd`).
178    NetbsdBuilder
179);
180define_builder!(
181    /// Boots a raw disk through its UEFI loader (`bsdkrun firmware`).
182    FirmwareBuilder
183);
184define_builder!(
185    /// Boots a kernel directly, no bootloader (`bsdkrun kernel`).
186    KernelBuilder
187);
188define_builder!(
189    /// Boots a Nanos unikernel image (`bsdkrun nanos`).
190    NanosBuilder
191);
192define_builder!(
193    /// Boots an OSv unikernel image (`bsdkrun osv`).
194    OsvBuilder
195);
196define_builder!(
197    /// Boots a Unikraft unikernel (`bsdkrun unikraft`).
198    UnikraftBuilder
199);
200define_builder!(
201    /// Boots a Solo5 (MirageOS) unikernel under the `solo5-hvt` tender
202    /// (`bsdkrun solo5`).
203    Solo5Builder
204);
205
206impl LinuxBuilder {
207    common_setters!();
208
209    /// Custom kernel image (`--kernel`).
210    pub fn kernel(mut self, kernel: impl Into<String>) -> Self {
211        self.opts.kernel = Some(kernel.into());
212        self
213    }
214
215    /// Kernel version to fetch (`--kernel-version`).
216    pub fn kernel_version(mut self, version: impl Into<String>) -> Self {
217        self.opts.kernel_version = Some(version.into());
218        self
219    }
220
221    /// Boot through an initramfs (`--initramfs`, a bare flag for Linux).
222    pub fn initramfs(mut self) -> Self {
223        self.opts.initramfs_flag = true;
224        self
225    }
226
227    /// Use a persistent CoW volume as the rootfs (`-v`).
228    pub fn volume(mut self, name: impl Into<String>) -> Self {
229        self.opts.volume = Some(name.into());
230        self
231    }
232
233    /// Share a host directory into the guest, `"HOST:GUEST"` or
234    /// `"HOST:GUEST:ro"` (`--mount`, repeatable).
235    pub fn mount(mut self, mount: impl Into<String>) -> Self {
236        self.opts.mounts.push(mount.into());
237        self
238    }
239
240    /// Override the image entrypoint (`--entrypoint`).
241    pub fn entrypoint(mut self, entrypoint: impl Into<String>) -> Self {
242        self.opts.entrypoint = Some(entrypoint.into());
243        self
244    }
245
246    /// Console device (`--console`).
247    pub fn console(mut self, console: impl Into<String>) -> Self {
248        self.opts.console = Some(console.into());
249        self
250    }
251
252    /// The command to run in the guest (argv after `--`).
253    pub fn command<I, S>(mut self, command: I) -> Self
254    where
255        I: IntoIterator<Item = S>,
256        S: Into<String>,
257    {
258        self.opts.command = strvec(command);
259        self
260    }
261}
262
263impl FreebsdBuilder {
264    common_setters!();
265    disk_setters!();
266
267    /// FreeBSD release to boot (`--version`).
268    pub fn version(mut self, version: impl Into<String>) -> Self {
269        self.opts.version = Some(version.into());
270        self
271    }
272
273    /// Custom EFI firmware (`--firmware`).
274    pub fn firmware(mut self, firmware: impl Into<String>) -> Self {
275        self.opts.firmware = Some(firmware.into());
276        self
277    }
278
279    /// Re-fetch the image even if cached (`--force`).
280    pub fn force(mut self) -> Self {
281        self.opts.force = true;
282        self
283    }
284}
285
286impl NetbsdBuilder {
287    common_setters!();
288    disk_setters!();
289
290    /// NetBSD release to boot (`--version`).
291    pub fn version(mut self, version: impl Into<String>) -> Self {
292        self.opts.version = Some(version.into());
293        self
294    }
295
296    /// Re-fetch the image even if cached (`--force`).
297    pub fn force(mut self) -> Self {
298        self.opts.force = true;
299        self
300    }
301}
302
303impl FirmwareBuilder {
304    common_setters!();
305    disk_setters!();
306}
307
308impl KernelBuilder {
309    common_setters!();
310    disk_setters!();
311
312    /// Kernel image format (`--format`, e.g. `"elf"`).
313    pub fn format(mut self, format: impl Into<String>) -> Self {
314        self.opts.format = Some(format.into());
315        self
316    }
317
318    /// Initramfs image path (`--initramfs` takes a value for direct-kernel
319    /// boots, unlike the Linux builder's bare flag).
320    pub fn initramfs(mut self, path: impl Into<String>) -> Self {
321        self.opts.initramfs_path = Some(path.into());
322        self
323    }
324
325    /// Kernel command line (`--cmdline`).
326    pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
327        self.opts.cmdline = Some(cmdline.into());
328        self
329    }
330
331    /// Root disk (`--disk`).
332    pub fn disk(mut self, disk: impl Into<String>) -> Self {
333        self.opts.disk = Some(disk.into());
334        self
335    }
336}
337
338impl NanosBuilder {
339    common_setters!();
340
341    /// Nanos kernel override (`--kernel`, Linux hosts).
342    pub fn kernel(mut self, kernel: impl Into<String>) -> Self {
343        self.opts.kernel = Some(kernel.into());
344        self
345    }
346
347    /// Kernel command line (`--cmdline`).
348    pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
349        self.opts.cmdline = Some(cmdline.into());
350        self
351    }
352
353    /// Keep the root disk across `rm` (`--persist`).
354    pub fn persist(mut self) -> Self {
355        self.opts.persist = true;
356        self
357    }
358}
359
360impl OsvBuilder {
361    common_setters!();
362
363    /// The application to run and its arguments (`--cmdline`, e.g. `"/hello.so"`).
364    pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
365        self.opts.cmdline = Some(cmdline.into());
366        self
367    }
368
369    /// Root disk, required on x86_64 (`--disk`).
370    pub fn disk(mut self, disk: impl Into<String>) -> Self {
371        self.opts.disk = Some(disk.into());
372        self
373    }
374
375    /// GIC version, aarch64 only (`--gic`, `"v2"` or `"v3"`).
376    pub fn gic(mut self, gic: impl Into<String>) -> Self {
377        self.opts.gic = Some(gic.into());
378        self
379    }
380
381    /// Keep the root disk across `rm` (`--persist`).
382    pub fn persist(mut self) -> Self {
383        self.opts.persist = true;
384        self
385    }
386}
387
388impl UnikraftBuilder {
389    common_setters!();
390
391    /// Kernel command line; Unikraft hands it to the application as argv
392    /// (`--cmdline`).
393    pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
394        self.opts.cmdline = Some(cmdline.into());
395        self
396    }
397
398    /// Initramfs image path (`--initramfs`).
399    pub fn initramfs(mut self, path: impl Into<String>) -> Self {
400        self.opts.initramfs_path = Some(path.into());
401        self
402    }
403
404    /// A virtio-fs share, `"HOST:GUEST"` with an absolute guest path
405    /// (`--mount`, repeatable). Needs a unikernel built for it.
406    pub fn mount(mut self, mount: impl Into<String>) -> Self {
407        self.opts.mounts.push(mount.into());
408        self
409    }
410}
411
412impl Solo5Builder {
413    common_setters!();
414
415    /// Backing file for a declared block device, `"NAME=FILE"` (`--block`,
416    /// repeatable). The `NAME=` may be omitted when the unikernel declares
417    /// exactly one.
418    pub fn block(mut self, block: impl Into<String>) -> Self {
419        self.opts.block.push(block.into());
420        self
421    }
422
423    /// Arguments passed to the unikernel itself, after a literal `--` (e.g.
424    /// MirageOS's `--ipv4=10.0.0.2/24`).
425    pub fn args<I, S>(mut self, args: I) -> Self
426    where
427        I: IntoIterator<Item = S>,
428        S: Into<String>,
429    {
430        self.opts.trailing_args = strvec(args);
431        self
432    }
433}
434
435// -- Sandbox ------------------------------------------------------------------
436
437impl Sandbox {
438    /// Boot an OCI image as a Linux microVM.
439    pub fn linux(image: impl Into<String>) -> LinuxBuilder {
440        LinuxBuilder {
441            kind: Kind::Linux,
442            opts: CreateOpts {
443                image: Some(image.into()),
444                ..Default::default()
445            },
446        }
447    }
448
449    /// Boot FreeBSD (EFI on macOS, PVH on Linux/amd64).
450    pub fn freebsd() -> FreebsdBuilder {
451        FreebsdBuilder {
452            kind: Kind::Freebsd,
453            opts: CreateOpts::default(),
454        }
455    }
456
457    /// Boot NetBSD (direct-kernel boot everywhere).
458    pub fn netbsd() -> NetbsdBuilder {
459        NetbsdBuilder {
460            kind: Kind::Netbsd,
461            opts: CreateOpts::default(),
462        }
463    }
464
465    /// Boot a raw disk through its UEFI loader.
466    pub fn firmware(firmware: impl Into<String>, disk: impl Into<String>) -> FirmwareBuilder {
467        FirmwareBuilder {
468            kind: Kind::Firmware,
469            opts: CreateOpts {
470                firmware: Some(firmware.into()),
471                disk: Some(disk.into()),
472                ..Default::default()
473            },
474        }
475    }
476
477    /// Boot a kernel directly, no bootloader.
478    pub fn kernel(kernel: impl Into<String>) -> KernelBuilder {
479        KernelBuilder {
480            kind: Kind::Kernel,
481            opts: CreateOpts {
482                kernel: Some(kernel.into()),
483                ..Default::default()
484            },
485        }
486    }
487
488    /// Boot a Nanos image (a path, or a bare name in `~/.ops/images`).
489    pub fn nanos(image: impl Into<String>) -> NanosBuilder {
490        NanosBuilder {
491            kind: Kind::Nanos,
492            opts: CreateOpts {
493                image: Some(image.into()),
494                ..Default::default()
495            },
496        }
497    }
498
499    /// Boot an OSv image (an aarch64 `loader.img`, or on x86_64 the loader
500    /// ELF plus a [`OsvBuilder::disk`]).
501    pub fn osv(image: impl Into<String>) -> OsvBuilder {
502        OsvBuilder {
503            kind: Kind::Osv,
504            opts: CreateOpts {
505                image: Some(image.into()),
506                ..Default::default()
507            },
508        }
509    }
510
511    /// Boot a Unikraft unikernel (a kraft project dir or a built image).
512    pub fn unikraft(path: impl Into<String>) -> UnikraftBuilder {
513        UnikraftBuilder {
514            kind: Kind::Unikraft,
515            opts: CreateOpts {
516                path: Some(path.into()),
517                ..Default::default()
518            },
519        }
520    }
521
522    /// Boot a Solo5 (MirageOS) unikernel (a `.hvt` binary or a project dir
523    /// whose `dist/` holds one).
524    pub fn solo5(path: impl Into<String>) -> Solo5Builder {
525        Solo5Builder {
526            kind: Kind::Solo5,
527            opts: CreateOpts {
528                path: Some(path.into()),
529                ..Default::default()
530            },
531        }
532    }
533
534    fn create_with(kind: Kind, opts: CreateOpts) -> Result<Sandbox> {
535        // Default log level 1 (boot diagnostics), unlike every other call:
536        // when a boot fails, the diagnostics are the error message.
537        let log_level = opts.log_level.unwrap_or(1);
538        let args = build_create_args(kind, &opts);
539        let res = run_full(&args, &[], None, log_level)?;
540        if res.exit_code != 0 {
541            return Err(Error::CommandFailed {
542                exit_code: res.exit_code,
543                stdout: res.stdout,
544                stderr: res.stderr,
545                command: "bsdkrun create".to_string(),
546            });
547        }
548
549        // Detached runs print just the machine id on stdout — take the last
550        // line that looks like one.
551        let machine_id = res
552            .stdout
553            .lines()
554            .map(str::trim)
555            .rfind(|line| looks_like_machine_id(line))
556            .map(str::to_string);
557        let Some(id) = machine_id else {
558            return Err(Error::CommandFailed {
559                exit_code: res.exit_code,
560                stdout: res.stdout,
561                stderr: res.stderr,
562                command: "bsdkrun create (no machine id in output)".to_string(),
563            });
564        };
565        let ssh_port = parse_ssh_port(&res.stderr);
566        Ok(Sandbox { id, ssh_port })
567    }
568
569    /// Wrap an already-known machine id without checking it exists.
570    pub fn from_id(id: impl Into<String>) -> Sandbox {
571        Sandbox {
572            id: id.into(),
573            ssh_port: None,
574        }
575    }
576
577    /// Reconnect to an existing machine by id (a unique prefix is enough).
578    pub fn get(id: &str) -> Result<Sandbox> {
579        for info in Self::list(true)? {
580            if info.id == id || info.id.starts_with(id) || info.name == Some(id.to_string()) {
581                return Ok(Sandbox {
582                    id: info.id,
583                    ssh_port: None,
584                });
585            }
586        }
587        Err(Error::SandboxNotFound { id: id.to_string() })
588    }
589
590    /// List machines. `all` includes exited ones (otherwise: running only).
591    pub fn list(all: bool) -> Result<Vec<SandboxInfo>> {
592        let mut args = vec!["ps".to_string(), "--json".to_string()];
593        if all {
594            args.push("--all".to_string());
595        }
596        let res = checked(&args, "bsdkrun ps")?;
597        let raw = if res.stdout.trim().is_empty() {
598            "[]".to_string()
599        } else {
600            res.stdout
601        };
602        let rows: Value = serde_json::from_str(&raw)?;
603        Ok(rows
604            .as_array()
605            .map(|rows| rows.iter().map(SandboxInfo::from_row).collect())
606            .unwrap_or_default())
607    }
608
609    /// The machine's Docker-style short id.
610    pub fn id(&self) -> &str {
611        &self.id
612    }
613
614    /// Host port forwarded to the guest's SSH, if the boot banner reported one.
615    pub fn ssh_port(&self) -> Option<u16> {
616        self.ssh_port
617    }
618
619    // -- commands ----------------------------------------------------------
620
621    /// Start building a guest command: program first, everything else chained.
622    ///
623    /// ```no_run
624    /// # let sandbox = bsdkrun_sdk::Sandbox::from_id("abc123");
625    /// let out = sandbox
626    ///     .command("node")
627    ///     .args(["-e", "console.log(1)"])
628    ///     .env("X", "hi")
629    ///     .cwd("/app")
630    ///     .run()?;
631    /// # Ok::<(), bsdkrun_sdk::Error>(())
632    /// ```
633    pub fn command(&self, program: impl Into<String>) -> CommandBuilder {
634        CommandBuilder {
635            sandbox_id: self.id.clone(),
636            argv: vec![program.into()],
637            env: Vec::new(),
638            cwd: None,
639            stdin: None,
640            tty: false,
641            log_level: 0,
642        }
643    }
644
645    /// Run an argv in the guest through its exec agent — the shorthand for
646    /// [`Sandbox::command`] with no extra options.
647    ///
648    /// A non-zero exit is reported in the [`ExecResult`], not raised; chain
649    /// [`ExecResult::ok_or_err`] to turn it into an error.
650    pub fn exec<I, S>(&self, argv: I) -> Result<ExecResult>
651    where
652        I: IntoIterator<Item = S>,
653        S: Into<String>,
654    {
655        let mut argv = strvec(argv).into_iter();
656        let Some(program) = argv.next() else {
657            return Err(Error::InvalidInput("exec needs a non-empty argv".into()));
658        };
659        let mut builder = self.command(program);
660        builder.argv.extend(argv);
661        builder.run()
662    }
663
664    /// Read the machine's console log.
665    pub fn logs(&self) -> Result<String> {
666        Ok(run_full(&strvec(["logs", self.id.as_str()]), &[], None, 0)?.stdout)
667    }
668
669    /// Read bsdkrun's boot log for the machine.
670    pub fn boot_logs(&self) -> Result<String> {
671        Ok(run_full(&strvec(["logs", "--boot", self.id.as_str()]), &[], None, 0)?.stdout)
672    }
673
674    /// Attach an interactive shell to the machine (inherits the terminal).
675    ///
676    /// Blocks until the shell exits and returns its exit code.
677    pub fn shell(&self) -> Result<i32> {
678        spawn(["shell", self.id.as_str()])
679    }
680
681    // -- inspection --------------------------------------------------------
682
683    /// Fetch this machine's current status row, or `None` if it's gone.
684    pub fn status(&self) -> Result<Option<SandboxInfo>> {
685        Ok(Self::list(true)?
686            .into_iter()
687            .find(|info| info.id == self.id))
688    }
689
690    /// Whether the machine is currently running.
691    pub fn is_running(&self) -> Result<bool> {
692        Ok(self.status()?.map(|info| info.running).unwrap_or(false))
693    }
694
695    // -- lifecycle ---------------------------------------------------------
696
697    /// Stop the machine (BSD: clean power-off; Linux: SIGTERM).
698    pub fn stop(&self) -> Result<()> {
699        checked(&strvec(["stop", self.id.as_str()]), "bsdkrun stop")?;
700        Ok(())
701    }
702
703    /// Restart a stopped machine in place — same id, disk/rootfs, network.
704    pub fn start(&self) -> Result<()> {
705        checked(&strvec(["start", self.id.as_str()]), "bsdkrun start")?;
706        Ok(())
707    }
708
709    /// Remove the machine and its state. `force` stops it first if running.
710    pub fn remove(&self, force: bool) -> Result<()> {
711        let mut args = vec!["rm".to_string()];
712        if force {
713            args.push("--force".to_string());
714        }
715        args.push(self.id.clone());
716        checked(&args, "bsdkrun rm")?;
717        Ok(())
718    }
719
720    /// Change the recorded vCPU / RAM; applies on the next [`Sandbox::start`].
721    ///
722    /// ```no_run
723    /// # let sandbox = bsdkrun_sdk::Sandbox::from_id("abc123");
724    /// sandbox.update().cpus(4).mem(2048).apply()?;
725    /// # Ok::<(), bsdkrun_sdk::Error>(())
726    /// ```
727    pub fn update(&self) -> UpdateBuilder {
728        UpdateBuilder {
729            id: self.id.clone(),
730            cpus: None,
731            mem: None,
732        }
733    }
734
735    /// Join or switch this machine to a global network (next start).
736    pub fn connect_network(&self, network: &str) -> Result<()> {
737        checked(
738            &strvec(["network", "connect", self.id.as_str(), network]),
739            "bsdkrun network connect",
740        )?;
741        Ok(())
742    }
743
744    /// Detach this machine from its network. Applies on the next start.
745    pub fn disconnect_network(&self) -> Result<()> {
746        checked(
747            &strvec(["network", "disconnect", self.id.as_str()]),
748            "bsdkrun network disconnect",
749        )?;
750        Ok(())
751    }
752
753    // -- in-guest agent helpers -------------------------------------------
754
755    /// Install SSH keys in the guest (`ssh setup`, via the agent).
756    ///
757    /// With no key, the CLI installs your local `~/.ssh/*.pub` keys.
758    ///
759    /// ```no_run
760    /// # let sandbox = bsdkrun_sdk::Sandbox::from_id("abc123");
761    /// sandbox.ssh_setup().user("tsiry").key("~/.ssh/work.pub").run()?;
762    /// # Ok::<(), bsdkrun_sdk::Error>(())
763    /// ```
764    pub fn ssh_setup(&self) -> SshSetupBuilder {
765        SshSetupBuilder {
766            id: self.id.clone(),
767            user: None,
768            keys: Vec::new(),
769        }
770    }
771
772    /// Put the guest on your tailnet (`tailscale setup`, via the agent).
773    ///
774    /// ```no_run
775    /// # let sandbox = bsdkrun_sdk::Sandbox::from_id("abc123");
776    /// sandbox.tailscale_up().authkey("tskey-auth-...").hostname("web").run()?;
777    /// # Ok::<(), bsdkrun_sdk::Error>(())
778    /// ```
779    pub fn tailscale_up(&self) -> TailscaleUpBuilder {
780        TailscaleUpBuilder {
781            id: self.id.clone(),
782            authkey: None,
783            hostname: None,
784            extra: Vec::new(),
785        }
786    }
787}
788
789/// A guest command being assembled — see [`Sandbox::command`].
790#[derive(Debug, Clone)]
791pub struct CommandBuilder {
792    sandbox_id: String,
793    argv: Vec<String>,
794    env: Vec<(String, String)>,
795    cwd: Option<String>,
796    stdin: Option<Vec<u8>>,
797    tty: bool,
798    log_level: u32,
799}
800
801impl CommandBuilder {
802    /// Append one argument.
803    pub fn arg(mut self, arg: impl Into<String>) -> Self {
804        self.argv.push(arg.into());
805        self
806    }
807
808    /// Append arguments.
809    pub fn args<I, S>(mut self, args: I) -> Self
810    where
811        I: IntoIterator<Item = S>,
812        S: Into<String>,
813    {
814        self.argv.extend(strvec(args));
815        self
816    }
817
818    /// Set a per-command environment variable (`-e K=V`).
819    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
820        self.env.push((key.into(), value.into()));
821        self
822    }
823
824    /// Run in a working directory (emulated: `cd`, then exec the real argv).
825    pub fn cwd(mut self, cwd: impl Into<String>) -> Self {
826        self.cwd = Some(cwd.into());
827        self
828    }
829
830    /// Pipe bytes (or a string) to the command's stdin.
831    pub fn stdin(mut self, data: impl AsRef<[u8]>) -> Self {
832        self.stdin = Some(data.as_ref().to_vec());
833        self
834    }
835
836    /// Allocate a PTY (`-t`).
837    pub fn tty(mut self, tty: bool) -> Self {
838        self.tty = tty;
839        self
840    }
841
842    /// bsdkrun's global `--log-level` for this call (default 0 — quiet).
843    pub fn log_level(mut self, level: u32) -> Self {
844        self.log_level = level;
845        self
846    }
847
848    /// Run the command to completion and capture the result.
849    ///
850    /// A non-zero exit is data, not an error — chain
851    /// [`ExecResult::ok_or_err`] when it should be one.
852    pub fn run(self) -> Result<ExecResult> {
853        let mut argv = self.argv;
854        if let Some(cwd) = &self.cwd {
855            // Emulate a working directory: cd, drop it, then exec the real argv.
856            let mut wrapped = strvec([
857                "/bin/sh",
858                "-c",
859                "cd \"$1\" && shift && exec \"$@\"",
860                "sh",
861                cwd.as_str(),
862            ]);
863            wrapped.append(&mut argv);
864            argv = wrapped;
865        }
866
867        let mut cli = vec!["exec".to_string()];
868        if self.tty {
869            cli.push("-t".to_string());
870        }
871        for (key, value) in &self.env {
872            cli.push("-e".to_string());
873            cli.push(format!("{key}={value}"));
874        }
875        cli.push(self.sandbox_id.clone());
876        cli.extend(argv.iter().cloned());
877
878        let res = run_full(&cli, &[], self.stdin.as_deref(), self.log_level)?;
879        Ok(ExecResult {
880            stdout: res.stdout,
881            stderr: res.stderr,
882            exit_code: res.exit_code,
883            command: format!("exec {}", argv.join(" ")),
884        })
885    }
886}
887
888/// Pending vCPU / RAM changes — see [`Sandbox::update`].
889#[derive(Debug, Clone)]
890pub struct UpdateBuilder {
891    id: String,
892    cpus: Option<u32>,
893    mem: Option<u32>,
894}
895
896impl UpdateBuilder {
897    pub fn cpus(mut self, cpus: u32) -> Self {
898        self.cpus = Some(cpus);
899        self
900    }
901
902    pub fn mem(mut self, mib: u32) -> Self {
903        self.mem = Some(mib);
904        self
905    }
906
907    /// Record the change; it applies on the machine's next start.
908    pub fn apply(self) -> Result<()> {
909        let mut args = strvec(["update", self.id.as_str()]);
910        if let Some(cpus) = self.cpus {
911            args.push("--cpus".to_string());
912            args.push(cpus.to_string());
913        }
914        if let Some(mem) = self.mem {
915            args.push("--mem".to_string());
916            args.push(mem.to_string());
917        }
918        checked(&args, "bsdkrun update")?;
919        Ok(())
920    }
921}
922
923/// An `ssh setup` invocation being assembled — see [`Sandbox::ssh_setup`].
924#[derive(Debug, Clone)]
925pub struct SshSetupBuilder {
926    id: String,
927    user: Option<String>,
928    keys: Vec<String>,
929}
930
931impl SshSetupBuilder {
932    /// The guest user to install keys for.
933    pub fn user(mut self, user: impl Into<String>) -> Self {
934        self.user = Some(user.into());
935        self
936    }
937
938    /// A literal `ssh-...` public key, or a local `.pub` path (repeatable).
939    pub fn key(mut self, key: impl Into<String>) -> Self {
940        self.keys.push(key.into());
941        self
942    }
943
944    /// Run the setup; a non-zero exit is an error here (unlike `exec`),
945    /// because a failed key install has nothing useful to report but failure.
946    pub fn run(self) -> Result<ExecResult> {
947        let mut action = vec!["setup".to_string()];
948        if let Some(user) = &self.user {
949            action.push("--user".to_string());
950            action.push(user.clone());
951        }
952        for key in &self.keys {
953            action.push("--key".to_string());
954            action.push(key.clone());
955        }
956        run_agent("ssh", &self.id, &action, &[])
957    }
958}
959
960/// A `tailscale setup` invocation being assembled — see [`Sandbox::tailscale_up`].
961#[derive(Debug, Clone)]
962pub struct TailscaleUpBuilder {
963    id: String,
964    authkey: Option<String>,
965    hostname: Option<String>,
966    extra: Vec<String>,
967}
968
969impl TailscaleUpBuilder {
970    /// A tailnet auth key — forwarded as the `TS_AUTHKEY` env var, kept off
971    /// the argument list so it never lands in a process listing.
972    pub fn authkey(mut self, authkey: impl Into<String>) -> Self {
973        self.authkey = Some(authkey.into());
974        self
975    }
976
977    /// The machine name on the tailnet.
978    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
979        self.hostname = Some(hostname.into());
980        self
981    }
982
983    /// Append a raw extra argument to the setup call.
984    pub fn arg(mut self, arg: impl Into<String>) -> Self {
985        self.extra.push(arg.into());
986        self
987    }
988
989    /// Run the setup; a non-zero exit is an error.
990    pub fn run(self) -> Result<ExecResult> {
991        let mut action = vec!["setup".to_string()];
992        if let Some(hostname) = &self.hostname {
993            action.push("--hostname".to_string());
994            action.push(hostname.clone());
995        }
996        action.extend(self.extra.iter().cloned());
997        let env: Vec<(String, String)> = self
998            .authkey
999            .map(|key| vec![("TS_AUTHKEY".to_string(), key)])
1000            .unwrap_or_default();
1001        run_agent("tailscale", &self.id, &action, &env)
1002    }
1003}
1004
1005fn run_agent(
1006    family: &str,
1007    id: &str,
1008    action: &[String],
1009    env: &[(String, String)],
1010) -> Result<ExecResult> {
1011    let mut args = vec![family.to_string(), id.to_string()];
1012    args.extend(action.iter().cloned());
1013    let res = run_full(&args, env, None, 0)?;
1014    ExecResult {
1015        stdout: res.stdout,
1016        stderr: res.stderr,
1017        exit_code: res.exit_code,
1018        command: format!("{family} {}", action.join(" ")),
1019    }
1020    .ok_or_err()
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use super::*;
1026
1027    fn s(items: &[&str]) -> Vec<String> {
1028        items.iter().map(|s| s.to_string()).collect()
1029    }
1030
1031    #[test]
1032    fn linux_minimal() {
1033        assert_eq!(
1034            Sandbox::linux("alpine").to_args(),
1035            s(&["linux", "alpine", "-d"])
1036        );
1037    }
1038
1039    #[test]
1040    fn linux_full() {
1041        let args = Sandbox::linux("ghcr.io/owner/name:tag")
1042            .kernel("vmlinux")
1043            .kernel_version("6.6")
1044            .initramfs()
1045            .volume("web")
1046            .mount("~/project:/src")
1047            .mount("~/data:/data:ro")
1048            .entrypoint("/bin/sh")
1049            .console("hvc0")
1050            .port("8080:80")
1051            .forward(2222, 22)
1052            .network("devnet")
1053            .name("api")
1054            .cpus(2)
1055            .mem(1024)
1056            .command(["node", "server.js"])
1057            .to_args();
1058        assert_eq!(
1059            args,
1060            s(&[
1061                "linux",
1062                "ghcr.io/owner/name:tag",
1063                "-d",
1064                "--kernel",
1065                "vmlinux",
1066                "--kernel-version",
1067                "6.6",
1068                "--initramfs",
1069                "-v",
1070                "web",
1071                "--mount",
1072                "~/project:/src",
1073                "--mount",
1074                "~/data:/data:ro",
1075                "--entrypoint",
1076                "/bin/sh",
1077                "--console",
1078                "hvc0",
1079                "--port",
1080                "8080:80",
1081                "--port",
1082                "2222:22",
1083                "--network",
1084                "devnet",
1085                "--name",
1086                "api",
1087                "--cpus",
1088                "2",
1089                "--mem",
1090                "1024",
1091                "--",
1092                "node",
1093                "server.js",
1094            ])
1095        );
1096    }
1097
1098    #[test]
1099    fn net_disabled_ordering() {
1100        // --no-net, then ports, then --mac, then --network.
1101        let args = Sandbox::linux("alpine")
1102            .no_net()
1103            .port("2222:22")
1104            .mac("de:ad:be:ef:00:01")
1105            .network("devnet")
1106            .to_args();
1107        assert_eq!(
1108            args,
1109            s(&[
1110                "linux",
1111                "alpine",
1112                "-d",
1113                "--no-net",
1114                "--port",
1115                "2222:22",
1116                "--mac",
1117                "de:ad:be:ef:00:01",
1118                "--network",
1119                "devnet",
1120            ])
1121        );
1122    }
1123
1124    #[test]
1125    fn freebsd_full() {
1126        let args = Sandbox::freebsd()
1127            .version("14.3")
1128            .firmware("KRUN_EFI.fd")
1129            .force()
1130            .persist()
1131            .volume("db")
1132            .attach_disk("extra.raw")
1133            .attach_disk("ro.raw:ro")
1134            .mem(2048)
1135            .name("bsd")
1136            .to_args();
1137        assert_eq!(
1138            args,
1139            s(&[
1140                "freebsd",
1141                "-d",
1142                "--version",
1143                "14.3",
1144                "--firmware",
1145                "KRUN_EFI.fd",
1146                "--force",
1147                "--persist",
1148                "-v",
1149                "db",
1150                "--attach-disk",
1151                "extra.raw",
1152                "--attach-disk",
1153                "ro.raw:ro",
1154                "--name",
1155                "bsd",
1156                "--mem",
1157                "2048",
1158            ])
1159        );
1160    }
1161
1162    #[test]
1163    fn netbsd_minimal() {
1164        assert_eq!(
1165            Sandbox::netbsd().version("10.1").volume("db").to_args(),
1166            s(&["netbsd", "-d", "--version", "10.1", "-v", "db"])
1167        );
1168    }
1169
1170    #[test]
1171    fn firmware_positionals() {
1172        assert_eq!(
1173            Sandbox::firmware("KRUN_EFI.fd", "disk.raw").to_args(),
1174            s(&[
1175                "firmware",
1176                "--firmware",
1177                "KRUN_EFI.fd",
1178                "--disk",
1179                "disk.raw",
1180                "-d",
1181            ])
1182        );
1183    }
1184
1185    #[test]
1186    fn kernel_initramfs_takes_a_path() {
1187        // For kernel, initramfs is a path (value), not a bare flag.
1188        let args = Sandbox::kernel("netbsd")
1189            .format("elf")
1190            .initramfs("initrd.img")
1191            .cmdline("root=ld0a")
1192            .disk("root.raw")
1193            .to_args();
1194        assert_eq!(
1195            args,
1196            s(&[
1197                "kernel",
1198                "--kernel",
1199                "netbsd",
1200                "-d",
1201                "--format",
1202                "elf",
1203                "--initramfs",
1204                "initrd.img",
1205                "--cmdline",
1206                "root=ld0a",
1207                "--disk",
1208                "root.raw",
1209            ])
1210        );
1211    }
1212
1213    #[test]
1214    fn nanos_image_goes_last() {
1215        let args = Sandbox::nanos("hello")
1216            .cmdline("x=1")
1217            .persist()
1218            .mem(512)
1219            .to_args();
1220        assert_eq!(
1221            args,
1222            s(&[
1223                "nanos",
1224                "-d",
1225                "--cmdline",
1226                "x=1",
1227                "--persist",
1228                "--mem",
1229                "512",
1230                "hello",
1231            ])
1232        );
1233    }
1234
1235    #[test]
1236    fn osv_image_goes_last() {
1237        let args = Sandbox::osv("loader.img")
1238            .disk("root.raw")
1239            .gic("v2")
1240            .to_args();
1241        assert_eq!(
1242            args,
1243            s(&[
1244                "osv",
1245                "-d",
1246                "--disk",
1247                "root.raw",
1248                "--gic",
1249                "v2",
1250                "loader.img",
1251            ])
1252        );
1253    }
1254
1255    #[test]
1256    fn unikraft_defaults_path() {
1257        assert_eq!(
1258            Sandbox::unikraft(".").cmdline("helloworld").to_args(),
1259            s(&["unikraft", "-d", "--cmdline", "helloworld", "."])
1260        );
1261    }
1262
1263    #[test]
1264    fn solo5_trailing_args_after_separator() {
1265        let args = Sandbox::solo5("dist/hello.hvt")
1266            .block("storage=disk.img")
1267            .args(["--ipv4=10.0.0.2/24"])
1268            .to_args();
1269        assert_eq!(
1270            args,
1271            s(&[
1272                "solo5",
1273                "-d",
1274                "--block",
1275                "storage=disk.img",
1276                "dist/hello.hvt",
1277                "--",
1278                "--ipv4=10.0.0.2/24",
1279            ])
1280        );
1281    }
1282
1283    #[test]
1284    fn machine_id_lines_are_recognized() {
1285        assert!(looks_like_machine_id("fab8f81e4f91"));
1286        assert!(looks_like_machine_id("abc123"));
1287        assert!(!looks_like_machine_id("abc12")); // too short
1288        assert!(!looks_like_machine_id("pulling alpine:3.20"));
1289        assert!(!looks_like_machine_id("FAB8F81E4F91")); // ids are lowercase
1290        assert!(!looks_like_machine_id(""));
1291    }
1292
1293    #[test]
1294    fn ssh_port_is_read_from_the_banner() {
1295        assert_eq!(
1296            parse_ssh_port("  connect with: ssh -p 2222 root@localhost\n"),
1297            Some(2222)
1298        );
1299        assert_eq!(parse_ssh_port("no banner here"), None);
1300    }
1301}