diff --git a/scripts/deploy_test14_com.py b/scripts/deploy_test14_com.py new file mode 100644 index 0000000..94b97b1 --- /dev/null +++ b/scripts/deploy_test14_com.py @@ -0,0 +1,232 @@ +"""Release test14's validated local artifacts to the US only, with rollback.""" +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import runpy +import shlex +import subprocess +import sys +import tarfile +import tempfile +from datetime import datetime, timezone + +ROOT = Path(__file__).resolve().parents[1] +PORTAL = '/var/www/nomadro.cn' +ADMIN = '/www/wwwroot/admin.nomadro.com' +SERVICES = 'nomadro nomadmini-api nomadro-social nomadro-work nomadro-notify nomadro-coffee' +RELEASE = 'test14-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') +STAGE = f'/var/tmp/nomadro-{RELEASE}' +BACKUP = f'/var/backups/nomadro-upgrade/{RELEASE}' +sys.stdout.reconfigure(encoding='utf-8', errors='replace', line_buffering=True) + + +def run(client, command, timeout=240): + _, out, err = client.exec_command(command, timeout=timeout) + output = out.read().decode('utf-8', 'replace') + error = err.read().decode('utf-8', 'replace') + code = out.channel.recv_exit_status() + if output.strip(): + print(output.strip()) + if error.strip(): + print(error.strip(), file=sys.stderr) + if code: + raise RuntimeError(f'remote step failed ({code})') + return output + + +def main(): + branch = subprocess.check_output(['git', 'branch', '--show-current'], cwd=ROOT, text=True).strip() + assert branch == 'test14', 'test14 only' + commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip() + build_id = (ROOT / '.next/BUILD_ID').read_text().strip() + assert (ROOT / 'apps/com/admin/dist/index.html').is_file() + # Confirm this build did not bake the development public-site proxy into prod. + routes = json.loads((ROOT / '.next/routes-manifest.json').read_text()) + rewrite_data = json.dumps(routes['rewrites']) + assert 'http://127.0.0.1:8010/api/v1' in rewrite_data + assert 'http://127.0.0.1:8020/api/social' in rewrite_data + + files = {} + source_names = [ + 'next.config.ts', 'src/proxy.ts', 'src/app/page.tsx', + 'src/components/portal-analytics.tsx', 'src/lib/client-request.ts', + 'src/lib/online-upstream.ts', 'src/lib/remote-config-client.ts', + ] + for name in source_names: + files[f'{PORTAL}/{name}'] = ROOT / name + pb = ROOT / 'apps/api/services/nomadro_pb/client.py' + for name in [ + f'{PORTAL}/apps/api/services/nomadro_pb/client.py', + '/opt/nomadmini/backend/nomadro_pb/client.py', + '/opt/nomadmini/backend/services/nomadro_pb/client.py', + ]: + files[name] = pb + for source in (ROOT / 'apps/com/admin/dist').rglob('*'): + if source.is_file(): + files[f'{ADMIN}/{source.relative_to(ROOT / "apps/com/admin/dist").as_posix()}'] = source + removed = [f'{PORTAL}/src/middleware.ts'] + manifest = {'files': list(files), 'removed': removed} + client = runpy.run_path(str(ROOT / 'apps/admin/deploy/_upload_next_us.py'))['connect']() + assert client.get_transport().getpeername()[0] == '108.174.50.68', 'US only' + mutations_started = False + try: + with tempfile.TemporaryDirectory() as temporary: + package = Path(temporary) / 'release.tgz' + runtime_env = Path(temporary) / 'upstreams.env' + runtime_env.write_text( + 'API_URL=http://127.0.0.1:8010\n' + 'SOCIAL_API_URL=http://127.0.0.1:8020\n' + 'WORK_API_URL=http://127.0.0.1:8021\n' + 'NOTIFY_API_URL=http://127.0.0.1:8023\n' + 'COFFEE_API_URL=http://127.0.0.1:8024\n', encoding='utf-8') + dropin = Path(temporary) / 'upstreams.conf' + dropin.write_text('[Service]\nEnvironmentFile=/etc/nomadro/test14-upstreams.env\n', encoding='utf-8') + files['/etc/nomadro/test14-upstreams.env'] = runtime_env + files['/etc/systemd/system/nomadro.service.d/zz-test14-upstreams.conf'] = dropin + manifest['files'] = list(files) + + def include(info): + if any(info.name == f'next/{part}' or info.name.startswith(f'next/{part}/') for part in ['cache', 'dev']): + return None + if info.name.endswith('/lock'): + return None + return info + + with tarfile.open(package, 'w:gz') as archive: + archive.add(ROOT / '.next', arcname='next', filter=include) + for target, source in files.items(): + archive.add(source, arcname='files/' + target.lstrip('/')) + plan = Path(temporary) / 'manifest.json' + plan.write_text(json.dumps(manifest), encoding='utf-8') + archive.add(plan, arcname='manifest.json') + digest = hashlib.sha256(package.read_bytes()).hexdigest() + remote_package = f'/var/tmp/nomadro-{RELEASE}.tgz' + print('release', RELEASE, 'build', build_id, 'MB', round(package.stat().st_size / 1024**2, 1)) + last_progress = [-1] + + def progress(sent, total): + fraction = int(sent * 10 / total) + if fraction != last_progress[0]: + last_progress[0] = fraction + print('upload', round(sent / 1024**2, 1), '/', round(total / 1024**2, 1), 'MB') + + with client.open_sftp() as sftp: + sftp.put(str(package), remote_package, callback=progress) + + run(client, f'''set -eu +echo '{digest} {remote_package}' | sha256sum -c - +mkdir -p {STAGE} {BACKUP} +chmod 700 {BACKUP} +tar -xzf {remote_package} -C {STAGE} +test "$(cat {STAGE}/next/BUILD_ID)" = {shlex.quote(build_id)} +python3 - <<'PY' +import json,pathlib,shutil,py_compile +stage=pathlib.Path({STAGE!r}); backup=pathlib.Path({BACKUP!r}) +plan=json.loads((stage/'manifest.json').read_text()) +state={{}} +for target in plan['files']+plan['removed']: + p=pathlib.Path(target) + state[target]=p.is_file() + if p.is_file(): + dest=backup/'files'/target.lstrip('/') + dest.parent.mkdir(parents=True,exist_ok=True) + shutil.copy2(p,dest) +for target in plan['files']: + if target.endswith('.py'): py_compile.compile(str(stage/'files'/target.lstrip('/')),doraise=True) +(backup/'manifest.json').write_text(json.dumps(state)) +print('Code backup ready') +PY +''') + mutations_started = True + run(client, f'''set -eu +systemctl stop {SERVICES} +mv {PORTAL}/.next {BACKUP}/next +mv {STAGE}/next {PORTAL}/.next +python3 - <<'PY' +import json,pathlib,shutil +stage=pathlib.Path({STAGE!r}) +plan=json.loads((stage/'manifest.json').read_text()) +for target in plan['files']: + dest=pathlib.Path(target); dest.parent.mkdir(parents=True,exist_ok=True) + temp=dest.with_name(dest.name+'.release-next') + shutil.copy2(stage/'files'/target.lstrip('/'),temp) + temp.replace(dest) +for target in plan['removed']: pathlib.Path(target).unlink(missing_ok=True) +PY +systemctl daemon-reload +systemctl start {SERVICES} +for attempt in $(seq 1 30); do + if curl -fsS --max-time 2 http://127.0.0.1:4003/api/health >/dev/null && curl -fsS --max-time 2 http://127.0.0.1:8010/health >/dev/null && curl -fsS --max-time 2 http://127.0.0.1:8020/health >/dev/null; then break; fi + sleep 1 +done +systemctl is-active {SERVICES} nginx +test "$(cat {PORTAL}/.next/BUILD_ID)" = {shlex.quote(build_id)} +curl -fsS --max-time 15 http://127.0.0.1:4003/api/health +curl -fsS --max-time 15 http://127.0.0.1:8010/health +curl -fsS --max-time 15 http://127.0.0.1:8020/health +curl -fsS --max-time 15 http://127.0.0.1:8021/health +curl -fsS --max-time 15 http://127.0.0.1:8023/api/notify/v1/health +curl -fsS --max-time 15 http://127.0.0.1:8024/api/coffee/v1/hosts >/dev/null +''') + # Public routes, exact redirects, build assets, deployed source hashes. + run(client, f'''python3 - <<'PY' +import urllib.request,urllib.error,pathlib,hashlib,json,re +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self,*args): return None +opener=urllib.request.build_opener(NoRedirect) +checks=[('https://nomadro.com/',200,None),('https://nomadro.com/social?release=test14',308,'/?release=test14'),('https://nomadro.com/social/places',200,None),('https://nomadro.com/social/work/pads',200,None),('https://nomadro.com/api/health',200,None),('https://nomadro.com/api/social/v1/health',200,None),('https://nomadro.com/api/work/v1/health',200,None),('https://nomadro.com/api/notify/v1/health',200,None),('https://nomadro.com/api/coffee/v1/hosts',200,None),('https://admin.nomadro.com/',200,None)] +for url,status,location in checks: + try: response=opener.open(url,timeout=25) + except urllib.error.HTTPError as error: response=error + with response: + assert response.code==status,(url,response.code) + if location: assert response.headers['Location'].endswith(location),(url,response.headers['Location']) + body=response.read().decode() + if url=='https://nomadro.com/': + assert 'community-root social-skin' in body + if url=='https://admin.nomadro.com/': + assert body==pathlib.Path({(ADMIN+'/index.html')!r}).read_text(), 'admin index differs' + for asset in re.findall(r'(?:src|href)="(/assets/[^" ]+)"',body): + with opener.open('https://admin.nomadro.com'+asset,timeout=25) as item: assert item.code==200 + print(url,status,'OK') +stage=pathlib.Path({STAGE!r}) +for target in json.loads((stage/'manifest.json').read_text())['files']: + assert hashlib.sha256(pathlib.Path(target).read_bytes()).digest()==hashlib.sha256((stage/'files'/target.lstrip('/')).read_bytes()).digest(),target +print('All deployed source and admin hashes verified') +PY +''') + report = dict(release=RELEASE, commit=commit, buildId=build_id, backup=BACKUP, + stage=STAGE, sha256=digest, deployed=True, target='nomadro.com') + destination = ROOT / 'artifacts/test14/deployment.json' + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(report, indent=2), encoding='utf-8') + print('DEPLOYED', json.dumps(report)) + except Exception: + if mutations_started: + print('Restoring previous code and build; databases remain untouched') + run(client, f'''set -eu +systemctl stop {SERVICES} +python3 - <<'PY' +import pathlib,json,shutil +backup=pathlib.Path({BACKUP!r}) +for target,existed in json.loads((backup/'manifest.json').read_text()).items(): + p=pathlib.Path(target) + if existed: shutil.copy2(backup/'files'/target.lstrip('/'),p) + else: p.unlink(missing_ok=True) +PY +if [ -d {BACKUP}/next ]; then + if [ -d {PORTAL}/.next ]; then mv {PORTAL}/.next {STAGE}/failed-next; fi + mv {BACKUP}/next {PORTAL}/.next +fi +systemctl daemon-reload +systemctl start {SERVICES} +''') + raise + finally: + client.close() + + +if __name__ == '__main__': + main()