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/engine_context.py

248 lines
9.1 KiB
Python

"""PHP-owned identities, stable host namespaces, and separate engine databases."""
from __future__ import annotations
import hashlib
import json
import threading
from contextvars import ContextVar
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Any
from .auth import Session
from .database import (DatabaseError, DatabaseRemoteHostManager, DatabaseStore,
DatabaseTemplateStore, _METRIC_MIGRATIONS, _METRIC_SCHEMA,
_SCHEMA, _TRAFFIC_CHECKPOINT_SCHEMA, _TRAFFIC_SCHEMA, pymysql)
TRUSTED_ACTOR: ContextVar[dict | None] = ContextVar("cloud_trusted_actor", default=None)
def actor() -> dict:
value = TRUSTED_ACTOR.get()
if value is None:
raise PermissionError("Missing authenticated PHP actor")
return value
def actor_session() -> Session:
value = actor()
return Session("internal", f"php:{value['user_id']}", "", float("inf"), value["user_id"])
def actor_account(session: Session) -> dict:
value = actor()
if session.user_id != value["user_id"]:
raise PermissionError("Actor does not match request")
return {"id": value["user_id"], "username": f"php:{value['user_id']}",
"admin": value["is_admin"], "approved": True, "email_verified": True}
class MainStore(DatabaseStore):
RECORD_TABLE = "engine_records"
def _initialize_schema(self) -> None:
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute(_SCHEMA.replace("panel_records", self.RECORD_TABLE))
cursor.execute("""CREATE TABLE IF NOT EXISTS engine_request_nonces (
nonce VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
expires_at BIGINT UNSIGNED NOT NULL,
PRIMARY KEY(nonce), KEY nonce_expiry(expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""")
connection.commit()
except pymysql.MySQLError as exc:
connection.rollback()
raise DatabaseError("无法初始化引擎数据库") from exc
finally:
connection.close()
def consume_nonce(self, nonce: str, expires_at: int, now: int) -> bool:
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute("DELETE FROM engine_request_nonces WHERE expires_at < %s LIMIT 1000", (now,))
cursor.execute("INSERT INTO engine_request_nonces(nonce,expires_at) VALUES(%s,%s)",
(nonce, expires_at))
connection.commit()
return True
except pymysql.err.IntegrityError as exc:
connection.rollback()
if exc.args and exc.args[0] == 1062:
return False
raise DatabaseError() from exc
except pymysql.MySQLError as exc:
connection.rollback()
raise DatabaseError() from exc
finally:
connection.close()
class LogStore(DatabaseStore):
METRIC_TABLE = "engine_vm_metric_samples"
TRAFFIC_TABLE = "engine_vm_traffic_totals"
TRAFFIC_CHECKPOINT_TABLE = "engine_vm_traffic_checkpoints"
def _initialize_schema(self) -> None:
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute(_METRIC_SCHEMA.replace("vm_metric_samples", self.METRIC_TABLE))
cursor.execute(_TRAFFIC_SCHEMA.replace("vm_traffic_totals", self.TRAFFIC_TABLE))
cursor.execute(_TRAFFIC_CHECKPOINT_SCHEMA.replace(
"vm_traffic_checkpoints", self.TRAFFIC_CHECKPOINT_TABLE))
for statement in _METRIC_MIGRATIONS:
cursor.execute(statement.format(metric_table=self.METRIC_TABLE))
connection.commit()
except pymysql.MySQLError as exc:
connection.rollback()
raise DatabaseError("无法初始化日志库的虚拟机指标表") from exc
finally:
connection.close()
class HostStore:
"""One current profile per stable host ID, never one shared current host."""
def __init__(self, store: Any, host_id: str):
self.store = store
self.prefix = hashlib.sha256(host_id.encode("ascii")).hexdigest() + ":"
self._compare_lock = threading.RLock()
def _key(self, key: str) -> str:
return self.prefix + key
def get(self, kind: str, key: str):
return self.store.get(kind, self._key(key))
def set(self, kind: str, key: str, value: str):
return self.store.set(kind, self._key(key), value)
def insert(self, kind: str, key: str, value: str):
return self.store.insert(kind, self._key(key), value)
def compare_and_set(
self, kind: str, key: str, expected: str | None, value: str,
) -> bool:
compare = getattr(self.store, "compare_and_set", None)
if callable(compare):
return compare(kind, self._key(key), expected, value)
# In-memory test stores do not need a database transaction, but they do
# need the same process-local semantics as production.
with self._compare_lock:
current = self.get(kind, key)
if current != expected:
return False
self.set(kind, key, value)
return True
def delete(self, kind: str, key: str):
return self.store.delete(kind, self._key(key))
def list(self, kind: str):
return {key[len(self.prefix):]: value for key, value in self.store.list(kind).items()
if key.startswith(self.prefix)}
def get_value(self, key: str):
return self.get("value", key)
def set_value(self, key: str, value: str):
return self.set("value", key, value)
def delete_value(self, key: str):
return self.delete("value", key)
def get_secret(self, key: str):
return self.get("secret", key)
def set_secret(self, key: str, value: str):
return self.set("secret", key, value)
class ExternalOwnership:
"""Immutable PHP subject -> host/UUID owner mapping, with no users FK."""
def __init__(self, store: HostStore):
self.store = store
@staticmethod
def _key(scope: str, vm_id: str) -> str:
return f"{scope}.{vm_id}"
def get_by_id(self, user_id: int):
value = actor()
return actor_account(actor_session()) if value["user_id"] == user_id else None
def owns_vm(self, scope: str, vm_id: str, user_id: int) -> bool:
return self.owner_of_vm(scope, vm_id) == user_id
def owner_of_vm(self, scope: str, vm_id: str) -> int | None:
raw = self.store.get("vm_owner", self._key(scope, vm_id))
return None if raw is None else int(json.loads(raw)["user_id"])
def assign_vm(self, scope: str, vm_id: str, user_id: int) -> None:
if isinstance(user_id, bool) or not isinstance(user_id, int) or user_id < 1:
raise ValueError("External owner must be a positive PHP user ID")
key = self._key(scope, vm_id)
payload = json.dumps({"user_id": user_id}, separators=(",", ":"))
if not self.store.insert("vm_owner", key, payload):
if not self.owns_vm(scope, vm_id, user_id):
raise DatabaseError("虚拟机已有其他归属,不能重复分配")
def list_owned_vm_ids(self, scope: str, user_id: int) -> set[str]:
prefix = scope + "."
return {key[len(prefix):] for key, raw in self.store.list("vm_owner").items()
if key.startswith(prefix) and json.loads(raw)["user_id"] == user_id}
def delete_vm_owner(self, scope: str, vm_id: str) -> None:
self.store.delete("vm_owner", self._key(scope, vm_id))
class StableHostManager(DatabaseRemoteHostManager):
def __init__(self, store, data_dir, *, host_id: str, **kwargs):
self.host_id = host_id
super().__init__(store, data_dir, **kwargs)
def current(self):
profile = super().current()
if profile is not None:
profile["host_id"] = self.host_id
return profile
def commit(self, staged):
profile = super().commit(staged)
profile["host_id"] = self.host_id
return profile
def unlock_current(self, passphrase):
profile = super().unlock_current(passphrase)
profile["host_id"] = self.host_id
return profile
def current_for_background(self):
profile = super().current_for_background()
if profile is not None:
profile["host_id"] = self.host_id
return profile
@dataclass
class EngineComponents:
state: Any
manager: Any
templates: Any
store: Any
metric_store: Any
user_isos: Any | None = None
cloud_templates: Any | None = None
@classmethod
def for_host(cls, store, log_store, host_id, data_dir, user_isos=None,
cloud_templates=None):
scoped = HostStore(store, host_id)
state = SimpleNamespace(users=ExternalOwnership(scoped))
manager = StableHostManager(scoped, data_dir, host_id=host_id)
return cls(
state, manager, DatabaseTemplateStore(scoped), scoped, log_store,
user_isos, cloud_templates,
)