diff --git a/website/integrations/ops/dunerealms-promote-safe-v2.py b/website/integrations/ops/dunerealms-promote-safe-v2.py new file mode 100644 index 00000000..2fd45acd --- /dev/null +++ b/website/integrations/ops/dunerealms-promote-safe-v2.py @@ -0,0 +1,147 @@ +#!/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('/var/lib/dunerealms-ci-promote') +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-enabled/'+name) for name in + ('dunerealms.com.conf','dunerealms-community-sites.conf','dunerealms-wiki.conf','cp.dunerealms.com.conf')] +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','PM2_HOME=/home/dunerealms/.pm2',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): + text=path.read_text() + allowed={3003,3103,3203} if path.name=='cp.dunerealms.com.conf' 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[3]) + 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[3]]: + 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}') + if p==NGINX[3]: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) + 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/integrations/ops/test_promoter.py b/website/integrations/ops/test_promoter.py new file mode 100644 index 00000000..3ede6bee --- /dev/null +++ b/website/integrations/ops/test_promoter.py @@ -0,0 +1,21 @@ +import pathlib,runpy,tempfile,unittest + +promoter=runpy.run_path(str(pathlib.Path(__file__).with_name('dunerealms-promote-safe-v2.py'))) + +class ServingPortTests(unittest.TestCase): + def config(self,name,text): + with tempfile.TemporaryDirectory() as directory: + path=pathlib.Path(directory)/name;path.write_text(text) + return promoter['config_port'](path) + + def test_world_status_proxy_cannot_impersonate_cp_backend(self): + self.assertEqual(self.config('cp.dunerealms.com.conf','location = /api/worlds { proxy_pass http://127.0.0.1:3200/api/worlds; }\nlocation / { proxy_pass http://127.0.0.1:3203; }'),3203) + + def test_duplicate_same_upstream_is_valid(self): + self.assertEqual(self.config('dunerealms.com.conf','proxy_pass http://127.0.0.1:3100/git;\nproxy_pass http://127.0.0.1:3100/;'),3100) + + def test_conflicting_or_unknown_backends_are_rejected(self): + for text in ['proxy_pass http://127.0.0.1:3103; proxy_pass http://127.0.0.1:3203;','proxy_pass http://127.0.0.1:18081;']: + with self.assertRaises(RuntimeError):self.config('cp.dunerealms.com.conf',text) + +if __name__=='__main__':unittest.main()