Skip to main content
Create and manage named persistent volumes, and build the mount configs that attach storage to a sandbox. See Volumes for usage examples and patterns.

Typical flow

from microsandbox import Sandbox, Volume

# 1. create a persistent named volume
await Volume.create("pip-cache", quota_mib=2048)

# 2. mount it into a sandbox via a mount factory
sb = await Sandbox.create(
    "worker",
    image="python",
    volumes={"/root/.cache/pip": Volume.named("pip-cache")},
)

# 3. inspect or edit the volume from the host, no sandbox required
handle = await Volume.get("pip-cache")
print(handle.used_bytes)

Static methods

Static methods on Volume that manage named persistent volumes. Volumes live independently of any sandbox, stored by default under ~/.microsandbox/volumes/<name>/.

Volume.create()

async def create(
    name: str,
    *,
    kind: str = "dir",
    size_mib: int | None = None,
    quota_mib: int | None = None,
    labels: dict[str, str] | None = None,
) -> Volume
await Volume.create("pip-cache", quota_mib=2048)
await Volume.create("docker-data", kind="disk", size_mib=20 * 1024)
Create a new named volume. A "dir" volume is a host directory; a "disk" volume is a backing disk image that requires size_mib.

Parameters

namestr
Volume name.
kindstr
Volume kind: “dir” (default) or “disk”.
size_mibint | None
Disk capacity in MiB; required with kind=“disk”.
quota_mibint | None
Quota in MiB recorded for directory volumes.
labelsdict[str, str] | None
Metadata labels.

Returns

Created volume, exposing name and path.

Volume.get()

async def get(name: str) -> VolumeHandle
handle = await Volume.get("pip-cache")
print(handle.kind, handle.used_bytes)
Get a lightweight handle to an existing named volume, with its metadata and a host-side filesystem handle.

Parameters

namestr
Volume name.

Returns

Handle with metadata and a filesystem accessor.

Volume.list()

async def list() -> list[VolumeHandle]
for v in await Volume.list():
    print(v.name, v.used_bytes)
List all named volumes.

Returns

All volume handles.

Volume.remove()

async def remove(name: str) -> None
await Volume.remove("pip-cache")
Delete a named volume and its contents. Fails if the volume is currently mounted.

Parameters

namestr
Volume name.

Mount factories

Static factory methods on Volume that build a MountConfig. Pass the result as a value in the volumes dict when creating a sandbox, keyed by the guest mount point.

Volume.bind()

def bind(
    path: str,
    *,
    readonly: bool = False,
    noexec: bool = False,
    nosuid: bool = False,
    nodev: bool = False,
) -> MountConfig
sb = await Sandbox.create(
    "build",
    image="python",
    volumes={"/src": Volume.bind("/home/me/project", readonly=True)},
)
Mount a host directory into the sandbox. Changes in the guest are reflected on the host and vice versa.

Parameters

pathstr
Directory path on the host.
readonlybool
Mount as read-only; virtiofs-backed mounts also reject writes in the host filesystem server.
noexecbool
Prevent direct execution from the mount.
nosuidbool
Ignore setuid and setgid privilege elevation from files on the mount.
nodevbool
Ignore device files on the mount.

Returns

Mount configuration.

Volume.named()

def named(
    name: str,
    *,
    readonly: bool = False,
    noexec: bool = False,
    nosuid: bool = False,
    nodev: bool = False,
) -> MountConfig
sb = await Sandbox.create(
    "worker",
    image="python",
    volumes={
        "/root/.cache/pip": Volume.named("pip-cache"),
        "/etc/config": Volume.named("shared-config", readonly=True),
    },
)
Mount an existing named volume. The volume must already exist; create it first with Volume.create().

Parameters

namestr
Volume name.
readonlybool
Mount as read-only; virtiofs-backed mounts also reject writes in the host filesystem server.
noexecbool
Prevent direct execution from the mount.
nosuidbool
Ignore setuid and setgid privilege elevation from files on the mount.
nodevbool
Ignore device files on the mount.

Returns

Mount configuration.

Volume.tmpfs()

def tmpfs(
    *,
    size_mib: int | None = None,
    readonly: bool = False,
    noexec: bool = False,
    nosuid: bool = False,
    nodev: bool = False,
) -> MountConfig
sb = await Sandbox.create(
    "scratch",
    image="python",
    volumes={"/tmp/work": Volume.tmpfs(size_mib=256)},
)
Use an in-memory filesystem. Contents are discarded when the sandbox stops.

Parameters

size_mibint | None
Maximum size in MiB.
readonlybool
Mount as read-only.
noexecbool
Prevent direct execution from the mount.
nosuidbool
Ignore setuid and setgid privilege elevation from files on the mount.
nodevbool
Ignore device files on the mount.

Returns

Mount configuration.

Volume.disk()

def disk(
    path: str,
    *,
    format: str | None = None,
    fstype: str | None = None,
    readonly: bool = False,
    noexec: bool = False,
    nosuid: bool = False,
    nodev: bool = False,
) -> MountConfig
sb = await Sandbox.create(
    "db",
    image="postgres",
    volumes={"/var/lib/postgresql": Volume.disk("/data/pg.qcow2", fstype="ext4")},
)
Mount a host disk image as a virtio-blk device. format is the disk image format ("qcow2", "raw", or "vmdk"); when omitted it is inferred from the file extension. fstype (e.g. "ext4") is the inner filesystem agentd mounts; when omitted, agentd probes /proc/filesystems for a type that mounts cleanly.

