deploy_qt_release.py 3.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env python3
  2. """Deploy an already-built Qt-clean candidate, preserving the former container."""
  3. import argparse
  4. import datetime
  5. import json
  6. import os
  7. from pathlib import Path
  8. import subprocess
  9. import tarfile
  10. import time
  11. def run(argv, **kwargs):
  12. return subprocess.run(argv, check=True, text=True, capture_output=True, **kwargs).stdout.strip()
  13. def main():
  14. parser = argparse.ArgumentParser()
  15. parser.add_argument('--image', required=True)
  16. parser.add_argument('--release', required=True)
  17. args = parser.parse_args()
  18. release = Path(args.release).resolve()
  19. production = Path('/home/user/XJKJ-STL')
  20. evidence = release / 'evidence'
  21. evidence.mkdir(parents=True, exist_ok=True)
  22. container = 'xjkj-stl-backend'
  23. previous = json.loads(run(['docker', 'inspect', container]))[0]
  24. stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
  25. saved_name = 'xjkj-stl-backend-before-qt-' + stamp.lower()
  26. backup = production.parent / 'XJKJ-STL-backups' / ('before-qt-' + stamp)
  27. backup.mkdir(parents=True)
  28. private = release / '.runtime.env'
  29. # Preserve the existing authorized runtime credentials without displaying them.
  30. values = [value for value in previous['Config']['Env']
  31. if value.split('=', 1)[0].startswith('STL_')
  32. and not value.startswith('STL_BUILD_COMMIT=')]
  33. private.write_text('\n'.join(values) + '\n')
  34. private.chmod(0o600)
  35. report = {'started_utc': stamp, 'image': args.image,
  36. 'previous_image': previous['Config']['Image'],
  37. 'previous_container': saved_name, 'backup': str(backup),
  38. 'original_source_directory': str(production), 'passed': False}
  39. renamed = False
  40. try:
  41. run(['docker', 'stop', '--time', '120', container])
  42. with tarfile.open(backup / 'config-data.tar.gz', 'w:gz') as archive:
  43. for name in ('config', 'data'):
  44. archive.add(production / name, arcname=name)
  45. run(['docker', 'rename', container, saved_name])
  46. renamed = True
  47. run(['docker', 'run', '-d', '--name', container, '--restart', 'unless-stopped',
  48. '--stop-timeout', '120', '--network', 'host', '--env-file', str(private),
  49. '-v', str(production / 'config') + ':/app/config:ro',
  50. '-v', str(production / 'data') + ':/app/data',
  51. args.image, 'python3', '-m', 'stl_backend.server',
  52. '--config', 'config/station0-live.json', '--listen', '0.0.0.0:50051',
  53. '--web-listen', '0.0.0.0:8080', '--data-dir', '/app/data'])
  54. for _ in range(25):
  55. p = subprocess.run(['docker', 'exec', container, 'python3', '-c',
  56. "import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/', timeout=2); assert r.status == 200"],
  57. capture_output=True, text=True)
  58. if p.returncode == 0:
  59. report['passed'] = True
  60. break
  61. time.sleep(1)
  62. if not report['passed']:
  63. raise RuntimeError('Candidate did not become HTTP-ready')
  64. report['container_id'] = run(['docker', 'inspect', '--format', '{{.Id}}', container])
  65. report['runtime_version'] = run(['docker', 'exec', container, 'python3', '-c',
  66. 'import stl_backend; print(stl_backend.__version__)'])
  67. except Exception as exc:
  68. report['error'] = str(exc)
  69. if renamed:
  70. subprocess.run(['docker', 'rm', '-f', container], capture_output=True)
  71. run(['docker', 'rename', saved_name, container])
  72. run(['docker', 'start', container])
  73. report['rolled_back'] = True
  74. raise
  75. finally:
  76. private.unlink(missing_ok=True)
  77. (evidence / 'deployment.json').write_text(json.dumps(report, indent=2) + '\n')
  78. print(json.dumps(report, indent=2), flush=True)
  79. if __name__ == '__main__':
  80. main()