#!/usr/bin/env python3 """Deploy an already-built Qt-clean candidate, preserving the former container.""" import argparse import datetime import json import os from pathlib import Path import subprocess import tarfile import time def run(argv, **kwargs): return subprocess.run(argv, check=True, text=True, capture_output=True, **kwargs).stdout.strip() def main(): parser = argparse.ArgumentParser() parser.add_argument('--image', required=True) parser.add_argument('--release', required=True) args = parser.parse_args() release = Path(args.release).resolve() production = Path('/home/user/XJKJ-STL') evidence = release / 'evidence' evidence.mkdir(parents=True, exist_ok=True) container = 'xjkj-stl-backend' previous = json.loads(run(['docker', 'inspect', container]))[0] stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ') saved_name = 'xjkj-stl-backend-before-qt-' + stamp.lower() backup = production.parent / 'XJKJ-STL-backups' / ('before-qt-' + stamp) backup.mkdir(parents=True) private = release / '.runtime.env' # Preserve the existing authorized runtime credentials without displaying them. values = [value for value in previous['Config']['Env'] if value.split('=', 1)[0].startswith('STL_') and not value.startswith('STL_BUILD_COMMIT=')] private.write_text('\n'.join(values) + '\n') private.chmod(0o600) report = {'started_utc': stamp, 'image': args.image, 'previous_image': previous['Config']['Image'], 'previous_container': saved_name, 'backup': str(backup), 'original_source_directory': str(production), 'passed': False} renamed = False try: run(['docker', 'stop', '--time', '120', container]) with tarfile.open(backup / 'config-data.tar.gz', 'w:gz') as archive: for name in ('config', 'data'): archive.add(production / name, arcname=name) run(['docker', 'rename', container, saved_name]) renamed = True run(['docker', 'run', '-d', '--name', container, '--restart', 'unless-stopped', '--stop-timeout', '120', '--network', 'host', '--env-file', str(private), '-v', str(production / 'config') + ':/app/config:ro', '-v', str(production / 'data') + ':/app/data', args.image, 'python3', '-m', 'stl_backend.server', '--config', 'config/station0-live.json', '--listen', '0.0.0.0:50051', '--web-listen', '0.0.0.0:8080', '--data-dir', '/app/data']) for _ in range(25): p = subprocess.run(['docker', 'exec', container, 'python3', '-c', "import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/', timeout=2); assert r.status == 200"], capture_output=True, text=True) if p.returncode == 0: report['passed'] = True break time.sleep(1) if not report['passed']: raise RuntimeError('Candidate did not become HTTP-ready') report['container_id'] = run(['docker', 'inspect', '--format', '{{.Id}}', container]) report['runtime_version'] = run(['docker', 'exec', container, 'python3', '-c', 'import stl_backend; print(stl_backend.__version__)']) except Exception as exc: report['error'] = str(exc) if renamed: subprocess.run(['docker', 'rm', '-f', container], capture_output=True) run(['docker', 'rename', saved_name, container]) run(['docker', 'start', container]) report['rolled_back'] = True raise finally: private.unlink(missing_ok=True) (evidence / 'deployment.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, indent=2), flush=True) if __name__ == '__main__': main()