Skip to content

automaton.container

WARNING

This documentation is almost entirely "vibe coded"; while a helpful resource for humans and agents to understand this codebase, it should not be considered a source of ground truth in the way documentation normally is, and the user is responsible for verifying that all instructions given here are safe.

automaton.container

Container management for Automaton.

Manages layered Charliecloud container builds using base, harness, and optional runtime templates, exposing built artifacts through path-like container references.

Automaton is content-free: it does not know where templates live or what runtime layers exist. Callers supply a :class:ContainerLayout describing:

  • the base Dockerfile template,
  • how to find a harness's Dockerfile template and enumerate harnesses,
  • how to enumerate runtime layers and find their Dockerfile templates and metadata.

The third ("runtime") layer is fully generic here. A benchmark orchestrator might back it with "task groups", but Automaton assigns no such meaning.

ContainerLayout dataclass

ContainerLayout(base_template_path: Path, harness_template_path: Callable[[str], Path], list_harnesses: Callable[[], list[str]], load_harness: Callable[[str], Harness], list_runtime_layers: Callable[[], list[str]], runtime_layer_metadata: Callable[[str], dict], runtime_template_path: Callable[[str], Path])

Describes where container templates and runtime layers come from.

Automaton stays content-free by delegating all template discovery to the caller through this layout.

Parameters:

Name Type Description Default
base_template_path Path

Path to the base Dockerfile template (rendered with {{ parent_image }}).

required
harness_template_path Callable[[str], Path]

Given a harness template name, return its Dockerfile template path.

required
list_harnesses Callable[[], list[str]]

Return the available harness ids.

required
load_harness Callable[[str], Harness]

Given a harness id, return a loaded :class:~automaton.harness.Harness. This is how the manager learns a harness's container_template.

required
list_runtime_layers Callable[[], list[str]]

Return the available runtime-layer ids (e.g. task-group ids).

required
runtime_layer_metadata Callable[[str], dict]

Given a runtime-layer id, return its metadata dict. The manager reads the optional container_template key (defaults to the layer id).

required
runtime_template_path Callable[[str], Path]

Given a runtime-layer template name, return its Dockerfile template path.

required

ContainerInfo dataclass

ContainerInfo(container_id: str, canonical_ref: str, aliases: tuple[str, ...], kind: str, path: Path, exists: bool, size_bytes: int | None = None, build_time: datetime | None = None)

Metadata about a buildable or built container artifact.

size_human

size_human() -> str

Return human-readable size.

Source code in automaton/container.py
def size_human(self) -> str:
    """Return human-readable size."""
    if self.size_bytes is None:
        return "unknown"
    size = float(self.size_bytes)
    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if size < 1024.0:
            return f"{size:.1f} {unit}"
        size /= 1024.0
    return f"{size:.1f} PB"

ContainerRef dataclass

ContainerRef(kind: str, harness_id: str | None = None, group_id: str | None = None)

Normalized container reference.

Kinds: base, harness, runtime. For runtime, group_id holds the runtime-layer id.

display_ref property

display_ref: str

Return the preferred shorthand container ref.

canonical_ref property

canonical_ref: str

Return the explicit container ref including the base root.

aliases property

aliases: tuple[str, ...]

Return accepted aliases for this ref.

ContainerManager

ContainerManager(layout: ContainerLayout, cache_root: Path | None = None, image_prefix: str = DEFAULT_IMAGE_PREFIX, build_force: str | bool | None = True)

Manage layered Charliecloud container builds and lifecycle.

Parameters:

Name Type Description Default
layout ContainerLayout

Describes template locations and runtime-layer discovery.

required
cache_root Path

Root for built artifacts and image storage. Defaults to the AUTOMATON_CONTAINER_BASE environment variable, else /var/tmp/automaton-{uid}.

None
image_prefix str

Prefix for Charliecloud image names. Default "automaton".

DEFAULT_IMAGE_PREFIX
build_force str | bool | None

Controls Charliecloud's --force unprivileged-build mode for ch-image build. Charliecloud's auto-detection of when fakeroot is needed is unreliable across base images and storage dirs, which can cause RUN steps that run apt-get/rm -rf to fail with errors like can't mkdir: var/lib/apt/lists: File exists. Passing --force up front makes this deterministic.

  • True (default): pass bare --force (Charliecloud picks method).
  • a string (e.g. "seccomp", "fakeroot"): pass --force=<value>.
  • False/None: do not pass --force (legacy behavior).

Overridable via the AUTOMATON_CH_FORCE environment variable, whose value is interpreted the same way ("0"/"false"/"none" -> disabled, "1"/"true" -> bare --force, any other non-empty string -> --force=<value>).

