83 lines
4.5 KiB
Python
83 lines
4.5 KiB
Python
#!/usr/local/bin/python3.9
|
|
"""203 game-only deployment. Keep db running; back up first; retain earned claims on rollback."""
|
|
import argparse,hashlib,json,os,shutil,signal,subprocess,time
|
|
from pathlib import Path
|
|
ROOT=Path('/usr/metin2/server')
|
|
CORES=[ROOT/'auth']+[ROOT/('channel%d/%s'%(ch,part)) for ch in range(1,5) for part in ('first','game1','game2')]+[ROOT/'game99']
|
|
LIVE=ROOT/'share/bin/game';CAL=ROOT/'share/locale/newcibn/port_events.tsv'
|
|
def digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
def alive(pid):
|
|
try:os.kill(pid,0);return True
|
|
except ProcessLookupError:return False
|
|
def pid(core):
|
|
try:return int((core/'pid').read_text().strip())
|
|
except (OSError,ValueError):return 0
|
|
def verified_pid(core):
|
|
value=pid(core)
|
|
if not value or not alive(value):return 0
|
|
details=subprocess.check_output(['procstat','-f',str(value)]).decode()
|
|
if not any(' cwd ' in line and str(core) in line for line in details.splitlines()):raise RuntimeError('Unexpected pid owner for '+str(core))
|
|
return value
|
|
def stop():
|
|
pending=[verified_pid(core) for core in CORES];pending=[p for p in pending if p]
|
|
for value in pending:os.kill(value,signal.SIGHUP)
|
|
deadline=time.time()+300
|
|
while any(alive(p) for p in pending):
|
|
if time.time()>deadline:raise RuntimeError('Graceful stop timed out; binary remains unchanged')
|
|
time.sleep(.5)
|
|
def port(core):
|
|
return int(next(line.split(':',1)[1] for line in (core/'CONFIG').read_text().splitlines() if line.startswith('PORT:')))
|
|
def start():
|
|
for core in CORES:
|
|
if verified_pid(core):continue
|
|
executable='./auth' if core.name=='auth' else './game'
|
|
subprocess.run(['daemon','-f','-o',str(core/'native-deploy.stdout'),executable],cwd=str(core),check=True)
|
|
time.sleep(.3)
|
|
deadline=time.time()+55
|
|
while True:
|
|
listeners=subprocess.check_output(['sockstat','-4','-l','-P','tcp']).decode()
|
|
missing=[str(core.relative_to(ROOT)) for core in CORES if not verified_pid(core) or (':%d '%port(core)) not in listeners]
|
|
if not missing:return
|
|
if time.time()>deadline:raise RuntimeError('Cores failed health check: '+','.join(missing))
|
|
time.sleep(1)
|
|
def replace(source):
|
|
target=LIVE.with_suffix('.native-new');shutil.copy2(source,target);target.chmod(0o755);target.replace(LIVE)
|
|
def report():
|
|
print(json.dumps({'game_sha256':digest(LIVE),'cores':{str(c.relative_to(ROOT)):verified_pid(c) for c in CORES},'db_running':alive(pid(ROOT/'db'))},sort_keys=True),flush=True)
|
|
def rollback(backup):
|
|
meta=json.loads((backup/'metadata.json').read_text());stop();replace(backup/'game')
|
|
# Progress/claim rows are intentionally retained: reverting them could pay rewards twice.
|
|
if not meta['calendar_existed'] and CAL.exists() and CAL.read_bytes()==b'MTCALENDAR 1\n':CAL.unlink()
|
|
start();report()
|
|
def deploy(candidate,expected,destination):
|
|
if digest(candidate)!=expected:raise RuntimeError('Staged candidate hash mismatch')
|
|
if not alive(pid(ROOT/'db')):raise RuntimeError('Production db is not running')
|
|
for core in CORES:verified_pid(core)
|
|
backup=destination/time.strftime('%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700)
|
|
shutil.copy2(LIVE,backup/'game')
|
|
meta={'old_hash':digest(LIVE),'new_hash':expected,'calendar_existed':CAL.exists(),'syserr_offsets':{str(c.relative_to(ROOT)):(c/'syserr').stat().st_size if (c/'syserr').exists() else 0 for c in CORES}}
|
|
(backup/'metadata.json').write_text(json.dumps(meta,indent=2)+'\n')
|
|
for name in ('port_events.tsv','port_battlepass.tsv'):
|
|
f=CAL.parent/name
|
|
if f.exists():shutil.copy2(f,backup/name)
|
|
for table in ('mt_battlepass_progress','mt_battlepass_claim'):
|
|
data=subprocess.check_output(['mysqldump','--no-create-info','--complete-insert','--skip-add-locks','player',table]);f=backup/(table+'.sql');f.write_bytes(data);f.chmod(0o600)
|
|
print('backup='+str(backup),flush=True)
|
|
try:
|
|
stop()
|
|
replace(candidate)
|
|
if not CAL.exists():
|
|
temporary=CAL.with_suffix('.native-new');temporary.write_bytes(b'MTCALENDAR 1\n');temporary.replace(CAL)
|
|
start();report()
|
|
except Exception:
|
|
rollback(backup);raise
|
|
(backup/'DEPLOYED').write_text(expected+'\n')
|
|
print('deployed='+str(backup),flush=True)
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser();p.add_argument('action',choices=['check','deploy','rollback']);p.add_argument('--candidate',type=Path);p.add_argument('--sha256');p.add_argument('--backups',type=Path,default=Path('/root/backup-native-systems'));p.add_argument('--backup',type=Path);a=p.parse_args()
|
|
if a.action=='check':report()
|
|
elif a.action=='rollback':rollback(a.backup)
|
|
else:
|
|
if not a.candidate or not a.sha256:p.error('deploy requires --candidate and --sha256')
|
|
deploy(a.candidate,a.sha256,a.backups)
|