pub struct BoxliteRuntime { /* private fields */ }Expand description
BoxliteRuntime provides the main entry point for creating and managing Boxes.
Architecture: Backend-agnostic — delegates to a RuntimeBackend implementation.
The default backend manages local VMs. Alternative backends (e.g., REST API)
can be selected via named constructors.
Lock Behavior (local backend): Only one local runtime can use a given
BOXLITE_HOME directory at a time. The filesystem lock is automatically
released when dropped.
Cloning: Runtime is cheaply cloneable via Arc - all clones share the same state.
Implementations§
Source§impl BoxliteRuntime
impl BoxliteRuntime
Sourcepub fn new(options: BoxliteOptions) -> BoxliteResult<Self>
pub fn new(options: BoxliteOptions) -> BoxliteResult<Self>
Create a new BoxliteRuntime with the provided options (local backend).
Prepare Before Execute: All setup (filesystem, locks, managers) completes before returning. No partial initialization states.
§Errors
Returns error if:
- Another
BoxliteRuntimeis already using the same home directory - Filesystem initialization fails
- Image API initialization fails
Sourcepub fn with_defaults() -> BoxliteResult<Self>
pub fn with_defaults() -> BoxliteResult<Self>
Create a new runtime with default options.
This is equivalent to BoxliteRuntime::new(BoxliteOptions::default())
but returns a Result instead of panicking.
Prefer default_runtime() for most use cases (shares global instance).
Use this when you need an owned, non-global runtime with default config.
§Example
use boxlite::runtime::BoxliteRuntime;
let runtime = BoxliteRuntime::with_defaults()?;Sourcepub fn default_runtime() -> &'static Self
pub fn default_runtime() -> &'static Self
Get or initialize the default global runtime with automatic signal handling.
This runtime uses BoxliteOptions::default() for configuration.
The runtime is created lazily on first access and reused for all
subsequent calls.
Signal Handling: On first call, this also installs SIGTERM and SIGINT handlers that will gracefully shutdown all boxes before exiting. This is the recommended way to use BoxLite for simple applications.
For applications that need custom signal handling, use BoxliteRuntime::new()
instead and call shutdown() manually in your signal handler.
§Panics
Panics if runtime initialization fails. This indicates a serious system issue (e.g., cannot create home directory, filesystem lock).
§Example
use boxlite::runtime::BoxliteRuntime;
let runtime = BoxliteRuntime::default_runtime();
// SIGTERM/SIGINT will automatically trigger graceful shutdown
// All subsequent calls return the same runtime
let same_runtime = BoxliteRuntime::default_runtime();Sourcepub fn try_default_runtime() -> Option<&'static Self>
pub fn try_default_runtime() -> Option<&'static Self>
Try to get the default runtime if it’s been initialized.
Returns None if the default runtime hasn’t been created yet.
Useful for checking if default runtime exists without creating it.
§Example
use boxlite::runtime::BoxliteRuntime;
if let Some(runtime) = BoxliteRuntime::try_default_runtime() {
println!("Default runtime already exists");
} else {
println!("Default runtime not yet created");
}Sourcepub fn init_default_runtime(options: BoxliteOptions) -> BoxliteResult<()>
pub fn init_default_runtime(options: BoxliteOptions) -> BoxliteResult<()>
Initialize the default runtime with custom options.
This must be called before the first use of default_runtime().
Returns an error if the default runtime has already been initialized.
§Errors
Returns error if:
- Default runtime already initialized (call this early in main!)
- Runtime initialization fails (filesystem, lock, etc.)
§Example
use boxlite::runtime::{BoxliteRuntime, BoxliteOptions};
use std::path::PathBuf;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut opts = BoxliteOptions::default();
opts.home_dir = PathBuf::from("/custom/boxlite");
BoxliteRuntime::init_default_runtime(opts)?;
// All subsequent default_runtime() calls use custom config
let runtime = BoxliteRuntime::default_runtime();
Ok(())
}Sourcepub async fn create(
&self,
options: BoxOptions,
name: Option<String>,
) -> BoxliteResult<LiteBox>
pub async fn create( &self, options: BoxOptions, name: Option<String>, ) -> BoxliteResult<LiteBox>
Create a box handle.
Allocates a lock, persists the box to database with Configured status,
and returns a LiteBox handle. The VM is not started until start() or
exec() is called.
The box is immediately visible in list_info() after creation.
Sourcepub async fn get_or_create(
&self,
options: BoxOptions,
name: Option<String>,
) -> BoxliteResult<(LiteBox, bool)>
pub async fn get_or_create( &self, options: BoxOptions, name: Option<String>, ) -> BoxliteResult<(LiteBox, bool)>
Get an existing box by name, or create a new one if it doesn’t exist.
Returns (LiteBox, true) if a new box was created, or (LiteBox, false)
if an existing box with the given name was found. When an existing box is
returned, the provided options are ignored (no config drift validation).
Sourcepub async fn get(&self, id_or_name: &str) -> BoxliteResult<Option<LiteBox>>
pub async fn get(&self, id_or_name: &str) -> BoxliteResult<Option<LiteBox>>
Get a handle to an existing box by ID or name.
The id_or_name parameter can be either:
- A box ID (full or prefix)
- A user-defined box name
Sourcepub async fn get_info(&self, id_or_name: &str) -> BoxliteResult<Option<BoxInfo>>
pub async fn get_info(&self, id_or_name: &str) -> BoxliteResult<Option<BoxInfo>>
Get information about a specific box by ID or name (without creating a handle).
Sourcepub async fn list_info(&self) -> BoxliteResult<Vec<BoxInfo>>
pub async fn list_info(&self) -> BoxliteResult<Vec<BoxInfo>>
List all boxes, sorted by creation time (newest first).
Sourcepub async fn exists(&self, id_or_name: &str) -> BoxliteResult<bool>
pub async fn exists(&self, id_or_name: &str) -> BoxliteResult<bool>
Check if a box with the given ID or name exists.
Sourcepub async fn metrics(&self) -> BoxliteResult<RuntimeMetrics>
pub async fn metrics(&self) -> BoxliteResult<RuntimeMetrics>
Get runtime-wide metrics.
Sourcepub async fn remove(&self, id_or_name: &str, force: bool) -> BoxliteResult<()>
pub async fn remove(&self, id_or_name: &str, force: bool) -> BoxliteResult<()>
Remove a box completely by ID or name.
Sourcepub async fn import_box(
&self,
archive: BoxArchive,
name: Option<String>,
) -> BoxliteResult<LiteBox>
pub async fn import_box( &self, archive: BoxArchive, name: Option<String>, ) -> BoxliteResult<LiteBox>
Import a box from a .boxlite archive.
Creates a new box with a new ID from archived disk images and configuration.
Pass name=None to keep the imported box unnamed.
Support depends on backend capabilities (local backends implement import).
Sourcepub async fn shutdown(&self, timeout: Option<i32>) -> BoxliteResult<()>
pub async fn shutdown(&self, timeout: Option<i32>) -> BoxliteResult<()>
Gracefully shutdown all boxes in this runtime.
This method stops all running boxes, waiting up to timeout seconds
for each box to stop gracefully before force-killing it.
After calling this method, the runtime is permanently shut down and
will return errors for any new operations (like create()).
§Arguments
timeout- Seconds to wait before force-killing each box:None- Use default timeout (10 seconds)Some(n)where n > 0 - Wait n secondsSome(-1)- Wait indefinitely (no timeout)
§Example
use boxlite::runtime::BoxliteRuntime;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let runtime = BoxliteRuntime::new(Default::default())?;
// ... create and use boxes ...
// On signal or shutdown request:
runtime.shutdown(None).await?; // Default 10s timeout
// or
runtime.shutdown(Some(30)).await?; // 30s timeout
// or
runtime.shutdown(Some(-1)).await?; // Wait forever
Ok(())
}Sourcepub fn images(&self) -> BoxliteResult<ImageHandle>
pub fn images(&self) -> BoxliteResult<ImageHandle>
Get a handle for image operations (pull, list).
Returns an ImageHandle that provides methods for pulling and listing images.
This abstraction separates image management from runtime management,
following the same pattern as LiteBox for box operations.
§Errors
Returns BoxliteError::Unsupported if called on a REST runtime,
as image operations are only supported for local runtimes.
§Example
use boxlite::runtime::BoxliteRuntime;
let runtime = BoxliteRuntime::with_defaults()?;
let images = runtime.images()?;
// Pull an image
let image = images.pull("alpine:latest").await?;
println!("Pulled: {}", image.reference());
// List all images
let all_images = images.list().await?;
println!("Total images: {}", all_images.len());Trait Implementations§
Source§impl Clone for BoxliteRuntime
impl Clone for BoxliteRuntime
Source§fn clone(&self) -> BoxliteRuntime
fn clone(&self) -> BoxliteRuntime
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreAuto Trait Implementations§
impl Freeze for BoxliteRuntime
impl !RefUnwindSafe for BoxliteRuntime
impl Send for BoxliteRuntime
impl Sync for BoxliteRuntime
impl Unpin for BoxliteRuntime
impl UnsafeUnpin for BoxliteRuntime
impl !UnwindSafe for BoxliteRuntime
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> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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 moreSource§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request