159 lines
8.8 KiB
Python
159 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Plan/apply the 32->40 wear-slot migration with cores/db stopped and a full backup.
|
|
|
|
The saved plan contains exact row IDs and before/after values. Reapplying that same plan
|
|
is safe after interruption; never regenerate a plan from partially migrated data.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import os
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import tempfile
|
|
|
|
NAME = 'ava2-shop-wear-40'
|
|
STATE_SQL="SHA2(CONCAT_WS(':',socket0,socket1,socket2,"+','.join('attrtype%d,attrvalue%d'%(i,i) for i in range(7))+"),256)"
|
|
|
|
|
|
def quickslots(blob):
|
|
if not blob:
|
|
return blob
|
|
if len(blob) != 108:
|
|
raise ValueError('Expected 36 three-byte quick slots')
|
|
output = bytearray(blob)
|
|
for index in range(0, len(blob), 3):
|
|
kind, lo, hi = blob[index:index+3]
|
|
pos = lo | hi << 8
|
|
if kind == 1 and (257 <= pos <= 268 or 287 <= pos <= 302):
|
|
output[index+1:index+3] = (pos+8).to_bytes(2, 'little')
|
|
return bytes(output)
|
|
|
|
|
|
def canonical(value):
|
|
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
|
|
|
|
|
|
def plan_digest(plan):
|
|
return hashlib.sha256(canonical({k:v for k,v in plan.items() if k != 'sha256'})).hexdigest()
|
|
|
|
|
|
def validate_plan(plan, identity):
|
|
if plan.get('version') != 2 or plan.get('target') != identity:
|
|
raise RuntimeError('Stale/foreign migration plan; target identity must match exactly')
|
|
if plan.get('sha256') != plan_digest(plan):
|
|
raise RuntimeError('Migration plan checksum mismatch')
|
|
for table,pid,old,new in plan['quickslots']:
|
|
if table not in ('player','player_deleted') or quickslots(bytes.fromhex(old)).hex()!=new:
|
|
raise RuntimeError('Invalid quickslot plan')
|
|
ids = [row[0] for row in plan['items']]
|
|
if len(ids) != len(set(ids)):
|
|
raise RuntimeError('Duplicate item IDs in plan')
|
|
for row in plan['items']:
|
|
if not re.fullmatch('[a-fA-F0-9]{64}',plan.get('item_state',{}).get(str(row[0]),'')):
|
|
raise RuntimeError('Missing full item state binding')
|
|
if len(row) != 8 or row[3] != row[2]+8 or row[1] not in ('EQUIPMENT','INVENTORY'):
|
|
raise RuntimeError('Invalid item migration record')
|
|
|
|
|
|
def validate_extra_schema(columns):
|
|
# SHOW COLUMNS: name,type,null,key,default,extra
|
|
extra = next((c for c in columns if c[0]=='port_extra'), None)
|
|
if extra is not None and (extra[1].lower()!='varbinary(69)' or extra[2]!='NO' or extra[4]!=''):
|
|
raise RuntimeError('item.port_extra must be VARBINARY(69) NOT NULL DEFAULT empty')
|
|
return extra is not None
|
|
|
|
|
|
def atomic_json(path, value):
|
|
descriptor,name=tempfile.mkstemp(prefix=path.name+'.',suffix='.tmp',dir=path.parent)
|
|
temporary=Path(name)
|
|
with os.fdopen(descriptor,'w') as out:
|
|
out.write(json.dumps(value,indent=2)+'\n');out.flush();os.fsync(out.fileno())
|
|
os.replace(temporary, path)
|
|
fd=os.open(path.parent,os.O_RDONLY)
|
|
try:os.fsync(fd)
|
|
finally:os.close(fd)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--player', required=True)
|
|
parser.add_argument('--plan', type=Path, required=True)
|
|
parser.add_argument('--apply', action='store_true')
|
|
parser.add_argument('--offline', action='store_true', help='confirm ALL target writers stopped')
|
|
parser.add_argument('--backup-id', help='verified backup identity required for apply')
|
|
args = parser.parse_args()
|
|
if args.apply and (not args.offline or not args.backup_id):
|
|
parser.error('--apply requires --offline and --backup-id')
|
|
if not re.fullmatch('[A-Za-z0-9_]+', args.player):
|
|
parser.error('Invalid database name')
|
|
|
|
def sql(query):
|
|
result = subprocess.run(['mysql', '-N', '-B', args.player], input=query,
|
|
text=True, capture_output=True, check=True)
|
|
return [line.split('\t') for line in result.stdout.splitlines()]
|
|
|
|
sql('CREATE TABLE IF NOT EXISTS mt_migration_target(id TINYINT PRIMARY KEY, identity CHAR(36) NOT NULL);')
|
|
sql('INSERT IGNORE INTO mt_migration_target(id,identity) VALUES(1,UUID());')
|
|
identity = sql('SELECT DATABASE(),@@hostname,@@port,@@server_id,identity FROM mt_migration_target WHERE id=1;')
|
|
if len(identity)!=1:raise RuntimeError('Cannot bind target identity')
|
|
columns=sql('SHOW COLUMNS FROM item;')
|
|
has_extra=validate_extra_schema(columns)
|
|
if has_extra:
|
|
bad=sql("SELECT id FROM item WHERE OCTET_LENGTH(port_extra) NOT IN (0,69) OR (OCTET_LENGTH(port_extra)=69 AND SUBSTRING(port_extra,69,1)<>X'00');")
|
|
if bad:raise RuntimeError('Corrupt extra: quarantine original rows before migration: '+repr(bad[:20]))
|
|
sql('CREATE TABLE IF NOT EXISTS mt_migration(name VARCHAR(64) PRIMARY KEY,done DATETIME);')
|
|
markers=sql("SELECT name FROM mt_migration WHERE name='%s';" % NAME)
|
|
if markers and not has_extra:raise RuntimeError('Completed marker has missing extra schema')
|
|
if args.plan.exists():
|
|
plan=json.loads(args.plan.read_text());validate_plan(plan,identity[0])
|
|
else:
|
|
if markers:raise RuntimeError('Completed marker has no bound plan; inspect instead of trusting marker')
|
|
bad=sql("SELECT i.id FROM item i LEFT JOIN item_proto p ON i.vnum=p.vnum WHERE i.window='EQUIPMENT' AND i.pos>=32 AND (i.pos>43 OR p.type IS NULL OR p.type NOT IN (29,30));")
|
|
if bad:raise RuntimeError('Unexpected equipment cells; inspect before migration')
|
|
rows=sql("SELECT id,window,pos,vnum,owner_id,count,%s,%s FROM item WHERE (window='EQUIPMENT' AND pos BETWEEN 32 AND 43) OR (window='INVENTORY' AND pos BETWEEN 287 AND 302) ORDER BY pos DESC;" % ('HEX(port_extra)' if has_extra else "''",STATE_SQL))
|
|
plan={'version':2,'schema':args.player,'target':identity[0], 'items':[], 'quickslots':[], 'item_state':{}}
|
|
for item,window,pos,vnum,owner,count,extra,state in rows:
|
|
plan['item_state'][item]=state
|
|
plan['items'].append([int(item),window,int(pos),int(pos)+8,int(vnum),int(owner),int(count),extra])
|
|
for table in ('player','player_deleted'):
|
|
for pid,value in sql('SELECT id,HEX(quickslot) FROM `%s`;' % table):
|
|
old=bytes.fromhex(value);new=quickslots(old)
|
|
if old!=new:plan['quickslots'].append([table,int(pid),old.hex(),new.hex()])
|
|
plan['sha256']=plan_digest(plan);args.plan.parent.mkdir(parents=True,exist_ok=True);atomic_json(args.plan,plan)
|
|
validate_plan(plan,identity[0])
|
|
print('planned items=%d quickslots=%d' % (len(plan['items']), len(plan['quickslots'])))
|
|
# Validate ALL rows before mutating any of them. Resume permits only each bound old/new state.
|
|
for item,window,old,new,vnum,owner,count,extra in plan['items']:
|
|
row=sql("SELECT window,pos,vnum,owner_id,count,%s,%s FROM item WHERE id=%d;" % ('HEX(port_extra)' if has_extra else "''",STATE_SQL,item))
|
|
expected=[window,str(new if markers else old),str(vnum),str(owner),str(count),extra,plan['item_state'][str(item)]]
|
|
alternative=list(expected);alternative[1]=str(new)
|
|
if len(row)!=1 or row[0] not in (expected,alternative):raise RuntimeError('Item identity/state differs from bound plan: '+str(item))
|
|
for table, pid, old, new in plan['quickslots']:
|
|
row = sql('SELECT HEX(quickslot) FROM `%s` WHERE id=%d;' % (table, pid))
|
|
if not row or row[0][0].lower() not in ((new,) if markers else (old,new)):
|
|
raise RuntimeError('Quickslot changed since planning')
|
|
if not args.apply:return
|
|
if not has_extra:
|
|
sql("ALTER TABLE item ADD port_extra VARBINARY(69) NOT NULL DEFAULT ''; ")
|
|
for item,window,old,new,vnum,owner,count,extra in plan['items']:
|
|
if markers:continue
|
|
sql("UPDATE item SET pos=%d WHERE id=%d AND window='%s' AND pos=%d AND vnum=%d AND owner_id=%d AND count=%d;" % (new,item,window,old,vnum,owner,count))
|
|
for table,pid,old,new in plan['quickslots']:
|
|
sql("UPDATE `%s` SET quickslot=X'%s' WHERE id=%d AND HEX(quickslot)='%s';" %
|
|
(table, new, pid, old.upper()))
|
|
# A completion marker is accepted only after re-reading every migrated target value.
|
|
for item,window,old,new,vnum,owner,count,extra in plan['items']:
|
|
if sql('SELECT pos FROM item WHERE id=%d;' % item)!=[[str(new)]]:raise RuntimeError('Item post-validation failed')
|
|
for table,pid,old,new in plan['quickslots']:
|
|
if sql('SELECT LOWER(HEX(quickslot)) FROM `%s` WHERE id=%d;' % (table,pid))!=[[new]]:raise RuntimeError('Quickslot post-validation failed')
|
|
validate_extra_schema(sql('SHOW COLUMNS FROM item;'))
|
|
sql("INSERT IGNORE INTO mt_migration(name,done) VALUES('%s',NOW());" % NAME)
|
|
atomic_json(args.plan.with_name(args.plan.name+'.receipt.json'),{'plan_sha256':plan['sha256'],'target':identity[0],'backup_id':args.backup_id,'verified':True})
|
|
print(NAME+': post-validated; preserve plan, receipt and backup')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|