Docker 镜像内置 microVM:构建时装好运行时、预拉沙箱镜像;deploy.sh 检测到 KVM 先试启动一台,起得来才交给容器;没有 KVM 时服务端不再选 microVM

- microvm_sandbox:Linux 上 available() 要求 /dev/kvm 存在且可读写,不可用时给出具体原因(没装、运行时没装、没有 KVM、没有权限)
- 新增 app.sandbox.selftest:真起一台 VM 执行一行代码,部署脚本用它判断
- Dockerfile:WITH_MICROVM(默认 1)构建期 install 并 pull python:3.12-slim,自带的 msb、libkrunfw 改为链接,镜像约多 150 MB
- deploy.sh:ENABLE_MICROVM=auto|0|1,有 KVM 时用临时容器试启动,成功才加 --device /dev/kvm 和所属组;部署完和 status 打印实际用的沙箱
- package-docker.sh:--no-microvm;部署说明、配置模板、README 同步
This commit is contained in:
ThearchyHelios
2026-09-30 11:17:19 +08:00
parent fec356089c
commit 78f24dfe3f
9 changed files with 440 additions and 51 deletions
+49 -15
View File
@@ -2,6 +2,8 @@ from __future__ import annotations
import asyncio
import logging
import os
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
@@ -34,6 +36,29 @@ _LANG = {
_MAX_FILE_BYTES = 8 * 1024 * 1024
_MANIFEST_CACHE = Path.home() / ".microsandbox" / "cache" / "manifests"
_KVM_DEVICE = Path("/dev/kvm")
def _on_linux() -> bool:
return sys.platform.startswith("linux")
def kvm_problem() -> str:
"""Linux 上 microVM 靠 KVM 启动:拿不到 /dev/kvm 时返回原因,能用(或不在 Linux 上)返回空串。
macOS 走 Hypervisor.framework,不查。以前 available() 只看运行时装没装,
运行时和镜像打进 Docker 镜像以后,没有 KVM 的机器上 auto 会选中 microVM,
之后每次执行代码都启动失败。
"""
if not _on_linux():
return ""
if not _KVM_DEVICE.exists():
return ("这台机器没有 KVM(找不到 /dev/kvm)。"
"在容器里运行时,宿主机要支持 KVM,并把 /dev/kvm 挂进容器")
if not os.access(_KVM_DEVICE, os.R_OK | os.W_OK):
return ("当前用户没有读写 /dev/kvm 的权限。把运行服务的用户加入 kvm 组;"
"在容器里运行时,要把宿主机上 /dev/kvm 所属的组加给容器")
return ""
@dataclass
@@ -86,8 +111,7 @@ class MicroVMSandbox(Sandbox):
# ---------------- 可用性 ----------------
@staticmethod
def available() -> bool:
"""SDK 装了、运行时也装好了才算可用。"""
def _runtime_installed() -> bool:
try:
import microsandbox as ms
except ImportError:
@@ -97,6 +121,22 @@ class MicroVMSandbox(Sandbox):
except Exception: # noqa: BLE001
return False
@classmethod
def available(cls) -> bool:
"""SDK 和运行时都装好、Linux 上还拿得到 KVM,才算可用。"""
return cls._runtime_installed() and not kvm_problem()
@classmethod
def unavailable_reason(cls) -> str:
"""不可用的原因;可用时返回空串。"""
try:
import microsandbox # noqa: F401
except ImportError:
return "未安装 microsandbox(pip install 'agentlab-backend[microvm]')"
if not cls._runtime_installed():
return "运行时未就绪(await microsandbox.install(),约 50 MB)"
return kvm_problem()
@staticmethod
def image_ready() -> bool:
"""镜像是否已经拉到本地。
@@ -112,7 +152,7 @@ class MicroVMSandbox(Sandbox):
async def health(self) -> dict[str, Any]:
try:
import microsandbox as ms
import microsandbox # noqa: F401
except ImportError:
return {
"backend": self.name,
@@ -120,17 +160,13 @@ class MicroVMSandbox(Sandbox):
"isolated": True,
"error": "未安装 microsandbox(pip install 'agentlab-backend[microvm]')",
}
installed = False
try:
installed = bool(ms.is_installed())
except Exception: # noqa: BLE001
pass
reason = self.unavailable_reason()
cached = self.image_ready()
return {
"backend": self.name,
"available": installed,
"available": not reason,
"isolated": True,
"isolation": "microVM:独立内核 + 独立内存 + 独立进程表(libkrun / Hypervisor.framework)",
"isolation": "microVM:独立内核 + 独立内存 + 独立进程表(libkrun;Linux 上用 KVM,macOS 上用 Hypervisor.framework)",
# 只有 network 不是真的——别的都由虚拟化边界强制执行
"enforced": {
"timeout": True,
@@ -148,7 +184,7 @@ class MicroVMSandbox(Sandbox):
"image": self._image,
"image_cached": cached,
"live_vms": len(self._leases),
**({} if installed else {"error": "运行时未就绪(await microsandbox.install(),约 50 MB)"}),
**({"error": reason} if reason else {}),
**({} if cached else {"first_run_cost": "镜像未缓存,首次启动需要拉取镜像(约 55 秒)"}),
}
@@ -261,10 +297,8 @@ class MicroVMSandbox(Sandbox):
if language not in _LANG:
return ExecResult(ok=False, backend=self.name, error=f"不支持的语言:{language}")
if not self.available():
return ExecResult(
ok=False, backend=self.name,
error="microVM 运行时未就绪:pip install 'agentlab-backend[microvm]' 后执行一次 install",
)
reason = self.unavailable_reason() or "运行时未就绪"
return ExecResult(ok=False, backend=self.name, error=f"microVM 不可用:{reason}")
ext, cmd = _LANG[language]
entry = entry_name(ext)
+46
View File
@@ -0,0 +1,46 @@
"""microVM 自检:真起一台 VM,跑一行代码。
deploy.sh 用它决定要不要把 /dev/kvm 交给容器。设备在、权限也对,不等于 VM 起得来:
Docker 的系统调用过滤、宿主机没开嵌套虚拟化,都可能让启动失败。起不来还把设备交给容器,
auto 就会选中 microVM,之后每次执行代码都失败。
python -m app.sandbox.selftest
成功退出码 0,失败 1。输出一行结论,给人看。
"""
from __future__ import annotations
import asyncio
import sys
from app.sandbox.base import SandboxLimits
from app.sandbox.microvm_sandbox import MicroVMSandbox
MARK = "agentlab-microvm-ok"
async def check() -> tuple[bool, str]:
sandbox = MicroVMSandbox()
if not sandbox.available():
return False, f"microVM 不可用:{sandbox.unavailable_reason() or '运行时未就绪'}"
try:
result = await sandbox.run(
f"print({MARK!r})",
limits=SandboxLimits(timeout=60, memory_mb=256, cpus=1, network=False),
)
finally:
await sandbox.close()
if result.ok and MARK in result.stdout:
return True, f"microVM 可用:启动并执行一行代码共用时 {result.duration_ms} ms"
detail = result.error or result.stderr.strip() or f"退出码 {result.exit_code},没有输出"
return False, detail if detail.startswith("microVM") else f"microVM 启动失败:{detail}"
def main() -> int:
ok, message = asyncio.run(check())
print(message)
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())
+151
View File
@@ -0,0 +1,151 @@
"""Linux 上 microVM 没有 KVM 就起不来,可用性判断要把这一条算进去。
以前 available() 只看运行时装没装。运行时和沙箱镜像打进 Docker 镜像以后,没有 KVM 的机器上
(Mac 上的 Docker Desktop、没开嵌套虚拟化的云主机)auto 会选中 microVM,每次执行代码都启动失败。
selftest 是部署脚本用的:真起一台 VM,起得来才把 /dev/kvm 交给容器。
"""
from __future__ import annotations
import asyncio
from pathlib import Path
import pytest
from app.sandbox import manager as mgr
from app.sandbox import microvm_sandbox as mv
from app.sandbox import selftest
from app.sandbox.base import ExecResult
from app.sandbox.local_sandbox import LocalSandbox
@pytest.fixture
def linux(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
"""在 Linux 上、运行时已装好、镜像已缓存;返回假的 /dev/kvm 路径,默认不存在。"""
kvm = tmp_path / "kvm"
monkeypatch.setattr(mv, "_on_linux", lambda: True)
monkeypatch.setattr(mv, "_KVM_DEVICE", kvm)
monkeypatch.setattr(mv.MicroVMSandbox, "_runtime_installed", staticmethod(lambda: True))
monkeypatch.setattr(mv.MicroVMSandbox, "image_ready", staticmethod(lambda: True))
return kvm
def test_no_kvm_device_means_unavailable(linux: Path) -> None:
assert mv.MicroVMSandbox.available() is False
reason = mv.MicroVMSandbox.unavailable_reason()
assert "/dev/kvm" in reason and "挂进容器" in reason
def test_kvm_without_permission_means_unavailable(linux: Path, monkeypatch: pytest.MonkeyPatch) -> None:
linux.touch()
monkeypatch.setattr(mv.os, "access", lambda path, mode: False)
assert mv.MicroVMSandbox.available() is False
assert "kvm 组" in mv.MicroVMSandbox.unavailable_reason()
def test_kvm_present_and_writable(linux: Path, monkeypatch: pytest.MonkeyPatch) -> None:
linux.touch()
monkeypatch.setattr(mv.os, "access", lambda path, mode: True)
assert mv.MicroVMSandbox.available() is True
assert mv.MicroVMSandbox.unavailable_reason() == ""
def test_macos_does_not_need_kvm(linux: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(mv, "_on_linux", lambda: False)
assert not linux.exists()
assert mv.kvm_problem() == ""
assert mv.MicroVMSandbox.available() is True
def test_runtime_missing_is_reported_before_kvm(linux: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(mv.MicroVMSandbox, "_runtime_installed", staticmethod(lambda: False))
assert "运行时未就绪" in mv.MicroVMSandbox.unavailable_reason()
def test_auto_skips_microvm_without_kvm(linux: Path, monkeypatch: pytest.MonkeyPatch) -> None:
# 运行时装了、镜像也缓存了,只差 KVM:auto 不能选它
monkeypatch.setattr(mgr.BubblewrapSandbox, "available", staticmethod(lambda: False))
monkeypatch.setattr(mgr.BubblewrapSandbox, "probe_failure", staticmethod(lambda: ""))
monkeypatch.setattr(mgr.SeatbeltSandbox, "available", staticmethod(lambda: False))
monkeypatch.setattr(mgr.settings, "sandbox_backend", "auto")
manager = mgr.SandboxManager()
assert isinstance(manager._resolve(), LocalSandbox)
# 节点上选 strict 档也点不到它
assert manager._resolve_named("strict") is None
def test_auto_picks_microvm_with_kvm(linux: Path, monkeypatch: pytest.MonkeyPatch) -> None:
linux.touch()
monkeypatch.setattr(mv.os, "access", lambda path, mode: True)
monkeypatch.setattr(mgr.settings, "sandbox_backend", "auto")
manager = mgr.SandboxManager()
assert isinstance(manager._resolve(), mv.MicroVMSandbox)
def test_run_says_why_without_booting(linux: Path, monkeypatch: pytest.MonkeyPatch) -> None:
async def must_not_boot(*args, **kwargs): # noqa: ANN002, ANN003, ANN202
raise AssertionError("没有 KVM 还去启动 VM")
monkeypatch.setattr(mv.MicroVMSandbox, "_lease", must_not_boot)
result = asyncio.run(mv.MicroVMSandbox().run("print(1)"))
assert result.ok is False
assert result.error and result.error.startswith("microVM 不可用:") and "/dev/kvm" in result.error
def test_health_reports_missing_kvm(linux: Path) -> None:
info = asyncio.run(mv.MicroVMSandbox().health())
assert info["available"] is False
assert "/dev/kvm" in info["error"]
assert "KVM" in info["isolation"]
# ---------------- selftest ----------------
def _fake_run(result: ExecResult, calls: list[str]):
async def run(self, code, **kwargs): # noqa: ANN001, ANN003, ANN202
calls.append(code)
return result
return run
def test_selftest_without_kvm_does_not_boot(linux: Path, monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str]) -> None:
calls: list[str] = []
monkeypatch.setattr(mv.MicroVMSandbox, "run", _fake_run(ExecResult(), calls))
assert selftest.main() == 1
assert calls == []
out = capsys.readouterr().out.strip()
assert out.startswith("microVM 不可用:") and "/dev/kvm" in out
def test_selftest_passes_when_the_vm_prints_the_mark(linux: Path, monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str]) -> None:
linux.touch()
monkeypatch.setattr(mv.os, "access", lambda path, mode: True)
calls: list[str] = []
ok = ExecResult(stdout=selftest.MARK + "\n", duration_ms=812, backend="microvm")
monkeypatch.setattr(mv.MicroVMSandbox, "run", _fake_run(ok, calls))
assert selftest.main() == 0
assert len(calls) == 1 and selftest.MARK in calls[0]
assert "812 ms" in capsys.readouterr().out
def test_selftest_reports_boot_failure(linux: Path, monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str]) -> None:
linux.touch()
monkeypatch.setattr(mv.os, "access", lambda path, mode: True)
failed = ExecResult(ok=False, backend="microvm", error="microVM 启动失败:虚拟机没有应答")
monkeypatch.setattr(mv.MicroVMSandbox, "run", _fake_run(failed, []))
assert selftest.main() == 1
assert capsys.readouterr().out.strip() == "microVM 启动失败:虚拟机没有应答"
def test_selftest_does_not_trust_exit_zero_without_output(linux: Path, monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str]) -> None:
# 退出码 0 但什么都没打印:VM 里的代码其实没跑起来,不能当成功
linux.touch()
monkeypatch.setattr(mv.os, "access", lambda path, mode: True)
monkeypatch.setattr(mv.MicroVMSandbox, "run", _fake_run(ExecResult(backend="microvm"), []))
assert selftest.main() == 1
assert capsys.readouterr().out.strip().startswith("microVM 启动失败:")