fix(engine): preserve host scope during connection validation

venix
admin 1 month ago
parent 07e41b2a0f
commit b82f3b855e

@ -20,6 +20,14 @@
宿主应用的快照、重装、救援等状态锁仅保护短状态更新;整段远程调用改用可回收的每 VM 请求锁。创建使用独立 allocation 锁,不阻塞已有 VM 的电源操作。宿主身份更换仍属于排他维护,有活动 VM 请求时立即拒绝,待原请求结束后再重试。
## 宿主注册与执行身份
宿主连接测试和保存使用暂存的 SSH 文件,其 libvirt URI 会随暂存目录变化。私有引擎必须从已绑定当前宿主的 `StableHostManager.host_id` 显式取得执行身份,与保存后的 VM 操作共用原始宿主 ID、并发预算、`storage:<host_id>` 锁及未决写入保护。首次添加时即使 `manager.current()` 为空也适用;不能按临时 URI 或指标使用的宿主哈希另建执行身份。
内部身份缺失或格式非法时,在 libvirt 操作前返回 409 并清理暂存连接;请求体不能指定或覆盖此身份。独立面板模式继续使用已验证的地址、端口、SSH 指纹三元组生成身份。本修复不改变数据库结构、指标历史或 VM 归属键,也不向用户接口恢复宿主字段。
旧版本异常留下的未决协调记录不会因本次修复或重启自动解除。若升级或后续请求被其阻塞,必须按下文人工恢复流程逐条核验;修复连接构造本身不证明历史远端操作已经结束。
## 数据库协议
`coordination.py` 使用现有加密 `engine_records` 表,`record_type=coordination`、`record_key=admission-v1`。版本 1 文档保存 revision、claims 和最多 100 条人工核验收据。通过现有 `DatabaseStore.compare_and_set` 的行锁事务完成短准入更新;远程调用期间不持有数据库事务。

