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>
This commit is contained in:
2026-11-10 23:26:49 +07:00
parent 30a1a9b8f0
commit 6320b6f244
96 changed files with 11061 additions and 725 deletions

157
tests/mbu/restic-orbits.py Normal file
View File

@@ -0,0 +1,157 @@
#!/usr/bin/env python3
"""Exercise the orbit source/access matrix with a TLS Rest Server and PostgreSQL."""
from contextlib import ExitStack
from io import BytesIO
from pathlib import Path
from subprocess import DEVNULL, Popen, run
from tempfile import TemporaryDirectory
from uuid import uuid4
from argparse import ArgumentParser
import json
import os
import tarfile
from fixture import PASSWORD, command, mysql_container, pair, port, start_agent, start_hub, stop, terminal, wait_until
def main(with_mysql):
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-restic-orbits-")))
password = root / "password"
password.write_text(PASSWORD + "\n")
password.chmod(0o600)
data = root / "db"
pg_port = port()
command("initdb", "-D", data, "-U", "fixture", "--auth-local=trust",
"--auth-host=scram-sha-256", "--pwfile", password, stdout=DEVNULL)
command("pg_ctl", "-D", data, "-l", root / "postgres.log", "-w", "start",
"-o", f"-h 127.0.0.1 -p {pg_port} -k {root}", stdout=DEVNULL)
cleanup.callback(command, "pg_ctl", "-D", data, "-m", "immediate", "-w", "stop", stdout=DEVNULL)
pg = ("-h", str(root), "-p", str(pg_port), "-U", "fixture")
for database in ("source", "restored"):
command("createdb", *pg, database)
command("psql", *pg, "-d", "source", "-v", "ON_ERROR_STOP=1", "-c",
"CREATE TABLE changes (id int PRIMARY KEY, value text);"
"INSERT INTO changes SELECT i, md5(i::text) FROM generate_series(1, 500000) i;",
stdout=DEVNULL)
db = {"engine": "postgres", "host": "127.0.0.1", "port": pg_port, "user": "fixture",
"database": "source", "password_file": str(password), "tls": {"mode": "disable"}}
folder = root / "source"
folder.mkdir()
original = os.urandom(3 * 1024 * 1024)
(folder / "test.bin").write_bytes(original)
cases = [
("filesystem", "filesystem", "filesystem", {"paths": [str(folder)]}),
("postgres", "database", "postgres_sql", {"source": db}),
]
if with_mysql:
mysql, _, mysql_port = mysql_container(cleanup, root)
command(*mysql, "-D", "fixture", "-e",
"CREATE TABLE changes (id INT PRIMARY KEY, value TEXT);"
"INSERT INTO changes VALUES (1, 'restored MySQL'); CREATE DATABASE restored;")
cases.append(("mysql", "database", "mysql_sql", {"source": {
"engine": "mysql", "transport": "direct", "host": "127.0.0.1", "port": mysql_port,
"user": "root", "database": "fixture", "password_file": str(password), "tls": {"mode": "required"},
}}))
api, url, _, hub_log = start_hub(cleanup, root)
paired = pair(api, "Restic fixture")
vault = root / "hub" / "vault"
repos = vault / "outposts"
repos.mkdir(exist_ok=True)
ca, key = root / "server.crt", root / "server.key"
command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-noenc", "-days", "1",
"-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost",
"-out", ca, "-keyout", key, stdout=DEVNULL, stderr=DEVNULL)
rest_port = port()
auth = root / "htpasswd"
auth.touch()
configs = {}
outposts = {}
for case, source, fmt, config in cases:
hub_config = config if source == "filesystem" else config["source"]
hub = api("orbits", {"name": f"{case} hub", "source": source, "access": "hub",
"provider_config": hub_config})
assert (hub["source"], hub["access"]) == (source, "hub")
api(f"orbits/{hub['id']}/run", {}, expected=204)
orbit = api("orbits", {"name": f"{case} outpost", "source": source, "access": "outpost",
"provider_config": {}, "retention": {
"keep_daily": 1, "keep_weekly": 0, "keep_monthly": 0, "keep_yearly": 0,
}})
assert (orbit["source"], orbit["access"]) == (source, "outpost")
orbit_id = orbit["id"]
application = str(uuid4())
outposts[case] = application
(vault / "keys" / f"outpost-{orbit_id}.json").write_text(json.dumps({
"outpost_id": paired["outpost_id"], "password": PASSWORD,
}))
command("restic", "-r", repos / orbit_id, "--password-file", password, "init", stdout=DEVNULL)
command("htpasswd", "-Bb", auth, orbit_id, PASSWORD, stdout=DEVNULL, stderr=DEVNULL)
other = "postgres_sql" if source == "filesystem" else "filesystem"
profile = {"orbit_id": orbit_id, "application_id": application, "outpost_id": paired["outpost_id"]}
api("capture-profiles", {**profile, "format": other}, expected=409)
api("capture-profiles", {**profile, "format": fmt}, expected=201)
configs[application] = {**config, "restic_repository": f"rest:https://localhost:{rest_port}/{orbit_id}/",
"restic_password_file": str(password), "rest_server_password_file": str(password)}
rest_log = cleanup.enter_context((root / "rest-server.log").open("w+"))
server = Popen(["rest-server", "--listen", f"127.0.0.1:{rest_port}", "--path", repos,
"--tls", "--tls-cert", ca, "--tls-key", key, "--htpasswd-file", auth,
"--append-only", "--private-repos"], stdout=rest_log, stderr=rest_log)
cleanup.callback(stop, server)
wait_until(lambda: run(["curl", "-s", "--cacert", ca, f"https://localhost:{rest_port}/"],
stdout=DEVNULL).returncode == 0)
_, agent_log = start_agent(cleanup, root, url, paired["upload_token"], configs,
settings={"RESTIC_CACERT": str(ca)})
def capture(application):
job = api(f"capture-profiles/{application}/jobs", {}, expected=202)["id"]
result = wait_until(lambda: terminal(api, job))
assert result["status"] == "completed", result
return next(snapshot for snapshot in api("snapshots") if snapshot["id"] == result["snapshot_id"])
try:
for case, application in outposts.items():
first = capture(application)
if case == "filesystem":
(folder / "tiny.txt").write_text("incremental")
elif case == "postgres":
command("psql", *pg, "-d", "source", "-c",
"UPDATE changes SET value = 'incremental' WHERE id = 50000;", stdout=DEVNULL)
second = capture(application)
assert second["stored_bytes"] < first["stored_bytes"], (first, second)
wait_until(lambda: first["id"] not in {snapshot["id"] for snapshot in api("snapshots")})
payload = api(f"snapshots/{second['id']}/download", raw=True)
if case == "filesystem":
with tarfile.open(fileobj=BytesIO(payload)) as archive:
files = {Path(member.name).name: archive.extractfile(member).read()
for member in archive if member.isfile()}
assert files == {"test.bin": original, "tiny.txt": b"incremental"}
elif case == "postgres":
assert second["capture"]["restore_ready"]
command("psql", *pg, "-d", "restored", "-v", "ON_ERROR_STOP=1",
input=payload, stdout=DEVNULL)
restored = command("psql", *pg, "-d", "restored", "-At", "-c",
"SELECT value FROM changes WHERE id = 50000;", capture_output=True)
assert restored.stdout.strip() == b"incremental"
else:
assert second["capture"]["restore_ready"] and second["new_data_chunks"] == 0
command(*mysql, "-D", "restored", input=payload)
restored = command(*mysql, "-NB", "-D", "restored", "-e",
"SELECT value FROM changes WHERE id = 1;", capture_output=True)
assert restored.stdout.strip() == b"restored MySQL"
print(f"{case}: {first['stored_bytes']} → {second['stored_bytes']} packed bytes, restore verified")
except Exception:
for log in (hub_log, agent_log, rest_log):
log.seek(0)
print(log.read())
raise
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("--mysql", action="store_true")
main(parser.parse_args().mysql)