MC/network/central-game-storage.py
2026-11-27 23:43:05 +00:00

41 lines
3.4 KiB
Python

"""Switch Core only; preserve the legacy LuckPerms/CoreProtect tunnel on 13307."""
import pathlib,subprocess,yaml,json,re,urllib.parse,os,pwd
ROOT=pathlib.Path('/opt/dunerealms/servers')
NAMES=['arrakis','caladan','giedi_prime','kaitain','sigma_draconis_iv']
def run(*args):return subprocess.run(args,check=True,text=True,capture_output=True).stdout.strip()
def main():
for name in NAMES:
state=subprocess.run(['systemctl','is-active','dune-'+name+'.service'],capture_output=True,text=True).stdout.strip()
if state not in ('inactive','failed'):raise RuntimeError('Stop all planet writers first: '+name)
staging=pathlib.Path('/root/dune-db-reconcile');central=yaml.safe_load((staging/'central-core.yml').read_text())['database']
uri=urllib.parse.urlparse(re.sub('^jdbc:','',central['jdbc-url']))
assert uri.hostname=='127.0.0.1' and uri.port==13308 and uri.path=='/dunegameplay'
target={k:central[k] for k in ['jdbc-url','username','password']}
if 'useServerPrepStmts=' not in target['jdbc-url']:target['jdbc-url']+='&useServerPrepStmts=true'
old_tunnel=run('systemctl','cat','dune-db-tunnel.service')
assert 'dunegamedb@162.55.87.104' in old_tunnel and 'dev@91.107.196.242' not in old_tunnel,'Legacy plugin database routing must remain unchanged'
unit=pathlib.Path('/etc/systemd/system/dune-gameplay-db-tunnel.service')
assert not unit.exists(),'Inspect the existing central tunnel before retrying'
patches=[]
for name in NAMES:
path=ROOT/name/'plugins/DuneCore/config.yml';assert path.is_file() and not path.is_symlink()
original=path.read_text();config=yaml.safe_load(original);assert ':13307/dunegameplay' in config['database']['jdbc-url']
ess=yaml.safe_load((ROOT/name/'plugins/DuneEss/config.yml').read_text())
if not ess.get('database',{}).get('use-core-database',True):raise ValueError('DuneEss must use Core storage: '+name)
changed=original
for k,v in target.items():
pattern=r'(?m)^( '+re.escape(k)+r':)\s*[^\n]*$'
changed,n=re.subn(pattern,lambda m:m[1]+' '+json.dumps(v),changed);assert n==1,(name,k)
parsed=yaml.safe_load(changed);expected=json.loads(json.dumps(config));expected['database'].update(target);assert parsed==expected
patches.append((name,path,original,changed))
# Keep one exact recovery copy privately; never restore it automatically.
uid=pwd.getpwnam('dune')
for name,path,original,changed in patches:
recovery=staging/(name+'-core-before.yml')
if recovery.exists():raise ValueError('This migration was already staged; inspect before retrying')
recovery.write_text(original);recovery.chmod(0o600)
tmp=path.with_name('config.yml.central-stage');tmp.write_text(changed);os.chown(tmp,uid.pw_uid,uid.pw_gid);tmp.chmod(path.stat().st_mode&0o777);tmp.replace(path)
unit.write_text('[Unit]\nDescription=Central DuneRealms shared game storage\nAfter=network-online.target\nWants=network-online.target\n[Service]\nExecStart=/usr/bin/ssh -NT -i /root/.ssh/dune-db-tunnel -o BatchMode=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=20 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=yes -o UserKnownHostsFile=/root/.ssh/dune-central-known-hosts -L 127.0.0.1:13308:127.0.0.1:3306 dev@91.107.196.242\nRestart=always\nRestartSec=5\n[Install]\nWantedBy=multi-user.target\n')
run('systemctl','daemon-reload');run('systemctl','enable','--now','dune-gameplay-db-tunnel.service')
print(json.dumps({'configured':NAMES,'database':'central:13308','otherPluginStorage':'original:13307','pluginJars':'unchanged'}))
if __name__=='__main__':main()