True
Source code in automaton/container.py
def __init__(
    self,
    layout: ContainerLayout,
    cache_root: Path | None = None,
    image_prefix: str = DEFAULT_IMAGE_PREFIX,
    build_force: str | bool | None = True,
):
    self.layout = layout
    self.image_prefix = image_prefix
    self.build_force = self._resolve_build_force(build_force)
    if cache_root is not None:
        self.cache_root = Path(cache_root).expanduser().resolve()
    else:
        env_base = os.environ.get("AUTOMATON_CONTAINER_BASE")
        if env_base:
            self.cache_root = Path(env_base).expanduser().resolve()
        else:
            self.cache_root = Path("/var/tmp") / f"{image_prefix}-{os.getuid()}"
    self.container_root = self.cache_root / "containers"

shared_image_storage property

shared_image_storage: Path

Shared Charliecloud builder storage for all Automaton images.

check_charliecloud_available staticmethod

check_charliecloud_available() -> tuple[bool, str]

Check if Charliecloud tools are available.

Source code in automaton/container.py
@staticmethod
def check_charliecloud_available() -> tuple[bool, str]:
    """Check if Charliecloud tools are available."""
    missing_tools = []
    for tool in ["ch-image", "ch-convert", "ch-run"]:
        result = subprocess.run(
            ["which", tool],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        if result.returncode != 0:
            missing_tools.append(tool)
    if missing_tools:
        error_msg = (
            f"Charliecloud is not available. Missing tools: {', '.join(missing_tools)}\n\n"
            f"Please install Charliecloud before building containers.\n"
            f"See: https://hpc.github.io/charliecloud/install.html\n\n"
            f"On many HPC systems, you can load it with:\n"
            f"  module load charliecloud"
        )
        return False, error_msg
    return True, ""

check_mpi_available staticmethod

check_mpi_available() -> tuple[bool, str]

Check if an MPI runtime is available (mpi4py can load libmpi).

Source code in automaton/container.py
@staticmethod
def check_mpi_available() -> tuple[bool, str]:
    """Check if an MPI runtime is available (mpi4py can load libmpi)."""
    try:
        from mpi4py import MPI  # noqa: F401
    except ImportError:
        error_msg = (
            "No MPI implementation is loaded.\n\n"
            "Please make an MPI implementation available before running with --mpi.\n\n"
            "On many HPC systems, you can load one with:\n"
            "  module load openmpi"
        )
        return False, error_msg
    return True, ""

available_container_refs

available_container_refs() -> list[ContainerRef]

Return all valid container refs known from the layout.

Source code in automaton/container.py
def available_container_refs(self) -> list[ContainerRef]:
    """Return all valid container refs known from the layout."""
    refs = [self.base_container_ref()]
    harnesses = self.layout.list_harnesses()
    groups = self.layout.list_runtime_layers()
    for harness_id in harnesses:
        refs.append(self.harness_container_ref(harness_id))
    for harness_id in harnesses:
        for group_id in groups:
            refs.append(self.runtime_container_ref(harness_id, group_id))
    return refs

resolve_container_ref

resolve_container_ref(ref: str | ContainerRef) -> ContainerRef

Normalize a user-supplied container ref.

Source code in automaton/container.py
def resolve_container_ref(self, ref: str | ContainerRef) -> ContainerRef:
    """Normalize a user-supplied container ref."""
    if isinstance(ref, ContainerRef):
        return self._validate_container_ref(ref)
    text = ref.strip()
    if not text:
        raise ValueError("container ref cannot be empty")
    parts = text.split("/")
    if parts == [BASE_CONTAINER_ID]:
        return self.base_container_ref()
    if len(parts) == 1:
        return self._validate_container_ref(self.harness_container_ref(parts[0]))
    if len(parts) == 2:
        if parts[0] == BASE_CONTAINER_ID:
            return self._validate_container_ref(self.harness_container_ref(parts[1]))
        return self._validate_container_ref(self.runtime_container_ref(parts[0], parts[1]))
    if len(parts) == 3 and parts[0] == BASE_CONTAINER_ID:
        return self._validate_container_ref(self.runtime_container_ref(parts[1], parts[2]))
    raise ValueError(
        "invalid container ref. Use one of: 'base', '<harness>', 'base/<harness>', "
        "'<harness>/<runtime-layer>', or 'base/<harness>/<runtime-layer>'"
    )

get_container_path

get_container_path(ref: str | ContainerRef) -> Path

Return the on-disk path for a built container artifact.

Source code in automaton/container.py
def get_container_path(self, ref: str | ContainerRef) -> Path:
    """Return the on-disk path for a built container artifact."""
    container_ref = self.resolve_container_ref(ref)
    if container_ref.kind == "base":
        return self.container_root / BASE_CONTAINER_ID
    if container_ref.kind == "harness":
        assert container_ref.harness_id is not None
        return self.container_root / f"harness__{container_ref.harness_id}"
    assert container_ref.harness_id is not None and container_ref.group_id is not None
    return self.container_root / f"runtime__{container_ref.harness_id}__{container_ref.group_id}"

get_container_info

get_container_info(ref: str | ContainerRef) -> ContainerInfo

Get metadata for a buildable or built container.

Source code in automaton/container.py
def get_container_info(self, ref: str | ContainerRef) -> ContainerInfo:
    """Get metadata for a buildable or built container."""
    container_ref = self.resolve_container_ref(ref)
    path = self.get_container_path(container_ref)
    exists = path.exists()
    size_bytes = None
    build_time = None
    if exists:
        size_bytes = self._safe_tree_size(path)
        build_time = datetime.fromtimestamp(path.stat().st_mtime)
    return ContainerInfo(
        container_id=container_ref.display_ref,
        canonical_ref=container_ref.canonical_ref,
        aliases=container_ref.aliases,
        kind=container_ref.kind,
        path=path,
        exists=exists,
        size_bytes=size_bytes,
        build_time=build_time,
    )

list_containers

list_containers(only_built: bool = False) -> dict[str, ContainerInfo]

List all buildable containers keyed by shorthand ref.

Source code in automaton/container.py
def list_containers(self, only_built: bool = False) -> dict[str, ContainerInfo]:
    """List all buildable containers keyed by shorthand ref."""
    container_infos: dict[str, ContainerInfo] = {}
    for ref in self.available_container_refs():
        info = self.get_container_info(ref)
        if only_built and not info.exists:
            continue
        container_infos[info.container_id] = info
    return container_infos

find_container_infos

find_container_infos(pattern: str, only_built: bool = False) -> list[ContainerInfo]

Find containers by exact ref or glob pattern.

Source code in automaton/container.py
def find_container_infos(self, pattern: str, only_built: bool = False) -> list[ContainerInfo]:
    """Find containers by exact ref or glob pattern."""
    infos = [self.get_container_info(ref) for ref in self.available_container_refs()]
    if only_built:
        infos = [info for info in infos if info.exists]
    for info in infos:
        if pattern in info.aliases:
            return [info]
    if not self._is_glob_pattern(pattern):
        return []
    matches = []
    for info in infos:
        if any(fnmatchcase(alias, pattern) for alias in info.aliases):
            matches.append(info)
    return matches

container_exists

container_exists(ref: str | ContainerRef) -> bool

Return True if the requested built container exists.

Source code in automaton/container.py
def container_exists(self, ref: str | ContainerRef) -> bool:
    """Return True if the requested built container exists."""
    return self.get_container_path(ref).exists()

build_container

build_container(ref: str | ContainerRef, force: bool = False, verbose: bool = True) -> Path

Build the requested container, auto-building parent layers as needed.

Source code in automaton/container.py
def build_container(self, ref: str | ContainerRef, force: bool = False, verbose: bool = True) -> Path:
    """Build the requested container, auto-building parent layers as needed."""
    available, error_msg = self.check_charliecloud_available()
    if not available:
        raise RuntimeError(error_msg)

    container_ref = self.resolve_container_ref(ref)
    if container_ref.kind == "base":
        return self._build_base_container(force=force, verbose=verbose)

    assert container_ref.harness_id is not None
    harness = self.layout.load_harness(container_ref.harness_id)
    errors = harness.validate()
    if errors:
        raise ValueError("Harness validation failed:\n" + "\n".join(errors))

    self._build_base_container(force=False, verbose=verbose)
    self._ensure_base_image(verbose=verbose)

    if container_ref.kind == "harness":
        return self._build_harness_container(harness, force=force, verbose=verbose)

    assert container_ref.group_id is not None
    runtime_layer = self._load_runtime_layer(container_ref.group_id)
    self._build_harness_container(harness, force=False, verbose=verbose)
    self._ensure_harness_image(harness.harness_id, verbose=verbose)
    return self._build_runtime_layer(harness, runtime_layer, force=force, verbose=verbose)

delete_container

delete_container(ref: str | ContainerRef, verbose: bool = True) -> bool

Delete a built container artifact.

Source code in automaton/container.py
def delete_container(self, ref: str | ContainerRef, verbose: bool = True) -> bool:
    """Delete a built container artifact."""
    container_ref = self.resolve_container_ref(ref)
    container_path = self.get_container_path(container_ref)
    if not container_path.exists():
        if verbose:
            print(f"Container does not exist: {container_ref.display_ref}")
        return False
    if verbose:
        info = self.get_container_info(container_ref)
        print(f"Deleting container: {info.container_id}")
        print(f"  Path: {container_path}")
        print(f"  Size: {info.size_human()}")
    shutil.rmtree(container_path)
    if verbose:
        print("Container deleted")
    return True

clear_cache

clear_cache(verbose: bool = True) -> bool

Remove all Automaton temporary containers and builder storage.

Source code in automaton/container.py
def clear_cache(self, verbose: bool = True) -> bool:
    """Remove all Automaton temporary containers and builder storage."""
    if not self.cache_root.exists():
        if verbose:
            print(f"Automaton cache does not exist: {self.cache_root}")
        return False
    if verbose:
        print(f"Removing Automaton cache: {self.cache_root}")
    shutil.rmtree(self.cache_root)
    if verbose:
        print("Cache cleared")
    return True