1use 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
25fn 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
34fn 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#[derive(Debug, Clone)]
50pub struct Sandbox {
51 id: String,
52 ssh_port: Option<u16>,
53}
54
55macro_rules! common_setters {
63 () => {
64 pub fn name(mut self, name: impl Into<String>) -> Self {
66 self.opts.name = Some(name.into());
67 self
68 }
69
70 pub fn cpus(mut self, cpus: u32) -> Self {
72 self.opts.cpus = Some(cpus);
73 self
74 }
75
76 pub fn mem(mut self, mib: u32) -> Self {
78 self.opts.mem = Some(mib);
79 self
80 }
81
82 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 pub fn forward(self, host: u16, guest: u16) -> Self {
91 self.port(format!("{host}:{guest}"))
92 }
93
94 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 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 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 pub fn log_level(mut self, level: u32) -> Self {
118 self.opts.log_level = Some(level);
119 self
120 }
121
122 pub fn to_args(&self) -> Vec<String> {
125 build_create_args(self.kind, &self.opts)
126 }
127
128 pub fn create(self) -> Result<Sandbox> {
130 Sandbox::create_with(self.kind, self.opts)
131 }
132 };
133}
134
135macro_rules! disk_setters {
136 () => {
137 pub fn persist(mut self) -> Self {
139 self.opts.persist = true;
140 self
141 }
142
143 pub fn volume(mut self, name: impl Into<String>) -> Self {
145 self.opts.volume = Some(name.into());
146 self
147 }
148
149 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 LinuxBuilder
171);
172define_builder!(
173 FreebsdBuilder
175);
176define_builder!(
177 NetbsdBuilder
179);
180define_builder!(
181 FirmwareBuilder
183);
184define_builder!(
185 KernelBuilder
187);
188define_builder!(
189 NanosBuilder
191);
192define_builder!(
193 OsvBuilder
195);
196define_builder!(
197 UnikraftBuilder
199);
200define_builder!(
201 Solo5Builder
204);
205
206impl LinuxBuilder {
207 common_setters!();
208
209 pub fn kernel(mut self, kernel: impl Into<String>) -> Self {
211 self.opts.kernel = Some(kernel.into());
212 self
213 }
214
215 pub fn kernel_version(mut self, version: impl Into<String>) -> Self {
217 self.opts.kernel_version = Some(version.into());
218 self
219 }
220
221 pub fn initramfs(mut self) -> Self {
223 self.opts.initramfs_flag = true;
224 self
225 }
226
227 pub fn volume(mut self, name: impl Into<String>) -> Self {
229 self.opts.volume = Some(name.into());
230 self
231 }
232
233 pub fn mount(mut self, mount: impl Into<String>) -> Self {
236 self.opts.mounts.push(mount.into());
237 self
238 }
239
240 pub fn entrypoint(mut self, entrypoint: impl Into<String>) -> Self {
242 self.opts.entrypoint = Some(entrypoint.into());
243 self
244 }
245
246 pub fn console(mut self, console: impl Into<String>) -> Self {
248 self.opts.console = Some(console.into());
249 self
250 }
251
252 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 pub fn version(mut self, version: impl Into<String>) -> Self {
269 self.opts.version = Some(version.into());
270 self
271 }
272
273 pub fn firmware(mut self, firmware: impl Into<String>) -> Self {
275 self.opts.firmware = Some(firmware.into());
276 self
277 }
278
279 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 pub fn version(mut self, version: impl Into<String>) -> Self {
292 self.opts.version = Some(version.into());
293 self
294 }
295
296 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 pub fn format(mut self, format: impl Into<String>) -> Self {
314 self.opts.format = Some(format.into());
315 self
316 }
317
318 pub fn initramfs(mut self, path: impl Into<String>) -> Self {
321 self.opts.initramfs_path = Some(path.into());
322 self
323 }
324
325 pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
327 self.opts.cmdline = Some(cmdline.into());
328 self
329 }
330
331 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 pub fn kernel(mut self, kernel: impl Into<String>) -> Self {
343 self.opts.kernel = Some(kernel.into());
344 self
345 }
346
347 pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
349 self.opts.cmdline = Some(cmdline.into());
350 self
351 }
352
353 pub fn persist(mut self) -> Self {
355 self.opts.persist = true;
356 self
357 }
358}
359
360impl OsvBuilder {
361 common_setters!();
362
363 pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
365 self.opts.cmdline = Some(cmdline.into());
366 self
367 }
368
369 pub fn disk(mut self, disk: impl Into<String>) -> Self {
371 self.opts.disk = Some(disk.into());
372 self
373 }
374
375 pub fn gic(mut self, gic: impl Into<String>) -> Self {
377 self.opts.gic = Some(gic.into());
378 self
379 }
380
381 pub fn persist(mut self) -> Self {
383 self.opts.persist = true;
384 self
385 }
386}
387
388impl UnikraftBuilder {
389 common_setters!();
390
391 pub fn cmdline(mut self, cmdline: impl Into<String>) -> Self {
394 self.opts.cmdline = Some(cmdline.into());
395 self
396 }
397
398 pub fn initramfs(mut self, path: impl Into<String>) -> Self {
400 self.opts.initramfs_path = Some(path.into());
401 self
402 }
403
404 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 pub fn block(mut self, block: impl Into<String>) -> Self {
419 self.opts.block.push(block.into());
420 self
421 }
422
423 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
435impl Sandbox {
438 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 pub fn freebsd() -> FreebsdBuilder {
451 FreebsdBuilder {
452 kind: Kind::Freebsd,
453 opts: CreateOpts::default(),
454 }
455 }
456
457 pub fn netbsd() -> NetbsdBuilder {
459 NetbsdBuilder {
460 kind: Kind::Netbsd,
461 opts: CreateOpts::default(),
462 }
463 }
464
465 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 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 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 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 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 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 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 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 pub fn from_id(id: impl Into<String>) -> Sandbox {
571 Sandbox {
572 id: id.into(),
573 ssh_port: None,
574 }
575 }
576
577 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 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 pub fn id(&self) -> &str {
611 &self.id
612 }
613
614 pub fn ssh_port(&self) -> Option<u16> {
616 self.ssh_port
617 }
618
619 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 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 pub fn logs(&self) -> Result<String> {
666 Ok(run_full(&strvec(["logs", self.id.as_str()]), &[], None, 0)?.stdout)
667 }
668
669 pub fn boot_logs(&self) -> Result<String> {
671 Ok(run_full(&strvec(["logs", "--boot", self.id.as_str()]), &[], None, 0)?.stdout)
672 }
673
674 pub fn shell(&self) -> Result<i32> {
678 spawn(["shell", self.id.as_str()])
679 }
680
681 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 pub fn is_running(&self) -> Result<bool> {
692 Ok(self.status()?.map(|info| info.running).unwrap_or(false))
693 }
694
695 pub fn stop(&self) -> Result<()> {
699 checked(&strvec(["stop", self.id.as_str()]), "bsdkrun stop")?;
700 Ok(())
701 }
702
703 pub fn start(&self) -> Result<()> {
705 checked(&strvec(["start", self.id.as_str()]), "bsdkrun start")?;
706 Ok(())
707 }
708
709 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 pub fn update(&self) -> UpdateBuilder {
728 UpdateBuilder {
729 id: self.id.clone(),
730 cpus: None,
731 mem: None,
732 }
733 }
734
735 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 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 pub fn ssh_setup(&self) -> SshSetupBuilder {
765 SshSetupBuilder {
766 id: self.id.clone(),
767 user: None,
768 keys: Vec::new(),
769 }
770 }
771
772 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#[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 pub fn arg(mut self, arg: impl Into<String>) -> Self {
804 self.argv.push(arg.into());
805 self
806 }
807
808 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 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 pub fn cwd(mut self, cwd: impl Into<String>) -> Self {
826 self.cwd = Some(cwd.into());
827 self
828 }
829
830 pub fn stdin(mut self, data: impl AsRef<[u8]>) -> Self {
832 self.stdin = Some(data.as_ref().to_vec());
833 self
834 }
835
836 pub fn tty(mut self, tty: bool) -> Self {
838 self.tty = tty;
839 self
840 }
841
842 pub fn log_level(mut self, level: u32) -> Self {
844 self.log_level = level;
845 self
846 }
847
848 pub fn run(self) -> Result<ExecResult> {
853 let mut argv = self.argv;
854 if let Some(cwd) = &self.cwd {
855 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#[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 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#[derive(Debug, Clone)]
925pub struct SshSetupBuilder {
926 id: String,
927 user: Option<String>,
928 keys: Vec<String>,
929}
930
931impl SshSetupBuilder {
932 pub fn user(mut self, user: impl Into<String>) -> Self {
934 self.user = Some(user.into());
935 self
936 }
937
938 pub fn key(mut self, key: impl Into<String>) -> Self {
940 self.keys.push(key.into());
941 self
942 }
943
944 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#[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 pub fn authkey(mut self, authkey: impl Into<String>) -> Self {
973 self.authkey = Some(authkey.into());
974 self
975 }
976
977 pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
979 self.hostname = Some(hostname.into());
980 self
981 }
982
983 pub fn arg(mut self, arg: impl Into<String>) -> Self {
985 self.extra.push(arg.into());
986 self
987 }
988
989 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 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 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")); assert!(!looks_like_machine_id("pulling alpine:3.20"));
1289 assert!(!looks_like_machine_id("FAB8F81E4F91")); 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}