MC/website/ops/retire-azuriom.py
2026-11-27 23:43:05 +00:00

58 lines
3.8 KiB
Python

"""Retire the standalone Azuriom installation after the reviewed replacement is live.
No backup is created. A dry-run plan and matching hash are mandatory before apply.
"""
import argparse,hashlib,json,os,re,shutil,subprocess
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('--expected-release',required=True);p.add_argument('--apply',action='store_true');p.add_argument('--plan-hash');args=p.parse_args()
assert re.fullmatch('[a-f0-9]{40}',args.expected_release)
release=Path('/home/dunerealms/apps/dunerealms/current').resolve(strict=True)
assert release.name=='ci-'+args.expected_release
app=Path('/home/dunerealms/apps/azuriom');assert not app.is_symlink() and app.resolve()==app and app.is_dir()
assert (app/'artisan').is_file() and (app/'composer.json').is_file()
env=(app/'.env').read_text();match=re.search(r'^DB_DATABASE=(.+)$',env,re.M)
assert match and match.group(1).strip('"\'')=='dunerealms_store'
# Other installed applications must not claim this database.
for file in Path('/home/dunerealms/apps').glob('*/.env'):
if file.parent==app:continue
assert not re.search(r'^DB_DATABASE=["\']?dunerealms_store["\']?\s*$',file.read_text(),re.M),str(file)
config=Path('/etc/nginx/sites-enabled/dunerealms-migration').resolve(strict=True)
assert config.is_relative_to('/etc/nginx')
old=config.read_text();new=old
for declaration in ['location = /store','location = /store/','location @dune_store','location ^~ /store/']:
pattern=re.compile(r'(?m)^\s*'+re.escape(declaration)+r'\s*\{')
match=pattern.search(new);assert match,declaration
start=match.start();cursor=match.end();depth=1
while depth and cursor<len(new):
if new[cursor]=='{':depth+=1
elif new[cursor]=='}':depth-=1
cursor+=1
assert depth==0
new=new[:start]+new[cursor:]
assert 'azuriom' not in new.lower() and '@dune_store' not in new
# Retired entry points lead to the replacement, without rewriting osCommerce configuration.
anchor=' server_name cp.dunerealms.com;';assert new.count(anchor)==1
new=new.replace(anchor,anchor+'\n location = /store { return 302 https://shop.dunerealms.com/; }\n location ~ ^/store/(?:admin|dune-login) { return 302 https://shop.dunerealms.com/admin/; }\n location /store/ { return 302 https://shop.dunerealms.com/; }',1)
workers=[]
for proc in Path('/proc').iterdir():
if not proc.name.isdigit():continue
try:
command=(proc/'cmdline').read_bytes().replace(b'\x00',b' ').decode(errors='replace')
if str(app) in command:workers.append(int(proc.name))
except (PermissionError,FileNotFoundError,ProcessLookupError):pass
assert not workers,'Azuriom-specific workers must be stopped before retirement'
plan={'release':args.expected_release,'app':str(app),'database':'dunerealms_store','nginx':str(config),'oldHash':hashlib.sha256(old.encode()).hexdigest(),'newHash':hashlib.sha256(new.encode()).hexdigest(),'backup':False}
digest=hashlib.sha256(json.dumps(plan,sort_keys=True).encode()).hexdigest();print(json.dumps({'plan':plan,'planHash':digest,'applied':False}))
if args.apply:
assert os.getuid()==0 and args.plan_hash==digest
assert config.read_text()==old
config.write_text(new)
check=subprocess.run(['nginx','-t'],capture_output=True)
if check.returncode:
config.write_text(old);raise RuntimeError('nginx validation failed; original configuration retained')
subprocess.run(['systemctl','reload','nginx'],check=True)
subprocess.run(['mysql','-e','DROP DATABASE IF EXISTS `dunerealms_store`;'],check=True,capture_output=True)
shutil.rmtree(app)
helper=Path('/etc/nginx/dune-store-fastcgi.conf')
if helper.is_file() and not any('dune-store-fastcgi.conf' in q.read_text(errors='replace') for q in Path('/etc/nginx/sites-enabled').glob('*') if q.is_file()):helper.unlink()
assert not app.exists()
print(json.dumps({'applied':True,'removedDatabase':'dunerealms_store','removedApp':str(app),'backup':False}))