You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/engine/tests/test_fabric_retained_operat...

452 lines
24 KiB
Python

"""Explicit recovery proves the exact old host jobs stopped before claim handoff."""
import asyncio
import hashlib
import json
import os
from pathlib import Path
import shlex
import subprocess
import threading
import pytest
from virsh_panel.coordination import (
CoordinationClaimRejected, CoordinationError, DurableCoordinator,
current_execution, execution_context,
)
from virsh_panel.fabric import (
FabricCoordinator, FabricError, FabricHostAdapter,
_fabric_operation_terminal_proof_script,
)
from virsh_panel.internal import _DurableAsyncLock
from test_durable_fabric_jobs import FabricStore
from test_fabric import (
AsyncCoordinatorAdapter, Registry, _active_fabric_record, _async_components,
_reconcile_observation, _remote_operation_status, plan,
)
OLD_ID = "a" * 32
SCOPE = ["catalog:network", "fabric:hk-fabric"]
class RecoveryAdapter(AsyncCoordinatorAdapter):
def terminal_operation_proof(self, operation_id, digest):
assert operation_id == OLD_ID and digest == plan().digest
self.manager.proof_calls += 1
if self.manager.proof_error:
raise self.manager.proof_error
return _remote_operation_status(operation_id, self.manager.proof_status)
def observe(self, current, host, keys):
result = super().observe(current, host, keys)
if self.manager.async_dispatch_calls == 0 and self.manager.old_readback_mismatch:
result.update(state="degraded", config_ok=False, transport_verified=False)
return result
def retained_fixture(monkeypatch, *, store=None):
current = plan()
store = store or FabricStore()
owner = DurableCoordinator(store)
catalog = _DurableAsyncLock(owner, ("catalog:network",))
components = _async_components(current)
for component in components.values():
component.manager.proof_calls = 0
component.manager.proof_status = "succeeded"
component.manager.proof_error = None
component.manager.old_readback_mismatch = True
fabric = FabricCoordinator(store, Registry(components), catalog_lock=lambda: catalog)
desired = _active_fabric_record(current)
desired["operation"] = fabric._new_root_operation(OLD_ID, "reconcile", 100)
desired["operation"].update(status="uncertain", started_at=101, finished_at=103)
for node in desired["nodes"]:
node["operation"] = fabric._new_node_operation(OLD_ID, "apply", 100)
node["operation"].update(status="uncertain", started_at=101, finished_at=103)
fabric._invalidate(desired)
fabric._save("fabric_desired", current.fabric_id, desired)
previous_owner = DurableCoordinator(store)
old = previous_owner.claim(
operation_id=OLD_ID, resources=SCOPE, kind="background",
metadata={"job_kind": "fabric_operation", "job_id": OLD_ID})
assert previous_owner.retain(old)
monkeypatch.setattr("virsh_panel.fabric.FabricHostAdapter", RecoveryAdapter)
monkeypatch.setattr("virsh_panel.fabric.FABRIC_OPERATION_POLL_INTERVAL_SECONDS", 0)
return store, owner, fabric, components, old
@pytest.mark.parametrize("old_status", ["succeeded", "failed"])
@pytest.mark.parametrize("mismatch", [False, True])
def test_explicit_terminal_recovery_closes_old_receipt_and_transfers_new_job(
monkeypatch, old_status, mismatch):
async def run():
store, owner, fabric, components, old = retained_fixture(monkeypatch)
for component in components.values():
component.manager.proof_status = old_status
component.manager.old_readback_mismatch = mismatch
parent = owner.claim(kind="request")
try:
with execution_context(owner, parent):
result = await fabric.enqueue_reconcile("hk-fabric")
assert result["operation"]["id"] != OLD_ID
current = fabric._load("fabric_desired", "hk-fabric")
receipt = current["reconciled_operation"]
assert receipt["operation"]["id"] == OLD_ID
assert receipt["operation"]["status"] == "failed"
assert all(node["remote_status"] == old_status for node in receipt["nodes"])
assert all(node["operation"]["status"] == receipt["operation"]["status"]
for node in receipt["nodes"])
assert receipt["claim_token"] == old.token
row = json.loads(store.get("coordination", "admission-v1"))
assert len(row["resolutions"]) == 1
assert row["resolutions"][0]["operation_id"] == OLD_ID
assert old.token not in row["claims"]
children = [claim for claim in row["claims"].values() if claim["kind"] == "background"]
assert len(children) == 1
assert children[0]["operation_id"] == result["operation"]["id"]
with pytest.raises(CoordinationClaimRejected):
DurableCoordinator(store).claim(maintenance=True, kind="update")
assert owner.release(parent)
await asyncio.wait_for(asyncio.gather(*tuple(fabric._operation_tasks)), 2)
assert owner.snapshot() == {}
assert all(component.manager.proof_calls == 1 for component in components.values())
assert all(component.manager.async_dispatch_calls == int(mismatch)
for component in components.values())
finally:
await fabric.shutdown_operations()
fabric.close()
asyncio.run(run())
@pytest.mark.parametrize("mutation", [
"active", "other_operation", "extra_resource", "wrong_kind", "wrong_job", "maintenance",
"extra_claim", "node_id", "node_phase", "node_checkpoint", "node_pending", "root_digest",
"root_kind", "root_status", "root_times", "host_profile",
"running_proof", "queued_proof", "uncertain_proof", "proof_failure",
])
def test_unproven_or_different_owner_is_never_resolved(monkeypatch, mutation):
async def run():
store, owner, fabric, components, old = retained_fixture(monkeypatch)
doc = json.loads(store.get("coordination", "admission-v1"))
claim = doc["claims"][old.token]
if mutation == "active": claim["state"] = "active"
elif mutation == "other_operation": claim["operation_id"] = "b" * 32
elif mutation == "extra_resource": claim["resources"].append("host:host-a")
elif mutation == "wrong_kind": claim["kind"] = "resource"
elif mutation == "wrong_job": claim["metadata"]["job_kind"] = "other_job"
elif mutation == "maintenance": claim["maintenance"] = True
elif mutation == "extra_claim":
extra = {**claim, "token": "d" * 64, "execution_id": "e" * 64}
doc["claims"][extra["token"]] = extra
store.set("coordination", "admission-v1", json.dumps(doc))
desired = fabric._load("fabric_desired", "hk-fabric")
node = desired["nodes"][1]["operation"]
if mutation == "node_id": node["id"] = "b" * 32
elif mutation == "node_phase": node["phase"] = "unknown"
elif mutation == "node_checkpoint": node["checkpoint"] = "unknown"
elif mutation == "node_pending": node.update(phase="identity", checkpoint="dispatch", status="pending")
elif mutation == "root_digest": desired["plan_digest"] = "0" * 64
elif mutation == "root_kind": desired["operation"]["kind"] = "other"
elif mutation == "root_status": desired["operation"]["status"] = "other"
elif mutation == "root_times": desired["operation"]["created_at"] = True
elif mutation == "host_profile": components["host-b"].manager.profile["host_id"] = "host-c"
fabric._save("fabric_desired", "hk-fabric", desired)
manager = components["host-b"].manager
if mutation.endswith("_proof"): manager.proof_status = mutation[:-6]
elif mutation == "proof_failure":
manager.proof_error = FabricError("unsafe private stderr", 502, "fabric_operation_status_invalid")
# Maintenance admission itself rejects the new request before it exists.
if mutation == "maintenance":
with pytest.raises(CoordinationClaimRejected): owner.claim(kind="request")
assert owner.snapshot()[old.token]["state"] == "uncertain"
fabric.close()
return
parent = owner.claim(kind="request")
before = store.get("fabric_desired", "hk-fabric")
try:
with execution_context(owner, parent), pytest.raises((FabricError, CoordinationError)):
await fabric.enqueue_reconcile("hk-fabric")
assert store.get("fabric_desired", "hk-fabric") == before
assert old.token in owner.snapshot()
assert json.loads(store.get("coordination", "admission-v1"))["resolutions"] == []
assert not fabric._operation_tasks
assert all(component.manager.async_dispatch_calls == 0 for component in components.values())
finally:
owner.release(parent)
fabric.close()
asyncio.run(run())
def test_periodic_observation_keeps_retained_claim_and_does_not_probe_or_dispatch(monkeypatch):
async def run():
store, owner, fabric, components, old = retained_fixture(monkeypatch)
before = store.get("fabric_desired", "hk-fabric")
await fabric.reconcile_all()
assert store.get("fabric_desired", "hk-fabric") == before
assert list(owner.snapshot()) == [old.token]
assert all(component.manager.proof_calls == 0 and component.manager.async_dispatch_calls == 0
for component in components.values())
fabric.close()
asyncio.run(run())
@pytest.mark.parametrize("change", ["metadata", "updated_at", "resources"])
def test_atomic_handoff_rejects_stale_claim_snapshot_without_resolution(change):
store = FabricStore()
old_owner, new_owner = DurableCoordinator(store), DurableCoordinator(store)
old = old_owner.claim(operation_id=OLD_ID, resources=SCOPE, kind="background")
old_owner.retain(old)
snapshot = new_owner.snapshot()[old.token]
if change == "metadata": old_owner.update_metadata(old, {"later": True})
elif change == "updated_at":
doc = json.loads(store.get("coordination", "admission-v1"))
doc["claims"][old.token]["updated_at"] += 1
store.set("coordination", "admission-v1", json.dumps(doc))
else:
doc = json.loads(store.get("coordination", "admission-v1"))
doc["claims"][old.token]["resources"].append("host:host-a")
store.set("coordination", "admission-v1", json.dumps(doc))
with pytest.raises(CoordinationClaimRejected):
new_owner.resolve_and_claim(snapshot, "terminal proof", execution_id="f" * 64)
doc = json.loads(store.get("coordination", "admission-v1"))
assert old.token in doc["claims"] and doc["resolutions"] == []
def test_every_atomic_commit_preserves_fence_and_failed_handoff_stays_exclusive(monkeypatch):
class InspectStore(FabricStore):
inspect = False
def compare_and_set(self, kind, key, expected, desired):
if self.inspect and kind == "coordination":
claims = json.loads(desired)["claims"].values()
assert any(set(SCOPE) <= set(row["resources"]) for row in claims)
return super().compare_and_set(kind, key, expected, desired)
async def run():
store = InspectStore()
store, owner, fabric, _components, old = retained_fixture(monkeypatch, store=store)
parent = owner.claim(kind="request")
store.inspect = True
original_save = fabric._save
def fail_terminal(kind, key, value):
if kind == "fabric_desired" and "reconciled_operation" in value:
raise RuntimeError("injected persistence failure")
return original_save(kind, key, value)
monkeypatch.setattr(fabric, "_save", fail_terminal)
try:
with execution_context(owner, parent), pytest.raises(RuntimeError):
await fabric.enqueue_reconcile("hk-fabric")
assert old.token not in owner.snapshot()
replacement = next(row for row in owner.snapshot().values() if row["resources"] == SCOPE)
assert replacement["state"] == "uncertain" and replacement["resources"] == SCOPE
with pytest.raises(CoordinationClaimRejected):
DurableCoordinator(store).claim(resources=("catalog:network",))
assert fabric._load("fabric_desired", "hk-fabric")["operation"]["id"] == OLD_ID
finally:
owner.release(parent)
fabric.close()
asyncio.run(run())
def test_lost_atomic_handoff_response_keeps_replacement_fence(monkeypatch):
class LostReplyStore(FabricStore):
lose_reply = False
def compare_and_set(self, kind, key, expected, desired):
committed = super().compare_and_set(kind, key, expected, desired)
if committed and self.lose_reply and kind == "coordination" and json.loads(desired)["resolutions"]:
self.lose_reply = False
raise RuntimeError("CAS committed, reply lost")
return committed
async def run():
store, owner, fabric, _components, old = retained_fixture(monkeypatch, store=LostReplyStore())
parent = owner.claim(kind="request")
store.lose_reply = True
try:
with execution_context(owner, parent), pytest.raises(CoordinationError) as raised:
await fabric.enqueue_reconcile("hk-fabric")
assert raised.value.error_code == "coordination_unavailable"
rows = owner.snapshot()
assert old.token not in rows
assert any(row["resources"] == SCOPE for row in rows.values())
assert fabric._load("fabric_desired", "hk-fabric")["operation"]["id"] == OLD_ID
assert not fabric._operation_tasks
with pytest.raises(CoordinationClaimRejected):
DurableCoordinator(store).claim(maintenance=True, kind="update")
finally:
owner.release(parent)
fabric.close()
asyncio.run(run())
@pytest.mark.parametrize("phase", ["proof", "handoff", "new_owner"])
def test_cancellation_cannot_release_fence_before_host_proof_or_new_owner(monkeypatch, phase):
async def run():
store, owner, fabric, components, old = retained_fixture(monkeypatch)
entered, resume = threading.Event(), threading.Event()
original_proof = RecoveryAdapter.terminal_operation_proof
original_handoff = owner.resolve_and_claim
original_claim = owner.claim
def block_proof(adapter, operation_id, digest):
if phase == "proof" and adapter.manager.host_id == "host-a":
entered.set(); assert resume.wait(3)
return original_proof(adapter, operation_id, digest)
def block_handoff(*args, **kwargs):
result = original_handoff(*args, **kwargs)
if phase == "handoff": entered.set(); assert resume.wait(3)
return result
def block_child(**kwargs):
result = original_claim(**kwargs)
if phase == "new_owner" and kwargs.get("kind") == "background":
entered.set(); assert resume.wait(3)
return result
monkeypatch.setattr(RecoveryAdapter, "terminal_operation_proof", block_proof)
monkeypatch.setattr(owner, "resolve_and_claim", block_handoff)
monkeypatch.setattr(owner, "claim", block_child)
parent = owner.claim(kind="request")
with execution_context(owner, parent): task = asyncio.create_task(fabric.enqueue_reconcile("hk-fabric"))
try:
for _ in range(300):
if entered.is_set(): break
await asyncio.sleep(.002)
assert entered.is_set()
task.cancel()
await asyncio.sleep(.01)
with pytest.raises(CoordinationClaimRejected):
DurableCoordinator(store).claim(maintenance=True, kind="update")
resume.set()
with pytest.raises(asyncio.CancelledError): await task
if phase == "proof":
assert old.token in owner.snapshot()
assert not fabric._operation_tasks
else:
assert old.token not in owner.snapshot()
await asyncio.gather(*tuple(fabric._operation_tasks))
assert not any(row["kind"] == "resource" for row in owner.snapshot().values())
owner.release(parent)
finally:
resume.set()
await fabric.shutdown_operations()
fabric.close()
asyncio.run(run())
def _proof_shell_fixture(tmp_path, *, status="succeeded", unit=None, drift=None):
base = tmp_path / "virt-cloud"
root = base / "fabric-operations"
operation = root / OLD_ID
operation.mkdir(parents=True)
for path in (base, root, operation): path.chmod(0o700)
digests = []
for name in ("apply", "update", "runner"):
path = operation / name
path.write_text(f"#!/bin/sh\n# {name}\nexit 0\n")
path.chmod(0o700)
digests.append(hashlib.sha256(path.read_bytes()).hexdigest())
manifest = operation / "manifest"
manifest.write_text("\n".join(("schema=1", f"operation_id={OLD_ID}",
f"plan_digest={plan().digest}", f"script_digest={digests[0]}",
f"update_digest={digests[1]}", f"runner_digest={digests[2]}", "created_at=100", "")))
manifest.chmod(0o600)
receipt = operation / "status"
receipt.write_text("\n".join(("schema=1", f"operation_id={OLD_ID}", f"status={status}",
"phase=apply", f"checkpoint={'complete' if status == 'succeeded' else 'preflight'}",
f"reason={'none' if status in {'succeeded', 'running', 'queued'} else 'command_failed'}",
"created_at=100", "started_at=101", "updated_at=103", "finished_at=103", "")))
receipt.chmod(0o600)
tools = tmp_path / "tools"
tools.mkdir()
# Root UID is simulated; mode and symlink checks exercise the actual spool.
stat = tools / "stat"
stat.write_text("#!/usr/bin/env python3\nimport os,stat,sys\ns=os.lstat(sys.argv[-1]); print('0:'+format(stat.S_IMODE(s.st_mode),'o'))\n")
sha = tools / "sha256sum"
sha.write_text("#!/usr/bin/env python3\nimport hashlib,sys\nfor p in sys.argv[1:]:\n print(hashlib.sha256(open(p,'rb').read()).hexdigest()+' '+p)\n")
systemctl = tools / "systemctl"
if unit is None:
unit = {"LoadState": "loaded", "ActiveState": "inactive", "SubState": "dead",
"Result": "success", "ExecMainCode": "1", "ExecMainStatus": "0",
"MainPID": "0", "Job": ""}
unit_path = tmp_path / "unit.json"
unit_path.write_text(json.dumps(unit))
control = f'''#!/usr/bin/env python3
import json,pathlib,sys
assert sys.argv[1]=='show'
log=pathlib.Path({str(tmp_path / 'calls')!r})
count=len(log.read_text().splitlines()) if log.exists() else 0
with log.open('a') as f: f.write('show\\n')
unit=json.loads(pathlib.Path({str(unit_path)!r}).read_text())
if count and {drift!r}=='unit': unit['Job']='45/run'
if count and {drift!r}=='artifact': pathlib.Path({str(operation / 'apply')!r}).write_text('changed')
if count and {drift!r}=='mode': pathlib.Path({str(operation / 'runner')!r}).chmod(0o755)
if not count and {drift!r}=='status':
p=pathlib.Path({str(operation / 'status')!r}); p.write_text(p.read_text().replace('status=succeeded','status=running'))
if not count and {drift!r}=='manifest':
p=pathlib.Path({str(manifest)!r}); p.write_text(p.read_text().replace({plan().digest!r},'0'*64))
for k,v in unit.items(): print(k+'='+v)
'''
systemctl.write_text(control)
for path in (stat, sha, systemctl): path.chmod(0o700)
script = _fabric_operation_terminal_proof_script(OLD_ID, plan().digest)
script = script.replace("/run/virt-cloud", str(base))
script = script.replace("PATH=/usr/sbin:/usr/bin:/sbin:/bin", f"PATH={shlex.quote(str(tools))}:" + os.environ["PATH"])
return script, operation, base, root
@pytest.mark.parametrize("shell", ["/bin/sh", "/bin/bash"])
@pytest.mark.parametrize("variant", ["success", "failed", "collected_success", "collected_failed"])
def test_real_terminal_proof_accepts_only_stopped_same_plan_spool(tmp_path, shell, variant):
failed = variant.endswith("failed")
unit = {"LoadState": "not-found" if variant.startswith("collected") else "loaded",
"ActiveState": "inactive" if variant.startswith("collected") or not failed else "failed",
"SubState": "dead" if variant.startswith("collected") or not failed else "failed",
"Result": "success" if variant.startswith("collected") or not failed else "exit-code",
"ExecMainCode": "0" if variant.startswith("collected") else "1",
"ExecMainStatus": "1" if failed and not variant.startswith("collected") else "0",
"MainPID": "0", "Job": ""}
script, *_ = _proof_shell_fixture(tmp_path, status="failed" if failed else "succeeded", unit=unit)
result = subprocess.run([shell], input=script, text=True, capture_output=True)
assert result.returncode == 0, result.stderr
adapter = object.__new__(FabricHostAdapter)
adapter._run = lambda *_args, **_kwargs: result.stdout
assert adapter.terminal_operation_proof(OLD_ID, plan().digest)["status"] == ("failed" if failed else "succeeded")
assert (tmp_path / "calls").read_text().splitlines() == ["show", "show"]
@pytest.mark.parametrize("mutation", [
"running", "queued", "uncertain", "interrupted", "active_unit", "job", "pid", "unknown_load",
"wrong_result", "wrong_exit", "unit_drift", "artifact_drift", "mode_drift", "status_drift",
"manifest_drift", "plan", "hash",
"parent_symlink", "parent_mode", "root_symlink", "root_mode", "extra_file", "artifact_symlink",
"status_symlink", "manifest_mode", "status_mode", "operation_mode", "missing_manifest",
])
def test_real_terminal_proof_rejects_live_unknown_or_drifting_evidence(tmp_path, mutation):
unit = {"LoadState": "loaded", "ActiveState": "inactive", "SubState": "dead",
"Result": "success", "ExecMainCode": "1", "ExecMainStatus": "0", "MainPID": "0", "Job": ""}
if mutation == "active_unit": unit.update(ActiveState="active", SubState="running")
elif mutation == "job": unit["Job"] = "42/start"
elif mutation == "pid": unit["MainPID"] = "123"
elif mutation == "unknown_load": unit["LoadState"] = "error"
elif mutation == "wrong_result": unit["Result"] = "exit-code"
elif mutation == "wrong_exit": unit["ExecMainCode"] = "0"
script, operation, base, root = _proof_shell_fixture(
tmp_path, status=mutation if mutation in {"running", "queued", "uncertain", "interrupted"} else "succeeded",
unit=unit, drift=mutation[:-6] if mutation.endswith("_drift") else None)
if mutation == "plan":
manifest = operation / "manifest"
manifest.write_text(manifest.read_text().replace(plan().digest, "0" * 64))
elif mutation == "hash": (operation / "apply").write_text("changed")
elif mutation == "extra_file": (operation / ".hidden").write_text("extra")
elif mutation in {"artifact_symlink", "status_symlink"}:
path = operation / ("apply" if mutation == "artifact_symlink" else "status")
target = tmp_path / "target"; target.write_bytes(path.read_bytes()); path.unlink(); path.symlink_to(target)
elif mutation.endswith("_mode"):
path = {"parent_mode": base, "root_mode": root, "manifest_mode": operation / "manifest",
"status_mode": operation / "status", "operation_mode": operation}[mutation]
path.chmod(0o755)
elif mutation in {"parent_symlink", "root_symlink"}:
path = base if mutation == "parent_symlink" else root
target = path.with_name(path.name + "-real"); path.rename(target); path.symlink_to(target)
elif mutation == "missing_manifest": (operation / "manifest").unlink()
result = subprocess.run(["/bin/sh"], input=script, text=True, capture_output=True)
assert result.returncode != 0, result.stdout