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/virsh_panel/coordination.py

593 lines
26 KiB
Python

"""Durable mutation admission shared by engine workers.
Only the small admission record is changed under a database CAS. No database
transaction remains open during host work. Claims have no lease expiry: an
absent worker, cancelled request or old timestamp cannot prove that remote work
has stopped. Uncertain claims require explicit reconciliation.
"""
from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass, field
import json
import re
import secrets
import threading
import time
from typing import Any, Mapping
RECORD_KIND = "coordination"
RECORD_KEY = "admission-v1"
_IDENTIFIER = re.compile(r"[A-Za-z0-9_.:-]{1,191}\Z")
_TOKEN = re.compile(r"[A-Za-z0-9_-]{16,128}\Z")
_KIND = re.compile(r"[a-z][a-z0-9_-]{0,63}\Z")
_UNKNOWN_CODES = frozenset({
"libvirt_execution_uncertain", "libvirt_execution_blocked",
"coordination_uncertain", "operation_uncertain",
})
_SAFE_EXECUTION_CODES = frozenset({
"libvirt_execution_timeout", "libvirt_execution_stopped",
})
class CoordinationError(Exception):
def __init__(self, error_code: str, status: int = 409):
messages = {
"coordination_busy": "资源正由其他任务占用,请稍后查询原操作",
"coordination_uncertain": "已有执行结果未确认的任务,请先核对原操作",
"coordination_unavailable": "无法确认持久执行占用,已拒绝新的修改",
}
super().__init__(messages.get(error_code, messages["coordination_unavailable"]))
self.error_code = error_code
self.status = status
class CoordinationAdmissionRejected(CoordinationError):
"""A confirmed admission conflict before this claim can dispatch work.
The old blocking claim remains authoritative; this exception only proves
that the rejected execution did not start its own remote mutation.
"""
class CoordinationClaimRejected(CoordinationAdmissionRejected):
"""A conflicting claim was observed without committing a new claim."""
@dataclass(frozen=True)
class Claim:
token: str
execution_id: str
owner_id: str
operation_id: str | None = None
resources: tuple[str, ...] = ()
kind: str = "request"
metadata: dict = field(default_factory=dict, compare=False, repr=False)
@dataclass(frozen=True)
class ExecutionContext:
coordinator: DurableCoordinator
claim: Claim
# Shared by nested claims and copied thread contexts for this execution.
# A later connection failure cannot erase an earlier session's writes.
remote_write_started: threading.Event = field(default_factory=threading.Event,
compare=False, repr=False)
connection_failure_safe: bool = False
# Opt in only where every remote mutation passes the RPC write hook.
# In particular, this is not implied by read-only SSH connection probes.
tracked_mutations: bool = False
admission_rejected: threading.Event = field(default_factory=threading.Event,
compare=False, repr=False)
execution_unknown: threading.Event = field(default_factory=threading.Event,
compare=False, repr=False)
_CURRENT_EXECUTION: ContextVar[ExecutionContext | None] = ContextVar(
"cloud_durable_execution", default=None)
_default_coordinator: DurableCoordinator | None = None
_default_lock = threading.Lock()
def _encode(value: Any) -> str:
return json.dumps(value, ensure_ascii=True, allow_nan=False,
separators=(",", ":"), sort_keys=True)
def _identity(claim: Claim | Mapping[str, Any]) -> tuple[str, str, str]:
values = ((claim.token, claim.execution_id, claim.owner_id)
if isinstance(claim, Claim) else
(claim.get("token"), claim.get("execution_id"), claim.get("owner_id")))
if any(not isinstance(value, str) or not _TOKEN.fullmatch(value) for value in values):
raise ValueError("Invalid coordination claim identity")
return values
def _resources(values) -> tuple[str, ...]:
if isinstance(values, (str, bytes)):
raise ValueError("Coordination resources must be a sequence")
result = tuple(sorted(set(values)))
if any(not isinstance(value, str) or not 1 <= len(value) <= 512
or any(ord(char) < 33 or ord(char) > 126 for char in value)
for value in result):
raise ValueError("Invalid coordination resource")
return result
class DurableCoordinator:
def __init__(self, store, *, owner_id: str | None = None, cas_attempts: int = 32,
max_claims: int = 1024):
if not all(callable(getattr(store, method, None)) for method in
("get", "insert", "compare_and_set")):
raise ValueError("Durable coordination requires atomic database CAS")
self.store = store
self.owner_id = owner_id or secrets.token_hex(32)
if not isinstance(self.owner_id, str) or not _TOKEN.fullmatch(self.owner_id):
raise ValueError("Invalid coordination owner")
if isinstance(cas_attempts, bool) or not isinstance(cas_attempts, int) or cas_attempts < 1:
raise ValueError("Invalid coordination retry bound")
self.cas_attempts = cas_attempts
if isinstance(max_claims, bool) or not isinstance(max_claims, int) or max_claims < 1:
raise ValueError("Invalid coordination capacity")
self.max_claims = max_claims
@staticmethod
def _decode(raw: str) -> dict:
try:
document = json.loads(raw)
if (not isinstance(document, dict) or document.get("version") != 1
or isinstance(document.get("version"), bool)
or isinstance(document.get("revision"), bool)
or not isinstance(document.get("revision"), int)
or document["revision"] < 0
or not isinstance(document.get("claims"), dict)
or not isinstance(document.get("resolutions", []), list)):
raise ValueError("Invalid coordination document")
for token, record in document["claims"].items():
if (not isinstance(record, dict) or _identity(record)[0] != token
or record.get("state") not in {"active", "uncertain"}
or not isinstance(record.get("maintenance"), bool)
or not isinstance(record.get("kind"), str)
or not _KIND.fullmatch(record["kind"])
or not isinstance(record.get("metadata"), dict)
or record.get("operation_id") is not None and (
not isinstance(record["operation_id"], str)
or not _IDENTIFIER.fullmatch(record["operation_id"]))
or list(_resources(record.get("resources", ()))) != record.get("resources")
or any(isinstance(record.get(field), bool)
or not isinstance(record.get(field), int)
or record[field] < 0
for field in ("created_at", "updated_at"))):
raise ValueError("Invalid coordination claim")
return document
except (TypeError, ValueError, AttributeError, KeyError):
raise CoordinationError("coordination_unavailable", 503) from None
def _read(self) -> tuple[str, dict]:
try:
raw = self.store.get(RECORD_KIND, RECORD_KEY)
if raw is None:
empty = _encode({"version": 1, "revision": 0, "claims": {}, "resolutions": []})
# Insert first so competing CAS transactions lock a real row,
# rather than racing inserts beneath missing-key gap locks.
self.store.insert(RECORD_KIND, RECORD_KEY, empty)
raw = self.store.get(RECORD_KIND, RECORD_KEY)
if raw is None:
raise CoordinationError("coordination_unavailable", 503)
return raw, self._decode(raw)
except CoordinationError:
mark_execution_unknown()
raise
except Exception:
mark_execution_unknown()
raise CoordinationError("coordination_unavailable", 503) from None
def _change(self, mutate):
for _attempt in range(self.cas_attempts):
raw, document = self._read()
try:
changed, result = mutate(document)
except CoordinationAdmissionRejected:
mark_admission_rejected()
raise
except CoordinationError:
mark_execution_unknown()
raise
if not changed:
return result
document["revision"] += 1
try:
if self.store.compare_and_set(RECORD_KIND, RECORD_KEY, raw, _encode(document)):
return result
except Exception:
# A lost commit response may still have installed this claim.
# Do not fall back to an in-memory lock or assume rollback.
mark_execution_unknown()
raise CoordinationError("coordination_unavailable", 503) from None
mark_execution_unknown()
raise CoordinationError("coordination_unavailable", 503)
def claim(self, operation_id: str | None = None, resources=(), maintenance: bool = False,
execution_id: str | None = None, kind: str = "request", metadata=None) -> Claim:
resources = _resources(resources)
if operation_id is not None and (
not isinstance(operation_id, str) or not _IDENTIFIER.fullmatch(operation_id)):
raise ValueError("Invalid coordination operation")
execution_id = execution_id or secrets.token_hex(32)
if (not isinstance(execution_id, str) or not _TOKEN.fullmatch(execution_id)
or execution_id in {operation_id, self.owner_id}):
raise ValueError("Execution identity must be an independent random token")
if not isinstance(maintenance, bool) or not isinstance(kind, str) or not _KIND.fullmatch(kind):
raise ValueError("Invalid coordination claim kind")
if metadata is None:
metadata = {}
if not isinstance(metadata, Mapping):
raise ValueError("Invalid coordination metadata")
metadata = json.loads(_encode(dict(metadata)))
if len(_encode(metadata)) > 8192:
raise ValueError("Coordination metadata is too large")
token = secrets.token_hex(32)
now = int(time.time())
record = {
"token": token, "execution_id": execution_id, "owner_id": self.owner_id,
"operation_id": operation_id, "resources": list(resources),
"maintenance": maintenance, "kind": kind, "metadata": metadata,
"state": "active", "created_at": now, "updated_at": now,
}
claim = Claim(token, execution_id, self.owner_id, operation_id, resources,
kind, json.loads(_encode(metadata)))
def mutate(document):
if len(document["claims"]) >= self.max_claims:
raise CoordinationClaimRejected("coordination_busy", 409)
conflicts = []
for existing in document["claims"].values():
conflict = (
maintenance or existing["maintenance"]
or (existing["state"] == "uncertain"
or existing["execution_id"] != execution_id)
and (operation_id is not None and existing["operation_id"] == operation_id
or bool(set(resources).intersection(existing["resources"])))
)
if conflict:
conflicts.append(existing)
if conflicts:
unknown = any(existing["state"] == "uncertain" for existing in conflicts)
raise CoordinationClaimRejected(
"coordination_uncertain" if unknown else "coordination_busy",
503 if unknown else 409)
document["claims"][token] = record
return True, claim
return self._change(mutate)
@staticmethod
def _owned(document, claim):
token, execution_id, owner_id = _identity(claim)
current = document["claims"].get(token)
if current is None or (current["execution_id"], current["owner_id"]) != (execution_id, owner_id):
return None
return current
def release(self, claim: Claim | Mapping[str, Any]) -> bool:
def mutate(document):
current = self._owned(document, claim)
if current is None or current["state"] != "active":
return False, False
del document["claims"][current["token"]]
return True, True
return self._change(mutate)
def retain(self, claim: Claim | Mapping[str, Any], reason_code: str = "operation_uncertain") -> bool:
if not isinstance(reason_code, str) or not _IDENTIFIER.fullmatch(reason_code):
raise ValueError("Invalid coordination reason code")
def mutate(document):
current = self._owned(document, claim)
if current is None:
return False, False
if current["state"] == "uncertain":
return False, True
current.update(state="uncertain", reason_code=reason_code, updated_at=int(time.time()))
return True, True
return self._change(mutate)
def refresh(self, claim: Claim | Mapping[str, Any]) -> bool:
def mutate(document):
current = self._owned(document, claim)
if current is None:
return False, False
now = int(time.time())
if current["updated_at"] == now:
return False, True
current["updated_at"] = now
return True, True
return self._change(mutate)
def update_metadata(self, claim: Claim | Mapping[str, Any], metadata: Mapping) -> bool:
if not isinstance(metadata, Mapping):
raise ValueError("Invalid coordination metadata")
additions = json.loads(_encode(dict(metadata)))
def mutate(document):
current = self._owned(document, claim)
if current is None:
return False, False
updated = {**current["metadata"], **additions}
if len(_encode(updated)) > 8192:
raise ValueError("Coordination metadata is too large")
current.update(metadata=updated, updated_at=int(time.time()))
return True, True
return self._change(mutate)
def add_resources(self, claim: Claim | Mapping[str, Any], resources) -> Claim:
additions = _resources(resources)
def mutate(document):
current = self._owned(document, claim)
if current is None:
raise CoordinationError("coordination_unavailable", 503)
if current["state"] != "active":
raise CoordinationError("coordination_uncertain", 503)
combined = _resources((*current["resources"], *additions))
for existing in document["claims"].values():
if existing["token"] == current["token"]:
continue
if existing["maintenance"] or (
(existing["state"] == "uncertain"
or existing["execution_id"] != current["execution_id"])
and bool(set(combined).intersection(existing["resources"]))
):
unknown = existing["state"] == "uncertain"
raise CoordinationClaimRejected(
"coordination_uncertain" if unknown else "coordination_busy",
503 if unknown else 409)
changed = list(combined) != current["resources"]
current.update(resources=list(combined), updated_at=int(time.time()))
return changed, Claim(current["token"], current["execution_id"],
current["owner_id"], current["operation_id"],
combined, current["kind"],
json.loads(_encode(current["metadata"])))
return self._change(mutate)
def snapshot(self) -> dict[str, dict]:
return self._read()[1]["claims"]
def operation_claim(self, operation_id: str) -> dict | None:
matches = [claim for claim in self.snapshot().values()
if claim["operation_id"] == operation_id]
return next((claim for claim in matches if claim["state"] == "uncertain"),
matches[0] if matches else None)
def has_work(self) -> bool:
return bool(self.snapshot())
def resolve(self, claim: Claim | Mapping[str, Any], evidence: str) -> bool:
"""Explicit operator reconciliation; never call on expiry or restart.
Evidence should reference the recorded host verification, not contain
credentials or raw host output. Keep a bounded reconciliation receipt
in the same atomic update that removes the claim.
"""
if not isinstance(evidence, str) or not evidence.strip() or len(evidence) > 1024:
raise ValueError("Explicit reconciliation evidence is required")
def mutate(document):
current = self._owned(document, claim)
if current is None:
return False, False
receipts = document.setdefault("resolutions", [])
receipts.append({
"token": current["token"], "operation_id": current["operation_id"],
"resolved_by": self.owner_id, "resolved_at": int(time.time()),
"evidence": evidence.strip(),
})
document["resolutions"] = receipts[-100:]
del document["claims"][current["token"]]
return True, True
return self._change(mutate)
def configure_default_coordinator(coordinator: DurableCoordinator | None) -> None:
global _default_coordinator
if coordinator is not None and not isinstance(coordinator, DurableCoordinator):
raise ValueError("Invalid default coordinator")
with _default_lock:
_default_coordinator = coordinator
def get_default_coordinator() -> DurableCoordinator | None:
with _default_lock:
return _default_coordinator
def current_execution() -> ExecutionContext | None:
return _CURRENT_EXECUTION.get()
def update_current_claim(claim: Claim) -> None:
context = current_execution()
if context is None or _identity(context.claim) != _identity(claim):
raise ValueError("Only the current execution claim may be updated")
_CURRENT_EXECUTION.set(ExecutionContext(
context.coordinator, claim, context.remote_write_started,
context.connection_failure_safe, context.tracked_mutations,
context.admission_rejected, context.execution_unknown))
def mark_remote_write_started() -> None:
"""Record conservative in-process proof before an RPC write is sent."""
context = current_execution()
if context is not None:
context.remote_write_started.set()
def mark_execution_unknown() -> None:
"""Never allow later no-write evidence to erase an ambiguous execution."""
context = current_execution()
if context is not None:
context.execution_unknown.set()
def mark_admission_rejected() -> None:
"""Called only by a confirmed local admission boundary before dispatch."""
context = current_execution()
if context is not None:
context.admission_rejected.set()
def execution_failure_before_write(error_code: str | None) -> bool:
"""Live no-dispatch evidence for explicitly tracked VM execution only.
This never reconciles a stored claim. A pending background owner must also
be checked by callers deciding whether the whole request has completed.
An error code cannot itself prove that someone else's fence rejected us.
"""
context = current_execution()
if (context is None or not context.tracked_mutations
or context.remote_write_started.is_set()
or context.execution_unknown.is_set()
or error_code == "coordination_unavailable"):
return False
if error_code in {"coordination_uncertain", "libvirt_execution_blocked"}:
return context.admission_rejected.is_set()
if (error_code in _UNKNOWN_CODES
or isinstance(error_code, str) and error_code.endswith("_uncertain")):
return False
return True
def connection_failure_before_write(error_code: str) -> bool:
"""Allow only explicitly libvirt-only scopes to use connection evidence.
Other workflows can mutate hosts over SSH before their first libvirt call.
An absent RPC write marker never proves those workflows were side-effect
free. Persisted unknown claims are not released through this local proof.
"""
context = current_execution()
return bool(error_code == "libvirt_connection_failed"
and context is not None and context.connection_failure_safe
and not context.execution_unknown.is_set()
and not context.remote_write_started.is_set())
@contextmanager
def execution_context(coordinator: DurableCoordinator, claim: Claim, *,
connection_failure_safe: bool | None = None,
tracked_mutations: bool | None = None):
parent = current_execution()
same_execution = (parent is not None and parent.coordinator is coordinator
and parent.claim.execution_id == claim.execution_id)
evidence = parent.remote_write_started if same_execution else threading.Event()
safe = (parent.connection_failure_safe if same_execution else False)
if connection_failure_safe is not None:
safe = connection_failure_safe
tracked = parent.tracked_mutations if same_execution else False
if tracked_mutations is not None:
tracked = tracked_mutations
rejected = parent.admission_rejected if same_execution else threading.Event()
unknown = parent.execution_unknown if same_execution else threading.Event()
token = _CURRENT_EXECUTION.set(ExecutionContext(
coordinator, claim, evidence, safe, tracked, rejected, unknown))
try:
yield
finally:
_CURRENT_EXECUTION.reset(token)
def _uncertain_exception(exc: BaseException) -> bool:
if isinstance(exc, CoordinationAdmissionRejected):
mark_admission_rejected()
context = current_execution()
if (isinstance(exc, CoordinationClaimRejected) and exc.status >= 500
and not execution_failure_before_write(exc.error_code)):
return True
return bool(context is not None and (context.remote_write_started.is_set()
or context.execution_unknown.is_set()))
context = current_execution()
if context is not None and context.execution_unknown.is_set():
return True
code = getattr(exc, "error_code", None)
# Cancellation may race another thread which has not published its write
# marker yet. A disconnected caller is not evidence of no dispatch.
if not isinstance(exc, Exception):
mark_execution_unknown()
return True
if isinstance(exc, CoordinationError) and exc.status >= 500:
mark_execution_unknown()
return True
if (code == "coordination_unavailable"
or code in _UNKNOWN_CODES
or isinstance(code, str) and code.endswith("_uncertain")):
if execution_failure_before_write(code):
return False
mark_execution_unknown()
return True
if execution_failure_before_write(code):
return False
if code in _SAFE_EXECUTION_CODES:
context = current_execution()
return bool(context is not None and context.remote_write_started.is_set())
if connection_failure_before_write(code):
return False
status = getattr(exc, "status", None)
return not isinstance(status, int) or status >= 500
@contextmanager
def resource_guard(resources, timeout: float = 5.0, *,
connection_failure_safe: bool | None = None,
tracked_mutations: bool | None = None):
import math
if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
or not math.isfinite(timeout) or timeout < 0):
raise ValueError("Invalid coordination wait bound")
resources = _resources(resources)
context = current_execution()
coordinator = context.coordinator if context is not None else get_default_coordinator()
if coordinator is None:
raise CoordinationError("coordination_unavailable", 503)
execution_id = context.claim.execution_id if context is not None else None
deadline = time.monotonic() + timeout
while True:
try:
claim = coordinator.claim(
operation_id=context.claim.operation_id if context is not None else None,
resources=resources, execution_id=execution_id, kind="resource",
metadata=context.claim.metadata if context is not None else None)
break
except CoordinationError as exc:
remaining = deadline - time.monotonic()
if exc.error_code != "coordination_busy" or remaining <= 0:
if isinstance(exc, CoordinationAdmissionRejected):
mark_admission_rejected()
else:
mark_execution_unknown()
raise
time.sleep(min(0.02, remaining))
with execution_context(coordinator, claim,
connection_failure_safe=connection_failure_safe,
tracked_mutations=tracked_mutations):
try:
yield claim
except BaseException as exc:
if _uncertain_exception(exc):
reason = getattr(exc, "error_code", None)
settled = coordinator.retain(
claim, reason if isinstance(reason, str)
and _IDENTIFIER.fullmatch(reason) else "operation_uncertain")
else:
settled = coordinator.release(claim)
if not settled:
mark_execution_unknown()
raise CoordinationError("coordination_uncertain", 503) from exc
raise
else:
if not coordinator.release(claim):
mark_execution_unknown()
raise CoordinationError("coordination_uncertain", 503)