nomadro/scripts/deploy_uiux_services_com.py
Eric 499f2d3e26 Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 18:19:37 +08:00

100 lines
5.0 KiB
Python

"""Focused US service release with backup and code/runtime rollback."""
from datetime import datetime, timezone
import hashlib
import io
import json
from pathlib import Path
import runpy
import sys
import tarfile
import tempfile
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')
PORTAL = '/var/www/nomadro.cn'
BACKUP = f'/var/backups/nomadro-upgrade/uiux-{RELEASE}'
STAGE = f'/var/tmp/nomadro-uiux-{RELEASE}'
API_FILES = ['routers/audience_admin.py', 'routers/social_blog_admin.py', 'services/audience_config.py', 'services/social_blog_ops.py']
def run(client, command, timeout=120):
_, out, err = client.exec_command(command, timeout=timeout)
output, error = out.read().decode('utf-8', 'replace'), 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})')
def main():
files = {}
for domain in ['coffee_svc', 'notify_svc']:
for source in (ROOT / 'apps/api/services' / domain).rglob('*.py'):
files[PORTAL + '/' + source.relative_to(ROOT).as_posix()] = source.read_bytes()
for name in ['coffee_main.py', 'notify_main.py', 'services/nomadro_pb/ensure.py', 'services/nomadro_pb/schemas.py', 'services/social_svc/notify_bridge.py', 'services/social_svc/onboarding.py']:
files[PORTAL + '/apps/api/' + name] = (ROOT / 'apps/api' / name).read_bytes()
for name in API_FILES:
source = (ROOT / 'apps/api/services/ebook_svc' / name).read_text(encoding='utf-8')
files['/opt/nomadmini/backend/app/' + name] = source.replace('ebook_svc.', 'app.').encode('utf-8')
files[PORTAL + '/apps/api/services/ebook_svc/' + name] = source.encode('utf-8')
manifest = list(files)
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 host only'
try:
with tempfile.TemporaryDirectory() as temporary:
package = Path(temporary) / 'services.tgz'
with tarfile.open(package, 'w:gz') as archive:
for target, blob in files.items():
info = tarfile.TarInfo(target.lstrip('/')); info.size = len(blob); info.mode = 0o644
archive.addfile(info, io.BytesIO(blob))
blob = json.dumps(manifest).encode()
info = tarfile.TarInfo('manifest.json'); info.size = len(blob)
archive.addfile(info, io.BytesIO(blob))
archive.add(ROOT / 'apps/com/deploy/install-uiux-services.py', arcname='install.py')
digest = hashlib.sha256(package.read_bytes()).hexdigest()
with client.open_sftp() as sftp: sftp.put(str(package), f'/tmp/nomadro-uiux-{RELEASE}.tgz')
run(client, f"mkdir -p {STAGE} {BACKUP} && chmod 700 {BACKUP} && echo '{digest} /tmp/nomadro-uiux-{RELEASE}.tgz' | sha256sum -c - && tar -xzf /tmp/nomadro-uiux-{RELEASE}.tgz -C {STAGE}")
try:
run(client, f'python3 {STAGE}/install.py {STAGE} {BACKUP}')
run(client, f'''set -eu
cd {PORTAL}/apps/api
.venv-social/bin/python -c 'import coffee_main,notify_main; print("service imports OK")'
cd /opt/nomadmini/backend
.venv/bin/python -c 'from app.routers import audience_admin,social_blog_admin; print("config API imports OK")'
systemctl daemon-reload
systemctl enable nomadro-notify nomadro-coffee
systemctl restart nomadro-notify nomadro-coffee
for attempt in $(seq 1 30); do
if curl -fsS --max-time 2 http://127.0.0.1:8023/api/notify/v1/health >/dev/null && curl -fsS --max-time 2 http://127.0.0.1:8024/api/coffee/v1/hosts >/dev/null; then break; fi
sleep 1
done
curl -fsS --max-time 5 http://127.0.0.1:8023/api/notify/v1/health
curl -fsS --max-time 5 http://127.0.0.1:8024/api/coffee/v1/hosts
systemctl restart nomadmini-api nomadro-social
systemctl is-active nomadro-notify nomadro-coffee nomadmini-api nomadro-social
''')
except Exception:
run(client, f'''systemctl stop nomadro-notify nomadro-coffee
python3 - <<'PY'
import json,pathlib,shutil
backup=pathlib.Path({BACKUP!r})
manifest=backup/'manifest.json'
for target,existed in json.loads(manifest.read_text()).items() if manifest.exists() else []:
p=pathlib.Path(target)
if existed: shutil.copy2(backup/'files'/target.lstrip('/'),p)
elif p.is_file(): p.unlink()
print('Code and runtime restored; database backup retained without overwriting user data.')
PY
systemctl daemon-reload
systemctl restart nomadmini-api nomadro-social
''')
raise
report = {'release': RELEASE, 'backup': BACKUP, 'sha256': digest, 'servicePorts': [8023, 8024], 'files': manifest, 'deployed': True}
(ROOT / 'artifacts/uiux-upgrade/services-deployment.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print('SERVICES DEPLOYED', RELEASE)
finally: client.close()
if __name__ == '__main__': main()