from __future__ import annotations import json import re import subprocess from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path DEFAULT_IMAGE = ( "volcengine/sandbox-fusion@" "sha256:dd7ff53d16132a8acad6d5da7f15154bb4a331381567a4cb21b3e97ce581f5f9" ) CONTAINER_NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$") @dataclass(frozen=True) class DockerSandboxConfig: image: str = DEFAULT_IMAGE platform: str = "linux/amd64" memory: str = "768m" cpus: str = "1.0" pids_limit: int = 64 @dataclass(frozen=True) class DockerSandboxReceipt: container_name: str container_id: str image: str image_id: str network: str = "none" root_read_only: bool = True workspace_mount: str = "/workspace" def to_dict(self) -> dict[str, str | bool]: return { "container_name": self.container_name, "container_id": self.container_id, "image": self.image, "image_id": self.image_id, "network": self.network, "root_read_only": self.root_read_only, "workspace_mount": self.workspace_mount, } def docker_sandbox_config(settings: Mapping[str, object]) -> DockerSandboxConfig | None: if not bool(settings.get("enabled", True)): return None return DockerSandboxConfig( image=str(settings.get("image", DEFAULT_IMAGE)), platform=str(settings.get("platform", "linux/amd64")), memory=str(settings.get("memory", "768m")), cpus=str(settings.get("cpus", "1.0")), pids_limit=int(settings.get("pids_limit", 64)), ) def _run(command: list[str], *, timeout: int = 60) -> subprocess.CompletedProcess[str]: return subprocess.run( command, text=True, capture_output=True, timeout=timeout, check=False, ) def _best_effort_stop(container_name: str) -> str: try: stop_docker_sandbox(container_name) except RuntimeError as error: return str(error) return "" def verify_docker_sandbox(config: DockerSandboxConfig) -> dict[str, str]: version = _run(["docker", "version", "--format", "{{.Server.Version}}"], timeout=15) if version.returncode != 0 or not version.stdout.strip(): raise RuntimeError(f"Docker is unavailable: {version.stderr.strip()}") image = _run( ["docker", "image", "inspect", config.image, "--format", "{{json .}}"], timeout=30, ) if image.returncode != 0: raise RuntimeError( f"required sandbox image is unavailable: {config.image}: {image.stderr.strip()}" ) metadata = json.loads(image.stdout) image_id = str(metadata.get("Id", "")) expected_digest = config.image.rpartition("@")[2] if expected_digest and image_id != expected_digest: raise RuntimeError( f"sandbox image ID mismatch: expected {expected_digest}, found {image_id}" ) return { "docker_server_version": version.stdout.strip(), "image": config.image, "image_id": image_id, "platform": config.platform, } def start_docker_sandbox( workspace: Path, container_name: str, config: DockerSandboxConfig, ) -> DockerSandboxReceipt: if not CONTAINER_NAME.fullmatch(container_name): raise ValueError(f"invalid Docker container name: {container_name}") workspace = workspace.resolve(strict=True) command = [ "docker", "run", "--detach", "--rm", "--platform", config.platform, "--network", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", str(config.pids_limit), "--memory", config.memory, "--cpus", config.cpus, "--tmpfs", "/tmp:rw,exec,nosuid,size=512m", "--mount", f"type=bind,source={workspace},target=/workspace", "--workdir", "/workspace", "--env", "HOME=/tmp/home", "--env", "JULIA_DEPOT_PATH=/tmp/julia", "--name", container_name, "--entrypoint", "/bin/bash", config.image, "-lc", "mkdir -p /tmp/home /tmp/julia && exec sleep infinity", ] try: started = _run(command, timeout=60) except Exception: _best_effort_stop(container_name) raise if started.returncode != 0: cleanup_error = _best_effort_stop(container_name) cleanup_suffix = f"; cleanup failed: {cleanup_error}" if cleanup_error else "" raise RuntimeError( f"could not start Docker sandbox: {started.stderr.strip()}{cleanup_suffix}" ) container_id = started.stdout.strip() try: inspected = _run( [ "docker", "inspect", container_name, "--format", "{{.State.Running}} {{.Image}}", ], timeout=15, ) fields = inspected.stdout.strip().split() if inspected.returncode != 0 or len(fields) != 2 or fields[0] != "true": raise RuntimeError( f"Docker sandbox did not remain running: {inspected.stderr.strip()}" ) return DockerSandboxReceipt( container_name=container_name, container_id=container_id, image=config.image, image_id=fields[1], ) except BaseException: stop_docker_sandbox(container_name) raise def stop_docker_sandbox(container_name: str) -> None: stopped = _run(["docker", "rm", "--force", container_name], timeout=30) if stopped.returncode != 0 and "No such container" not in stopped.stderr: raise RuntimeError(f"could not remove Docker sandbox: {stopped.stderr.strip()}")