cmvr-wms/mobile-app/deploy/install-ota.py

131 lines
6.4 KiB
Python
Raw Normal View History

"""Initial OTA deployment only. Upload public, signed release files; never keys.
Run on the authorized production server as its existing deployment user.
Backs up nginx, validates before reload, and preserves the existing backend.
"""
import datetime
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tarfile
import time
import urllib.request
APP = Path('/data/apps/cmvr-project-prod')
OTA = APP / 'mobile-ota'
RUNTIME = 'ac523f4137469f9f4b0faaca30982e68445686df'
def run(*args):
return subprocess.check_output(args, stderr=subprocess.STDOUT, text=True).strip()
def get(url, headers=None):
with urllib.request.urlopen(urllib.request.Request(url, headers=headers or {}), timeout=10) as response:
return response.status, dict(response.headers), response.read()
def main():
archive, expected_hash, image = sys.argv[1:]
if not re.fullmatch(r'(?:node@)?sha256:[a-f0-9]{64}', image):
raise ValueError('Require a pinned, verified Node runtime image digest')
if not run('docker', 'run', '--rm', '--network', 'none', image, 'node', '--version').startswith('v24.'):
raise ValueError('Require the verified Node 24 runtime')
if hashlib.sha256(Path(archive).read_bytes()).hexdigest() != expected_hash:
raise ValueError('Deployment archive hash mismatch')
if (OTA / 'deployment.json').exists():
raise RuntimeError('Initial deployment already completed; inspect before a subsequent release')
nginx = (APP / 'current/nginx.conf').resolve(strict=True)
if not str(nginx).startswith(str(APP / 'releases') + '/'):
raise RuntimeError('Unexpected production nginx path')
original = nginx.read_bytes()
if b'/updates/prod' in original or b'127.0.0.1:8190' in original:
raise RuntimeError('OTA nginx routes already exist; inspect before modifying')
before = run('docker', 'inspect', 'cmvr-project-prod-backend', '--format', '{{.State.StartedAt}}')
frontend_before = run('docker', 'inspect', 'cmvr-project-prod-frontend', '--format', '{{.State.StartedAt}}')
date = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%d-%H%M%S')
backup = APP / 'backups' / ('mobile-ota-' + date)
backup.mkdir(mode=0o700)
shutil.copy2(nginx, backup / 'nginx.conf')
OTA.mkdir(mode=0o700, exist_ok=True)
release = OTA / 'releases' / date
release.mkdir(parents=True)
with tarfile.open(archive, 'r:gz') as bundle:
for member in bundle.getmembers():
target = (release / member.name).resolve()
if not target.is_relative_to(release.resolve()) or not (member.isfile() or member.isdir()):
raise ValueError('Unsafe deployment archive member')
bundle.extractall(release)
for entry in release.rglob('*'):
if entry.suffix in {'.p12', '.jks', '.keystore', '.dpapi'} or 'private-key' in entry.name:
raise ValueError('Private material is forbidden on update server')
entry.chmod(0o755 if entry.is_dir() else 0o644)
release.chmod(0o755)
os.symlink(release, OTA / 'current')
shutil.copytree(release / 'data', OTA / 'data')
shutil.copy2(release / 'docker-compose.yml', OTA / 'docker-compose.yml')
(OTA / '.env').write_text('OTA_NODE_IMAGE=' + image + '\n')
(OTA / '.env').chmod(0o600)
locations = (release / 'nginx-ota.locations.conf').read_text()
candidate = original.decode().rstrip()
if not candidate.endswith('}'):
raise ValueError('Unexpected nginx structure')
candidate = candidate[:-1] + locations + '\n}\n'
candidate_path = backup / 'nginx-candidate.conf'
candidate_path.write_text(candidate)
run('docker', 'run', '--rm', '--network', 'none', '-v', str(candidate_path) + ':/etc/nginx/conf.d/default.conf:ro',
'nginx:1.25.5', 'nginx', '-t')
compose = ['docker', 'compose', '--project-directory', str(OTA), '-f', str(OTA / 'docker-compose.yml')]
nginx_changed = False
try:
run(*compose, 'up', '-d', '--no-deps', 'ota')
for attempt in range(20):
try:
if get('http://127.0.0.1:8190/health')[0] == 200:
break
except Exception:
time.sleep(1)
else:
raise RuntimeError('OTA health check timed out')
# Preserve the inode: the running nginx has a read-only bind mount of this file.
nginx.write_text(candidate)
nginx_changed = True
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-t')
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-s', 'reload')
time.sleep(1)
status, headers, body = get('http://127.0.0.1/updates/prod', {
'expo-platform': 'android', 'expo-runtime-version': RUNTIME, 'expo-protocol-version': '1'})
manifest = json.loads(body)
if status != 200 or manifest['runtimeVersion'] != RUNTIME or manifest['metadata']['environment'] != 'prod':
raise RuntimeError('Public route did not return production manifest')
if not any(key.lower() == 'expo-signature' for key in headers):
raise RuntimeError('Signature header missing after proxy')
after = run('docker', 'inspect', 'cmvr-project-prod-backend', '--format', '{{.State.StartedAt}}')
frontend_after = run('docker', 'inspect', 'cmvr-project-prod-frontend', '--format', '{{.State.StartedAt}}')
if before != after or frontend_before != frontend_after:
raise RuntimeError('Existing application container unexpectedly restarted')
result = {'deployedAt': date, 'url': 'http://192.168.28.10/updates/prod', 'container': 'cmvr-mobile-ota-prod',
'image': image, 'runtime': RUNTIME, 'updateId': manifest['id'], 'backup': str(backup),
'backendRestarted': False, 'frontendRestarted': False, 'databaseTouched': False}
(OTA / 'deployment.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result))
except Exception:
if nginx_changed:
nginx.write_bytes(original)
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-t')
run('docker', 'exec', 'cmvr-project-prod-frontend', 'nginx', '-s', 'reload')
run(*compose, 'stop', 'ota')
raise
if __name__ == '__main__':
with (APP / '.mobile-ota-deploy.lock').open('w') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
main()