Skip to content

The platform for continuously improving AI agents.

7.6 KB
Raw Blame
"""Research executors as containers of a local engine, for development."""

import hashlib
import http.client
import json
import socket
from urllib.parse import quote, urlencode

from django.conf import settings

from overbae.core.errors import InputValidationError
from overbae.services.research_executor.launch import (
    RUNNER,
    ExecutorUnavailableError,
    Launch,
    Status,
    mismatch,
)

USER = "10001:10001"
RUNTIME_SOURCE = "COPY agent_runtime /opt/runtime/agent_runtime"
LICENSE_COPY = "COPY docker/research/OPENHANDS-LICENSE /opt/runtime/OPENHANDS-LICENSE"


class _EngineConnection(http.client.HTTPConnection):
    def __init__(self, path, timeout):
        super().__init__("localhost", timeout=timeout)
        self.path = path

    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.settimeout(self.timeout)
        self.sock.connect(self.path)


class DockerExecutor:
    def __init__(self, socket_path):
        self.socket_path = socket_path

    def request(self, method, path, body=None, *, missing_ok=False):
        connection = _EngineConnection(self.socket_path, 40)
        try:
            connection.request(
                method,
                path,
                body=json.dumps(body).encode() if body is not None else None,
                headers={"Content-Type": "application/json"},
            )
            response = connection.getresponse()
            data = response.read()
        except (OSError, http.client.HTTPException) as error:
            raise ExecutorUnavailableError("The container engine did not answer") from error
        finally:
            connection.close()
        if missing_ok and response.status == 404:
            return None
        if response.status in {502, 503, 504}:
            raise ExecutorUnavailableError("The container engine is temporarily unavailable")
        if response.status >= 400:
            raise RuntimeError(f"The container engine returned HTTP {response.status}")
        return json.loads(data) if data else None

    def release(self):
        """The sha256 identity of RESEARCH_DOCKER_IMAGE, a tag or an identity: a conversation
        keeps the identity it started with when the tag moves to a newer build."""
        image = self.request(
            "GET",
            f"/images/{quote(settings.RESEARCH_DOCKER_IMAGE, safe=':')}/json",
            missing_ok=True,
        )
        if image is None:
            raise InputValidationError("Build the research image first: make research-image")
        return image["Id"]

    def dependencies(self, release):
        """What a release upgrade must keep: the image's layers below the runner's own source,
        its build steps, platform and configuration. Nothing may change the environment after
        the source is copied."""
        image = self.request("GET", f"/images/{quote(release, safe=':')}/json")
        history = self.request("GET", f"/images/{quote(release, safe=':')}/history")
        layers = image["RootFS"]["Layers"]
        steps = [step for step in reversed(history) if step.get("Size", 0) > 0]
        boundaries = [
            index
            for index, step in enumerate(steps)
            if step["CreatedBy"].startswith(RUNTIME_SOURCE)
        ]
        if image["Id"] != release or len(steps) != len(layers) or len(boundaries) != 1:
            raise InputValidationError("Cannot verify the executor dependency layers")
        boundary = boundaries[0]
        if not boundary:
            raise InputValidationError("The executor has no retained dependency layers")
        if any(
            not step["CreatedBy"].startswith((LICENSE_COPY, "WORKDIR /opt/runtime"))
            for step in steps[boundary + 1 :]
        ):
            raise InputValidationError(
                "The executor modifies its environment after copying runtime source"
            )
        identity = {
            "layers": [
                "runtime-source"
                if index == boundary
                else "runtime-license"
                if step["CreatedBy"].startswith(LICENSE_COPY)
                else layers[index]
                for index, step in enumerate(steps)
            ],
            "steps": [step["CreatedBy"] for step in history],
            "architecture": image.get("Architecture"),
            "os": image.get("Os"),
            "configuration": {
                key: image["Config"].get(key) for key in ("User", "Entrypoint", "WorkingDir", "Env")
            },
        }
        return hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()

    def _inspect(self, launch):
        container = self.request("GET", f"/containers/{launch.name}/json", missing_ok=True)
        if container is None:
            return None
        mounts = {
            item["Name"]: item["Destination"]
            for item in container["Mounts"]
            if item["Type"] == "volume"
        }
        labels = container["Config"].get("Labels") or {}
        if (
            container["Image"] != launch.release
            or mounts != launch.volumes
            or any(labels.get(key) != value for key, value in launch.labels.items())
            or not container["HostConfig"]["ReadonlyRootfs"]
            or container["Config"]["User"] != USER
        ):
            raise mismatch()
        return container

    def launch(self, launch, environment):
        container = self._inspect(launch)
        if container is None:
            self.request(
                "POST",
                "/containers/create?" + urlencode({"name": launch.name}),
                {
                    "Image": launch.release,
                    "Cmd": list(RUNNER),
                    "User": USER,
                    "Env": [f"{key}={value}" for key, value in environment.items()],
                    "Labels": launch.labels,
                    "WorkingDir": "/opt/runtime",
                    "HostConfig": {
                        "NetworkMode": settings.RESEARCH_DOCKER_NETWORK,
                        "CapDrop": ["ALL"],
                        "SecurityOpt": ["no-new-privileges:true"],
                        "PidsLimit": 128,
                        "Memory": 2 * 1024**3,
                        "NanoCpus": 2 * 10**9,
                        "ReadonlyRootfs": True,
                        "Tmpfs": {
                            "/tmp": "rw,nosuid,nodev,size=256m",
                            "/home/runner": "rw,nosuid,nodev,size=64m,uid=10001,gid=10001,mode=0700",
                        },
                        "Mounts": [
                            {"Type": "volume", "Source": source, "Target": target}
                            for source, target in launch.volumes.items()
                        ],
                    },
                },
            )
        elif container["State"]["Status"] != "created":
            return
        self.request("POST", f"/containers/{launch.name}/start")

    def status(self, launch):
        container = self._inspect(launch)
        if container is None:
            return None
        state = container["State"]
        if state["Status"] == "created":
            return Status("created")
        if state["Running"] or state.get("Restarting") or state.get("Paused"):
            return Status("running")
        return Status("exited", state.get("ExitCode", 0))

    def stop(self, launch: Launch):
        current = self.status(launch)
        if current is None or not current.running:
            return
        self.request("POST", f"/containers/{launch.name}/stop?t=10")
        if (after := self.status(launch)) is not None and after.running:
            raise RuntimeError("A previous executor is still running")