|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +"""Extract local Docker images into rootfs directories for sandboxing. |
| 3 | +
|
| 4 | +Uses ``docker create`` + ``docker export`` to extract a locally available |
| 5 | +image into a cached rootfs directory. No registry pulling — the image |
| 6 | +must already be present in the local Docker storage. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import hashlib |
| 12 | +import json |
| 13 | +import os |
| 14 | +import subprocess |
| 15 | +import tarfile |
| 16 | +import tempfile |
| 17 | +from pathlib import Path |
| 18 | + |
| 19 | +from .exceptions import SandboxError |
| 20 | + |
| 21 | + |
| 22 | +_CACHE_DIR = Path("~/.cache/sandlock/images").expanduser() |
| 23 | + |
| 24 | + |
| 25 | +def extract(image: str, cache_dir: Path | None = None) -> str: |
| 26 | + """Extract a local Docker image into a rootfs directory. |
| 27 | +
|
| 28 | + Creates a temporary container from the image, exports its filesystem, |
| 29 | + and extracts it into a cached directory. Subsequent calls with the |
| 30 | + same image name return the cached path immediately. |
| 31 | +
|
| 32 | + Args: |
| 33 | + image: Docker image name (e.g. "python:3.12-slim", "alpine"). |
| 34 | + Must already be pulled locally. |
| 35 | + cache_dir: Override cache directory (default ~/.cache/sandlock/images). |
| 36 | +
|
| 37 | + Returns: |
| 38 | + Absolute path to the extracted rootfs directory. |
| 39 | +
|
| 40 | + Raises: |
| 41 | + SandboxError: If docker is not available or the image is not found. |
| 42 | + """ |
| 43 | + cache = cache_dir or _CACHE_DIR |
| 44 | + cache_key = hashlib.sha256(image.encode()).hexdigest()[:16] |
| 45 | + rootfs = cache / cache_key / "rootfs" |
| 46 | + |
| 47 | + # Return cached rootfs if available |
| 48 | + if rootfs.is_dir() and any(rootfs.iterdir()): |
| 49 | + return str(rootfs) |
| 50 | + |
| 51 | + # Create a temporary container (does not start it) |
| 52 | + try: |
| 53 | + container_id = subprocess.check_output( |
| 54 | + ["docker", "create", image, "/bin/true"], |
| 55 | + stderr=subprocess.PIPE, |
| 56 | + ).decode().strip() |
| 57 | + except FileNotFoundError: |
| 58 | + raise SandboxError("docker CLI not found") |
| 59 | + except subprocess.CalledProcessError as e: |
| 60 | + raise SandboxError(f"docker create failed: {e.stderr.decode().strip()}") |
| 61 | + |
| 62 | + try: |
| 63 | + rootfs.mkdir(parents=True, exist_ok=True) |
| 64 | + |
| 65 | + # Export and extract |
| 66 | + with tempfile.NamedTemporaryFile(suffix=".tar", delete=True) as tmp: |
| 67 | + subprocess.check_call( |
| 68 | + ["docker", "export", "-o", tmp.name, container_id], |
| 69 | + stderr=subprocess.PIPE, |
| 70 | + ) |
| 71 | + with tarfile.open(tmp.name, "r:*") as tar: |
| 72 | + members = [ |
| 73 | + m for m in tar.getmembers() |
| 74 | + if not m.name.startswith("/") |
| 75 | + and ".." not in m.name |
| 76 | + and m.type not in (tarfile.CHRTYPE, tarfile.BLKTYPE) |
| 77 | + ] |
| 78 | + tar.extractall(rootfs, members=members) |
| 79 | + except Exception: |
| 80 | + # Clean up partial extraction |
| 81 | + import shutil |
| 82 | + shutil.rmtree(rootfs, ignore_errors=True) |
| 83 | + raise |
| 84 | + finally: |
| 85 | + subprocess.call( |
| 86 | + ["docker", "rm", container_id], |
| 87 | + stdout=subprocess.DEVNULL, |
| 88 | + stderr=subprocess.DEVNULL, |
| 89 | + ) |
| 90 | + |
| 91 | + return str(rootfs) |
| 92 | + |
| 93 | + |
| 94 | +def get_default_cmd(image: str) -> list[str]: |
| 95 | + """Get the default command (ENTRYPOINT + CMD) for a local Docker image. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + Command list, or ["/bin/sh"] if none is configured. |
| 99 | +
|
| 100 | + Raises: |
| 101 | + SandboxError: If docker inspect fails. |
| 102 | + """ |
| 103 | + try: |
| 104 | + raw = subprocess.check_output( |
| 105 | + ["docker", "inspect", "--format", |
| 106 | + "{{json .Config.Entrypoint}}|{{json .Config.Cmd}}", image], |
| 107 | + stderr=subprocess.PIPE, |
| 108 | + ).decode().strip() |
| 109 | + except (FileNotFoundError, subprocess.CalledProcessError): |
| 110 | + return ["/bin/sh"] |
| 111 | + |
| 112 | + parts = raw.split("|", 1) |
| 113 | + entrypoint = json.loads(parts[0]) if parts[0] != "null" else None |
| 114 | + cmd = json.loads(parts[1]) if len(parts) > 1 and parts[1] != "null" else None |
| 115 | + |
| 116 | + if entrypoint and cmd: |
| 117 | + return entrypoint + cmd |
| 118 | + if entrypoint: |
| 119 | + return entrypoint |
| 120 | + if cmd: |
| 121 | + return cmd |
| 122 | + return ["/bin/sh"] |
0 commit comments