Prepare, configure, and manage Firecracker microVMs in seconds!
virtualization
linux
microvm
firecracker
1use anyhow::Result;
2
3use crate::command::{run_command, run_command_with_stdout_inherit};
4
5pub fn extract_squashfs(squashfs_file: &str, output_dir: &str) -> Result<()> {
6 if std::path::Path::new(output_dir).exists() {
7 println!(
8 "[!] Warning: {} already exists, skipping extraction.",
9 output_dir
10 );
11 return Ok(());
12 }
13
14 println!("Extracting rootfs...");
15 run_command("unsquashfs", &["-d", output_dir, squashfs_file], false)?;
16 Ok(())
17}
18
19pub fn create_ext4_filesystem(squashfs_dir: &str, output_file: &str, size: usize) -> Result<()> {
20 run_command("chown", &["-R", "root:root", squashfs_dir], true)?;
21 run_command(
22 "truncate",
23 &["-s", &format!("{}M", size), output_file],
24 false,
25 )?;
26 run_command("mkfs.ext4", &["-d", squashfs_dir, "-F", output_file], true)?;
27 Ok(())
28}
29
30pub fn create_squashfs(squashfs_dir: &str, output_file: &str) -> Result<()> {
31 if std::path::Path::new(output_file).exists() {
32 println!(
33 "[!] Warning: {} already exists, skipping. Delete it and try again if you want to recreate it.",
34 output_file
35 );
36 return Ok(());
37 }
38 run_command_with_stdout_inherit("mksquashfs", &[squashfs_dir, output_file], true)?;
39 Ok(())
40}
41
42pub fn create_overlay_dirs(rootfs_dir: &str) -> Result<()> {
43 run_command(
44 "mkdir",
45 &[
46 "-p",
47 &format!("{}/overlay/work", rootfs_dir),
48 &format!("{}/overlay/root", rootfs_dir),
49 &format!("{}/rom", rootfs_dir),
50 ],
51 true,
52 )?;
53 Ok(())
54}
55
56pub fn add_overlay_init(rootfs_dir: &str) -> Result<()> {
57 const OVERLAY_INIT: &str = include_str!("./scripts/overlay-init.sh");
58 // add overlay-init script to rootfs/sbin/overlay-init
59 println!("Adding overlay-init script...");
60 std::fs::write("/tmp/overlay-init", OVERLAY_INIT)?;
61 run_command("mkdir", &["-p", &format!("{}/sbin", rootfs_dir)], true)?;
62 run_command(
63 "mv",
64 &["/tmp/overlay-init", &format!("{}/sbin", rootfs_dir)],
65 true,
66 )?;
67 println!("Making overlay-init executable...");
68 run_command(
69 "chmod",
70 &["+x", &format!("{}/sbin/overlay-init", rootfs_dir)],
71 true,
72 )?;
73 Ok(())
74}