Skip to content

unaiverse.utils.sandbox

A node can run code that it did not write. The code of the roles of a world arrives with the world and runs inside the node of every agent that joins. This module runs a Python script inside an isolated container so that such code sees only the folders that the user mounts. It builds a container image with the dependencies of the SDK, mounts the folder of the SDK read-only, runs the script and removes the image at the end. The functions drive the command-line client of a container engine. That client must be installed and on PATH.

The sandbox does not start in the current version

sandbox() always mounts two writable folders that do not exist in the package: runners next to the unaiverse package folder and unaiverse/library inside it. run_in_docker() refuses a mount that is not an existing directory. The run therefore stops with Error: Writable host path '.../runners' does not exist or is not a directory. Cannot mount. and the process exits with status 1 after the image was built. Creating the two empty folders by hand works around it.

From a terminal:

python -m unaiverse.utils.sandbox run_agent.py -p 13000 -r /data/images -w /data/out
Option Meaning
script The Python file to run. It must end with .py.
-p, --port Required. The first of the four consecutive ports of the node. It must be a positive integer and becomes the environment variable NODE_STARTING_PORT.
-r, --read-only Folders mounted read-only, separated by : (for example /a:/b).
-w, --writable Folders mounted writable, separated by :.

DOCKER_IMAGE_NAME module-attribute

DOCKER_IMAGE_NAME = 'unaiverse-sandbox'

"unaiverse-sandbox", the tag of the image that the module builds and removes.

CONTAINER_NAME_BASE module-attribute

CONTAINER_NAME_BASE = 'unaiverse-sandbox-container'

"unaiverse-sandbox-container", the prefix of the container names. The cleanup removes every container whose name contains it.

CONTAINER_NAME module-attribute

CONTAINER_NAME = f'{CONTAINER_NAME_BASE}-{uuid.uuid4().hex[:8]}'

CONTAINER_NAME_BASE followed by - and eight random hexadecimal digits. It is generated once per process when the module is imported.

DOCKERFILE_CONTENT module-attribute

DOCKERFILE_CONTENT = '\n\n# Debian image, automatically guessed architecture\nFROM python:3.12-slim-bookworm\n\n# Installing Go compiler\nRUN apt-get update && apt-get install -y --no-install-recommends build-essential curl git\nRUN rm -rf /var/lib/apt/lists/*\nRUN ARCH=$(dpkg --print-architecture) && curl -LO https://go.dev/dl/go1.24.5.linux-${ARCH}.tar.gz\nRUN ARCH=$(dpkg --print-architecture) && tar -C /usr/local -xzf go1.24.5.linux-${ARCH}.tar.gz\nRUN ARCH=$(dpkg --print-architecture) && rm go1.24.5.linux-${ARCH}.tar.gz\n\n# Set Go environment variables\nENV PATH="/usr/local/go/bin:${PATH}"\nENV GOPATH="/go"\nRUN mkdir -p /go/bin /go/src /go/pkg\n\n# Setting the working directory inside the container\nWORKDIR /unaiverse\n\n# Dependencies\nRUN <create_requirements.txt>\nRUN pip install --no-cache-dir -r requirements.txt --break-system-packages\n'

The template of the build file of the image. The image starts from Python 3.12 on Debian (slim), installs build-essential, curl and git and the compiler of the native networking library and works in /unaiverse. The placeholder line RUN <create_requirements.txt> becomes a command that writes the dependencies of the installed package to requirements.txt before pip install.

sandbox

