158 lines
8.6 KiB
Python
158 lines
8.6 KiB
Python
"""Backup, isolated recovery and atomic selection of the expressly authorised synthetic demo."""
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import secrets
|
|
import subprocess
|
|
import sys
|
|
import uuid
|
|
|
|
|
|
def run(args, **kwargs):
|
|
result = subprocess.run(args, text=True, capture_output=True, **kwargs)
|
|
if result.returncode:
|
|
raise RuntimeError(f"Command failed: {args[0]} {args[1:3]}\n{result.stderr[-1200:]}\n{result.stdout[-1200:]}")
|
|
return result.stdout
|
|
|
|
|
|
def sql(database, statement):
|
|
return run(['runuser', '-u', 'postgres', '--', 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-At', '-d', database, '-c', statement]).strip()
|
|
|
|
|
|
def frames(database):
|
|
tables = sql(database, "SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename").splitlines()
|
|
result = {}
|
|
for table in tables:
|
|
assert table.replace('_', '').isalnum()
|
|
result[table] = sql(database, 'SELECT md5(COALESCE(string_agg(j,chr(10) ORDER BY j),\'\')) FROM (SELECT row_to_json(t)::text AS j FROM "'+table+'" t) s')
|
|
return result
|
|
|
|
|
|
def main():
|
|
assert os.geteuid() == 0 and sys.argv[1] == '--activate-authorized-synthetic'
|
|
base = Path('/var/www/compras-deploy')
|
|
demo = base / 'demonstration-20261129'
|
|
release = base / 'releases/presentation-20261129'
|
|
previous = Path((demo / 'previous-release.txt').read_text())
|
|
assert (base / 'current').resolve() == previous
|
|
assert json.loads((demo / 'evidence-check.json').read_text())['state'] == 'passed'
|
|
finance = run(['php', 'scripts/check-public-demo-finance.php', '--read-only'], cwd=release)
|
|
assert json.loads(finance)['state'] == 'passed'
|
|
(demo / 'finance-check.json').write_text(finance)
|
|
http = run(['python3', '/root/check-public-demonstration.py', '--check-authorized-synthetic'])
|
|
assert json.loads(http)['state'] == 'passed'
|
|
(demo / 'staging-http-check.json').write_text(http)
|
|
backup = Path('/var/backups/compras-presentation-20261129')
|
|
assert not backup.exists(), 'Do not overwrite an existing deployment backup'
|
|
backup.mkdir(mode=0o700)
|
|
shutil.copy2(previous / '.env', backup / 'previous.env.private')
|
|
(backup / 'previous-release.txt').write_text(str(previous))
|
|
previous_hash = hashlib.sha256((previous / '.env').read_bytes()).hexdigest()
|
|
for database, name in [('compras_db', 'previous.dump'), ('compras_demo_20261129', 'demonstration.dump')]:
|
|
with (backup / name).open('xb') as out:
|
|
result = subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', database], stdout=out, stderr=subprocess.PIPE)
|
|
assert result.returncode == 0, result.stderr.decode()[:500]
|
|
run(['pg_restore', '--list', str(backup / name)])
|
|
original = frames('compras_demo_20261129')
|
|
recovery = 'compras_demo_recovery_20261129'
|
|
assert not sql('postgres', f"SELECT datname FROM pg_database WHERE datname='{recovery}'")
|
|
recovery_role = 'compras_demo_recovery_app_20261129'
|
|
recovery_password = secrets.token_hex(32)
|
|
sql('postgres', f"CREATE ROLE {recovery_role} LOGIN PASSWORD '{recovery_password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS")
|
|
run(['runuser', '-u', 'postgres', '--', 'createdb', '-O', recovery_role, recovery])
|
|
try:
|
|
restore_env = {**os.environ, 'PGPASSWORD': recovery_password}
|
|
with (backup / 'demonstration.dump').open('rb') as source:
|
|
restored = subprocess.run(['pg_restore', '-h', '127.0.0.1', '-U', recovery_role, '--no-owner', '--no-acl', '-d', recovery],
|
|
stdin=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=restore_env)
|
|
assert restored.returncode == 0, restored.stderr.decode()[:800]
|
|
assert frames(recovery) == original, 'Synthetic backup recovery mismatch'
|
|
recovery_env = {**os.environ, 'DB_DATABASE': recovery, 'DB_USERNAME': recovery_role, 'DB_PASSWORD': recovery_password,
|
|
'APP_CONFIG_CACHE': str(demo / 'storage/framework/cache/recovery-config.php'),
|
|
'COMPRAS_RUNTIME_ENABLED': 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'true', 'COMPRAS_RUNTIME_INSTALLATION_ID': str(uuid.uuid4())}
|
|
run(['php', 'artisan', 'compras:runtime:prepare', '--expected-database='+recovery, '--expected-role='+recovery_role,
|
|
'--operator=Tempo presentation recovery', '--reason=Explicit synthetic restoration and new installation binding verification', '--rebind', '--apply'], cwd=release, env=recovery_env)
|
|
rebound = frames(recovery)
|
|
assert {k:v for k,v in rebound.items() if k != 'compras_runtime_installations'} == {k:v for k,v in original.items() if k != 'compras_runtime_installations'}
|
|
recovery_env.update({'COMPRAS_RUNTIME_ENABLED': 'true', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'false'})
|
|
boot = "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();$r=app(App\\Services\\StandaloneRuntime::class);foreach($r::FEATURES as $f){if(!$r->feature($f,Illuminate\\Support\\Facades\\DB::connection()))throw new LogicException('Recovery capability unavailable');}echo '24 recovery capabilities verified';"
|
|
assert run(['php', '-r', boot], cwd=release, env=recovery_env) == '24 recovery capabilities verified'
|
|
finally:
|
|
run(['runuser', '-u', 'postgres', '--', 'dropdb', recovery])
|
|
sql('postgres', f'DROP ROLE {recovery_role}')
|
|
units = Path('/etc/systemd/system')
|
|
service = units / 'compras-demo-operations.service'
|
|
timer = units / 'compras-demo-operations.timer'
|
|
assert not service.exists() and not timer.exists(), 'Do not replace an existing service'
|
|
service.write_text(f'''[Unit]
|
|
Description=Compras synthetic presentation recurring operations
|
|
After=postgresql.service
|
|
|
|
[Service]
|
|
Type=oneshot
|
|
User=www-data
|
|
Group=www-data
|
|
WorkingDirectory={release}
|
|
ExecStart=/usr/bin/php artisan sgc:approval-deadlines-tick
|
|
ExecStart=/usr/bin/php artisan sgc:replenishment-tick
|
|
TimeoutStartSec=60
|
|
UMask=0077
|
|
NoNewPrivileges=true
|
|
PrivateTmp=true
|
|
ProtectSystem=strict
|
|
ProtectHome=true
|
|
ReadWritePaths={demo}/storage
|
|
''')
|
|
timer.write_text('''[Unit]
|
|
Description=Compras synthetic presentation minute observation
|
|
|
|
[Timer]
|
|
OnBootSec=60
|
|
OnUnitActiveSec=60
|
|
Unit=compras-demo-operations.service
|
|
AccuracySec=5
|
|
|
|
[Install]
|
|
WantedBy=timers.target
|
|
''')
|
|
run(['systemd-analyze', 'verify', str(service), str(timer)])
|
|
run(['systemctl', 'daemon-reload'])
|
|
run(['systemctl', 'start', service.name])
|
|
before_restart = frames('compras_demo_20261129')
|
|
run(['systemctl', 'restart', service.name])
|
|
after_restart = frames('compras_demo_20261129')
|
|
changed = [name for name in before_restart if before_restart[name] != after_restart[name]]
|
|
assert set(changed).issubset({'replenishment_work'}), changed
|
|
assert run(['systemctl', 'show', service.name, '-p', 'ExecMainStatus', '--value']).strip() == '0'
|
|
assert hashlib.sha256((previous / '.env').read_bytes()).hexdigest() == previous_hash
|
|
assert (base / 'current').resolve() == previous
|
|
temporary = base / 'current.presentation.tmp'
|
|
assert not temporary.exists() and not temporary.is_symlink()
|
|
temporary.symlink_to(release, target_is_directory=True)
|
|
os.replace(temporary, base / 'current')
|
|
try:
|
|
run(['systemctl', 'enable', '--now', timer.name])
|
|
public = run(['python3', '/root/check-public-demonstration.py', '--check-authorized-synthetic', 'https://compras.tempo.co.mz'])
|
|
assert json.loads(public)['state'] == 'passed'
|
|
(demo / 'public-http-check.json').write_text(public)
|
|
except BaseException:
|
|
run(['systemctl', 'disable', '--now', timer.name])
|
|
temporary.symlink_to(previous, target_is_directory=True)
|
|
os.replace(temporary, base / 'current')
|
|
raise
|
|
result = {'state': 'passed', 'domain': 'https://compras.tempo.co.mz', 'release': str(release), 'previous_release': str(previous),
|
|
'synthetic_database': 'compras_demo_20261129', 'previous_database_unchanged_by_deployment': True, 'previous_env_hash_preserved': previous_hash,
|
|
'backup': str(backup), 'synthetic_recovery_tables_exact': len(original), 'recovery_database_removed': True,
|
|
'recovery_new_native_binding_and_24_capabilities_verified': True, 'recovery_business_tables_preserved_after_rebind': True,
|
|
'worker_runs_as': 'www-data', 'worker_restart_exit': 0, 'business_tables_unchanged_by_worker_restart': True,
|
|
'worker_restart_changed_tables': changed, 'interactive_windows_session_required': False, 'timer_enabled': True,
|
|
'host_reboot_executed': False, 'jue_or_bank_external_execution': False}
|
|
(demo / 'activation.json').write_text(json.dumps(result, indent=2))
|
|
print(json.dumps(result, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|