#!/usr/bin/env python3 """Coordinated mt20261030 deployment. Run on 203; candidates must already be tested. Inventory uses CONFIG DB_PORT, not channel numbers: CH5 currently belongs to sbtest. """ import argparse,hashlib,json,os,pathlib,shutil,signal,subprocess,time from migrate import run as migrate ROOT=pathlib.Path('/usr/metin2/server') def digest(path):return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest() def alive(pid): try:os.kill(pid,0);return True except ProcessLookupError:return False def pid(core): try:value=int((core/'pid').read_text().strip()) except (ValueError,OSError):return 0 if not alive(value):return 0 output=subprocess.check_output(['procstat','-f',str(value)]).decode() if not any(' cwd ' in line and str(core) in line for line in output.splitlines()): raise RuntimeError('PID does not belong to '+str(core)) return value def config(path): result={} for line in path.read_text(errors='replace').splitlines(): key,sep,value=line.partition(':') if sep:result[key.strip()]=value.strip() return result def inventory(scope): dbport='15040' if scope=='test' else '15000' configs=list(ROOT.glob('channel*/**/CONFIG'))+[ROOT/'auth/CONFIG',ROOT/'game99/CONFIG']+list((ROOT/'sbtest').glob('*/CONFIG')) cores=[] for path in sorted(set(configs)): if not path.is_file():continue cfg=config(path) if cfg.get('DB_PORT')!=dbport:continue directory=path.parent exe='auth' if directory.name=='auth' else 'game' cores.append(dict(path=str(directory),executable=exe,port=int(cfg['PORT']),pid=pid(directory))) db=ROOT/('sbtest/db' if scope=='test' else 'db') return dict(scope=scope,cores=cores,db=dict(path=str(db),executable='db',port=int(dbport),pid=pid(db))) def stop(entries): running=[] for entry in entries: value=pid(pathlib.Path(entry['path'])) if value:os.kill(value,signal.SIGHUP);running.append(value) deadline=time.time()+180 while any(alive(value) for value in running): if time.time()>deadline:raise RuntimeError('graceful stop timed out') time.sleep(.5) def replace(source,target): target=pathlib.Path(target);tmp=target.with_name(target.name+'.stack2000-new') shutil.copy2(source,tmp);tmp.chmod(0o755);tmp.replace(target) def start(entries,qa_login='',legacy=False): env=dict(os.environ) if qa_login:env['PORT_MATERIAL_STACK_QA_LOGIN']=qa_login else:env.pop('PORT_MATERIAL_STACK_QA_LOGIN',None) if legacy:env['PORT_MATERIAL_STACK_LEGACY_MODE']='1' else:env.pop('PORT_MATERIAL_STACK_LEGACY_MODE',None) for entry in entries: directory=pathlib.Path(entry['path']) if pid(directory):raise RuntimeError('process still running before startup') subprocess.run(['daemon','-f','-o',str(directory/'stack2000.stdout'),'./'+entry['executable']],cwd=directory,env=env,check=True) time.sleep(.25) deadline=time.time()+90 while True: sockets=subprocess.check_output(['sockstat','-4','-l','-P','tcp']).decode() missing=[e['path'] for e in entries if not pid(pathlib.Path(e['path'])) or (':'+str(e['port'])+' ') not in sockets] if not missing:return if time.time()>deadline:raise RuntimeError('startup failed: '+','.join(missing)) time.sleep(1) def deploy(scope,candidate,backup,qa_login): state=inventory(scope) state['configured_cores']=list(state['cores']) state['cores']=[entry for entry in state['cores'] if entry['pid']] if not state['cores'] or not state['db']['pid']:raise RuntimeError('no running cluster to deploy') candidate=pathlib.Path(candidate);backup=pathlib.Path(backup) if backup.exists():raise RuntimeError('backup path already exists') for name in ['game','db']: if not (candidate/name).is_file():raise RuntimeError('candidate missing '+name) backup.mkdir(parents=True,mode=0o700) state['candidates']={name:digest(candidate/name) for name in ['game','db']} for entry in state['configured_cores']+[state['db']]: directory=pathlib.Path(entry['path']);exe=directory/entry['executable'] entry['original_target']=str(exe.resolve());entry['was_symlink']=exe.is_symlink() entry['original_sha256']=digest(exe) if scope=='production': expected=ROOT/'share/bin'/('db' if entry['executable']=='db' else 'game') if exe.resolve()!=expected.resolve():raise RuntimeError('unhandled production binary path: '+str(exe)) label=directory.relative_to(ROOT).as_posix().replace('/','_') shutil.copy2(exe,backup/(label+'.binary')) for filename in ['CONFIG','conf.txt']: path=directory/filename if path.exists():shutil.copy2(path,backup/(label+'.'+filename)) error=directory/'syserr';entry['error_offset']=error.stat().st_size if error.exists() else 0 (backup/'metadata.json').write_text(json.dumps(state,indent=2));(backup/'metadata.json').chmod(0o600) stop(state['cores']);stop([state['db']]) schemas=['player_sb','account_sb','common_sb'] if scope=='test' else ['player','account','common'] for schema in schemas: path=backup/(schema+'.sql') with path.open('wb') as out:subprocess.run(['mysqldump','--default-character-set=binary','--single-transaction','--routines','--triggers',schema],stdout=out,stderr=subprocess.PIPE,check=True) path.chmod(0o600) report=migrate(schemas[0],True) (backup/'migration.json').write_text(json.dumps(report,indent=2)) if scope=='production': replace(candidate/'game',ROOT/'share/bin/game');replace(candidate/'db',ROOT/'share/bin/db') else: for name in ['game','db']:replace(candidate/name,ROOT/('sbtest/'+name+'.stack2000')) for entry in state['configured_cores']+[state['db']]: exe=pathlib.Path(entry['path'])/entry['executable'];source=ROOT/('sbtest/'+('db' if entry['executable']=='db' else 'game')+'.stack2000') temp=exe.with_name(exe.name+'.stack2000-link');temp.symlink_to(source);temp.replace(exe) start([state['db']],qa_login);start(state['cores'],qa_login) (backup/'DEPLOYED_QA').write_text(json.dumps(state['candidates'])) print(json.dumps({'backup':str(backup),'inventory':inventory(scope),'qa_only':bool(qa_login)})) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('action',choices=['inventory','deploy','open','fallback']);p.add_argument('--scope',choices=['test','production'],required=True);p.add_argument('--candidate');p.add_argument('--backup');p.add_argument('--qa-login',default='');a=p.parse_args() if a.action=='inventory':print(json.dumps(inventory(a.scope),indent=2)) elif a.action=='deploy': if not a.candidate or not a.backup or not a.qa_login:p.error('deploy requires candidate, backup and QA login') deploy(a.scope,a.candidate,a.backup,a.qa_login) else: state=inventory(a.scope);cores=[e for e in state['cores'] if e['pid']] stop(cores);stop([state['db']]);start([state['db']],a.qa_login,legacy=a.action=='fallback');start(cores,a.qa_login,legacy=a.action=='fallback') print(json.dumps({'inventory':inventory(a.scope),'legacy_growth':a.action=='fallback'}))