"""Deploy locally validated artifacts to .com only, with retained rollback copies.""" from __future__ import annotations import hashlib import io import json import runpy import sys import tarfile import tempfile from datetime import datetime, timezone from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.stdout.reconfigure(encoding='utf-8', errors='replace', line_buffering=True) RELEASE = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') BACKUP = f'/var/backups/nomadro-upgrade/{RELEASE}' STAGE = f'/var/www/nomadro.cn/.upgrade-{RELEASE}' PORTAL = '/var/www/nomadro.cn' ADMIN = '/www/wwwroot/admin.nomadro.com' API_FILES = [ 'routers/ops_admin.py', 'routers/public_config.py', 'routers/weapp_switches_admin.py', 'services/weapp_switches.py', ] SOCIAL_FILES = ['pb_data.py', 'store.py', 'routers/api.py'] SOURCE_FILES = [ 'next.config.ts', 'src/middleware.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts', 'src/lib/remote-config-live.ts', 'src/lib/remote-config-store.ts', 'src/lib/use-remote-config.ts', 'src/app/api/config/stream/route.ts', 'src/app/api/pay/confirm/route.ts', 'src/app/api/auth/sync-session/route.ts', 'src/app/api/portal/join-leads/route.ts', 'src/app/api/admin/social/ugc/join-leads/route.ts', 'src/app/api/work/v1/[[...path]]/route.ts', 'src/app/api/notify/v1/[[...path]]/route.ts', 'src/app/api/coffee/v1/[[...path]]/route.ts', 'src/modules/social/components/PeopleClient.tsx', 'src/modules/social/components/PlaceMapPreview.tsx', 'src/modules/social/components/SocialMapCanvas.tsx', 'src/modules/social/lib/phrases.ts', 'src/modules/work/lib/store.ts', 'src/modules/work/micro/custom-elements.d.ts', ] def run(client, command, timeout=180): _, stdout, stderr = client.exec_command(command, timeout=timeout) output = stdout.read().decode('utf-8', 'replace') error = stderr.read().decode('utf-8', 'replace') code = stdout.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})') def main(): assert (ROOT / '.next/BUILD_ID').is_file(), 'build Next locally first' assert (ROOT / 'apps/com/admin/dist/index.html').is_file(), 'build admin locally first' build_id = (ROOT / '.next/BUILD_ID').read_text().strip() client = runpy.run_path(str(ROOT / 'apps/admin/deploy/_upload_next_us.py'))['connect']() mutations_started = False with tempfile.TemporaryDirectory() as temporary: package = Path(temporary) / 'upgrade.tgz' with tarfile.open(package, 'w:gz') as archive: def include(info): if any(info.name == f'portal/.next/{part}' or info.name.startswith(f'portal/.next/{part}/') for part in ['cache', 'dev']): return None if info.name.endswith('/lock'): return None return info archive.add(ROOT / '.next', arcname='portal/.next', filter=include) for relative in SOURCE_FILES: archive.add(ROOT / relative, arcname='portal/' + relative) archive.add(ROOT / 'apps/com/admin/dist', arcname='admin') for relative in API_FILES: text = (ROOT / 'apps/api/services/ebook_svc' / relative).read_text(encoding='utf-8').replace('ebook_svc.', 'app.') blob = text.encode('utf-8') entry = tarfile.TarInfo('api/' + relative); entry.size = len(blob); entry.mode = 0o644 archive.addfile(entry, io.BytesIO(blob)) for relative in SOCIAL_FILES: archive.add(ROOT / 'apps/api/services/social_svc' / relative, arcname='social/' + relative) digest = hashlib.sha256(package.read_bytes()).hexdigest() print('release', RELEASE, 'build', build_id, 'packageMB', round(package.stat().st_size / 1024**2, 1)) sftp = client.open_sftp() try: sftp.put(str(package), f'/tmp/nomadro-upgrade-{RELEASE}.tgz') finally: sftp.close() targets = [f'/opt/nomadmini/backend/app/{name}' for name in API_FILES] + [f'{PORTAL}/apps/api/services/social_svc/{name}' for name in SOCIAL_FILES] target_args = ' '.join(targets) try: run(client, f'''set -eu echo '{digest} /tmp/nomadro-upgrade-{RELEASE}.tgz' | sha256sum -c - mkdir -p {STAGE} {BACKUP} tar -xzf /tmp/nomadro-upgrade-{RELEASE}.tgz -C {STAGE} tar -czf {BACKUP}/backend.tgz {target_args} cp -a {ADMIN} {BACKUP}/admin cp /etc/nginx/sites-available/admin.nomadro.com.conf {BACKUP}/admin-nginx.conf cp {PORTAL}/data/remote-config.json {BACKUP}/remote-config.json python3 -m compileall -q {STAGE}/api {STAGE}/social test -f {STAGE}/portal/.next/BUILD_ID ''') mutations_started = True for relative in API_FILES: run(client, f'cp {STAGE}/api/{relative} /opt/nomadmini/backend/app/{relative}') for relative in SOCIAL_FILES: run(client, f'cp {STAGE}/social/{relative} {PORTAL}/apps/api/services/social_svc/{relative}') # Source parity for the legacy API tree and repository service tree. for relative in API_FILES: source = ROOT / 'apps/api/services/ebook_svc' / relative destination = f'{PORTAL}/apps/api/services/ebook_svc/{relative}' sftp = client.open_sftp() try: sftp.put(str(source), destination) finally: sftp.close() run(client, '''set -eu cd /opt/nomadmini/backend .venv/bin/python -c 'from app.routers import ops_admin,public_config,weapp_switches_admin; print("API imports OK")' systemctl restart nomadmini-api nomadro-social ''') run(client, f'''set -eu cd {PORTAL} systemctl stop nomadro mv .next {BACKUP}/next mv {STAGE}/portal/.next .next cp -a {STAGE}/portal/. {PORTAL}/ if [ -f src/proxy.ts ]; then mv src/proxy.ts {BACKUP}/proxy.ts; fi systemctl start nomadro for attempt in $(seq 1 30); do if curl --fail --silent --max-time 3 http://127.0.0.1:4003/api/health >/dev/null; then break; fi sleep 1 done curl --fail --silent --max-time 10 http://127.0.0.1:4003/api/health >/dev/null curl --fail --silent --max-time 15 https://nomadro.com/ >/dev/null curl --fail --silent --max-time 15 https://nomadro.com/social/chat >/dev/null curl --fail --silent --max-time 15 https://nomadro.com/notifications/settings >/dev/null curl --fail --silent --max-time 10 http://127.0.0.1:8010/health >/dev/null curl --fail --silent --max-time 10 http://127.0.0.1:8020/health >/dev/null cp -a {STAGE}/admin/assets/. {ADMIN}/assets/ cp {STAGE}/admin/index.html {ADMIN}/index.html.next mv {ADMIN}/index.html.next {ADMIN}/index.html systemctl is-active nomadro nomadmini-api nomadro-social nginx ''') report = {'release': RELEASE, 'buildId': build_id, 'backup': BACKUP, 'stage': STAGE, 'sha256': digest, 'deployed': True} (ROOT / 'artifacts/platform-upgrade/deployment.json').write_text(json.dumps(report, indent=2), encoding='utf-8') print('DEPLOYED', json.dumps(report)) except Exception: if mutations_started: print('Rolling back runtime artifacts') run(client, f'''set -eu tar -xzf {BACKUP}/backend.tgz -C / if [ -d {BACKUP}/next ]; then systemctl stop nomadro if [ -d {PORTAL}/.next ]; then mv {PORTAL}/.next {STAGE}/failed-next; fi mv {BACKUP}/next {PORTAL}/.next fi cp -a {BACKUP}/admin/. {ADMIN}/ systemctl restart nomadmini-api nomadro-social nomadro ''') raise finally: client.close() if __name__ == '__main__': main()