Initial ABSDEV deployment framework development preview
ABSDEV Framework CI / framework-validation (push) Canceled after 0s
ABSDEV Framework CI / framework-validation (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,768 @@
|
||||
"""Disposable MySQL backup and restoration integration test."""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from core.database import get_adapter
|
||||
from core.backup import BackupEngine
|
||||
from core.execution import CommandRunner
|
||||
|
||||
|
||||
ROOT = Path.cwd()
|
||||
|
||||
IMAGE = (
|
||||
"sha256:"
|
||||
"8c233bad33d520a7aae1c1e619c3a9775"
|
||||
"f4a1ba2d463d692fada04ec7f40be00"
|
||||
)
|
||||
|
||||
LABEL = "absdev.framework.integration"
|
||||
|
||||
SOURCE_DATABASE = "example_db"
|
||||
RESTORE_DATABASE = "isolated_restore_mysql"
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
|
||||
if not condition:
|
||||
raise RuntimeError(message)
|
||||
|
||||
|
||||
def command(*args, input_data=None, timeout=120):
|
||||
|
||||
result = subprocess.run(
|
||||
args,
|
||||
input=input_data,
|
||||
stdin=(
|
||||
subprocess.DEVNULL
|
||||
if input_data is None
|
||||
else None
|
||||
),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
require(
|
||||
result.returncode == 0,
|
||||
f"Command failed with status {result.returncode}",
|
||||
)
|
||||
|
||||
return result.stdout
|
||||
|
||||
|
||||
def inspect(cid):
|
||||
|
||||
return json.loads(
|
||||
command("docker", "inspect", cid)
|
||||
)[0]
|
||||
|
||||
|
||||
def production_inventory():
|
||||
|
||||
inventory = {}
|
||||
|
||||
for cid in command(
|
||||
"docker", "ps", "-aq", "--no-trunc"
|
||||
).decode().splitlines():
|
||||
|
||||
details = inspect(cid)
|
||||
|
||||
if (
|
||||
details["Config"]["Labels"] or {}
|
||||
).get(LABEL) == "true":
|
||||
|
||||
continue
|
||||
|
||||
inventory[cid] = {
|
||||
"name": details["Name"],
|
||||
"running": details["State"]["Running"],
|
||||
"started": details["State"]["StartedAt"],
|
||||
"restart_policy": (
|
||||
details["HostConfig"]["RestartPolicy"]
|
||||
),
|
||||
}
|
||||
|
||||
return inventory
|
||||
|
||||
|
||||
class MySQLIntegrationTests(unittest.TestCase):
|
||||
|
||||
def test_backup_and_restore(self):
|
||||
|
||||
import socket
|
||||
|
||||
if socket.gethostname().split(".")[0].lower() == "absdev":
|
||||
self.skipTest(
|
||||
"Database integration tests prohibited on ABSDEV"
|
||||
)
|
||||
|
||||
if os.environ.get("ABSDEV_INTEGRATION_TESTS") != "1":
|
||||
self.skipTest(
|
||||
"Explicit integration test authorisation required"
|
||||
)
|
||||
|
||||
|
||||
before = production_inventory()
|
||||
|
||||
token = secrets.token_hex(8)
|
||||
|
||||
name = f"absdev-integration-mysql-{token}"
|
||||
|
||||
password = secrets.token_hex(32)
|
||||
|
||||
cid = None
|
||||
|
||||
evidence = {
|
||||
"driver": "mysql",
|
||||
"image": IMAGE,
|
||||
"started_at": datetime.now(
|
||||
timezone.utc
|
||||
).isoformat(),
|
||||
"result": "INCOMPLETE",
|
||||
}
|
||||
|
||||
runtime = (
|
||||
ROOT / "runtime/integration"
|
||||
)
|
||||
|
||||
work = runtime / name
|
||||
work.mkdir(mode=0o700)
|
||||
|
||||
backup_root = work / "backups"
|
||||
backup_root.mkdir(mode=0o700)
|
||||
|
||||
try:
|
||||
|
||||
available = int(
|
||||
next(
|
||||
line.split()[1]
|
||||
for line in Path(
|
||||
"/proc/meminfo"
|
||||
).read_text().splitlines()
|
||||
if line.startswith("MemAvailable:")
|
||||
)
|
||||
)
|
||||
|
||||
require(
|
||||
available >= 786432,
|
||||
"Insufficient available memory",
|
||||
)
|
||||
|
||||
require(
|
||||
not command(
|
||||
"docker", "ps", "-aq",
|
||||
"--filter", f"label={LABEL}=true",
|
||||
).strip(),
|
||||
"Existing integration container requires review",
|
||||
)
|
||||
|
||||
image = json.loads(
|
||||
command(
|
||||
"docker", "image", "inspect", IMAGE
|
||||
)
|
||||
)[0]
|
||||
|
||||
require(
|
||||
image["Id"] == IMAGE,
|
||||
"Unexpected database image",
|
||||
)
|
||||
|
||||
print("\n=== CREATE DISPOSABLE MYSQL ===")
|
||||
|
||||
with tempfile.TemporaryDirectory(
|
||||
dir=work
|
||||
) as directory:
|
||||
|
||||
secret_dir = Path(directory)
|
||||
|
||||
envfile = secret_dir / "mysql.env"
|
||||
|
||||
envfile.write_text(
|
||||
f"MYSQL_ROOT_PASSWORD={password}\n"
|
||||
f"MYSQL_DATABASE={SOURCE_DATABASE}\n"
|
||||
)
|
||||
|
||||
envfile.chmod(0o600)
|
||||
|
||||
# Create before starting so isolation
|
||||
# can be independently verified.
|
||||
|
||||
cid = command(
|
||||
"docker", "create",
|
||||
"--pull=never",
|
||||
"--name", name,
|
||||
"--label", f"{LABEL}=true",
|
||||
"--label", f"absdev.integration.token={token}",
|
||||
"--network", "none",
|
||||
"--restart", "no",
|
||||
"--memory", "512m",
|
||||
"--memory-swap", "768m",
|
||||
"--cpus", "0.5",
|
||||
"--pids-limit", "256",
|
||||
"--security-opt",
|
||||
"no-new-privileges=true",
|
||||
"--env-file", str(envfile),
|
||||
IMAGE,
|
||||
"--innodb-buffer-pool-size=64M",
|
||||
"--max-connections=20",
|
||||
"--performance-schema=OFF",
|
||||
"--skip-log-bin",
|
||||
).decode().strip()
|
||||
|
||||
def verify_isolation():
|
||||
|
||||
item = inspect(cid)
|
||||
|
||||
labels = item["Config"]["Labels"]
|
||||
|
||||
host = item["HostConfig"]
|
||||
|
||||
require(
|
||||
item["Id"] == cid
|
||||
and item["Name"] == "/" + name
|
||||
and item["Image"] == IMAGE,
|
||||
"Unexpected test container identity",
|
||||
)
|
||||
|
||||
require(
|
||||
labels.get(LABEL) == "true"
|
||||
and labels.get(
|
||||
"absdev.integration.token"
|
||||
) == token,
|
||||
"Invalid integration ownership",
|
||||
)
|
||||
|
||||
require(
|
||||
host["NetworkMode"] == "none"
|
||||
and not host["PortBindings"]
|
||||
and not host["Privileged"]
|
||||
and not host["Binds"]
|
||||
and not host.get("VolumesFrom")
|
||||
and host["RestartPolicy"]["Name"] == "no",
|
||||
"Container isolation failed",
|
||||
)
|
||||
|
||||
require(
|
||||
host["Memory"] == 512 * 1024 * 1024
|
||||
and host["MemorySwap"]
|
||||
== 768 * 1024 * 1024,
|
||||
"Resource limits changed",
|
||||
)
|
||||
|
||||
production_sources = set()
|
||||
|
||||
for original in before:
|
||||
|
||||
for mount in inspect(original)["Mounts"]:
|
||||
|
||||
production_sources.add(
|
||||
mount["Source"]
|
||||
)
|
||||
|
||||
for mount in item["Mounts"]:
|
||||
|
||||
require(
|
||||
mount["Type"] == "volume"
|
||||
and mount["Source"]
|
||||
not in production_sources,
|
||||
"Unexpected or shared database mount",
|
||||
)
|
||||
|
||||
return item
|
||||
|
||||
verify_isolation()
|
||||
|
||||
command("docker", "start", cid)
|
||||
|
||||
print("PASS: Disposable container started")
|
||||
|
||||
deadline = time.monotonic() + 180
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
|
||||
state = verify_isolation()["State"]
|
||||
|
||||
require(
|
||||
state["Running"]
|
||||
and not state["OOMKilled"],
|
||||
"Test database stopped unexpectedly",
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
result = command(
|
||||
"docker", "exec", cid,
|
||||
"mysqladmin",
|
||||
"--protocol=TCP",
|
||||
"--host=127.0.0.1",
|
||||
"--silent",
|
||||
"ping",
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
if b"mysqld is alive" in result:
|
||||
break
|
||||
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
else:
|
||||
|
||||
raise RuntimeError(
|
||||
"MySQL readiness timed out"
|
||||
)
|
||||
|
||||
print("PASS: MySQL TCP service ready")
|
||||
|
||||
# Install credentials inside the disposable
|
||||
# container without displaying their values.
|
||||
|
||||
client = (
|
||||
"[client]\n"
|
||||
"user=root\n"
|
||||
f"password={password}\n"
|
||||
"host=127.0.0.1\n"
|
||||
"protocol=TCP\n"
|
||||
).encode()
|
||||
|
||||
command(
|
||||
"docker", "exec", "-i", cid,
|
||||
"sh", "-c",
|
||||
"umask 077; "
|
||||
"mkdir -p /run/secrets; "
|
||||
"cat > /run/secrets/absdev-client.cnf",
|
||||
input_data=client,
|
||||
)
|
||||
|
||||
def sql(statement, database=None):
|
||||
|
||||
verify_isolation()
|
||||
|
||||
args = [
|
||||
"docker", "exec", cid,
|
||||
"timeout", "-k", "5s", "60s",
|
||||
"mysql",
|
||||
"--defaults-file="
|
||||
"/run/secrets/absdev-client.cnf",
|
||||
"--batch",
|
||||
"--skip-column-names",
|
||||
]
|
||||
|
||||
if database is not None:
|
||||
|
||||
require(
|
||||
database in (
|
||||
SOURCE_DATABASE,
|
||||
RESTORE_DATABASE,
|
||||
),
|
||||
"Invalid integration database target",
|
||||
)
|
||||
|
||||
args.append(
|
||||
f"--database={database}"
|
||||
)
|
||||
|
||||
args.extend([
|
||||
"--execute",
|
||||
statement,
|
||||
])
|
||||
|
||||
return command(*args)
|
||||
|
||||
print("\n=== CREATE SYNTHETIC TEST DATABASE ===")
|
||||
|
||||
sql(
|
||||
"""
|
||||
CREATE TABLE users (
|
||||
id BIGINT UNSIGNED PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
UNIQUE KEY users_email_unique (email)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
CREATE TABLE orders (
|
||||
id BIGINT UNSIGNED PRIMARY KEY,
|
||||
user_id BIGINT UNSIGNED NOT NULL,
|
||||
amount DECIMAL(12,2) NOT NULL,
|
||||
payload BLOB,
|
||||
CONSTRAINT orders_user_fk
|
||||
FOREIGN KEY (user_id)
|
||||
REFERENCES users(id)
|
||||
) ENGINE=InnoDB;
|
||||
|
||||
CREATE TABLE migrations (
|
||||
id INT UNSIGNED PRIMARY KEY,
|
||||
migration VARCHAR(255) NOT NULL,
|
||||
batch INT NOT NULL
|
||||
) ENGINE=InnoDB;
|
||||
|
||||
INSERT INTO users VALUES
|
||||
(1, 'Alice', '[email protected]'),
|
||||
(2, 'José', '[email protected]');
|
||||
|
||||
INSERT INTO orders VALUES
|
||||
(1, 1, 12.50, UNHEX('000102FF')),
|
||||
(2, 2, 99.95, UNHEX('AABBCCDD'));
|
||||
|
||||
INSERT INTO migrations VALUES
|
||||
(1, 'create_users_table', 1),
|
||||
(2, 'create_orders_table', 1),
|
||||
(3, 'add_payload_column', 2);
|
||||
""",
|
||||
SOURCE_DATABASE,
|
||||
)
|
||||
|
||||
print("PASS: Synthetic database created")
|
||||
|
||||
config = json.loads(
|
||||
(ROOT / "config/site.example.json")
|
||||
.read_text()
|
||||
)
|
||||
|
||||
config["database"].update({
|
||||
"driver": "mysql",
|
||||
"container": name,
|
||||
"host": "127.0.0.1",
|
||||
"port": 3306,
|
||||
"name": SOURCE_DATABASE,
|
||||
"username": "root",
|
||||
})
|
||||
|
||||
adapter = get_adapter(config)
|
||||
|
||||
# Bind execution to the exact disposable
|
||||
# container ID rather than its mutable name.
|
||||
# Enforce a timeout inside the container too.
|
||||
|
||||
def bounded(args):
|
||||
|
||||
result = list(args)
|
||||
|
||||
require(
|
||||
result[:2] == ["docker", "exec"],
|
||||
"Unexpected adapter command",
|
||||
)
|
||||
|
||||
index = 3 if result[2] == "-i" else 2
|
||||
|
||||
require(
|
||||
result[index] == name,
|
||||
"Unexpected database target",
|
||||
)
|
||||
|
||||
result[index] = cid
|
||||
|
||||
result[index + 1:index + 1] = [
|
||||
"timeout",
|
||||
"-k", "5s",
|
||||
"60s",
|
||||
]
|
||||
|
||||
return result
|
||||
|
||||
allowed = [
|
||||
bounded(adapter.identity_command()),
|
||||
bounded(adapter.backup_command()),
|
||||
bounded(adapter.ping_command()),
|
||||
bounded(adapter.version_command()),
|
||||
]
|
||||
|
||||
runner = CommandRunner(
|
||||
allowed_commands=allowed,
|
||||
timeout=75,
|
||||
)
|
||||
|
||||
def guarded_runner(args, output):
|
||||
|
||||
verify_isolation()
|
||||
|
||||
runner(
|
||||
bounded(args),
|
||||
output,
|
||||
)
|
||||
|
||||
output = io.BytesIO()
|
||||
|
||||
guarded_runner(
|
||||
adapter.ping_command(),
|
||||
output,
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
output.getvalue().strip(),
|
||||
b"1",
|
||||
)
|
||||
|
||||
print("PASS: Authenticated connectivity")
|
||||
|
||||
output = io.BytesIO()
|
||||
|
||||
guarded_runner(
|
||||
adapter.version_command(),
|
||||
output,
|
||||
)
|
||||
|
||||
version = output.getvalue().decode().strip()
|
||||
|
||||
print("MySQL version:", version)
|
||||
|
||||
evidence["database_version"] = version
|
||||
|
||||
print("\n=== EXECUTE FRAMEWORK BACKUP ===")
|
||||
|
||||
engine = BackupEngine(
|
||||
adapter,
|
||||
backup_root,
|
||||
guarded_runner,
|
||||
)
|
||||
|
||||
backup = engine.create()
|
||||
manifest = engine.verify(backup)
|
||||
|
||||
print("PASS: Real MySQL backup created")
|
||||
print("Backup bytes:", manifest["bytes"])
|
||||
print("SHA-256:", manifest["sha256"])
|
||||
|
||||
evidence["backup"] = str(
|
||||
backup.relative_to(ROOT)
|
||||
)
|
||||
|
||||
evidence["backup_sha256"] = manifest["sha256"]
|
||||
|
||||
evidence["backup_bytes"] = manifest["bytes"]
|
||||
|
||||
print("\n=== CREATE ISOLATED RESTORE TARGET ===")
|
||||
|
||||
sql(
|
||||
"CREATE DATABASE isolated_restore_mysql "
|
||||
"CHARACTER SET utf8mb4"
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
sql(
|
||||
"SELECT COUNT(*) FROM "
|
||||
"information_schema.tables "
|
||||
"WHERE table_schema = "
|
||||
"'isolated_restore_mysql'"
|
||||
).strip(),
|
||||
b"0",
|
||||
)
|
||||
|
||||
print("PASS: Restore target is empty")
|
||||
|
||||
restore = bounded(
|
||||
adapter.restore_command(
|
||||
RESTORE_DATABASE
|
||||
)
|
||||
)
|
||||
|
||||
verify_isolation()
|
||||
|
||||
engine.verify(backup)
|
||||
|
||||
# The restore path is intentionally
|
||||
# separate from the backup-only runner.
|
||||
|
||||
with (backup / "database.sql").open("rb") as handle:
|
||||
|
||||
result = subprocess.run(
|
||||
restore,
|
||||
stdin=handle,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=75,
|
||||
)
|
||||
|
||||
require(
|
||||
result.returncode == 0,
|
||||
"MySQL restoration failed",
|
||||
)
|
||||
|
||||
print("PASS: Real MySQL restoration completed")
|
||||
|
||||
print("\n=== COMPARE SOURCE AND RESTORED DATA ===")
|
||||
|
||||
queries = {
|
||||
"users": (
|
||||
"SELECT id, name, email "
|
||||
"FROM users ORDER BY id"
|
||||
),
|
||||
"orders": (
|
||||
"SELECT id, user_id, amount, "
|
||||
"HEX(payload) FROM orders ORDER BY id"
|
||||
),
|
||||
"migrations": (
|
||||
"SELECT id, migration, batch "
|
||||
"FROM migrations ORDER BY id"
|
||||
),
|
||||
"table_columns": (
|
||||
"SELECT TABLE_NAME, COLUMN_NAME, "
|
||||
"COLUMN_TYPE, IS_NULLABLE "
|
||||
"FROM information_schema.COLUMNS "
|
||||
"WHERE TABLE_SCHEMA=DATABASE() "
|
||||
"ORDER BY TABLE_NAME, ORDINAL_POSITION"
|
||||
),
|
||||
"indexes": (
|
||||
"SELECT TABLE_NAME, INDEX_NAME, "
|
||||
"NON_UNIQUE, SEQ_IN_INDEX, COLUMN_NAME "
|
||||
"FROM information_schema.STATISTICS "
|
||||
"WHERE TABLE_SCHEMA=DATABASE() "
|
||||
"ORDER BY TABLE_NAME, INDEX_NAME, "
|
||||
"SEQ_IN_INDEX"
|
||||
),
|
||||
"foreign_keys": (
|
||||
"SELECT TABLE_NAME, CONSTRAINT_NAME, "
|
||||
"COLUMN_NAME, REFERENCED_TABLE_NAME, "
|
||||
"REFERENCED_COLUMN_NAME "
|
||||
"FROM information_schema.KEY_COLUMN_USAGE "
|
||||
"WHERE TABLE_SCHEMA=DATABASE() "
|
||||
"AND REFERENCED_TABLE_NAME IS NOT NULL "
|
||||
"ORDER BY TABLE_NAME, CONSTRAINT_NAME, "
|
||||
"ORDINAL_POSITION"
|
||||
),
|
||||
}
|
||||
|
||||
for label, query in queries.items():
|
||||
|
||||
original = sql(
|
||||
query,
|
||||
SOURCE_DATABASE,
|
||||
)
|
||||
|
||||
restored = sql(
|
||||
query,
|
||||
RESTORE_DATABASE,
|
||||
)
|
||||
|
||||
self.assertTrue(original)
|
||||
|
||||
self.assertEqual(
|
||||
original,
|
||||
restored,
|
||||
f"Restoration mismatch: {label}",
|
||||
)
|
||||
|
||||
print("PASS:", label)
|
||||
|
||||
self.assertEqual(
|
||||
sql(
|
||||
"SELECT COUNT(*) FROM users",
|
||||
RESTORE_DATABASE,
|
||||
).strip(),
|
||||
b"2",
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
sql(
|
||||
"SELECT COUNT(*) FROM orders",
|
||||
RESTORE_DATABASE,
|
||||
).strip(),
|
||||
b"2",
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
sql(
|
||||
"SELECT COUNT(*) FROM migrations",
|
||||
RESTORE_DATABASE,
|
||||
).strip(),
|
||||
b"3",
|
||||
)
|
||||
|
||||
print("PASS: Expected record counts verified")
|
||||
|
||||
print("\n=== VERIFY FOREIGN KEY ENFORCEMENT ===")
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
|
||||
sql(
|
||||
"INSERT INTO orders VALUES "
|
||||
"(999, 999, 1.00, NULL)",
|
||||
RESTORE_DATABASE,
|
||||
)
|
||||
|
||||
print("PASS: Invalid foreign key rejected")
|
||||
|
||||
print("\n=== VERIFY BACKUP INTEGRITY AGAIN ===")
|
||||
|
||||
engine.verify(backup)
|
||||
|
||||
evidence["verified_checks"] = list(queries)
|
||||
|
||||
evidence["result"] = "MYSQL_RESTORE_VERIFIED"
|
||||
|
||||
finally:
|
||||
|
||||
print("\n=== REMOVE DISPOSABLE DATABASE ===")
|
||||
|
||||
if cid is not None:
|
||||
|
||||
item = inspect(cid)
|
||||
|
||||
labels = item["Config"]["Labels"]
|
||||
|
||||
require(
|
||||
item["Id"] == cid
|
||||
and labels.get(LABEL) == "true"
|
||||
and labels.get(
|
||||
"absdev.integration.token"
|
||||
) == token,
|
||||
"Unsafe cleanup target",
|
||||
)
|
||||
|
||||
command(
|
||||
"docker", "rm", "-f", "-v", cid
|
||||
)
|
||||
|
||||
print("PASS: Test container removed")
|
||||
|
||||
after = production_inventory()
|
||||
|
||||
evidence["production_inventory_unchanged"] = (
|
||||
before == after
|
||||
)
|
||||
|
||||
evidence["completed_at"] = datetime.now(
|
||||
timezone.utc
|
||||
).isoformat()
|
||||
|
||||
report = work / "result.json"
|
||||
|
||||
with report.open("x") as handle:
|
||||
|
||||
json.dump(
|
||||
evidence,
|
||||
handle,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
handle.write("\n")
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
|
||||
print("Integration evidence:", report)
|
||||
|
||||
self.assertEqual(
|
||||
before,
|
||||
after,
|
||||
"Production container inventory changed",
|
||||
)
|
||||
|
||||
print("PASS: Production container uptime preserved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user