Skip to main content

BoxliteRuntime

Struct BoxliteRuntime 

Source
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

Source

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 BoxliteRuntime is already using the same home directory
  • Filesystem initialization fails
  • Image API initialization fails
Source

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()?;
Source

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();
Source

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");
}
Source

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(())
}
Source

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.

Source

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).

Source

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
Source

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).

Source

pub async fn list_info(&self) -> BoxliteResult<Vec<BoxInfo>>

List all boxes, sorted by creation time (newest first).

Source

pub async fn exists(&self, id_or_name: &str) -> BoxliteResult<bool>

Check if a box with the given ID or name exists.

Source

pub async fn metrics(&self) -> BoxliteResult<RuntimeMetrics>

Get runtime-wide metrics.

Source

pub async fn remove(&self, id_or_name: &str, force: bool) -> BoxliteResult<()>

Remove a box completely by ID or name.

Source

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).

Source

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 seconds
    • Some(-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(())
}
Source

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

Source§

fn clone(&self) -> BoxliteRuntime

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BoxliteRuntime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more