From 275c7e521175dd82a7a07aa075be10596d2e90b2 Mon Sep 17 00:00:00 2001 From: shen <> Date: Mon, 19 Oct 2026 16:59:31 -0700 Subject: [PATCH] Deploy verified native itemshop to production with economic backups --- .gitignore | 1 + tools/ava2-itemshop/README.md | 38 +++++++- tools/ava2-itemshop/deploy.py | 179 ++++++++++++++++++++++++++++++++++ 3 files changed, 216 insertions(+), 2 deletions(-) create mode 100644 tools/ava2-itemshop/deploy.py diff --git a/.gitignore b/.gitignore index b88df76f..24f9d4cd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ # Local metadata and generated build output +/build/ .DS_Store ._* __pycache__/ diff --git a/tools/ava2-itemshop/README.md b/tools/ava2-itemshop/README.md index 7fea8cd7..05d7aa5a 100644 --- a/tools/ava2-itemshop/README.md +++ b/tools/ava2-itemshop/README.md @@ -31,5 +31,39 @@ award rows. New clients use revision mt20261020. Legacy clients cannot request G No web recharge service or wheel reward service is enabled. Acceptance evidence: `metin2-client/docs/AVA2-ITEMSHOP.md` and -`metin2-client/audit/evidence/itemshop/`. Only sbtest was changed; production binaries, -prices, balances and catalogue activation were not deployed by this task. +`metin2-client/audit/evidence/itemshop/`. + +## Production release, 2026-10-20 (server CEST) + +203 now runs the verified sbtest game/db pair: game `56975b48aa2fd40389c57eab84d017b0a2518cf6e1b573d967bf239f4ae04aba`, +db `dc940401fe6ccc3410c8d90ce98d2a5bad2e2c023279665bcd664c008d011699`. +The deployment retains the existing native battle pass, wiki, calendar and other cumulative game changes. +The release delta is the native shop, DB prototype-index fix, transactional schema and +49 enabled original offers. The remaining 168 offers, recharge and wheel services stay disabled. +Production 70002 was still ITEM_NONE; its text/SQL prototype is now ITEM_USE/USE_SPECIAL, +matching the tested third-hand implementation. Other prototypes were not replaced with test data. + +Deployment package: `/root/deploy-features/20261020-itemshop`. +Backup: `/root/backup-itemshop/20261020-014955` (old binaries, original prototype, +full account/player SQL dump and pre-deployment error-log offsets). +`deploy.py` gracefully stops game/auth, then db; backs up SQL before migration; starts +db first and then auth and all 13 production game cores. sbtest remains independent. + +Read-only health check: +``` +/usr/local/bin/python3.9 /root/deploy-features/20261020-itemshop/deploy.py check +``` +Binary rollback: +``` +/usr/local/bin/python3.9 /root/deploy-features/20261020-itemshop/deploy.py rollback --backup /root/backup-itemshop/20261020-014955 +``` +Rollback retains InnoDB, coins, orders, awards and the compatible third-hand prototype. +Never restore the pre-release SQL dump over subsequent player purchases. + +CH1 acceptance with a temporary ordinary account verified all 49 catalogue entries/icons, +insufficient funds without an order, a 99-coin purchase, same-token replay without another +charge/order, purchase history and mall redemption into inventory. Test account, character, +coins, orders, awards and items were removed; its one test sale was subtracted without +resetting other sales. Existing players received no test currency. db/auth/13 cores remained +healthy after cleanup. macOS release bundle and connected Android client's APK/resources +were updated; Android in-game purchase acceptance is not claimed by this release. diff --git a/tools/ava2-itemshop/deploy.py b/tools/ava2-itemshop/deploy.py new file mode 100644 index 00000000..abfeb553 --- /dev/null +++ b/tools/ava2-itemshop/deploy.py @@ -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)