Parameters

pathstr
Host path to the disk image.
formatstr | None
Disk image format hint. See DiskImageFormat.
fstypestr | None
Inner filesystem type.
readonlybool
Mount as read-only.
noexecbool
Prevent direct execution from the mount.
nosuidbool
Ignore setuid and setgid privilege elevation from files on the mount.
nodevbool
Ignore device files on the mount.

Returns

Mount configuration.

Instance properties

Read-only properties on a Volume returned by Volume.create().

volume.name

name: str
Volume name.

volume.path

path: str
Host path to the volume’s directory.

VolumeFs methods

Host-side filesystem operations on a named volume, obtained via the fs property on a VolumeHandle. These run directly on the host filesystem; no running sandbox is required. All paths are relative to the volume root.

fs.read()

async def read(path: str) -> bytes
handle = await Volume.get("pip-cache")
data = await handle.fs.read("index.json")
Read the entire contents of a file as raw bytes.

Parameters

pathstr
Path relative to the volume root.

Returns

bytes
File contents as raw bytes.

fs.read_text()

async def read_text(path: str) -> str
Read the entire contents of a file and decode it as UTF-8.

Parameters

pathstr
Path relative to the volume root.

Returns

str
File contents as a string.

fs.write()

async def write(path: str, data: bytes) -> None
handle = await Volume.get("pip-cache")
await handle.fs.write("seed.txt", b"hello")
Write content to a file, creating it if it doesn’t exist and overwriting if it does.

Parameters

pathstr
Path relative to the volume root.
databytes
File content.

fs.list()

async def list(path: str) -> list[FsEntry]
List the entries in a directory.

Parameters

pathstr
Path relative to the volume root.

Returns

Directory entries.

fs.mkdir()

async def mkdir(path: str) -> None
Create a directory and all parent directories.

Parameters

pathstr
Path relative to the volume root.

fs.remove_file()

async def remove_file(path: str) -> None
Remove a file.

Parameters

pathstr
Path relative to the volume root.

fs.exists()

async def exists(path: str) -> bool
Check whether a path exists within the volume.

Parameters

pathstr
Path relative to the volume root.

Returns

bool
True if the path exists.

Types

VolumeHandle

Returned by Volume.get(), Volume.list()

A lightweight handle to a named volume, with its database metadata and a host-side filesystem accessor.
Property / MethodTypeDescription
namestrVolume name
kindstrVolume kind: dir or disk
quota_mibint | NoneStorage quota in MiB
used_bytesintCurrent disk usage in bytes
capacity_bytesint | NoneDisk capacity in bytes
disk_formatstr | NoneDisk image format
disk_fstypestr | NoneDisk filesystem type
labelsdict[str, str]Metadata labels
created_atfloat | NoneCreation timestamp (ms since epoch)
fsVolumeFsHost-side filesystem handle
remove()(async) NoneDelete this volume

VolumeFs

Returned by VolumeHandle.fs

Host-side filesystem operations on a named volume. No running sandbox is required. See the VolumeFs methods above for the full API.
MethodSignatureDescription
readread(path) -> bytesRead a file as raw bytes
read_textread_text(path) -> strRead a file as UTF-8 text
writewrite(path, data) -> NoneWrite bytes to a file
listlist(path) -> list[FsEntry]List a directory
mkdirmkdir(path) -> NoneCreate a directory
remove_fileremove_file(path) -> NoneRemove a file
existsexists(path) -> boolCheck a path exists

MountConfig

Returned by Volume.bind(), Volume.named(), Volume.tmpfs(), Volume.disk()

Frozen dataclass representing a mount configuration. Build one with a mount factory and pass it as a value in the sandbox volumes dict. stat_virtualization and host_permissions apply only to virtiofs-backed mounts (BIND and NAMED); setting either on a TMPFS or DISK mount raises ValueError.
FieldTypeDefaultDescription
kindMountKind-Type of mount (required)
bindstr | NoneNoneHost path for bind mounts
namedstr | NoneNoneVolume name for named mounts
named_mode"existing" | "create" | "ensure-exists" | NoneNoneNamed-volume creation behavior
named_kind"dir" | "directory" | "disk" | NoneNoneStorage kind for created named volumes
quota_mibint | NoneNoneQuota in MiB for directory named volumes
size_mibint | NoneNoneSize limit for tmpfs, or capacity for disk named volumes
readonlyboolFalseWhether the mount is read-only
noexecboolFalseWhether direct execution from the mount is disabled
nosuidboolFalseWhether setuid/setgid privilege elevation is ignored
nodevboolFalseWhether device files on the mount are ignored
diskstr | NoneNoneHost path to a disk image for disk mounts
formatDiskImageFormat | str | NoneNoneDisk image format for disk mounts
fstypestr | NoneNoneInner filesystem type for disk mounts
stat_virtualizationStatVirtualization | str | NoneNonePer-mount stat-virtualization policy (virtiofs-backed only)
host_permissionsHostPermissions | str | NoneNonePer-mount host-permission policy (virtiofs-backed only)

MountKind

Used by MountConfig

String enum (StrEnum) for the type of mount.
ValueDescription
"bind"Host bind mount
"named"Named volume mount
"tmpfs"In-memory filesystem
"disk"Host disk image mount

DiskImageFormat

Used by Volume.disk(), MountConfig

String enum (StrEnum) for the format of a backing disk image.
ValueDescription
"qcow2"QEMU copy-on-write v2 image
"raw"Raw disk image
"vmdk"VMware disk image