Deploy verified native itemshop to production with economic backups
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
#!/usr/local/bin/python3.9
|
||||
"""Deploy the verified shop binaries and migration; retain economic rows on rollback."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
ROOT = Path('/usr/metin2/server')
|
||||
PACKAGE = Path(__file__).resolve().parent
|
||||
CORES = [ROOT/'auth'] + [ROOT/('channel%d/%s' % (ch, part))
|
||||
for ch in range(1, 5) for part in ('first', 'game1', 'game2')] + [ROOT/'game99']
|
||||
DB = ROOT/'db'
|
||||
GAME_HASH = '56975b48aa2fd40389c57eab84d017b0a2518cf6e1b573d967bf239f4ae04aba'
|
||||
DB_HASH = 'dc940401fe6ccc3410c8d90ce98d2a5bad2e2c023279665bcd664c008d011699'
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def pid(core):
|
||||
try:
|
||||
value = int((core/'pid').read_text().strip())
|
||||
os.kill(value, 0)
|
||||
except (OSError, ValueError):
|
||||
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: ' + str(core))
|
||||
return value
|
||||
|
||||
|
||||
def stop(cores):
|
||||
pending = [pid(core) for core in cores]
|
||||
for value in pending:
|
||||
if value:
|
||||
os.kill(value, signal.SIGHUP)
|
||||
deadline = time.time() + 300
|
||||
while any(pid(core) for core in cores):
|
||||
if time.time() > deadline:
|
||||
raise RuntimeError('Graceful stop timeout; no forced termination')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def listeners():
|
||||
return subprocess.check_output(['sockstat', '-4', '-l', '-P', 'tcp']).decode()
|
||||
|
||||
|
||||
def wait_for(cores, ports):
|
||||
deadline = time.time() + 180
|
||||
while True:
|
||||
active = listeners()
|
||||
if all(pid(c) for c in cores) and all(':%d ' % p in active for p in ports):
|
||||
return
|
||||
if time.time() > deadline:
|
||||
raise RuntimeError('Start health check timed out')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def port(core):
|
||||
return int(next(line.split(':', 1)[1] for line in
|
||||
(core/'CONFIG').read_text().splitlines() if line.startswith('PORT:')))
|
||||
|
||||
|
||||
def start():
|
||||
if not pid(DB):
|
||||
subprocess.run(['daemon', '-f', '-o', str(DB/'itemshop-deploy.stdout'), './db'], cwd=DB, check=True)
|
||||
wait_for([DB], [15000])
|
||||
for core in CORES:
|
||||
if not pid(core):
|
||||
executable = './auth' if core.name == 'auth' else './game'
|
||||
subprocess.run(['daemon', '-f', '-o', str(core/'itemshop-deploy.stdout'), executable], cwd=core, check=True)
|
||||
time.sleep(.3)
|
||||
wait_for(CORES, [port(c) for c in CORES])
|
||||
|
||||
|
||||
def mysql(sql):
|
||||
return subprocess.check_output(['mysql', '-N'], input=sql.encode()).decode().strip()
|
||||
|
||||
|
||||
def replace(source, target):
|
||||
temporary = target.with_name(target.name + '.shop-new')
|
||||
shutil.copy2(source, temporary)
|
||||
temporary.chmod(0o755)
|
||||
temporary.replace(target)
|
||||
|
||||
|
||||
def report():
|
||||
return {'game_sha256': digest(ROOT/'share/bin/game'),
|
||||
'db_sha256': digest(ROOT/'share/bin/db'),
|
||||
'pids': {str(c.relative_to(ROOT)): pid(c) for c in [DB]+CORES},
|
||||
'enabled_products': mysql('SELECT COUNT(*) FROM player.ishop_data WHERE enabled=1;')}
|
||||
|
||||
|
||||
def rollback(backup):
|
||||
stop(CORES)
|
||||
stop([DB])
|
||||
replace(backup/'game', ROOT/'share/bin/game')
|
||||
replace(backup/'db', ROOT/'share/bin/db')
|
||||
# Keep InnoDB, coins, orders and awards. Reverting them could discard purchases.
|
||||
# Keep the compatible 70002 prototype so already delivered items remain usable.
|
||||
start()
|
||||
print(json.dumps({'rollback': str(backup), **report()}), flush=True)
|
||||
|
||||
|
||||
def deploy():
|
||||
candidate = Path('/root/deploy-features/20261018-ava2-parity/itemshop-build/bin')
|
||||
if digest(candidate/'game') != GAME_HASH or digest(candidate/'db') != DB_HASH:
|
||||
raise RuntimeError('Candidate binary hash mismatch')
|
||||
if not all(pid(c) for c in [DB]+CORES):
|
||||
raise RuntimeError('Production baseline is not healthy')
|
||||
backup = Path('/root/backup-itemshop')/time.strftime('%Y%m%d-%H%M%S')
|
||||
backup.mkdir(parents=True, mode=0o700)
|
||||
for name in ('game', 'db'):
|
||||
shutil.copy2(ROOT/'share/bin'/name, backup/name)
|
||||
meta = {'before': {n: digest(backup/n) for n in ('game', 'db')},
|
||||
'source_revision': '3283101',
|
||||
'syserr_offsets': {str(c.relative_to(ROOT)): (c/'syserr').stat().st_size
|
||||
if (c/'syserr').exists() else 0 for c in [DB]+CORES}}
|
||||
(backup/'metadata.json').write_text(json.dumps(meta, indent=2)+'\n')
|
||||
proto = (ROOT/'share/conf/item_proto.txt').resolve()
|
||||
shutil.copy2(proto, backup/'item_proto.txt')
|
||||
(PACKAGE/'LAST_BACKUP').write_text(str(backup)+'\n')
|
||||
print('backup=' + str(backup), flush=True)
|
||||
stop(CORES)
|
||||
print('game/auth stopped gracefully', flush=True)
|
||||
stop([DB])
|
||||
print('db stopped gracefully', flush=True)
|
||||
try:
|
||||
with (backup/'account-player.sql').open('wb') as out:
|
||||
subprocess.run(['mysqldump', '--lock-all-tables', '--routines', '--triggers',
|
||||
'--databases', 'account', 'player'], stdout=out, check=True)
|
||||
(backup/'account-player.sql').chmod(0o600)
|
||||
print('account/player backup complete', flush=True)
|
||||
lines = proto.read_bytes().splitlines(keepends=True)
|
||||
changed = 0
|
||||
for i, line in enumerate(lines):
|
||||
if line.startswith(b'70002\t'):
|
||||
row = line.rstrip(b'\r\n').split(b'\t')
|
||||
row[2], row[3], row[7] = b'ITEM_USE', b'USE_SPECIAL', b'NONE'
|
||||
lines[i] = b'\t'.join(row)+b'\n'
|
||||
changed += 1
|
||||
if changed != 1:
|
||||
raise RuntimeError('Expected exactly one 70002 prototype')
|
||||
proto.write_bytes(b''.join(lines))
|
||||
mysql('UPDATE player.item_proto SET type=3,subtype=10,wearflag=0 WHERE vnum=70002;')
|
||||
for name in ('migrate.sql', 'enable.sql'):
|
||||
mysql((PACKAGE/name).read_text())
|
||||
if mysql('SELECT COUNT(*) FROM player.ishop_data WHERE enabled=1;') != '49':
|
||||
raise RuntimeError('Expected 49 verified products')
|
||||
replace(candidate/'game', ROOT/'share/bin/game')
|
||||
replace(candidate/'db', ROOT/'share/bin/db')
|
||||
start()
|
||||
result = report()
|
||||
(backup/'DEPLOYED.json').write_text(json.dumps(result, indent=2)+'\n')
|
||||
print(json.dumps(result), flush=True)
|
||||
except Exception:
|
||||
rollback(backup)
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=['deploy', 'check', 'rollback'])
|
||||
parser.add_argument('--backup', type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.action == 'deploy':
|
||||
deploy()
|
||||
elif args.action == 'check':
|
||||
print(json.dumps(report()), flush=True)
|
||||
else:
|
||||
if not args.backup:
|
||||
parser.error('rollback requires --backup')
|
||||
rollback(args.backup)
|
||||
Reference in New Issue
Block a user