sandbox(file_to_run: str, read_only_paths: tuple[str] | list[str] | None = None, writable_paths: tuple[str] | list[str] | None = None) -> None
Source code in unaiverse/utils/sandbox.py
def sandbox(file_to_run: str,
            read_only_paths: tuple[str] | list[str] | None = None,
            writable_paths: tuple[str] | list[str] | None = None) -> None:

    # Path of this file
    absolute_path_of_this_file = str(os.path.abspath(__file__))

    # Folders composing the path (and file name at the end)
    path_components = list(Path(absolute_path_of_this_file).parts)

    # Ensuring the folder/file structure was not manipulated
    assert path_components[-1] == 'sandbox.py', "Major security issue, stopping."
    assert path_components[-2] == 'utils', "Major security issue, stopping."
    assert path_components[-3] == 'unaiverse', "Major security issue, stopping."

    # Main folder of UNaIVERSE
    abspath_of_unaiverse_code = str(Path(*path_components[0:-3]))

    # Clean up any remnants from previous runs first (safety)
    cleanup_docker_artifacts(where=abspath_of_unaiverse_code)

    # Requirements: the dependencies declared by the installed package (pyproject.toml), without the optional
    # extras (e.g., the dev tooling)
    lines = [r for r in (metadata.requires("unaiverse") or []) if "extra ==" not in r]
    echoed_contents_of_requirements = 'printf "' + "\\n".join(lines) + '\\n" > requirements.txt'

    # Create Dockerfile
    print("Creating Dockerfile...")
    with open(os.path.join(abspath_of_unaiverse_code, "Dockerfile"), "w") as f:
        f.write(DOCKERFILE_CONTENT.replace('<create_requirements.txt>', echoed_contents_of_requirements))

    # Building Docker image
    if not build_docker_image(where=abspath_of_unaiverse_code):
        print("Exiting due to Docker image build failure")
        cleanup_docker_artifacts(where=abspath_of_unaiverse_code)  # Try to clean up what was created (if any)
        sys.exit(1)

    # Read only folders from the host machine
    read_only_mount_paths = ([abspath_of_unaiverse_code] +
                             (list(read_only_paths) if read_only_paths is not None else []))

    # Writable folders in host machine
    writable_mount_paths = ([os.path.join(abspath_of_unaiverse_code, 'runners'),
                             os.path.join(abspath_of_unaiverse_code, 'unaiverse', 'library'),
                             os.path.join(abspath_of_unaiverse_code, 'unaiverse', 'networking', 'p2p')] +
                            (list(writable_paths) if writable_paths is not None else []))

    # Running
    if not run_in_docker(file_to_run=os.path.abspath(file_to_run),
                         read_only_host_paths=read_only_mount_paths,
                         writable_host_paths=writable_mount_paths):
        print("Exiting due to Docker container run failure")
        sys.exit(1)

    # Final cleanup
    cleanup_docker_artifacts(where=abspath_of_unaiverse_code)

Builds the image, runs file_to_run in a container and cleans up.

Argument Type Default Meaning
file_to_run str required The script. The container runs python3 <absolute path>.
read_only_paths sequence of str or None None Extra folders mounted read-only.
writable_paths sequence of str or None None Extra folders mounted writable.

The steps are these:

  1. The function checks that its own file is unaiverse/utils/sandbox.py and raises AssertionError("Major security issue, stopping.") otherwise. The folder that contains the unaiverse package (the src folder of a checkout, site-packages for an installed package) is the root of the sandbox.
  2. It runs cleanup_docker_artifacts on the root.
  3. It reads the dependencies of the installed distribution unaiverse without the optional extras. The package must be installed because a bare checkout raises importlib.metadata.PackageNotFoundError.
  4. It writes the build file Dockerfile into the root and builds the image with the whole root as build context. A failed build cleans up and exits the process with status 1.
  5. It mounts the root read-only and the extra read-only folders. It mounts writable the folders <root>/runners, <root>/unaiverse/library and <root>/unaiverse/networking/p2p and the extra writable folders. Each folder appears at the same path inside the container.
  6. It runs the container with run_in_docker. A failure exits the process with status 1 without the final cleanup and leaves the image and the build file in place.
  7. It runs the cleanup again.

The function prints its progress with print. It returns None.

run_in_docker

run_in_docker(file_to_run: str, read_only_host_paths: list[str] | None = None, writable_host_paths: list[str] | None = None)
Source code in unaiverse/utils/sandbox.py
def run_in_docker(file_to_run: str, read_only_host_paths: list[str] | None = None,
                  writable_host_paths: list[str] | None = None):
    """Runs the code in a Docker container with optional mounts."""
    print(f"\nRunning code in Docker container '{CONTAINER_NAME}'...")

    # Building command (it will continue below...)
    command = ["docker", "run",
               "--rm",  # Automatically remove the container when it exits
               "-e", "PYTHONUNBUFFERED=1",  # Ensure Python output is unbuffered
               "-e", "NODE_STARTING_PORT",
               "--name", CONTAINER_NAME]

    if sys.platform.startswith('linux'):

        # Linux
        command.extend(["--net", "host"]),  # Expose the host network (in macOS and Windows it is still a virtual host)
    else:

        # Not-linux: check ports (adding -p port:port)
        port_int = int(os.getenv("NODE_STARTING_PORT", "0"))
        if port_int > 0:
            command.extend(["-p", str(port_int + 0) + ":" + str(port_int + 0)])
            command.extend(["-p", str(port_int + 1) + ":" + str(port_int + 1) + "/udp"])
            command.extend(["-p", str(port_int + 2) + ":" + str(port_int + 2)])
            command.extend(["-p", str(port_int + 3) + ":" + str(port_int + 3) + "/udp"])

    # Add read-only mount if path is provided
    if read_only_host_paths is not None and len(read_only_host_paths) > 0:
        for path in read_only_host_paths:

            # Ensure the host path exists and is a directory
            if not os.path.isdir(path):
                print(
                    f"Error: Read-only host path '{path}' does not exist or is not a directory. Cannot mount.")
                return False
            else:

                # Augmenting command
                path = os.path.abspath(path)
                command.extend(["-v", f"{path}:{path}:ro"])
                print(f"Mounted host '{path}' as read-only to container")

    # Add writable mount if path is provided
    if writable_host_paths is not None and len(writable_host_paths) > 0:
        for path in writable_host_paths:

            # Ensure the host path exists and is a directory
            if not os.path.isdir(path):
                print(
                    f"Error: Writable host path '{path}' does not exist or is not a directory. Cannot mount.")
                return False
            else:

                # Augmenting command
                path = os.path.abspath(path)
                command.extend(["-v", f"{path}:{path}"])
                print(f"Mounted host '{path}' as writable to container")

    # Completing command
    command.append(DOCKER_IMAGE_NAME)

    process = None
    try:
        try:
            command.extend(["python3", file_to_run])
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
            assert process.stdout is not None
            for line in iter(process.stdout.readline, ''):
                sys.stdout.write(line)
            process.wait()
            if process.returncode != 0:
                print(f"Container exited with non-zero status code: {process.returncode}")
        except KeyboardInterrupt:
            pass

        print(f"\nContainer '{CONTAINER_NAME}' finished execution.")
        return process is not None and process.returncode == 0   # was: return True
    except FileNotFoundError:
        print("Error: Docker command not found. Is Docker installed and in your PATH?")
        print("Please ensure Docker is installed and running.")
        return False
    except subprocess.CalledProcessError as e:
        print(f"Error running Docker container: {e}")
        return False