@ -755,6 +755,33 @@ HAVING live_subnets <> 1 OR deleting_subnets <> 0;
和签名健康检查。命令已对照当前代码与 unit,Bash/Python 语法检查通过;未在本机
执行安装、导库或服务启动,真实服务器安装仍需按实际目录、PHP 路径和 FPM 用户配置。
## 2026-10-12:宿主连接测试和保存的执行身份
- 修复 `b3ea192` 引入的暂存连接构造回归:`new_service` 开始使用执行身份后,
注册路径仍传入只有 URI 和资源设置的临时配置,导致 `host_scope` 读取不存在的
`host` 字段并报 503。该临时配置自最初实现就未含 `host_id`,问题不来自套餐或
用户接口移除宿主字段。
- 私有引擎从可信 `StableHostManager.host_id` 显式传入执行身份;首次注册、编辑、
连接测试及保存后的 VM 操作继续共享同一宿主预算、存储锁和未决写保护。
身份异常在 libvirt 写入前返回 409;独立模式仅使用已验证的地址、端口、指纹。
不改变数据库结构、指标哈希、VM 归属键或用户 API。详见
[宿主注册与执行身份](ENGINE_COORDINATION.md#宿主注册与执行身份)。
- 新增宿主作用域回归 **25 passed**,保留真实 `VMService` 构造、资源查询、存储
准备和连接适配逻辑;SSH、RPC 运行时及远端对象使用替身,资源锁入口记录实际键。
覆盖首次添加/编辑、测试/保存、变化的暂存 URI、非法内部身份、请求体注入、独立
模式和存储失败回滚,并校验读写预算及 `storage:7`。隔离加载修复前 HEAD 的
`app.py` 运行其中 7 个正常场景,全部复现 `KeyError: 'host'`。额外通过真实签名
请求和 `EngineApplication` 协调器验证非法身份:请求期间存在活动占用,409 后
暂存连接清理且占用释放,未启动 libvirt 操作。
- libvirt RPC、持久协调及资源锁回归 **67 passed**。扩展应用、私有边界、引擎协调、
数据库 HTTP 和指标回归 **293 passed、2 failed**;两项失败在修复前 HEAD
同样复现:模板创建期望缺少 `platform_network_policy_snapshot`,重装未决错误
用例仍读取 `detail` 而实际返回 `error`。未放宽断言或修改这些无关业务逻辑。
三个既有测试替身仅补齐生产已有的暂存 metadata 和可信 manager 身份契约。
- 使用 Python 3.12.14 与真实 pytest 9.1.1。本轮修复验证没有连接生产 SSH/libvirt、
部署或重启服务;真实新增宿主流程仍需更新引擎后验收。旧未决协调记录保持原样,
不因修复自动清空或重放。
## 在具备依赖的环境复测
不要使用生产数据库/宿主机运行额外真实集成测试;以下默认单元/隔离测试:

@ -648,6 +648,8 @@ class FakeRemoteManager:
return SimpleNamespace(
libvirt_uri="qemu+ssh://root@vp-managed/system?command=staged",
profile=profile,
metadata={"host": profile.host, "port": profile.port,
"fingerprint": confirmed_fingerprint},
)
def test(self, staged):

@ -251,6 +251,7 @@ def boundary(tmp_path):
(tmp_path / host_id).mkdir(mode=0o700, exist_ok=True)
scoped = HostStore(store, host_id)
manager = FakeRemoteManager()
manager.host_id = host_id
manager.profile = {"host_id": host_id, "host": "host.example.test", "port": 22,
"fingerprint": "SHA256:example", "key_locked": False, "storage_pool": "images",
"iso_pool": "iso", "rescue_iso_pool": "rescue", "default_network": "default",

@ -64,6 +64,7 @@ async def running_engine(directory, store=None):
host_directory.mkdir(exist_ok=True)
scoped = HostStore(store, host_id)
manager = FakeRemoteManager()
manager.host_id = host_id
manager.profile = {
"host_id": host_id, "host": host_id + ".example.test", "port": 22,
"fingerprint": "SHA256:example", "key_locked": False,

@ -0,0 +1,259 @@
"""Host connection probes use the same execution identity as saved services.
Keep the real VMService constructor, resource methods, local admission guard
and RPC connection adapter. Fake SSH staging, remote objects, the RPC runtime
and durable admission in focused tests; the final signed HTTP boundary test
uses the real EngineApplication coordinator with in-memory persistence.
"""
from contextlib import contextmanager
from types import SimpleNamespace
import pytest
from fastapi.testclient import TestClient
from test_app import FakeRemoteManager, HOST_BODY, ORIGIN, setup_admin
from test_engine_boundary import MemoryStore, SUPER, boundary, call
from virsh_panel.app import HostBody, create_app
from virsh_panel.config import Settings
from virsh_panel.database import DatabaseTemplateStore
from virsh_panel.engine_context import (
EngineComponents, ExternalOwnership, HostStore, TRUSTED_ACTOR,
)
from virsh_panel.libvirt_service import (
GIB, LIBVIRT_MUTATION_BUDGET, LIBVIRT_READ_BUDGET, VMError, VMService,
)
from virsh_panel.metrics import MetricsCollector, host_scope
from virsh_panel.panel_state import PanelState
class StagedManager(FakeRemoteManager):
"""Model StableHostManager's trusted identity independently of the body."""
def stage(self, profile, confirmed_fingerprint):
staged = super().stage(profile, confirmed_fingerprint)
staged.libvirt_uri += str(len(self.staged_profiles))
# An unexpected metadata field must not become an execution identity.
staged.metadata["host_id"] = "untrusted-metadata-id"
return staged
def commit(self, staged):
profile = super().commit(staged)
if hasattr(self, "host_id"):
profile["host_id"] = self.host_id
return profile
@pytest.fixture
def host_app(tmp_path, monkeypatch):
opened = []
locks = []
closed = []
services = []
connection = SimpleNamespace(
networkLookupByName=lambda _name: SimpleNamespace(isActive=lambda: True),
)
def open_session(uri, scope, *, timeout):
opened.append((uri, scope, timeout))
return SimpleNamespace(connection=connection, failure=None,
close=lambda: closed.append(uri))
runtime = SimpleNamespace(open=open_session, queue_timeout=1)
monkeypatch.setattr("virsh_panel.app.get_runtime", lambda: runtime)
monkeypatch.setattr("virsh_panel.libvirt_service.get_runtime", lambda: runtime)
monkeypatch.setattr(MetricsCollector, "start", lambda _self: None)
@contextmanager
def resource_guard(resources, *, timeout):
locks.append(tuple(resources))
yield
monkeypatch.setattr("virsh_panel.coordination.resource_guard", resource_guard)
def pool(service, _connection, name, *_args):
services.append(service)
return SimpleNamespace(name=lambda: name, listVolumes=lambda: [],
info=lambda: (0, 100 * GIB, 0, 100 * GIB))
monkeypatch.setattr(VMService, "_active_pool", pool)
monkeypatch.setattr(VMService, "_ensure_pool", pool)
monkeypatch.setattr(VMService, "_refresh_directory_pool", lambda *_args: None)
monkeypatch.setattr(VMService, "_same_pool_location", lambda *_args: False)
@contextmanager
def build(*, internal=True, host_id="7", existing=False):
directory = tmp_path / str(len(opened))
directory.mkdir(mode=0o700, exist_ok=True)
manager = StagedManager()
if internal:
manager.host_id = host_id
if existing:
staged = manager.stage(
HostBody(**HOST_BODY).profile(),
HOST_BODY["confirmed_fingerprint"],
)
manager.commit(staged)
manager.calls.clear()
settings = Settings(data_dir=directory)
if internal:
store = HostStore(MemoryStore(), "7")
components = EngineComponents(
SimpleNamespace(users=ExternalOwnership(store)), manager,
DatabaseTemplateStore(store), store, MemoryStore(),
)
app = create_app(settings, engine_components=components)
@app.middleware("http")
async def trusted_actor(request, call_next):
token = TRUSTED_ACTOR.set(SUPER)
try:
return await call_next(request)
finally:
TRUSTED_ACTOR.reset(token)
else:
state = PanelState(directory)
app = create_app(settings, panel_state=state, remote_manager=manager)
with TestClient(app, base_url=ORIGIN) as client:
headers = {}
if not internal:
token = state.token_file.read_text().strip()
headers["X-CSRF-Token"] = setup_admin(client, token)
yield SimpleNamespace(client=client, manager=manager, headers=headers,
opened=opened, locks=locks, closed=closed,
services=services)
return build
@pytest.mark.parametrize("existing", [False, True], ids=["add", "edit"])
@pytest.mark.parametrize("method,path,ensure", [
("POST", "/api/v1/host/test", False),
("PUT", "/api/v1/host", True),
])
def test_internal_probe_and_save_use_trusted_stable_host_scope(
host_app, existing, method, path, ensure):
with host_app(existing=existing) as app:
response = app.client.request(method, path, json=HOST_BODY)
assert response.status_code == 200, response.text
assert [call[1:] for call in app.opened] == (
[("7", LIBVIRT_MUTATION_BUDGET), ("7", LIBVIRT_READ_BUDGET)]
if ensure else [("7", LIBVIRT_READ_BUDGET)]
)
assert app.locks == ([("storage:7",)] if ensure else [])
assert all(type(service) is VMService for service in app.services)
assert all(service.execution_scope == "7" for service in app.services)
assert all(service._resource_scope == "7" for service in app.services)
assert len(app.closed) == len(app.opened)
actions = [call[0] for call in app.manager.calls]
assert ("commit" in actions) is ensure
assert ("abort" in actions) is not ensure
def test_staged_uri_changes_and_saved_service_share_execution_scope(host_app):
with host_app() as app:
for method, path in (("POST", "/api/v1/host/test"),
("PUT", "/api/v1/host")):
response = app.client.request(method, path, json=HOST_BODY)
assert response.status_code == 200, response.text
response = app.client.get("/api/v1/resources")
assert response.status_code == 200, response.text
assert len({uri for uri, _scope, _timeout in app.opened}) == 3
assert {scope for _uri, scope, _timeout in app.opened} == {"7"}
assert app.locks == [("storage:7",)]
@pytest.mark.parametrize("host_id", [None, "", "bad/id", "a" * 65, 7, True])
@pytest.mark.parametrize("method,path", [
("POST", "/api/v1/host/test"), ("PUT", "/api/v1/host"),
])
def test_internal_invalid_identity_fails_closed_before_libvirt(
host_app, host_id, method, path):
with host_app(host_id=host_id) as app:
response = app.client.request(method, path, json=HOST_BODY)
assert response.status_code == 409, response.text
assert app.opened == []
assert app.services == []
assert app.manager.current() is None
assert [call[0] for call in app.manager.calls] == ["stage", "test", "abort"]
@pytest.mark.parametrize("ensure", [False, True])
def test_standalone_probe_uses_verified_identity_hash(host_app, ensure):
with host_app(internal=False) as app:
method, path = (("PUT", "/api/v1/host") if ensure
else ("POST", "/api/v1/host/test"))
response = app.client.request(method, path, json=HOST_BODY, headers=app.headers)
assert response.status_code == 200, response.text
scope = host_scope({"host": HOST_BODY["host"], "port": HOST_BODY["port"],
"fingerprint": HOST_BODY["confirmed_fingerprint"]})
assert {call[1] for call in app.opened} == {scope}
assert app.locks == ([(f"storage:{scope}",)] if ensure else [])
@pytest.mark.parametrize("method,path", [
("POST", "/api/v1/host/test"), ("PUT", "/api/v1/host"),
])
def test_request_cannot_choose_execution_host_id(host_app, method, path):
with host_app() as app:
response = app.client.request(method, path, json={
**HOST_BODY, "host_id": "another-host",
})
assert response.status_code == 422, response.text
assert app.opened == []
assert app.manager.calls == []
def test_named_pools_without_rescue_skip_ensure_paths(host_app):
with host_app() as app:
response = app.client.put("/api/v1/host", json={**HOST_BODY, "rescue_iso_pool": ""})
assert response.status_code == 200, response.text
assert [call[1:] for call in app.opened] == [("7", LIBVIRT_READ_BUDGET)]
assert app.locks == []
@pytest.mark.parametrize("existing", [False, True], ids=["add", "edit"])
def test_storage_validation_failure_aborts_without_replacing_profile(
host_app, monkeypatch, existing):
def unavailable(*_args):
raise VMError("storage unavailable", 502)
monkeypatch.setattr(VMService, "_ensure_pool", unavailable)
with host_app(existing=existing) as app:
original = app.manager.current()
response = app.client.put("/api/v1/host", json=HOST_BODY)
assert response.status_code == 502, response.text
assert app.manager.current() is original
assert [call[0] for call in app.manager.calls] == ["stage", "test", "abort"]
assert [call[1:] for call in app.opened] == [("7", LIBVIRT_MUTATION_BUDGET)]
assert len(app.closed) == 1
def test_signed_save_with_missing_identity_releases_durable_claim(boundary, monkeypatch):
client, engine, _store, _logs, services = boundary
path = "/internal/v1/hosts/hk/host"
assert call(client, "GET", path, SUPER).status_code == 200
manager = engine.registry.components["hk"].manager
manager.host_id = None
manager.profile = None
services["hk"].calls.clear()
assert engine.coordinator.snapshot() == {}
observed_claims = []
remote_test = manager.test
def inspect_admission(staged):
observed_claims.extend(engine.coordinator.snapshot().values())
return remote_test(staged)
monkeypatch.setattr(manager, "test", inspect_admission)
response = call(client, "PUT", path, SUPER, HOST_BODY)
assert response.status_code == 409, response.text
assert [entry[0] for entry in manager.calls] == ["stage", "test", "abort"]
assert manager.current() is None
assert services["hk"].calls == []
assert len(observed_claims) == 1
assert observed_claims[0]["state"] == "active"
assert observed_claims[0]["kind"] == "request"
assert engine.coordinator.snapshot() == {}

@ -2417,7 +2417,7 @@ def create_app(
except ResourceLockTimeout as exc:
raise TemplateError("救援模版正在使用,请稍后重试", 409) from exc
def new_service(profile: dict) -> VMService:
def new_service(profile: dict, *, execution_scope: str | None = None) -> VMService:
if service_factory is not None:
return service_factory(profile)
return VMService(
@ -2426,7 +2426,8 @@ def create_app(
profile["iso_pool"],
profile["default_network"],
rescue_iso_pool=profile.get("rescue_iso_pool", ""),
execution_scope=profile.get("host_id") or host_scope(profile),
execution_scope=(execution_scope if execution_scope is not None
else profile.get("host_id") or host_scope(profile)),
)
def verified_created_vm(profile: dict, result: dict, requested_uuid: str) -> dict:
@ -2451,13 +2452,27 @@ def create_app(
def validate_staged_libvirt(
staged, body: HostBody, *, ensure_paths: bool = False,
) -> tuple[dict | None, str | None]:
# A staged URI identifies temporary SSH files, not a new host. Keep
# registration on the same executor/storage lane as saved VM work,
# including first registration when manager.current() is still empty.
if internal_mode:
execution_scope = getattr(manager, "host_id", None)
if (not isinstance(execution_scope, str)
or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", execution_scope) is None):
# No libvirt write has started: reject the precondition
# without retaining an ambiguous execution claim.
raise VMError("宿主机执行身份不可用,请核对引擎配置", 409)
else:
execution_scope = host_scope({
key: staged.metadata[key] for key in ("host", "port", "fingerprint")
})
service = new_service({
"libvirt_uri": staged.libvirt_uri,
"storage_pool": body.storage_pool,
"iso_pool": body.iso_pool,
"rescue_iso_pool": body.rescue_iso_pool,
"default_network": body.default_network,
})
}, execution_scope=execution_scope)
# Validate only host-owned storage/network resources here. Host save
# and connection testing must never enumerate every guest domain;
# capacity and IP scheduling are panel-owned and VM operations use

Loading…
Cancel
Save