pub struct MicroVmBuilder<RootPath, RamMib> { /* private fields */ }Expand description
The builder for a MicroVm.
This struct provides a fluent interface for configuring and creating a MicroVm instance.
It allows you to set various parameters such as the log level, root path, number of vCPUs,
RAM size, virtio-fs mounts, port mappings, resource limits, working directory, executable path,
arguments, environment variables, and console output.
§Examples
use monocore::vm::{MicroVmBuilder, LogLevel};
use std::path::PathBuf;
let vm = MicroVmBuilder::default()
.log_level(LogLevel::Debug)
.root_path("/tmp")
.num_vcpus(2)
.ram_mib(1024)
.mapped_dirs(["/home:/guest/mount".parse()?])
.port_map(["8080:80".parse()?])
.rlimits(["RLIMIT_NOFILE=1024:1024".parse()?])
.workdir_path("/workdir")
.exec_path("/bin/example")
.args(["arg1", "arg2"])
.env(["KEY1=VALUE1".parse()?, "KEY2=VALUE2".parse()?])
.console_output("/tmp/console.log")
.build()?;Implementations§
Source§impl<RootPath, RamMib> MicroVmBuilder<RootPath, RamMib>
impl<RootPath, RamMib> MicroVmBuilder<RootPath, RamMib>
Sourcepub fn log_level(self, log_level: LogLevel) -> Self
pub fn log_level(self, log_level: LogLevel) -> Self
Sets the log level for the MicroVm.
The log level controls the verbosity of the MicroVm’s logging output.
§Examples
use monocore::vm::{LogLevel, MicroVmBuilder};
use tempfile::TempDir;
let temp_dir = TempDir::new()?;
let vm = MicroVmBuilder::default()
.log_level(LogLevel::Debug) // Enable debug logging
.root_path(temp_dir.path())
.ram_mib(1024)
.build()?;§Log Levels
Off- No logging (default)Error- Only error messagesWarn- Warnings and errorsInfo- Informational messages, warnings, and errorsDebug- Debug information and all aboveTrace- Detailed trace information and all above
Sourcepub fn root_path(
self,
root_path: impl Into<PathBuf>,
) -> MicroVmBuilder<PathBuf, RamMib>
pub fn root_path( self, root_path: impl Into<PathBuf>, ) -> MicroVmBuilder<PathBuf, RamMib>
Sets the root filesystem path for the MicroVm.
This path serves as the root directory for the MicroVm’s filesystem. It should contain all necessary files and directories for the guest system to operate.
§Examples
use monocore::vm::MicroVmBuilder;
use tempfile::TempDir;
let temp_dir = TempDir::new()?;
let vm = MicroVmBuilder::default()
.root_path(temp_dir.path()) // Use temporary root filesystem
.ram_mib(1024)
.build()?;§Notes
- The path must exist and be accessible
- The path should contain a valid root filesystem structure
- Common choices include Alpine Linux or Ubuntu root filesystems
- This is a required field - the build will fail if not set
Sourcepub fn num_vcpus(self, num_vcpus: u8) -> Self
pub fn num_vcpus(self, num_vcpus: u8) -> Self
Sets the number of virtual CPUs (vCPUs) for the MicroVm.
This determines how many CPU cores are available to the guest system.
§Examples
use monocore::vm::MicroVmBuilder;
use tempfile::TempDir;
let temp_dir = TempDir::new()?;
let vm = MicroVmBuilder::default()
.root_path(temp_dir.path())
.ram_mib(1024)
.num_vcpus(2) // Allocate 2 virtual CPU cores
.build()?;§Notes
- The default is 1 vCPU if not specified
- The number of vCPUs should not exceed the host’s physical CPU cores
- More vCPUs aren’t always better - consider the workload’s needs
Sourcepub fn ram_mib(self, ram_mib: u32) -> MicroVmBuilder<RootPath, u32>
pub fn ram_mib(self, ram_mib: u32) -> MicroVmBuilder<RootPath, u32>
Sets the amount of RAM in MiB for the MicroVm.
This determines how much memory is available to the guest system.
§Examples
use monocore::vm::MicroVmBuilder;
use tempfile::TempDir;
let temp_dir = TempDir::new()?;
let vm = MicroVmBuilder::default()
.root_path(temp_dir.path())
.ram_mib(1024) // Allocate 1 GiB of RAM
.build()?;§Notes
- The value is in MiB (1 GiB = 1024 MiB)
- Consider the host’s available memory when setting this value
- Common values: 512 MiB for minimal systems, 1024-2048 MiB for typical workloads
- This is a required field - the build will fail if not set
Sourcepub fn mapped_dirs(
self,
mapped_dirs: impl IntoIterator<Item = PathPair>,
) -> Self
pub fn mapped_dirs( self, mapped_dirs: impl IntoIterator<Item = PathPair>, ) -> Self
Sets the directory mappings for the MicroVm using virtio-fs.
Each mapping follows Docker’s volume mapping convention using the format host:guest.
§Examples
use monocore::vm::MicroVmConfigBuilder;
let config = MicroVmConfigBuilder::default()
.mapped_dirs([
// Share host's /data directory as /mnt/data in guest
"/data:/mnt/data".parse()?,
// Share current directory as /app in guest
"./:/app".parse()?,
// Use same path in both host and guest
"/shared".parse()?
]);Sourcepub fn port_map(self, port_map: impl IntoIterator<Item = PortPair>) -> Self
pub fn port_map(self, port_map: impl IntoIterator<Item = PortPair>) -> Self
Sets the port mappings between host and guest for the MicroVm.
Port mappings follow Docker’s convention using the format host:guest, where:
hostis the port number on the host machineguestis the port number inside the MicroVm
§Examples
use monocore::vm::MicroVmBuilder;
use monocore::config::PortPair;
let vm = MicroVmBuilder::default()
.port_map([
// Map host port 8080 to guest port 80 (for web server)
"8080:80".parse()?,
// Map host port 2222 to guest port 22 (for SSH)
"2222:22".parse()?,
// Use same port (3000) on both host and guest
"3000".parse()?
]);§Notes
- If you don’t call this method, no ports will be mapped between host and guest
- The guest application will need to use the guest port number to listen for connections
- External connections should use the host port number to connect to the service
- Port mapping is not supported when using passt networking mode
Sourcepub fn rlimits(self, rlimits: impl IntoIterator<Item = LinuxRlimit>) -> Self
pub fn rlimits(self, rlimits: impl IntoIterator<Item = LinuxRlimit>) -> Self
Sets the resource limits for the MicroVm.
§Examples
use monocore::vm::MicroVmBuilder;
MicroVmBuilder::default().rlimits(["RLIMIT_NOFILE=1024:1024".parse()?]);Sourcepub fn workdir_path(self, workdir_path: impl Into<Utf8UnixPathBuf>) -> Self
pub fn workdir_path(self, workdir_path: impl Into<Utf8UnixPathBuf>) -> Self
Sets the working directory path for the MicroVm.
§Examples
use monocore::vm::MicroVmBuilder;
MicroVmBuilder::default().workdir_path("/path/to/workdir");Sourcepub fn exec_path(self, exec_path: impl Into<Utf8UnixPathBuf>) -> Self
pub fn exec_path(self, exec_path: impl Into<Utf8UnixPathBuf>) -> Self
Sets the executable path for the MicroVm.
§Examples
use monocore::vm::MicroVmBuilder;
MicroVmBuilder::default().exec_path("/path/to/exec");Sourcepub fn args<'a>(self, args: impl IntoIterator<Item = &'a str>) -> Self
pub fn args<'a>(self, args: impl IntoIterator<Item = &'a str>) -> Self
Sets the command-line arguments for the executable.
These arguments will be passed to the program specified by exec_path.
§Examples
use monocore::vm::MicroVmBuilder;
let vm = MicroVmBuilder::default()
.args([
"-m", "http.server", // Run Python's HTTP server module
"8080", // Listen on port 8080
"--directory", "/data" // Serve files from /data
]);§Notes
- Arguments are passed in the order they appear in the iterator
- The program name (argv[0]) is automatically set from exec_path
- Each argument should be a separate string
Sourcepub fn env(self, env: impl IntoIterator<Item = EnvPair>) -> Self
pub fn env(self, env: impl IntoIterator<Item = EnvPair>) -> Self
Sets environment variables for processes in the MicroVm.
Environment variables follow the standard format KEY=VALUE and are available
to all processes in the guest system.
§Examples
use monocore::vm::MicroVmBuilder;
let vm = MicroVmBuilder::default()
.env([
// Set application environment
"APP_ENV=production".parse()?,
// Configure logging
"LOG_LEVEL=info".parse()?,
// Set timezone
"TZ=UTC".parse()?,
// Multiple values are OK
"ALLOWED_HOSTS=localhost,127.0.0.1".parse()?
]);§Notes
- Variables are available to all processes in the guest
- Values should be properly escaped if they contain special characters
- Common uses include configuration and runtime settings
- Some programs expect specific environment variables to function
Sourcepub fn console_output(self, console_output: impl Into<Utf8UnixPathBuf>) -> Self
pub fn console_output(self, console_output: impl Into<Utf8UnixPathBuf>) -> Self
Sets the path for capturing console output from the MicroVm.
This allows redirecting and saving all console output (stdout/stderr) from the guest system to a file on the host.
§Examples
use monocore::vm::MicroVmBuilder;
let vm = MicroVmBuilder::default()
.console_output("/var/log/microvm.log") // Save output to log file
.exec_path("/usr/local/bin/myapp"); // Run application§Notes
- The path must be writable on the host system
- The file will be created if it doesn’t exist
- Useful for debugging and logging
- Captures both stdout and stderr
Sourcepub fn assigned_ip(self, assigned_ip: Ipv4Addr) -> Self
pub fn assigned_ip(self, assigned_ip: Ipv4Addr) -> Self
Sets the assigned IP address for the MicroVm.
Sourcepub fn local_only(self, local_only: bool) -> Self
pub fn local_only(self, local_only: bool) -> Self
Sets whether the MicroVm is restricted to local connections only.
Source§impl MicroVmBuilder<PathBuf, u32>
impl MicroVmBuilder<PathBuf, u32>
Sourcepub fn build(self) -> MonocoreResult<MicroVm>
pub fn build(self) -> MonocoreResult<MicroVm>
Builds the MicroVm.
This method creates a MicroVm instance based on the configuration set in the builder.
The MicroVm will be ready to start but won’t be running until you call start().
§Examples
use monocore::vm::MicroVmBuilder;
use tempfile::TempDir;
let temp_dir = TempDir::new()?;
let vm = MicroVmBuilder::default()
.root_path(temp_dir.path())
.ram_mib(1024)
.exec_path("/usr/bin/python3")
.args(["-c", "print('Hello from MicroVm!')"])
.build()?;
// // Start the MicroVm
// vm.start()?; // This would actually run the VM§Required Configuration
root_path- Path to the root filesystemram_mib- Amount of RAM to allocate
§Notes
- The build will fail if required configuration is missing
- The build will fail if the root path doesn’t exist
- The build will fail if RAM or vCPU values are invalid
- After building, use
start()to run the MicroVm
Trait Implementations§
Auto Trait Implementations§
impl<RootPath, RamMib> Freeze for MicroVmBuilder<RootPath, RamMib>
impl<RootPath, RamMib> RefUnwindSafe for MicroVmBuilder<RootPath, RamMib>where
RootPath: RefUnwindSafe,
RamMib: RefUnwindSafe,
impl<RootPath, RamMib> Send for MicroVmBuilder<RootPath, RamMib>
impl<RootPath, RamMib> Sync for MicroVmBuilder<RootPath, RamMib>
impl<RootPath, RamMib> Unpin for MicroVmBuilder<RootPath, RamMib>
impl<RootPath, RamMib> UnwindSafe for MicroVmBuilder<RootPath, RamMib>where
RootPath: UnwindSafe,
RamMib: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more