"""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', 'routers/social_ugc_admin.py', 'routers/google_admin.py', 'routers/social_blog_admin.py', 'routers/hub_ugc_admin.py', 'routers/hub_locale_geo_admin.py', 'routers/hub_blog_admin.py', 'services/weapp_switches.py', 'services/config_live.py', 'services/google_link.py', 'services/google_oauth.py', 'services/social_blog_ops.py', 'services/hub_ugc.py', 'services/hub_experience.py', 'services/hub_locale_geo.py', 'services/hub_blog_ops.py', 'services/hub_ops.py', 'services/hub_join_config.py', 'services/ntfy.py', 'services/track.py', 'services/social_ugc.py', ] SOCIAL_FILES = ['pb_data.py', 'store.py', 'face_check.py', 'routers/api.py', 's3_upload.py'] # Full hub_svc tree for nomadro-hub + nomadmini-api (/api/admin/hub needs config/security_denylist/…) HUB_FILES = [ 'pb_data.py', 'store.py', 'face_check.py', 'config.py', 's3_upload.py', 'community_board.py', 'security_denylist.py', 'realtime.py', 'live.py', 'remote_flags.py', 'trial_gate.py', 'onboarding.py', 'notify_bridge.py', 'im.py', 'contract.py', 'geo_pb.py', 'geo_cities.py', 'geo_store.py', 'geo_h3.py', 'photon.py', '__init__.py', 'routers/__init__.py', 'routers/api.py', 'routers/geo.py', ] SOURCE_FILES = [ 'next.config.ts', 'src/proxy.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts', 'src/lib/ntfy.ts', 'src/lib/ntfy-rich.ts', 'src/lib/feedback-identity.ts', 'src/lib/remote-config-live.ts', 'src/lib/remote-config-store.ts', 'src/lib/use-remote-config.ts', 'src/lib/remote-config.ts', 'src/app/api/config/stream/route.ts', 'src/app/api/config/meta/route.ts', 'src/app/api/config/notify/route.ts', 'src/app/api/pay/confirm/route.ts', 'src/app/api/auth/sync-session/route.ts', 'src/app/api/admin/config/route.ts', 'src/app/api/admin/notify/route.ts', 'src/app/api/portal/join-leads/route.ts', 'src/app/api/portal/feedback/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/vip/app/api/track/route.ts', 'src/modules/social/components/PeopleClient.tsx', 'src/modules/social/components/PlacesClient.tsx', 'src/modules/social/components/CafeDirectory.tsx', 'src/modules/social/components/SiteShell.tsx', 'src/modules/social/components/MeetupLiveClient.tsx', 'src/modules/social/components/PlaceMapPreview.tsx', 'src/modules/social/components/SocialMapCanvas.tsx', 'src/modules/social/components/RoleBoard.tsx', 'src/modules/social/components/SocialFeedbackMate.tsx', 'src/modules/social/components/SocialFeedbackMate.css', 'src/modules/social/app/studio.css', 'src/modules/social/lib/phrases.ts', 'src/modules/social/lib/joinModal.ts', 'src/modules/social/lib/silentRoomRecorder.ts', 'src/modules/social/lib/api.ts', 'src/modules/social/lib/feedbackMeta.ts', 'src/modules/social/lib/pages.en.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) # book.server.ts 运行时读 cwd/src/modules/ebook-content — 必须随包上线 ebook_content = ROOT / 'src/modules/ebook-content' if ebook_content.is_dir(): def ebook_filter(info): if 'chapters.bak' in info.name or '/.git' in info.name: return None return info archive.add(ebook_content, arcname='portal/src/modules/ebook-content', filter=ebook_filter) for relative in SOURCE_FILES: path = ROOT / relative if not path.is_file(): print('skip missing', relative) continue archive.add(path, 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) for relative in HUB_FILES: path = ROOT / 'apps/api/services/hub_svc' / relative if path.is_file(): archive.add(path, arcname='hub/' + relative) hub_main = ROOT / 'apps/api/hub_main.py' if hub_main.is_file(): archive.add(hub_main, arcname='hub_main.py') schemas = ROOT / 'apps/api/services/nomadro_pb/schemas.py' if schemas.is_file(): archive.add(schemas, arcname='nomadro_pb/schemas.py') 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] + [f'/opt/nomadmini/backend/social_svc/{name}' for name in SOCIAL_FILES] + [f'{PORTAL}/apps/api/services/hub_svc/{name}' for name in HUB_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} EXISTING="" for f in {target_args}; do if [ -e "$f" ]; then EXISTING="$EXISTING $f"; fi done if [ -n "$EXISTING" ]; then tar -czf {BACKUP}/backend.tgz $EXISTING; else tar -czf {BACKUP}/backend.tgz --files-from /dev/null; fi 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}') # admin.nomadro.com → :8010 imports /opt/nomadmini/backend/social_svc (not portal tree) run(client, f'mkdir -p /opt/nomadmini/backend/social_svc/$(dirname {relative}) && cp {STAGE}/social/{relative} /opt/nomadmini/backend/social_svc/{relative}') for relative in HUB_FILES: run(client, f'mkdir -p {PORTAL}/apps/api/services/hub_svc/$(dirname {relative}) && cp {STAGE}/hub/{relative} {PORTAL}/apps/api/services/hub_svc/{relative}') # admin.nomadro.com → :8010 also needs hub_svc for /api/admin/hub/* run(client, f'mkdir -p /opt/nomadmini/backend/hub_svc/$(dirname {relative}) && cp {STAGE}/hub/{relative} /opt/nomadmini/backend/hub_svc/{relative}') run(client, f'test -f {STAGE}/hub_main.py && cp {STAGE}/hub_main.py {PORTAL}/apps/api/hub_main.py || true') run(client, f'test -f {STAGE}/nomadro_pb/schemas.py && cp {STAGE}/nomadro_pb/schemas.py {PORTAL}/apps/api/services/nomadro_pb/schemas.py || true') run(client, f'test -f {STAGE}/nomadro_pb/schemas.py && mkdir -p /opt/nomadmini/backend/nomadro_pb && cp {STAGE}/nomadro_pb/schemas.py /opt/nomadmini/backend/nomadro_pb/schemas.py || true') # Source parity for the legacy API tree and repository service tree. for relative in API_FILES: source = ROOT / 'apps/api/services/ebook_svc' / relative if not source.is_file(): print('skip missing api source', relative) continue destination = f'{PORTAL}/apps/api/services/ebook_svc/{relative}' sftp = client.open_sftp() try: sftp.put(str(source), destination) finally: sftp.close() # Ensure production main.py mounts hub admin routers (file-level API copy alone is not enough) run(client, r'''set -eu python3 - <<'PY' from pathlib import Path p = Path('/opt/nomadmini/backend/app/main.py') text = p.read_text(encoding='utf-8') if 'include_router(hub_ugc_admin.router)' in text: print('main.py hub routers ok') else: needle = 'app.include_router(social_ugc_admin.router)\n' if needle not in text: raise SystemExit('main.py missing social_ugc anchor') imports = ( 'from app.routers import hub_ugc_admin # noqa: E402\n' 'from app.routers import hub_locale_geo_admin # noqa: E402\n' 'from app.routers import hub_blog_admin # noqa: E402\n' ) includes = ( 'app.include_router(hub_ugc_admin.router)\n' 'app.include_router(hub_locale_geo_admin.router)\n' 'app.include_router(hub_blog_admin.router)\n' ) if 'hub_ugc_admin' not in text: text = text.replace( 'from app.routers import social_ugc_admin # noqa: E402\n', 'from app.routers import social_ugc_admin # noqa: E402\n' + imports, 1, ) text = text.replace(needle, needle + includes, 1) p.write_text(text, encoding='utf-8') print('main.py hub routers patched') PY mkdir -p /etc/systemd/system/nomadmini-api.service.d cat >/etc/systemd/system/nomadmini-api.service.d/hub-path.conf <<'EOF' [Service] Environment=PYTHONPATH=/opt/nomadmini/backend Environment=HUB_INTERNAL_URL=http://127.0.0.1:8025 EOF systemctl daemon-reload ''') run(client, '''set -eu cd /opt/nomadmini/backend .venv/bin/python -c 'from app.routers import ops_admin,public_config,weapp_switches_admin,hub_ugc_admin; print("API imports OK", hub_ugc_admin.router.prefix)' systemctl restart nomadmini-api nomadro-social nomadro-hub ''') 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/hub/home >/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 curl --fail --silent --max-time 10 http://127.0.0.1:8025/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 nomadro-hub 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()