Runs python3 file_to_run in a new container of the image and returns True when the script exits with status 0.

Argument Type Default Meaning
file_to_run str required The absolute path of the script.
read_only_host_paths list[str] or None None Folders mounted read-only at the same path.
writable_host_paths list[str] or None None Folders mounted writable at the same path.

The container is removed when it exits. It receives PYTHONUNBUFFERED=1 and the value of NODE_STARTING_PORT of the host. On Linux it shares the network of the host. On the other systems it publishes the four ports of the node when NODE_STARTING_PORT is positive: p and p+2 over TCP, p+1 and p+3 over UDP. A mount path that is not an existing directory makes the function print an error and return False before starting anything. The output of the container is copied line by line to the standard output. Ctrl-C stops the copy. A missing command-line client returns False.

build_docker_image

build_docker_image(where: str)
Source code in unaiverse/utils/sandbox.py
def build_docker_image(where: str):
    """Builds the Docker image."""
    print(f"Building Docker image '{DOCKER_IMAGE_NAME}'...")

    try:

        # The '.' at the end means build from the current directory
        subprocess.run(["docker", "build", "-t", DOCKER_IMAGE_NAME, where], check=True)
        print(f"Docker image '{DOCKER_IMAGE_NAME}' built successfully.")
        return True
    except subprocess.CalledProcessError as e:
        print(f"Error building Docker image: {e}")
        return False

Builds the image DOCKER_IMAGE_NAME from the build file and the context in the folder where. It returns True on success and False when the build fails.

cleanup_docker_artifacts

cleanup_docker_artifacts(where: str)
Source code in unaiverse/utils/sandbox.py
def cleanup_docker_artifacts(where: str):
    """Cleans up the generated files and Docker image."""
    print("Cleaning...")

    # Stop and remove ANY sandbox container (this run or an orphan from a crashed previous run)
    try:
        result = subprocess.run(["docker", "ps", "-aq", "--filter", f"name={CONTAINER_NAME_BASE}"],
                                check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        ids = [c for c in result.stdout.split() if c]
        if ids:
            subprocess.run(["docker", "stop", *ids], check=False,
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            subprocess.run(["docker", "rm", *ids], check=False,
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    except Exception as e:
        print(f"Error during preliminary container cleanup: {e}")

    # Remove the Docker image
    try:
        print(f"Removing Docker image '{DOCKER_IMAGE_NAME}'...")
        subprocess.run(["docker", "rmi", DOCKER_IMAGE_NAME], check=True)
        print("Docker image removed.")
    except subprocess.CalledProcessError as e:
        print(f"Error removing Docker image '{DOCKER_IMAGE_NAME}': {e}")

    # Remove the generated Dockerfile
    if os.path.exists(os.path.join(where, "Dockerfile")):
        os.remove(os.path.join(where, "Dockerfile"))
        print("Removed Dockerfile.")

Stops and removes every container whose name contains CONTAINER_NAME_BASE, removes the image DOCKER_IMAGE_NAME and deletes the file Dockerfile in where. The first step also removes the containers of other sandboxes running on the same machine. A missing image prints an error and the function continues.