Bundle firecracker runtime and switch ollama demo to live logs
This commit is contained in:
parent
ef0ddeaa11
commit
65f7c0d262
26 changed files with 1896 additions and 408 deletions
|
|
@ -1,5 +1,6 @@
|
|||
"""Public package surface for pyro_mcp."""
|
||||
|
||||
from pyro_mcp.server import HELLO_STATIC_PAYLOAD, create_server
|
||||
from pyro_mcp.server import create_server
|
||||
from pyro_mcp.vm_manager import VmManager
|
||||
|
||||
__all__ = ["HELLO_STATIC_PAYLOAD", "create_server"]
|
||||
__all__ = ["VmManager", "create_server"]
|
||||
|
|
|
|||
|
|
@ -1,35 +1,23 @@
|
|||
"""Runnable demonstration for the static MCP tool."""
|
||||
"""Runnable deterministic demo for VM lifecycle tools."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from mcp.types import TextContent
|
||||
|
||||
from pyro_mcp.server import HELLO_STATIC_PAYLOAD, create_server
|
||||
from pyro_mcp.vm_manager import VmManager
|
||||
|
||||
|
||||
async def run_demo() -> dict[str, str]:
|
||||
"""Call the static MCP tool and return its structured payload."""
|
||||
server = create_server()
|
||||
result = await server.call_tool("hello_static", {})
|
||||
blocks, structured = result
|
||||
|
||||
are_text_blocks = all(isinstance(item, TextContent) for item in blocks)
|
||||
if not isinstance(blocks, Sequence) or not are_text_blocks:
|
||||
raise TypeError("unexpected MCP content block output")
|
||||
if not isinstance(structured, dict):
|
||||
raise TypeError("expected a structured dictionary payload")
|
||||
if structured != HELLO_STATIC_PAYLOAD:
|
||||
raise ValueError("static payload did not match expected value")
|
||||
|
||||
typed: dict[str, str] = {str(key): str(value) for key, value in structured.items()}
|
||||
return typed
|
||||
def run_demo() -> dict[str, Any]:
|
||||
"""Create/start/exec/delete a VM and return command output."""
|
||||
manager = VmManager()
|
||||
created = manager.create_vm(profile="debian-git", vcpu_count=1, mem_mib=512, ttl_seconds=600)
|
||||
vm_id = str(created["vm_id"])
|
||||
manager.start_vm(vm_id)
|
||||
executed = manager.exec_vm(vm_id, command="git --version", timeout_seconds=30)
|
||||
return executed
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Run the demonstration and print the JSON payload."""
|
||||
payload = asyncio.run(run_demo())
|
||||
print(json.dumps(payload, indent=2, sort_keys=True))
|
||||
"""Run the deterministic lifecycle demo."""
|
||||
print(json.dumps(run_demo(), indent=2, sort_keys=True))
|
||||
|
|
|
|||
20
src/pyro_mcp/doctor.py
Normal file
20
src/pyro_mcp/doctor.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
"""Runtime diagnostics CLI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
|
||||
from pyro_mcp.runtime import DEFAULT_PLATFORM, doctor_report
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="Inspect bundled runtime health for pyro-mcp.")
|
||||
parser.add_argument("--platform", default=DEFAULT_PLATFORM)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = _build_parser().parse_args()
|
||||
report = doctor_report(platform=args.platform)
|
||||
print(json.dumps(report, indent=2, sort_keys=True))
|
||||
|
|
@ -1,32 +1,97 @@
|
|||
"""Ollama chat-completions demo that triggers `hello_static` tool usage."""
|
||||
"""Ollama demo that drives VM lifecycle tools to run an ephemeral command."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections.abc import Callable
|
||||
from typing import Any, Final, cast
|
||||
|
||||
from pyro_mcp.demo import run_demo
|
||||
from pyro_mcp.vm_manager import VmManager
|
||||
|
||||
__all__ = ["VmManager", "run_ollama_tool_demo"]
|
||||
|
||||
DEFAULT_OLLAMA_BASE_URL: Final[str] = "http://localhost:11434/v1"
|
||||
DEFAULT_OLLAMA_MODEL: Final[str] = "llama:3.2-3b"
|
||||
TOOL_NAME: Final[str] = "hello_static"
|
||||
MAX_TOOL_ROUNDS: Final[int] = 12
|
||||
|
||||
TOOL_SPEC: Final[dict[str, Any]] = {
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": TOOL_NAME,
|
||||
"description": "Returns a deterministic static payload from pyro_mcp.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"additionalProperties": False,
|
||||
TOOL_SPECS: Final[list[dict[str, Any]]] = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "vm_list_profiles",
|
||||
"description": "List standard VM environment profiles.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "vm_create",
|
||||
"description": "Create an ephemeral VM with explicit vCPU and memory sizing.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"profile": {"type": "string"},
|
||||
"vcpu_count": {"type": "integer"},
|
||||
"mem_mib": {"type": "integer"},
|
||||
"ttl_seconds": {"type": "integer"},
|
||||
},
|
||||
"required": ["profile", "vcpu_count", "mem_mib"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "vm_start",
|
||||
"description": "Start a VM before command execution.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"vm_id": {"type": "string"}},
|
||||
"required": ["vm_id"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "vm_exec",
|
||||
"description": "Run one non-interactive command inside the VM and auto-clean it.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"vm_id": {"type": "string"},
|
||||
"command": {"type": "string"},
|
||||
"timeout_seconds": {"type": "integer"},
|
||||
},
|
||||
"required": ["vm_id", "command"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "vm_status",
|
||||
"description": "Read current VM status and metadata.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"vm_id": {"type": "string"}},
|
||||
"required": ["vm_id"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _post_chat_completion(base_url: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
|
@ -39,13 +104,12 @@ def _post_chat_completion(base_url: str, payload: dict[str, Any]) -> dict[str, A
|
|||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
with urllib.request.urlopen(request, timeout=90) as response:
|
||||
response_text = response.read().decode("utf-8")
|
||||
except urllib.error.URLError as exc:
|
||||
raise RuntimeError(
|
||||
"failed to call Ollama. Ensure `ollama serve` is running and the model is available."
|
||||
) from exc
|
||||
|
||||
parsed = json.loads(response_text)
|
||||
if not isinstance(parsed, dict):
|
||||
raise TypeError("unexpected Ollama response shape")
|
||||
|
|
@ -80,89 +144,205 @@ def _parse_tool_arguments(raw_arguments: Any) -> dict[str, Any]:
|
|||
raise TypeError("tool arguments must be a dictionary or JSON object string")
|
||||
|
||||
|
||||
def _require_str(arguments: dict[str, Any], key: str) -> str:
|
||||
value = arguments.get(key)
|
||||
if not isinstance(value, str) or value == "":
|
||||
raise ValueError(f"{key} must be a non-empty string")
|
||||
return value
|
||||
|
||||
|
||||
def _require_int(arguments: dict[str, Any], key: str) -> int:
|
||||
value = arguments.get(key)
|
||||
if not isinstance(value, int):
|
||||
raise ValueError(f"{key} must be an integer")
|
||||
return value
|
||||
|
||||
|
||||
def _dispatch_tool_call(
|
||||
manager: VmManager, tool_name: str, arguments: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
if tool_name == "vm_list_profiles":
|
||||
return {"profiles": manager.list_profiles()}
|
||||
if tool_name == "vm_create":
|
||||
return manager.create_vm(
|
||||
profile=_require_str(arguments, "profile"),
|
||||
vcpu_count=_require_int(arguments, "vcpu_count"),
|
||||
mem_mib=_require_int(arguments, "mem_mib"),
|
||||
ttl_seconds=arguments.get("ttl_seconds", 600)
|
||||
if isinstance(arguments.get("ttl_seconds"), int)
|
||||
else 600,
|
||||
)
|
||||
if tool_name == "vm_start":
|
||||
return manager.start_vm(_require_str(arguments, "vm_id"))
|
||||
if tool_name == "vm_exec":
|
||||
return manager.exec_vm(
|
||||
_require_str(arguments, "vm_id"),
|
||||
command=_require_str(arguments, "command"),
|
||||
timeout_seconds=arguments.get("timeout_seconds", 30)
|
||||
if isinstance(arguments.get("timeout_seconds"), int)
|
||||
else 30,
|
||||
)
|
||||
if tool_name == "vm_status":
|
||||
return manager.status_vm(_require_str(arguments, "vm_id"))
|
||||
raise RuntimeError(f"unexpected tool requested by model: {tool_name!r}")
|
||||
|
||||
|
||||
def _format_tool_error(tool_name: str, arguments: dict[str, Any], exc: Exception) -> dict[str, Any]:
|
||||
return {
|
||||
"ok": False,
|
||||
"tool_name": tool_name,
|
||||
"arguments": arguments,
|
||||
"error_type": exc.__class__.__name__,
|
||||
"error": str(exc),
|
||||
}
|
||||
|
||||
|
||||
def _run_direct_lifecycle_fallback(manager: VmManager) -> dict[str, Any]:
|
||||
created = manager.create_vm(profile="debian-git", vcpu_count=1, mem_mib=512, ttl_seconds=600)
|
||||
vm_id = str(created["vm_id"])
|
||||
manager.start_vm(vm_id)
|
||||
return manager.exec_vm(vm_id, command="git --version", timeout_seconds=30)
|
||||
|
||||
|
||||
def run_ollama_tool_demo(
|
||||
base_url: str = DEFAULT_OLLAMA_BASE_URL,
|
||||
model: str = DEFAULT_OLLAMA_MODEL,
|
||||
*,
|
||||
strict: bool = True,
|
||||
log: Callable[[str], None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Ask Ollama to call the static tool, execute it, and return final model output."""
|
||||
"""Ask Ollama to run git version check in an ephemeral VM through lifecycle tools."""
|
||||
emit = log or (lambda _: None)
|
||||
emit(f"[ollama] starting tool demo with model={model}")
|
||||
manager = VmManager()
|
||||
messages: list[dict[str, Any]] = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
"Use the hello_static tool and then summarize its payload in one short sentence."
|
||||
"Use the lifecycle tools to run `git --version` in an ephemeral VM.\n"
|
||||
"Required order: vm_list_profiles -> vm_create -> vm_start -> vm_exec.\n"
|
||||
"Use profile `debian-git`, choose adequate vCPU/memory, and pass the `vm_id` "
|
||||
"returned by vm_create into vm_start/vm_exec.\n"
|
||||
"If a tool returns an error, fix arguments and retry."
|
||||
),
|
||||
}
|
||||
]
|
||||
first_payload: dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"tools": [TOOL_SPEC],
|
||||
"tool_choice": "auto",
|
||||
"temperature": 0,
|
||||
}
|
||||
first_response = _post_chat_completion(base_url, first_payload)
|
||||
assistant_message = _extract_message(first_response)
|
||||
tool_events: list[dict[str, Any]] = []
|
||||
final_response = ""
|
||||
|
||||
tool_calls = assistant_message.get("tool_calls")
|
||||
if not isinstance(tool_calls, list) or not tool_calls:
|
||||
raise RuntimeError("model did not trigger any tool call")
|
||||
for round_index in range(1, MAX_TOOL_ROUNDS + 1):
|
||||
emit(f"[ollama] round {round_index}: requesting completion")
|
||||
response = _post_chat_completion(
|
||||
base_url,
|
||||
{
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"tools": TOOL_SPECS,
|
||||
"tool_choice": "auto",
|
||||
"temperature": 0,
|
||||
},
|
||||
)
|
||||
assistant_message = _extract_message(response)
|
||||
tool_calls = assistant_message.get("tool_calls")
|
||||
if not isinstance(tool_calls, list) or not tool_calls:
|
||||
final_response = str(assistant_message.get("content") or "")
|
||||
emit("[ollama] no tool calls returned; stopping loop")
|
||||
break
|
||||
|
||||
messages.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": str(assistant_message.get("content") or ""),
|
||||
"tool_calls": tool_calls,
|
||||
}
|
||||
)
|
||||
|
||||
tool_payload: dict[str, str] | None = None
|
||||
for tool_call in tool_calls:
|
||||
if not isinstance(tool_call, dict):
|
||||
raise RuntimeError("invalid tool call entry returned by model")
|
||||
function = tool_call.get("function")
|
||||
if not isinstance(function, dict):
|
||||
raise RuntimeError("tool call did not include function metadata")
|
||||
name = function.get("name")
|
||||
if name != TOOL_NAME:
|
||||
raise RuntimeError(f"unexpected tool requested by model: {name!r}")
|
||||
arguments = _parse_tool_arguments(function.get("arguments"))
|
||||
if arguments:
|
||||
raise RuntimeError("hello_static does not accept arguments")
|
||||
call_id = tool_call.get("id")
|
||||
if not isinstance(call_id, str) or call_id == "":
|
||||
raise RuntimeError("tool call did not provide a valid call id")
|
||||
|
||||
tool_payload = asyncio.run(run_demo())
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": call_id,
|
||||
"name": TOOL_NAME,
|
||||
"content": json.dumps(tool_payload, sort_keys=True),
|
||||
"role": "assistant",
|
||||
"content": str(assistant_message.get("content") or ""),
|
||||
"tool_calls": tool_calls,
|
||||
}
|
||||
)
|
||||
|
||||
if tool_payload is None:
|
||||
raise RuntimeError("tool payload was not generated")
|
||||
for tool_call in tool_calls:
|
||||
if not isinstance(tool_call, dict):
|
||||
raise RuntimeError("invalid tool call entry returned by model")
|
||||
call_id = tool_call.get("id")
|
||||
if not isinstance(call_id, str) or call_id == "":
|
||||
raise RuntimeError("tool call did not provide a valid call id")
|
||||
function = tool_call.get("function")
|
||||
if not isinstance(function, dict):
|
||||
raise RuntimeError("tool call did not include function metadata")
|
||||
tool_name = function.get("name")
|
||||
if not isinstance(tool_name, str):
|
||||
raise RuntimeError("tool call function name is invalid")
|
||||
arguments = _parse_tool_arguments(function.get("arguments"))
|
||||
emit(f"[tool] calling {tool_name} with args={arguments}")
|
||||
try:
|
||||
result = _dispatch_tool_call(manager, tool_name, arguments)
|
||||
success = True
|
||||
emit(f"[tool] {tool_name} succeeded")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
result = _format_tool_error(tool_name, arguments, exc)
|
||||
success = False
|
||||
emit(f"[tool] {tool_name} failed: {exc}")
|
||||
tool_events.append(
|
||||
{
|
||||
"tool_name": tool_name,
|
||||
"arguments": arguments,
|
||||
"result": result,
|
||||
"success": success,
|
||||
}
|
||||
)
|
||||
messages.append(
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": call_id,
|
||||
"name": tool_name,
|
||||
"content": json.dumps(result, sort_keys=True),
|
||||
}
|
||||
)
|
||||
else:
|
||||
raise RuntimeError("tool-calling loop exceeded maximum rounds")
|
||||
|
||||
second_payload: dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"temperature": 0,
|
||||
}
|
||||
second_response = _post_chat_completion(base_url, second_payload)
|
||||
final_message = _extract_message(second_response)
|
||||
exec_event = next(
|
||||
(
|
||||
event
|
||||
for event in reversed(tool_events)
|
||||
if event.get("tool_name") == "vm_exec" and bool(event.get("success"))
|
||||
),
|
||||
None,
|
||||
)
|
||||
fallback_used = False
|
||||
if exec_event is None:
|
||||
if strict:
|
||||
raise RuntimeError("demo did not execute a successful vm_exec")
|
||||
emit("[fallback] model did not complete vm_exec; running direct lifecycle command")
|
||||
exec_result = _run_direct_lifecycle_fallback(manager)
|
||||
fallback_used = True
|
||||
tool_events.append(
|
||||
{
|
||||
"tool_name": "vm_exec_fallback",
|
||||
"arguments": {"command": "git --version"},
|
||||
"result": exec_result,
|
||||
"success": True,
|
||||
}
|
||||
)
|
||||
else:
|
||||
exec_result = exec_event["result"]
|
||||
if not isinstance(exec_result, dict):
|
||||
raise RuntimeError("vm_exec result shape is invalid")
|
||||
if int(exec_result.get("exit_code", -1)) != 0:
|
||||
raise RuntimeError("vm_exec failed; expected exit_code=0")
|
||||
if "git version" not in str(exec_result.get("stdout", "")):
|
||||
raise RuntimeError("vm_exec output did not contain `git version`")
|
||||
emit("[done] command execution succeeded")
|
||||
|
||||
return {
|
||||
"model": model,
|
||||
"tool_name": TOOL_NAME,
|
||||
"tool_payload": tool_payload,
|
||||
"final_response": str(final_message.get("content") or ""),
|
||||
"command": "git --version",
|
||||
"exec_result": exec_result,
|
||||
"tool_events": tool_events,
|
||||
"final_response": final_response,
|
||||
"fallback_used": fallback_used,
|
||||
}
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="Run Ollama tool-calling demo for pyro_mcp.")
|
||||
parser = argparse.ArgumentParser(description="Run Ollama tool-calling demo for ephemeral VMs.")
|
||||
parser.add_argument("--base-url", default=DEFAULT_OLLAMA_BASE_URL)
|
||||
parser.add_argument("--model", default=DEFAULT_OLLAMA_MODEL)
|
||||
return parser
|
||||
|
|
@ -171,5 +351,18 @@ def _build_parser() -> argparse.ArgumentParser:
|
|||
def main() -> None:
|
||||
"""CLI entrypoint for Ollama tool-calling demo."""
|
||||
args = _build_parser().parse_args()
|
||||
result = run_ollama_tool_demo(base_url=args.base_url, model=args.model)
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
result = run_ollama_tool_demo(
|
||||
base_url=args.base_url,
|
||||
model=args.model,
|
||||
strict=False,
|
||||
log=lambda message: print(message, flush=True),
|
||||
)
|
||||
exec_result = result["exec_result"]
|
||||
if not isinstance(exec_result, dict):
|
||||
raise RuntimeError("demo produced invalid execution result")
|
||||
print(
|
||||
f"[summary] exit_code={int(exec_result.get('exit_code', -1))} "
|
||||
f"fallback_used={bool(result.get('fallback_used'))}",
|
||||
flush=True,
|
||||
)
|
||||
print(f"[summary] stdout={str(exec_result.get('stdout', '')).strip()}", flush=True)
|
||||
|
|
|
|||
171
src/pyro_mcp/runtime.py
Normal file
171
src/pyro_mcp/runtime.py
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
"""Bundled runtime resolver and diagnostics."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.resources as resources
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
DEFAULT_PLATFORM = "linux-x86_64"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimePaths:
|
||||
"""Resolved paths for bundled runtime components."""
|
||||
|
||||
bundle_root: Path
|
||||
manifest_path: Path
|
||||
firecracker_bin: Path
|
||||
jailer_bin: Path
|
||||
artifacts_dir: Path
|
||||
notice_path: Path
|
||||
manifest: dict[str, Any]
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as fp:
|
||||
for block in iter(lambda: fp.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _ensure_executable(path: Path) -> None:
|
||||
mode = path.stat().st_mode
|
||||
if mode & stat.S_IXUSR:
|
||||
return
|
||||
path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
||||
|
||||
|
||||
def _default_bundle_parent() -> Path:
|
||||
return Path(str(resources.files("pyro_mcp.runtime_bundle")))
|
||||
|
||||
|
||||
def resolve_runtime_paths(
|
||||
*,
|
||||
platform: str = DEFAULT_PLATFORM,
|
||||
verify_checksums: bool = True,
|
||||
) -> RuntimePaths:
|
||||
"""Resolve and validate bundled runtime assets."""
|
||||
bundle_parent = Path(os.environ.get("PYRO_RUNTIME_BUNDLE_DIR", _default_bundle_parent()))
|
||||
bundle_root = bundle_parent / platform
|
||||
manifest_path = bundle_root / "manifest.json"
|
||||
notice_path = bundle_parent / "NOTICE"
|
||||
|
||||
if not manifest_path.exists():
|
||||
raise RuntimeError(
|
||||
f"bundled runtime manifest not found at {manifest_path}; reinstall package or "
|
||||
"use a wheel that includes bundled runtime assets"
|
||||
)
|
||||
if not notice_path.exists():
|
||||
raise RuntimeError(f"runtime NOTICE file missing at {notice_path}")
|
||||
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
if not isinstance(manifest, dict):
|
||||
raise RuntimeError("invalid runtime manifest format")
|
||||
|
||||
binaries = manifest.get("binaries")
|
||||
if not isinstance(binaries, dict):
|
||||
raise RuntimeError("runtime manifest is missing `binaries`")
|
||||
firecracker_entry = binaries.get("firecracker")
|
||||
jailer_entry = binaries.get("jailer")
|
||||
if not isinstance(firecracker_entry, dict) or not isinstance(jailer_entry, dict):
|
||||
raise RuntimeError("runtime manifest does not define firecracker/jailer binaries")
|
||||
|
||||
firecracker_bin = bundle_root / str(firecracker_entry.get("path", ""))
|
||||
jailer_bin = bundle_root / str(jailer_entry.get("path", ""))
|
||||
artifacts_dir = bundle_root / "profiles"
|
||||
|
||||
for path in (firecracker_bin, jailer_bin, artifacts_dir):
|
||||
if not path.exists():
|
||||
raise RuntimeError(f"runtime asset missing: {path}")
|
||||
|
||||
_ensure_executable(firecracker_bin)
|
||||
_ensure_executable(jailer_bin)
|
||||
|
||||
if verify_checksums:
|
||||
for entry in (firecracker_entry, jailer_entry):
|
||||
raw_path = entry.get("path")
|
||||
raw_hash = entry.get("sha256")
|
||||
if not isinstance(raw_path, str) or not isinstance(raw_hash, str):
|
||||
raise RuntimeError("runtime binary manifest entry is malformed")
|
||||
full_path = bundle_root / raw_path
|
||||
actual = _sha256(full_path)
|
||||
if actual != raw_hash:
|
||||
raise RuntimeError(
|
||||
f"runtime checksum mismatch for {full_path}; expected {raw_hash}, got {actual}"
|
||||
)
|
||||
profiles = manifest.get("profiles")
|
||||
if not isinstance(profiles, dict):
|
||||
raise RuntimeError("runtime manifest is missing `profiles`")
|
||||
for profile_name, profile_spec in profiles.items():
|
||||
if not isinstance(profile_spec, dict):
|
||||
raise RuntimeError(f"profile manifest entry for {profile_name!r} is malformed")
|
||||
for kind in ("kernel", "rootfs"):
|
||||
spec = profile_spec.get(kind)
|
||||
if not isinstance(spec, dict):
|
||||
raise RuntimeError(f"profile {profile_name!r} is missing {kind} spec")
|
||||
raw_path = spec.get("path")
|
||||
raw_hash = spec.get("sha256")
|
||||
if not isinstance(raw_path, str) or not isinstance(raw_hash, str):
|
||||
raise RuntimeError(f"profile {profile_name!r} {kind} spec is malformed")
|
||||
full_path = bundle_root / raw_path
|
||||
if not full_path.exists():
|
||||
raise RuntimeError(f"profile asset missing: {full_path}")
|
||||
actual = _sha256(full_path)
|
||||
if actual != raw_hash:
|
||||
raise RuntimeError(
|
||||
f"profile checksum mismatch for {full_path}; "
|
||||
f"expected {raw_hash}, got {actual}"
|
||||
)
|
||||
|
||||
return RuntimePaths(
|
||||
bundle_root=bundle_root,
|
||||
manifest_path=manifest_path,
|
||||
firecracker_bin=firecracker_bin,
|
||||
jailer_bin=jailer_bin,
|
||||
artifacts_dir=artifacts_dir,
|
||||
notice_path=notice_path,
|
||||
manifest=manifest,
|
||||
)
|
||||
|
||||
|
||||
def doctor_report(*, platform: str = DEFAULT_PLATFORM) -> dict[str, Any]:
|
||||
"""Build a runtime diagnostics report."""
|
||||
report: dict[str, Any] = {
|
||||
"platform": platform,
|
||||
"runtime_ok": False,
|
||||
"issues": [],
|
||||
"kvm": {
|
||||
"exists": Path("/dev/kvm").exists(),
|
||||
"readable": os.access("/dev/kvm", os.R_OK),
|
||||
"writable": os.access("/dev/kvm", os.W_OK),
|
||||
},
|
||||
}
|
||||
try:
|
||||
paths = resolve_runtime_paths(platform=platform, verify_checksums=True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
report["issues"] = [str(exc)]
|
||||
return report
|
||||
|
||||
profiles = paths.manifest.get("profiles", {})
|
||||
profile_names = sorted(profiles.keys()) if isinstance(profiles, dict) else []
|
||||
report["runtime_ok"] = True
|
||||
report["runtime"] = {
|
||||
"bundle_root": str(paths.bundle_root),
|
||||
"manifest_path": str(paths.manifest_path),
|
||||
"firecracker_bin": str(paths.firecracker_bin),
|
||||
"jailer_bin": str(paths.jailer_bin),
|
||||
"artifacts_dir": str(paths.artifacts_dir),
|
||||
"notice_path": str(paths.notice_path),
|
||||
"bundle_version": paths.manifest.get("bundle_version"),
|
||||
"profiles": profile_names,
|
||||
}
|
||||
if not report["kvm"]["exists"]:
|
||||
report["issues"] = ["/dev/kvm is not available on this host"]
|
||||
return report
|
||||
5
src/pyro_mcp/runtime_bundle/NOTICE
Normal file
5
src/pyro_mcp/runtime_bundle/NOTICE
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
pyro-mcp runtime bundle
|
||||
|
||||
This package includes bundled runtime components intended for local developer workflows.
|
||||
Replace shims with official Firecracker/jailer binaries and production profile artifacts
|
||||
for real VM isolation in release builds.
|
||||
2
src/pyro_mcp/runtime_bundle/__init__.py
Normal file
2
src/pyro_mcp/runtime_bundle/__init__.py
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
"""Bundled runtime assets for pyro_mcp."""
|
||||
|
||||
12
src/pyro_mcp/runtime_bundle/linux-x86_64/bin/firecracker
Executable file
12
src/pyro_mcp/runtime_bundle/linux-x86_64/bin/firecracker
Executable file
|
|
@ -0,0 +1,12 @@
|
|||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
if [ "${1:-}" = "--version" ]; then
|
||||
echo "Firecracker v1.8.0 (bundled shim)"
|
||||
exit 0
|
||||
fi
|
||||
if [ "${1:-}" = "--help" ]; then
|
||||
echo "bundled firecracker shim"
|
||||
exit 0
|
||||
fi
|
||||
echo "bundled firecracker shim: unsupported args: $*" >&2
|
||||
exit 2
|
||||
8
src/pyro_mcp/runtime_bundle/linux-x86_64/bin/jailer
Executable file
8
src/pyro_mcp/runtime_bundle/linux-x86_64/bin/jailer
Executable file
|
|
@ -0,0 +1,8 @@
|
|||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
if [ "${1:-}" = "--version" ]; then
|
||||
echo "Jailer v1.8.0 (bundled shim)"
|
||||
exit 0
|
||||
fi
|
||||
echo "bundled jailer shim"
|
||||
exit 0
|
||||
49
src/pyro_mcp/runtime_bundle/linux-x86_64/manifest.json
Normal file
49
src/pyro_mcp/runtime_bundle/linux-x86_64/manifest.json
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
{
|
||||
"bundle_version": "0.1.0",
|
||||
"platform": "linux-x86_64",
|
||||
"binaries": {
|
||||
"firecracker": {
|
||||
"path": "bin/firecracker",
|
||||
"sha256": "2ff2d53551abcbf7ddebd921077214bff31910d4dfd894cc6fe66511d9f188e7"
|
||||
},
|
||||
"jailer": {
|
||||
"path": "bin/jailer",
|
||||
"sha256": "d79e972b3ede34b1c3eb9d54c9f1853a62a8525f78c39c8dab4d5d79a6783fe9"
|
||||
}
|
||||
},
|
||||
"profiles": {
|
||||
"debian-base": {
|
||||
"description": "Minimal Debian userspace for shell and core Unix tooling.",
|
||||
"kernel": {
|
||||
"path": "profiles/debian-base/vmlinux",
|
||||
"sha256": "a0bd6422be1061bb3b70a7895e82f66c25c59022d1e8a72b6fc9cdee4136f108"
|
||||
},
|
||||
"rootfs": {
|
||||
"path": "profiles/debian-base/rootfs.ext4",
|
||||
"sha256": "2794a4bdc232b6a6267cfc1eaaa696f0efccd2f8f2e130f3ade736637de89dcd"
|
||||
}
|
||||
},
|
||||
"debian-git": {
|
||||
"description": "Debian base environment with Git preinstalled.",
|
||||
"kernel": {
|
||||
"path": "profiles/debian-git/vmlinux",
|
||||
"sha256": "eaf871c952bf6476f0299b1f501eddc302105e53c99c86161fa815e90cf5bc9f"
|
||||
},
|
||||
"rootfs": {
|
||||
"path": "profiles/debian-git/rootfs.ext4",
|
||||
"sha256": "17863bd1496a9a08d89d6e4c73bd619d39bbe7f6089f1903837525629557c076"
|
||||
}
|
||||
},
|
||||
"debian-build": {
|
||||
"description": "Debian Git environment with common build tools for source builds.",
|
||||
"kernel": {
|
||||
"path": "profiles/debian-build/vmlinux",
|
||||
"sha256": "c33994b1da43cf2f11ac9d437c034eaa71496b566a45028a9ae6f657105dc2b6"
|
||||
},
|
||||
"rootfs": {
|
||||
"path": "profiles/debian-build/rootfs.ext4",
|
||||
"sha256": "ac148235c86a51c87228e17a8cf2c9452921886c094de42b470d5f42dab70226"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,26 +1,68 @@
|
|||
"""MCP server definition for the v0.0.1 static tool demo."""
|
||||
"""MCP server exposing ephemeral VM lifecycle tools."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Final
|
||||
from typing import Any
|
||||
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
HELLO_STATIC_PAYLOAD: Final[dict[str, str]] = {
|
||||
"message": "hello from pyro_mcp",
|
||||
"status": "ok",
|
||||
"version": "0.0.1",
|
||||
}
|
||||
from pyro_mcp.vm_manager import VmManager
|
||||
|
||||
|
||||
def create_server() -> FastMCP:
|
||||
def create_server(manager: VmManager | None = None) -> FastMCP:
|
||||
"""Create and return a configured MCP server instance."""
|
||||
vm_manager = manager or VmManager()
|
||||
server = FastMCP(name="pyro_mcp")
|
||||
|
||||
@server.tool()
|
||||
async def hello_static() -> dict[str, str]:
|
||||
"""Return a deterministic static payload."""
|
||||
return HELLO_STATIC_PAYLOAD.copy()
|
||||
async def vm_list_profiles() -> list[dict[str, object]]:
|
||||
"""List standard environment profiles and package highlights."""
|
||||
return vm_manager.list_profiles()
|
||||
|
||||
@server.tool()
|
||||
async def vm_create(
|
||||
profile: str,
|
||||
vcpu_count: int,
|
||||
mem_mib: int,
|
||||
ttl_seconds: int = 600,
|
||||
) -> dict[str, Any]:
|
||||
"""Create an ephemeral VM record with profile and resource sizing."""
|
||||
return vm_manager.create_vm(
|
||||
profile=profile,
|
||||
vcpu_count=vcpu_count,
|
||||
mem_mib=mem_mib,
|
||||
ttl_seconds=ttl_seconds,
|
||||
)
|
||||
|
||||
@server.tool()
|
||||
async def vm_start(vm_id: str) -> dict[str, Any]:
|
||||
"""Start a created VM and transition it into a command-ready state."""
|
||||
return vm_manager.start_vm(vm_id)
|
||||
|
||||
@server.tool()
|
||||
async def vm_exec(vm_id: str, command: str, timeout_seconds: int = 30) -> dict[str, Any]:
|
||||
"""Run one non-interactive command and auto-clean the VM."""
|
||||
return vm_manager.exec_vm(vm_id, command=command, timeout_seconds=timeout_seconds)
|
||||
|
||||
@server.tool()
|
||||
async def vm_stop(vm_id: str) -> dict[str, Any]:
|
||||
"""Stop a running VM."""
|
||||
return vm_manager.stop_vm(vm_id)
|
||||
|
||||
@server.tool()
|
||||
async def vm_delete(vm_id: str) -> dict[str, Any]:
|
||||
"""Delete a VM and its runtime artifacts."""
|
||||
return vm_manager.delete_vm(vm_id)
|
||||
|
||||
@server.tool()
|
||||
async def vm_status(vm_id: str) -> dict[str, Any]:
|
||||
"""Get the current state and metadata for a VM."""
|
||||
return vm_manager.status_vm(vm_id)
|
||||
|
||||
@server.tool()
|
||||
async def vm_reap_expired() -> dict[str, Any]:
|
||||
"""Delete VMs whose TTL has expired."""
|
||||
return vm_manager.reap_expired()
|
||||
|
||||
return server
|
||||
|
||||
|
|
|
|||
359
src/pyro_mcp/vm_manager.py
Normal file
359
src/pyro_mcp/vm_manager.py
Normal file
|
|
@ -0,0 +1,359 @@
|
|||
"""Lifecycle manager for ephemeral VM environments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
from pyro_mcp.runtime import RuntimePaths, resolve_runtime_paths
|
||||
from pyro_mcp.vm_profiles import get_profile, list_profiles, resolve_artifacts
|
||||
|
||||
VmState = Literal["created", "started", "stopped"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class VmInstance:
|
||||
"""In-memory VM lifecycle record."""
|
||||
|
||||
vm_id: str
|
||||
profile: str
|
||||
vcpu_count: int
|
||||
mem_mib: int
|
||||
ttl_seconds: int
|
||||
created_at: float
|
||||
expires_at: float
|
||||
workdir: Path
|
||||
state: VmState = "created"
|
||||
firecracker_pid: int | None = None
|
||||
last_error: str | None = None
|
||||
metadata: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VmExecResult:
|
||||
"""Command execution output."""
|
||||
|
||||
stdout: str
|
||||
stderr: str
|
||||
exit_code: int
|
||||
duration_ms: int
|
||||
|
||||
|
||||
def _run_host_command(workdir: Path, command: str, timeout_seconds: int) -> VmExecResult:
|
||||
started = time.monotonic()
|
||||
env = {"PATH": os.environ.get("PATH", ""), "HOME": str(workdir)}
|
||||
try:
|
||||
proc = subprocess.run( # noqa: S603
|
||||
["bash", "-lc", command], # noqa: S607
|
||||
cwd=workdir,
|
||||
env=env,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout_seconds,
|
||||
check=False,
|
||||
)
|
||||
return VmExecResult(
|
||||
stdout=proc.stdout,
|
||||
stderr=proc.stderr,
|
||||
exit_code=proc.returncode,
|
||||
duration_ms=int((time.monotonic() - started) * 1000),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return VmExecResult(
|
||||
stdout="",
|
||||
stderr=f"command timed out after {timeout_seconds}s",
|
||||
exit_code=124,
|
||||
duration_ms=int((time.monotonic() - started) * 1000),
|
||||
)
|
||||
|
||||
|
||||
class VmBackend:
|
||||
"""Backend interface for lifecycle operations."""
|
||||
|
||||
def create(self, instance: VmInstance) -> None: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def start(self, instance: VmInstance) -> None: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def exec( # pragma: no cover
|
||||
self, instance: VmInstance, command: str, timeout_seconds: int
|
||||
) -> VmExecResult:
|
||||
raise NotImplementedError
|
||||
|
||||
def stop(self, instance: VmInstance) -> None: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
def delete(self, instance: VmInstance) -> None: # pragma: no cover
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class MockBackend(VmBackend):
|
||||
"""Host-process backend used for development and testability."""
|
||||
|
||||
def create(self, instance: VmInstance) -> None:
|
||||
instance.workdir.mkdir(parents=True, exist_ok=False)
|
||||
|
||||
def start(self, instance: VmInstance) -> None:
|
||||
marker_path = instance.workdir / ".started"
|
||||
marker_path.write_text("started\n", encoding="utf-8")
|
||||
|
||||
def exec(self, instance: VmInstance, command: str, timeout_seconds: int) -> VmExecResult:
|
||||
return _run_host_command(instance.workdir, command, timeout_seconds)
|
||||
|
||||
def stop(self, instance: VmInstance) -> None:
|
||||
marker_path = instance.workdir / ".stopped"
|
||||
marker_path.write_text("stopped\n", encoding="utf-8")
|
||||
|
||||
def delete(self, instance: VmInstance) -> None:
|
||||
shutil.rmtree(instance.workdir, ignore_errors=True)
|
||||
|
||||
|
||||
class FirecrackerBackend(VmBackend): # pragma: no cover
|
||||
"""Host-gated backend that validates Firecracker prerequisites."""
|
||||
|
||||
def __init__(self, artifacts_dir: Path, firecracker_bin: Path, jailer_bin: Path) -> None:
|
||||
self._artifacts_dir = artifacts_dir
|
||||
self._firecracker_bin = firecracker_bin
|
||||
self._jailer_bin = jailer_bin
|
||||
if not self._firecracker_bin.exists():
|
||||
raise RuntimeError(f"bundled firecracker binary not found at {self._firecracker_bin}")
|
||||
if not self._jailer_bin.exists():
|
||||
raise RuntimeError(f"bundled jailer binary not found at {self._jailer_bin}")
|
||||
if not Path("/dev/kvm").exists():
|
||||
raise RuntimeError("/dev/kvm is not available on this host")
|
||||
|
||||
def create(self, instance: VmInstance) -> None:
|
||||
instance.workdir.mkdir(parents=True, exist_ok=False)
|
||||
artifacts = resolve_artifacts(self._artifacts_dir, instance.profile)
|
||||
if not artifacts.kernel_image.exists() or not artifacts.rootfs_image.exists():
|
||||
raise RuntimeError(
|
||||
f"missing profile artifacts for {instance.profile}; expected "
|
||||
f"{artifacts.kernel_image} and {artifacts.rootfs_image}"
|
||||
)
|
||||
instance.metadata["kernel_image"] = str(artifacts.kernel_image)
|
||||
instance.metadata["rootfs_image"] = str(artifacts.rootfs_image)
|
||||
|
||||
def start(self, instance: VmInstance) -> None:
|
||||
proc = subprocess.run( # noqa: S603
|
||||
[str(self._firecracker_bin), "--version"],
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"firecracker startup preflight failed: {proc.stderr.strip()}")
|
||||
instance.metadata["firecracker_version"] = proc.stdout.strip()
|
||||
instance.metadata["jailer_path"] = str(self._jailer_bin)
|
||||
|
||||
def exec(self, instance: VmInstance, command: str, timeout_seconds: int) -> VmExecResult:
|
||||
# Temporary compatibility path until guest-side execution agent is integrated.
|
||||
return _run_host_command(instance.workdir, command, timeout_seconds)
|
||||
|
||||
def stop(self, instance: VmInstance) -> None:
|
||||
del instance
|
||||
|
||||
def delete(self, instance: VmInstance) -> None:
|
||||
shutil.rmtree(instance.workdir, ignore_errors=True)
|
||||
|
||||
|
||||
class VmManager:
|
||||
"""In-process lifecycle manager for ephemeral VM environments."""
|
||||
|
||||
MIN_VCPUS = 1
|
||||
MAX_VCPUS = 8
|
||||
MIN_MEM_MIB = 256
|
||||
MAX_MEM_MIB = 32768
|
||||
MIN_TTL_SECONDS = 60
|
||||
MAX_TTL_SECONDS = 3600
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
backend_name: str | None = None,
|
||||
base_dir: Path | None = None,
|
||||
artifacts_dir: Path | None = None,
|
||||
max_active_vms: int = 4,
|
||||
runtime_paths: RuntimePaths | None = None,
|
||||
) -> None:
|
||||
self._backend_name = backend_name or "firecracker"
|
||||
self._base_dir = base_dir or Path("/tmp/pyro-mcp")
|
||||
self._runtime_paths = runtime_paths
|
||||
if self._backend_name == "firecracker":
|
||||
self._runtime_paths = self._runtime_paths or resolve_runtime_paths()
|
||||
self._artifacts_dir = artifacts_dir or self._runtime_paths.artifacts_dir
|
||||
else:
|
||||
self._artifacts_dir = artifacts_dir or Path(
|
||||
os.environ.get("PYRO_VM_ARTIFACTS_DIR", "/opt/pyro-mcp/artifacts")
|
||||
)
|
||||
self._max_active_vms = max_active_vms
|
||||
self._lock = threading.Lock()
|
||||
self._instances: dict[str, VmInstance] = {}
|
||||
self._base_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._backend = self._build_backend()
|
||||
|
||||
def _build_backend(self) -> VmBackend:
|
||||
if self._backend_name == "mock":
|
||||
return MockBackend()
|
||||
if self._backend_name == "firecracker":
|
||||
if self._runtime_paths is None:
|
||||
raise RuntimeError("runtime paths were not initialized for firecracker backend")
|
||||
return FirecrackerBackend(
|
||||
self._artifacts_dir,
|
||||
firecracker_bin=self._runtime_paths.firecracker_bin,
|
||||
jailer_bin=self._runtime_paths.jailer_bin,
|
||||
)
|
||||
raise ValueError("invalid backend; expected one of: mock, firecracker")
|
||||
|
||||
def list_profiles(self) -> list[dict[str, object]]:
|
||||
return list_profiles()
|
||||
|
||||
def create_vm(
|
||||
self, *, profile: str, vcpu_count: int, mem_mib: int, ttl_seconds: int
|
||||
) -> dict[str, Any]:
|
||||
self._validate_limits(vcpu_count=vcpu_count, mem_mib=mem_mib, ttl_seconds=ttl_seconds)
|
||||
get_profile(profile)
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
self._reap_expired_locked(now)
|
||||
active_count = len(self._instances)
|
||||
if active_count >= self._max_active_vms:
|
||||
raise RuntimeError(
|
||||
f"max active VMs reached ({self._max_active_vms}); delete old VMs first"
|
||||
)
|
||||
vm_id = uuid.uuid4().hex[:12]
|
||||
instance = VmInstance(
|
||||
vm_id=vm_id,
|
||||
profile=profile,
|
||||
vcpu_count=vcpu_count,
|
||||
mem_mib=mem_mib,
|
||||
ttl_seconds=ttl_seconds,
|
||||
created_at=now,
|
||||
expires_at=now + ttl_seconds,
|
||||
workdir=self._base_dir / vm_id,
|
||||
)
|
||||
self._backend.create(instance)
|
||||
self._instances[vm_id] = instance
|
||||
return self._serialize(instance)
|
||||
|
||||
def start_vm(self, vm_id: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
instance = self._get_instance_locked(vm_id)
|
||||
self._ensure_not_expired_locked(instance, time.time())
|
||||
if instance.state not in {"created", "stopped"}:
|
||||
raise RuntimeError(f"vm {vm_id} cannot be started from state {instance.state!r}")
|
||||
self._backend.start(instance)
|
||||
instance.state = "started"
|
||||
return self._serialize(instance)
|
||||
|
||||
def exec_vm(self, vm_id: str, *, command: str, timeout_seconds: int) -> dict[str, Any]:
|
||||
if timeout_seconds <= 0:
|
||||
raise ValueError("timeout_seconds must be positive")
|
||||
with self._lock:
|
||||
instance = self._get_instance_locked(vm_id)
|
||||
self._ensure_not_expired_locked(instance, time.time())
|
||||
if instance.state != "started":
|
||||
raise RuntimeError(f"vm {vm_id} must be in 'started' state before vm_exec")
|
||||
exec_result = self._backend.exec(instance, command, timeout_seconds)
|
||||
cleanup = self.delete_vm(vm_id, reason="post_exec_cleanup")
|
||||
return {
|
||||
"vm_id": vm_id,
|
||||
"command": command,
|
||||
"stdout": exec_result.stdout,
|
||||
"stderr": exec_result.stderr,
|
||||
"exit_code": exec_result.exit_code,
|
||||
"duration_ms": exec_result.duration_ms,
|
||||
"cleanup": cleanup,
|
||||
}
|
||||
|
||||
def stop_vm(self, vm_id: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
instance = self._get_instance_locked(vm_id)
|
||||
self._backend.stop(instance)
|
||||
instance.state = "stopped"
|
||||
return self._serialize(instance)
|
||||
|
||||
def delete_vm(self, vm_id: str, *, reason: str = "explicit_delete") -> dict[str, Any]:
|
||||
with self._lock:
|
||||
instance = self._get_instance_locked(vm_id)
|
||||
if instance.state == "started":
|
||||
self._backend.stop(instance)
|
||||
instance.state = "stopped"
|
||||
self._backend.delete(instance)
|
||||
del self._instances[vm_id]
|
||||
return {"vm_id": vm_id, "deleted": True, "reason": reason}
|
||||
|
||||
def status_vm(self, vm_id: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
instance = self._get_instance_locked(vm_id)
|
||||
self._ensure_not_expired_locked(instance, time.time())
|
||||
return self._serialize(instance)
|
||||
|
||||
def reap_expired(self) -> dict[str, Any]:
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
expired_vm_ids = [
|
||||
vm_id for vm_id, inst in self._instances.items() if inst.expires_at <= now
|
||||
]
|
||||
for vm_id in expired_vm_ids:
|
||||
instance = self._instances[vm_id]
|
||||
if instance.state == "started":
|
||||
self._backend.stop(instance)
|
||||
instance.state = "stopped"
|
||||
self._backend.delete(instance)
|
||||
del self._instances[vm_id]
|
||||
return {"deleted_vm_ids": expired_vm_ids, "count": len(expired_vm_ids)}
|
||||
|
||||
def _validate_limits(self, *, vcpu_count: int, mem_mib: int, ttl_seconds: int) -> None:
|
||||
if not self.MIN_VCPUS <= vcpu_count <= self.MAX_VCPUS:
|
||||
raise ValueError(f"vcpu_count must be between {self.MIN_VCPUS} and {self.MAX_VCPUS}")
|
||||
if not self.MIN_MEM_MIB <= mem_mib <= self.MAX_MEM_MIB:
|
||||
raise ValueError(f"mem_mib must be between {self.MIN_MEM_MIB} and {self.MAX_MEM_MIB}")
|
||||
if not self.MIN_TTL_SECONDS <= ttl_seconds <= self.MAX_TTL_SECONDS:
|
||||
raise ValueError(
|
||||
f"ttl_seconds must be between {self.MIN_TTL_SECONDS} and {self.MAX_TTL_SECONDS}"
|
||||
)
|
||||
|
||||
def _serialize(self, instance: VmInstance) -> dict[str, Any]:
|
||||
return {
|
||||
"vm_id": instance.vm_id,
|
||||
"profile": instance.profile,
|
||||
"vcpu_count": instance.vcpu_count,
|
||||
"mem_mib": instance.mem_mib,
|
||||
"ttl_seconds": instance.ttl_seconds,
|
||||
"created_at": instance.created_at,
|
||||
"expires_at": instance.expires_at,
|
||||
"state": instance.state,
|
||||
"metadata": instance.metadata,
|
||||
}
|
||||
|
||||
def _get_instance_locked(self, vm_id: str) -> VmInstance:
|
||||
try:
|
||||
return self._instances[vm_id]
|
||||
except KeyError as exc:
|
||||
raise ValueError(f"vm {vm_id!r} does not exist") from exc
|
||||
|
||||
def _reap_expired_locked(self, now: float) -> None:
|
||||
expired_vm_ids = [
|
||||
vm_id for vm_id, inst in self._instances.items() if inst.expires_at <= now
|
||||
]
|
||||
for vm_id in expired_vm_ids:
|
||||
instance = self._instances[vm_id]
|
||||
if instance.state == "started":
|
||||
self._backend.stop(instance)
|
||||
instance.state = "stopped"
|
||||
self._backend.delete(instance)
|
||||
del self._instances[vm_id]
|
||||
|
||||
def _ensure_not_expired_locked(self, instance: VmInstance, now: float) -> None:
|
||||
if instance.expires_at <= now:
|
||||
vm_id = instance.vm_id
|
||||
self._reap_expired_locked(now)
|
||||
raise RuntimeError(f"vm {vm_id!r} expired and was automatically deleted")
|
||||
72
src/pyro_mcp/vm_profiles.py
Normal file
72
src/pyro_mcp/vm_profiles.py
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
"""Standard VM environment profiles for ephemeral coding environments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VmProfile:
|
||||
"""Profile metadata describing guest OS/tooling flavor."""
|
||||
|
||||
name: str
|
||||
description: str
|
||||
default_packages: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VmArtifacts:
|
||||
"""Resolved artifact paths for a profile."""
|
||||
|
||||
kernel_image: Path
|
||||
rootfs_image: Path
|
||||
|
||||
|
||||
PROFILE_CATALOG: dict[str, VmProfile] = {
|
||||
"debian-base": VmProfile(
|
||||
name="debian-base",
|
||||
description="Minimal Debian userspace for shell and core Unix tooling.",
|
||||
default_packages=("bash", "coreutils"),
|
||||
),
|
||||
"debian-git": VmProfile(
|
||||
name="debian-git",
|
||||
description="Debian base environment with Git preinstalled.",
|
||||
default_packages=("bash", "coreutils", "git"),
|
||||
),
|
||||
"debian-build": VmProfile(
|
||||
name="debian-build",
|
||||
description="Debian Git environment with common build tools for source builds.",
|
||||
default_packages=("bash", "coreutils", "git", "gcc", "make", "cmake", "python3"),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, object]]:
|
||||
"""Return profile metadata in a JSON-safe format."""
|
||||
return [
|
||||
{
|
||||
"name": profile.name,
|
||||
"description": profile.description,
|
||||
"default_packages": list(profile.default_packages),
|
||||
}
|
||||
for profile in PROFILE_CATALOG.values()
|
||||
]
|
||||
|
||||
|
||||
def get_profile(name: str) -> VmProfile:
|
||||
"""Resolve a profile by name."""
|
||||
try:
|
||||
return PROFILE_CATALOG[name]
|
||||
except KeyError as exc:
|
||||
known = ", ".join(sorted(PROFILE_CATALOG))
|
||||
raise ValueError(f"unknown profile {name!r}; expected one of: {known}") from exc
|
||||
|
||||
|
||||
def resolve_artifacts(artifacts_dir: Path, profile_name: str) -> VmArtifacts:
|
||||
"""Resolve kernel/rootfs file locations for a profile."""
|
||||
profile_dir = artifacts_dir / profile_name
|
||||
return VmArtifacts(
|
||||
kernel_image=profile_dir / "vmlinux",
|
||||
rootfs_image=profile_dir / "rootfs.ext4",
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue