Files
tessera/tests/mbu/matrix.py
Adnan Zahir 6320b6f244 feat: add managed database capture and operator restore
PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 23:26:49 +07:00

161 lines
8.6 KiB
Python

#!/usr/bin/env python3
"""Isolated rehearsal of the ten application shapes, including scheduled capture."""
from contextlib import ExitStack
from datetime import datetime, timedelta, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
import json
import sqlite3
from fixture import bastion, command, mysql_container, pair, postgres, s3_container, start_agent, start_hub, wait_until
POSTGRES = [
"lti", "presensi", "sso", "helpdesk", "manbu", "daily_checklist",
"odoo_mas", "odoo_fta", "dashboard_management",
]
CAPTURE_ONLY = {"odoo_fta", "dashboard_management"}
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-matrix-")))
pg, connection = postgres(cleanup, root, POSTGRES + [
app + "_staging" for app in POSTGRES if app not in CAPTURE_ONLY
])
pinned, _ = bastion(cleanup, root)
mysql, defaults, _ = mysql_container(cleanup, root)
offsite_password = root / "offsite-password"
offsite_password.write_text("fixture-matrix-s3-vault\n")
offsite_password.chmod(0o600)
endpoint, aws = s3_container(cleanup, "tessera-matrix")
api, url, _, _ = start_hub(cleanup, root, {
**aws, "TESSERA_OFFSITE_REPOSITORY": f"s3:{endpoint}/tessera-matrix/rehearsal",
"TESSERA_OFFSITE_PASSWORD_FILE": str(offsite_password),
})
def pg_sql(database, statement):
return command("psql", *pg, "-d", database, "-Atc", statement,
capture_output=True, text=True).stdout.strip()
def mysql_sql(database, statement):
return command(*mysql, "-NB", "-D", database, "-e", statement,
capture_output=True, text=True).stdout.strip()
pg_id = pg_sql("postgres", "SELECT system_identifier FROM pg_control_system()")
mysql_id = mysql_sql("fixture", "SELECT LOWER(@@server_uuid)")
mysql_sql("fixture", "CREATE DATABASE boiler_staging; CREATE TABLE sample(value VARCHAR(40));"
"INSERT INTO sample VALUES ('boiler'); CREATE VIEW sample_view AS SELECT value FROM sample")
mysql_sql("boiler_staging", "CREATE TABLE sample(value VARCHAR(40)); INSERT INTO sample VALUES ('previous')")
groups = {kind: {"agent": pair(api, f"fixture-{kind}"), "profiles": {}}
for kind in ("direct", "bastion", "mysql")}
applications = {}
for app in POSTGRES + ["boiler"]:
mysql_app = app == "boiler"
group = groups["mysql" if mysql_app else "bastion" if app in ("odoo_mas", "odoo_fta") else "direct"]
node = group["agent"]["outpost_id"]
orbit = api("orbits", {"name": app, "provider": "wormhole", "provider_config": {}})
app_id = str(uuid4())
engine = "mysql" if mysql_app else "postgres"
format = "mysql_sql" if mysql_app else "postgres_sql" if app == "daily_checklist" else "postgres_custom"
api("capture-profiles", {"application_id": app_id, "orbit_id": orbit["id"], "outpost_id": node,
"format": format, "schedule": {"hour": 2, "timezone": "Asia/Jakarta"}}, expected=201)
target_db = app + "_staging"
if mysql_app:
source = {"transport": "ssh", "bastion": pinned, "defaults_file": str(defaults), "database": "fixture"}
target = {"engine": engine, "connection": {**source, "database": target_db},
"recreate_database": True, "use_target_definer": True}
else:
pg_sql(app, "CREATE SCHEMA fixture; CREATE TABLE fixture.sample(value text);"
f"INSERT INTO fixture.sample VALUES ('{app}')")
source = connection(app)
if app in ("odoo_mas", "odoo_fta"):
source["bastion"] = pinned
mode = {"reset": "recreate_database"} if app == "odoo_mas" else {"reset": "schema", "schema": "fixture"}
target = {"engine": engine, "connection": {**source, "database": target_db}, "mode": mode}
if app == "daily_checklist":
post = root / "checklist.sql"
post.write_text("INSERT INTO fixture.sample VALUES ('post-restore');")
target["post_restore_sql"] = str(post)
profile = {"source": {"engine": engine, **source}, "timeout_seconds": 120}
target_id = None
if app not in CAPTURE_ONLY:
target_id = str(uuid4())
api("restore-targets", {"id": target_id, "application_id": app_id, "outpost_id": node,
"name": target_db, "engine": engine, "identity": {
"instance": mysql_id if mysql_app else pg_id, "database": target_db,
}}, expected=201)
profile["targets"] = {target_id: target}
group["profiles"][app_id] = profile
manual = api(f"capture-profiles/{app_id}/jobs", {}, expected=202)["id"]
applications[app] = (app_id, target_id, manual, target_db)
# Backdate registration to just before one elapsed slot, then let the real scheduler tick.
now = datetime.now(timezone.utc)
slot = now.replace(hour=19, minute=0, second=0, microsecond=0)
if slot > now:
slot -= timedelta(days=1)
with sqlite3.connect(root / "hub" / "tessera.db") as db:
db.execute("UPDATE capture_profiles SET registered_at = ?", (int(slot.timestamp()) - 1,))
for kind, group in groups.items():
directory = root / kind
directory.mkdir(mode=0o700)
start_agent(cleanup, directory, url, group["agent"]["upload_token"], group["profiles"])
def completed_captures():
jobs = api("capture-jobs?limit=100")
assert all(job["status"] != "failed" for job in jobs), jobs
return jobs if len(jobs) == 20 and all(job["status"] == "completed" and job["offsite_status"] == "copied" for job in jobs) else None
captures = wait_until(completed_captures, seconds=240)
snapshots = {snap["id"]: snap for snap in api("snapshots")}
stats, restores = {}, {}
for app, (app_id, target, manual, _) in applications.items():
jobs = [job for job in captures if job["profile"]["application_id"] == app_id]
assert {job["actor"] for job in jobs} == {"api-token", "scheduler"}
scheduled = next(job for job in jobs if job["actor"] == "scheduler")
current = next(job for job in jobs if job["id"] == manual)
stats[app] = {
"manual_seconds": current["updated_at"] - current["created_at"],
"scheduled_seconds": scheduled["updated_at"] - scheduled["created_at"],
"freshness_seconds": int(datetime.now(timezone.utc).timestamp()) - scheduled["updated_at"],
"bytes": snapshots[scheduled["snapshot_id"]]["size_bytes"],
"offsite": scheduled["offsite_status"],
}
if target:
restores[app] = api("restore-jobs", {"snapshot_id": manual, "target_id": target,
"confirmation": f"RESTORE {manual} TO {target}"}, expected=202)["id"]
else:
assert api(f"capture-profiles/{app_id}/restore-targets") == []
stats[app]["restore"] = "capture_only"
def restores_done():
results = {app: api(f"restore-jobs/{job}") for app, job in restores.items()}
assert all(job["status"] not in ("failed", "recovery_required") for job in results.values()), results
return results if all(job["status"] == "completed" for job in results.values()) else None
results = wait_until(restores_done, seconds=180)
for app, result in results.items():
_, _, _, database = applications[app]
assert result["safety_snapshot_id"]
if app == "boiler":
assert mysql_sql(database, "SELECT value FROM sample_view") == app
else:
expected = app + "\npost-restore" if app == "daily_checklist" else app
assert pg_sql(database, "SELECT value FROM fixture.sample ORDER BY value") == expected
stats[app]["restore"] = "verified"
archive = applications["lti"][2]
expected = api(f"snapshots/{archive}/download", raw=True)
primary = root / "hub" / "vault" / "restic"
primary.rename(primary.with_name("restic-offline"))
assert api(f"snapshots/{archive}/download", raw=True) == expected
print(json.dumps(stats, indent=2, sort_keys=True))
if __name__ == "__main__":
main()