diff --git a/.forgejo/workflows/web-deploy.yml b/.forgejo/workflows/web-deploy.yml index eb8f3e04..7cbd480e 100644 --- a/.forgejo/workflows/web-deploy.yml +++ b/.forgejo/workflows/web-deploy.yml @@ -42,7 +42,9 @@ jobs: node website/scripts/publication-changes.mjs "$BEFORE" "$GITHUB_SHA" - name: Verify deployment policy - run: node --test .forgejo/tests/web-deploy.test.mjs + run: | + node --test .forgejo/tests/web-deploy.test.mjs + python3 -m unittest discover -s website/ops -p 'test_*.py' - name: Build and test website working-directory: website @@ -68,6 +70,7 @@ jobs: install -m 700 -d ~/.ssh printf '%s\n' "$DEPLOY_KEY" > ~/.ssh/deploy_key chmod 600 ~/.ssh/deploy_key - printf '%s\n' '162.55.87.104 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILy1N6Eo+BMRgstSpYc90ZHDQtm+8iTYiNMTI3XMVi5h root@Debian-bookworm-latest-amd64-base' >> ~/.ssh/known_hosts - ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes dunedeploy@162.55.87.104 "$GITHUB_SHA" + trap 'rm -f ~/.ssh/deploy_key' EXIT + printf '%s\n' '91.107.196.242 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC8x/XocsIz41fWHGty0DbZhSvafSQFt9jaHHgzdr55W root@ubuntu-4gb-fsn1-1' >> ~/.ssh/known_hosts + ssh -p 22 -i ~/.ssh/deploy_key -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes dunedeploy@91.107.196.242 "$GITHUB_SHA" rm -f ~/.ssh/deploy_key diff --git a/website/ops/README.md b/website/ops/README.md new file mode 100644 index 00000000..37abb5c4 --- /dev/null +++ b/website/ops/README.md @@ -0,0 +1,28 @@ +# Migrated web deployment + +The production website is hosted at `91.107.196.242`. The Forgejo Actions +workflow pins that host's SSH key and can trigger deployment only from `main`. +Its deploy key is restricted to `/usr/local/bin/dunerealms-ci-trigger`, which +rejects commits that do not match the current main branch. + +Forgejo, repositories, artifact storage, the rootless runner, container data, +build workspaces and deployment state use `/mnt/HC_Volume_107481500/dunegit`. +Compatibility links preserve the existing application and home-directory paths. +The volume is part of the live service and must remain attached. The services +require its mount before starting, rather than writing to an empty mountpoint. + +`promote-safe-v3.py` is installed as +`/usr/local/sbin/dunerealms-promote-safe-v3`. It prepares an immutable release, +checks a candidate website and panel, updates their shared nginx configuration, +checks public readiness, and restores the previous routing if that check fails. +Retired background workers are stopped and the active process list is saved. + +The first successful promotion retires the migrated baseline systemd website +services. Subsequent candidates are supervised by `dunerealms-runtime.service`. +The separate Forgejo service remains `dunegit.service`. + +Run the promoter routing checks with: + +```sh +python3 -m unittest discover -s website/ops -p 'test_*.py' +``` diff --git a/website/ops/promote-safe-v3.py b/website/ops/promote-safe-v3.py new file mode 100644 index 00000000..25cf4c30 --- /dev/null +++ b/website/ops/promote-safe-v3.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""DuneRealms CI blue/green promoter. Never restarts the serving PM2 processes.""" +import fcntl, json, os, pathlib, re, shutil, subprocess, sys, time, traceback +APP=pathlib.Path('/home/dunerealms/apps/dunerealms') +CI=pathlib.Path('/home/dunedeploy/ci-deploy') +STATE=pathlib.Path('/mnt/HC_Volume_107481500/dunegit/ci/promotion') +PM2='/home/dunerealms/.local/node_modules/pm2/bin/pm2' +NODE='/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node' +ENV='/home/dunerealms/.config/dunerealms.env' +NGINX=[pathlib.Path('/etc/nginx/sites-available/dunerealms-migration')] +PM2_HOME='/mnt/HC_Volume_107481500/dunegit/ci/pm2' +SLOTS={'blue':(3100,3103),'green':(3200,3203)} +def run(args,check=True,timeout=120): + p=subprocess.run(args,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=timeout) + if check and p.returncode: raise RuntimeError(f"{args[0]} exited {p.returncode}: {p.stdout[-2000:]}") + return p +def pm2(*args,check=True): + return run(['runuser','-u','dunerealms','--','env','PATH=/home/dunerealms/.nvm/versions/node/v22.23.3/bin:/usr/local/bin:/usr/bin:/bin','PM2_HOME='+PM2_HOME,NODE,PM2,*args],check=check,timeout=90) +def status(url,host=None): + args=['curl','-sS','-L','--retry','2','--retry-all-errors','--retry-delay','1','-o','/dev/null','-w','\nDUNE_HTTP_STATUS:%{http_code}\n','--max-time','6'] + if host:args+=['-H',f'Host: {host}'] + p=run(args+[url],check=False,timeout=25) + ok=p.returncode==0 and p.stdout.rstrip().endswith('DUNE_HTTP_STATUS:200') + if not ok: print('READINESS FAILURE',url,'http='+p.stdout.strip(),'exit='+str(p.returncode),flush=True) + return ok +def wait_local(web,cp): + for i in range(30): + if status(f'http://127.0.0.1:{web}/','www.dunerealms.com') and status(f'http://127.0.0.1:{cp}/','cp.dunerealms.com'): + return True + time.sleep(2) + return False +def public_ok(): + return all(status(u) for u in ('https://www.dunerealms.com/','https://cp.dunerealms.com/','https://www.dunerealms.com/git/')) +def config_port(path,kind="web"): + text=path.read_text() + allowed={3003,3103,3203} if kind=='cp' else {3000,3100,3200} + ports={int(value) for value in re.findall(r'proxy_pass\s+http://127\.0\.0\.1:(\d+)',text)} & allowed + if len(ports)!=1:raise RuntimeError(f'Ambiguous serving upstream in {path}: {sorted(ports)}') + return ports.pop() + +def atomic_write(path,text): + tmp=path.with_name(path.name+'.safe-promote-tmp') + if tmp.exists():raise RuntimeError('Stale temporary config '+str(tmp)) + tmp.write_text(text) + shutil.copymode(path,tmp) + os.replace(tmp,path) +def nginx_reload(): + run(['/usr/sbin/nginx','-t'],timeout=20) + run(['/usr/sbin/nginx','-s','reload'],timeout=20) +def stop_candidate(slot): + for name in (f'dunerealms-web-{slot}',f'dunerealms-cp-{slot}'): + pm2('delete',name,check=False) +def prepare_release(sha,previous): + source=CI/'artifacts'/sha/'website' + required=('dist/server/index.js','node/start.mjs','control-panel/start.mjs','package.json') + if not all((source/f).is_file() for f in required):raise RuntimeError('CI artifact incomplete') + release=APP/'releases'/('ci-'+sha) + if not release.exists(): + temp=APP/'releases'/('.safe-'+sha) + if temp.exists():raise RuntimeError('Stale release staging directory; manual review required') + temp.mkdir() + try: + run(['rsync','-a','--exclude=node_modules','--exclude=.env','--exclude=.env.*','--exclude=*.sqlite','--exclude=*.db','--exclude=uploads/',str(source)+'/',str(temp)+'/'],timeout=240) + (temp/'node_modules').symlink_to((previous/'node_modules').resolve()) + for entry in ('node/start.mjs','control-panel/start.mjs'): + run([NODE,'--check',str(temp/entry)]) + run(['chown','-R','dunerealms:dunerealms',str(temp)],timeout=120) + temp.rename(release) + except Exception: + shutil.rmtree(temp,ignore_errors=True) + raise + return release +def main(): + STATE.mkdir(exist_ok=True) + with open(STATE/'safe-lock','w') as lock: + try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError:return print('Another promotion is running') + if not (CI/'built-commit').exists() or not (CI/'pending-commit').exists():return print('No pending build') + sha=(CI/'built-commit').read_text().strip() + pending=(CI/'pending-commit').read_text().strip() + if not re.fullmatch(r'[0-9a-f]{40}',sha) or sha!=pending:return print('No approved matching build') + if (STATE/'deployed').exists() and (STATE/'deployed').read_text().strip()==sha:return print('Already deployed') + if (STATE/'blocked-sha').exists() and (STATE/'blocked-sha').read_text().strip()==sha:return print('Known failing build blocked') + old_web=config_port(NGINX[0]);old_cp=config_port(NGINX[0],'cp') + if (old_web,old_cp) not in [(3000,3003),*SLOTS.values()]:raise RuntimeError('Unexpected live ports; refusing') + if not public_ok():raise RuntimeError('Production unhealthy before promotion; refusing') + slot='blue' if old_web!=3100 else 'green' + web,cp=SLOTS[slot] + previous=(APP/'current').resolve() + release=prepare_release(sha,previous) + stop_candidate(slot) + config=STATE/f'pm2-{slot}.config.cjs' + apps=[] + for name,entry in ((f'dunerealms-web-{slot}','node/start.mjs'),(f'dunerealms-cp-{slot}','control-panel/start.mjs')): + apps.append({'name':name,'cwd':str(release),'script':entry,'exec_mode':'fork','instances':1, + 'interpreter':NODE,'node_args':'--env-file='+ENV,'autorestart':True, + 'max_memory_restart':'2G','env':{'NODE_ENV':'production','PORT':str(web),'CP_PORT':str(cp)}}) + config.write_text('module.exports = '+json.dumps({'apps':apps})+';\n') + print('Starting candidate',sha,slot,flush=True) + pm2('start',str(config),timeout=90) if False else pm2('start',str(config)) + if not wait_local(web,cp): + stop_candidate(slot) + (STATE/'blocked-sha').write_text(sha+'\n') + raise RuntimeError('Candidate failed local readiness; production unchanged') + originals={p:p.read_text() for p in NGINX} + if not any(f'127.0.0.1:{old_web}' in originals[p] for p in NGINX): + raise RuntimeError('Old website upstream not found') + if f'127.0.0.1:{old_cp}' not in originals[NGINX[0]]: + raise RuntimeError('Old CP upstream not found') + switched=False + try: + for p,text in originals.items(): + text=text.replace(f'127.0.0.1:{old_web}',f'127.0.0.1:{web}') + text=text.replace(f'127.0.0.1:{old_cp}',f'127.0.0.1:{cp}') + if text!=originals[p]:atomic_write(p,text) + nginx_reload() + switched=True + if not all(public_ok() for _ in range(3)): + raise RuntimeError('Public health failed after traffic switch') + nextlink=APP/'current.safe-next' + if nextlink.exists() or nextlink.is_symlink():raise RuntimeError('Stale current.safe-next') + nextlink.symlink_to(release) + os.replace(nextlink,APP/'current') + (STATE/'deployed').write_text(sha+'\n') + (STATE/'active-slot').write_text(slot+'\n') + (STATE/'previous-release').write_text(str(previous)+'\n') + (STATE/'blocked-sha').unlink(missing_ok=True) + print('LIVE DEPLOYED:',sha,'slot',slot,'old slot retained for rollback',flush=True) + except Exception: + print('Switch failed; restoring nginx routing',flush=True) + for p,text in originals.items(): + if p.read_text()!=text:atomic_write(p,text) + nginx_reload() + stop_candidate(slot) + (STATE/'blocked-sha').write_text(sha+'\n') + raise + # Standby processes contain background workers too. Keep their files/config + # for rollback, but never leave an obsolete synchronizer running after cutover. + retired = ('dunerealms-web-blue','dunerealms-cp-blue') if old_web==3100 else ('dunerealms-web-green','dunerealms-cp-green') if old_web==3200 else ('dunerealms-web','dunerealms-account-panel') + for name in retired: + pm2('stop',name,check=False) + # The migrated baseline is supervised by systemd until its first promotion. + for unit in ('dunerealms-web.service','dunerealms-panel.service'): + if run(['systemctl','is-active','--quiet',unit],check=False).returncode==0: + run(['systemctl','disable','--now',unit]) + pm2('save') + for unit in ('dunerealms-news-delivery.service','dunerealms-political-forum.service'): + if run(['systemctl','is-active','--quiet',unit],check=False).returncode==0: + run(['systemctl','restart',unit]) + print('Retired background workers stopped; previous release retained for rollback',flush=True) +if __name__=='__main__': + try:main() + except Exception as exc: + print('SAFE PROMOTION FAILED:',exc,file=sys.stderr) + sys.exit(1) + diff --git a/website/ops/test_promote_safe_v3.py b/website/ops/test_promote_safe_v3.py new file mode 100644 index 00000000..054df1f8 --- /dev/null +++ b/website/ops/test_promote_safe_v3.py @@ -0,0 +1,38 @@ +import importlib.util +import pathlib +import tempfile +import unittest + + +spec = importlib.util.spec_from_file_location( + "promoter", pathlib.Path(__file__).with_name("promote-safe-v3.py") +) +promoter = importlib.util.module_from_spec(spec) +spec.loader.exec_module(promoter) + + +class ServingPortsTest(unittest.TestCase): + def test_combined_virtual_hosts_select_web_and_panel_separately(self): + with tempfile.TemporaryDirectory() as directory: + config = pathlib.Path(directory) / "combined.conf" + config.write_text( + "proxy_pass http://127.0.0.1:3200;\n" + "proxy_pass http://127.0.0.1:3203;\n" + "proxy_pass http://127.0.0.1:3200/api/worlds;\n" + ) + self.assertEqual(promoter.config_port(config), 3200) + self.assertEqual(promoter.config_port(config, "cp"), 3203) + + def test_ambiguous_live_web_ports_refuse_promotion(self): + with tempfile.TemporaryDirectory() as directory: + config = pathlib.Path(directory) / "combined.conf" + config.write_text( + "proxy_pass http://127.0.0.1:3100;\n" + "proxy_pass http://127.0.0.1:3200;\n" + ) + with self.assertRaises(RuntimeError): + promoter.config_port(config) + + +if __name__ == "__main__": + unittest.main()