134 lines
4.4 KiB
Python
134 lines
4.4 KiB
Python
"""Docker sandbox backend providing container isolation."""
|
|
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import time
|
|
from typing import Optional
|
|
|
|
from extensions.sandbox.base import BaseSandboxBackend, ExecutionResult
|
|
from homeagent.config import get_settings
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class DockerBackend(BaseSandboxBackend):
|
|
"""Executes processes inside isolated Docker containers."""
|
|
|
|
def __init__(self) -> None:
|
|
self.settings = get_settings()
|
|
self.docker_bin = shutil.which("docker")
|
|
self._available: Optional[bool] = None
|
|
|
|
def is_available(self) -> bool:
|
|
if self._available is not None:
|
|
return self._available
|
|
|
|
if not self.docker_bin:
|
|
self._available = False
|
|
return False
|
|
|
|
try:
|
|
# Check if Docker daemon is running and accessible
|
|
res = subprocess.run(
|
|
[self.docker_bin, "info"],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
timeout=3.0,
|
|
)
|
|
self._available = (res.returncode == 0)
|
|
except Exception:
|
|
self._available = False
|
|
|
|
return self._available
|
|
|
|
async def execute(
|
|
self,
|
|
cmd: list[str],
|
|
workspace_dir: Path,
|
|
timeout: int,
|
|
allow_network: bool = False,
|
|
env: Optional[dict[str, str]] = None,
|
|
) -> ExecutionResult:
|
|
if not self.is_available():
|
|
raise RuntimeError("Docker is not available or daemon is not running.")
|
|
|
|
workspace_dir.mkdir(parents=True, exist_ok=True)
|
|
mem_mb = self.settings.SANDBOX_MEMORY_LIMIT_MB
|
|
cpus = self.settings.SANDBOX_CPU_LIMIT
|
|
image = self.settings.SANDBOX_DOCKER_IMAGE
|
|
|
|
docker_args: list[str] = [
|
|
self.docker_bin,
|
|
"run",
|
|
"--rm",
|
|
"-i",
|
|
"--read-only",
|
|
"--tmpfs", "/tmp:rw,noexec,nosuid,size=64m",
|
|
"--memory", f"{mem_mb}m",
|
|
"--cpus", str(cpus),
|
|
"-v", f"{workspace_dir}:/workspace:rw",
|
|
"-w", "/workspace",
|
|
]
|
|
|
|
if not allow_network:
|
|
docker_args.extend(["--network", "none"])
|
|
|
|
if env:
|
|
for k, v in env.items():
|
|
docker_args.extend(["-e", f"{k}={v}"])
|
|
|
|
docker_args.append(image)
|
|
docker_args.extend(cmd)
|
|
|
|
start_time = time.monotonic()
|
|
try:
|
|
proc = await asyncio.create_subprocess_exec(
|
|
*docker_args,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
stderr=asyncio.subprocess.PIPE,
|
|
preexec_fn=os.setsid,
|
|
)
|
|
|
|
try:
|
|
stdout_data, stderr_data = await asyncio.wait_for(
|
|
proc.communicate(),
|
|
timeout=float(timeout),
|
|
)
|
|
duration = time.monotonic() - start_time
|
|
return ExecutionResult(
|
|
stdout=stdout_data.decode("utf-8", errors="replace"),
|
|
stderr=stderr_data.decode("utf-8", errors="replace"),
|
|
exit_code=proc.returncode if proc.returncode is not None else -1,
|
|
duration_seconds=round(duration, 3),
|
|
timed_out=False,
|
|
)
|
|
except asyncio.TimeoutError:
|
|
duration = time.monotonic() - start_time
|
|
logger.warning("Docker sandbox timed out after %ds, killing container", timeout)
|
|
try:
|
|
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
|
|
except ProcessLookupError:
|
|
pass
|
|
return ExecutionResult(
|
|
stdout="",
|
|
stderr=f"Ошибка: превышен максимальный таймаут выполнения ({timeout} сек).",
|
|
exit_code=-1,
|
|
duration_seconds=round(duration, 3),
|
|
timed_out=True,
|
|
)
|
|
except Exception as e:
|
|
duration = time.monotonic() - start_time
|
|
logger.error("Failed to execute in Docker sandbox: %s", e)
|
|
return ExecutionResult(
|
|
stdout="",
|
|
stderr=f"Docker sandbox error: {type(e).__name__}: {str(e)}",
|
|
exit_code=-1,
|
|
duration_seconds=round(duration, 3),
|
|
timed_out=False,
|
|
)
|