feat: support Linux/ARM cross-platform build and AVA2 feature updates

- Port server core and libraries to Linux and 32-bit ARM (armhf):
  * Replace FreeBSD kqueue with Linux epoll in libthecore fdwatch
  * Fix unaligned float and 64-bit int memory stores in utils.h str_to_number to avoid ARM VFP alignment fault (SIGBUS)
  * Fix getopt loop variable type in main.cpp (char -> int) to eliminate infinite loop caused by default unsigned char on ARM
  * Add -fsigned-char and multi-architecture flags to Makefiles (x86_64 -m32, i386, and ARM armhf)
  * Update libsql for modern MariaDB client library (removed reconnect field) and C++20 concept/syntax compatibility
  * Replace Win32 xdirent with standard POSIX dirent on Unix/Linux
  * Include xmd5 in libthecore on non-FreeBSD platforms
- AVA2 unlock features and tools:
  * Material stacking up to 2000 count, refine material resolution and test suites
  * AVA2 ticket shop and point drop configuration updates
This commit is contained in:
shenlei
2026-11-11 00:59:49 -08:00
parent 30ea96f418
commit bb0963210e
71 changed files with 1778 additions and 485 deletions
+65
View File
@@ -82,4 +82,69 @@ Offline shop mutation and startup expiry cleanup are explicitly closed in game/d
Keep the `.lock` sidecar in place for the writer's lifetime. Stop old binaries before upgrading a process that uses the same journal path; mixed old/new concurrent writers are unsupported. An I/O error pauses issuance, retaining a complete recovery source; fix the storage problem and preserve journal evidence before restarting. A corrupt log is not automatically truncated or compacted. These changes have standalone fault tests, including ELF32 probes, and do not replace real database/process-crash acceptance.
## 2026-10-26: increased rewards, no daily cap
Current production/sbtest rules, explicitly selected by the user:
monsters and bosses have a 50% chance to award 3–5 points; stones always award
15–30 points. `points_daily_cap=0` means unlimited daily earnings, not zero
earnings. The minimum target level of 1 and maximum overlevel gap of 15 remain.
The profile in `points-wide.json` and the rollout tool defaults both use these
values. The 2026-10-25 profile below is historical and has been superseded.
Applied through authenticated EVENT commands to production's 13 cores and
isolated channel5 without restarting or replacing any process. SQL and every
core's event log match all nine settings. Backups of the prior states are under
`/root/deploy-features/20261026-point-drops-increase/`: production uses
`production-before.json`, and the selected sbtest rollout uses
`sbtest-selected-before.json`. The initial `sbtest-before.json` preserves the
older 5%/1, 3–8, cap-500 profile before a temporary suggested profile; production
was updated directly from that older profile to the selected 50% profile.
Ten point-related tests passed, including actual DB-handler code with a prior
daily total above 500, repeated 30-point awards with cap zero, and same-token
deduplication. This is a configuration/settlement test record, not a claim of a
controlled live kill after the change. Details and runtime evidence:
`metin2-client/docs/POINT-DROPS-INCREASE-20261026.md`.
## 2026-10-25: restore missing point-drop flags (historical)
The current production/sbtest game and db already include point rewards, but both
quest tables had no `points_*` event flags. Missing chance flags mean zero chance,
so neither monsters/bosses nor stones could award shop points. The then-approved rules
were enabled on production's 13 cores and isolated channel5 on 2026-10-25:
5% for monsters/bosses (1 point), 100% for stones (3–8), target at most 15 levels
below the character, and 500 points per account/day. Points credit the account
wallet; they are not ground items. No restart or binary replacement was needed.
`configure_point_drops.py` defaults to a read-only plan. It verifies DB_PORT,
explicit player/account schemas and transactional tables, then uses the existing
authenticated admin EVENT channel so db persists and broadcasts the flags to all
connected cores. It first sets both chances to zero, applies limits/eligibility,
and enables the approved chances last. An exact match is a no-op. Credentials are
read locally from CONFIG and excluded from output/backups. For a core bound to
its LAN address, use `--host` while retaining the loopback source allowlist.
```sh
# On 203; omit --apply/--backup to inspect only.
python3.9 configure_point_drops.py \
--config /usr/metin2/server/channel1/first/CONFIG \
--db-config /usr/metin2/server/db/conf.txt \
--player player --account account --db-port 15000 --host 192.168.21.203 \
--apply --backup /root/deploy-features/20261025-point-drops/NEW-before.json
```
Production backup: `/root/deploy-features/20261025-point-drops/production-before.json`.
Isolated backup: `sbtest-before-r2.json` in the same directory. To restore the
previous disabled state, add `--restore BACKUP` with the same explicit target and
a new `--backup` output. Absent flags restore as zero-valued disabled flags;
wallet balances and reward history are preserved. The first sbtest attempt
against a loopback-only destination was refused before any flags changed.
Verification: five rollout guard tests plus seven existing eligibility,
settlement, completion and journal tests passed. SQL contains all nine expected
flags, and each of the 13 production cores plus channel5 logged the same values
without changing PIDs. No controlled post-change kill is claimed by this rollout;
reward ledgers were still empty at the observation checkpoint. Evidence and
client-facing notes: `metin2-client/docs/POINT-DROPS-ENABLE-20261025.md`.
Strict builds also promote `-Wshorten-64-to-32` to an error. The broader strict warning gate is still failing on legacy code; see the maintenance evidence for the exact blockers.
@@ -0,0 +1,172 @@
#!/usr/bin/env python3
"""Review/apply approved point flags through a running core, without restarting it.
Reads admin credentials only from CONFIG; never includes them in output/backups.
EVENT goes through game -> db -> all cores and persists flags in the quest table.
"""
import argparse
import datetime
import json
from pathlib import Path
import re
import socket
import subprocess
import time
CHANCES = ('points_mob_chance', 'points_stone_chance')
APPROVED = {'points_mob_chance': 5000, 'points_mob_min': 3, 'points_mob_max': 5,
'points_stone_chance': 10000, 'points_stone_min': 15, 'points_stone_max': 30,
'points_min_level': 1, 'points_max_overlevel': 15, 'points_daily_cap': 0}
def config_values(path):
result = {}
for line in path.read_text().splitlines():
words = line.split(None, 1)
if len(words) == 2:
result[words[0].rstrip(':').lower()] = words[1].strip()
return result
def db_schemas(path):
result = {}
for line in path.read_text().splitlines():
match = re.match(r'^\s*(SQL_PLAYER|SQL_ACCOUNT)\s*=\s*"([^"]*)"', line)
if match:
result[match[1]] = match[2].split()[1]
return result
def validate_target(config, db_config, player, account, db_port):
for schema in (player, account):
if not re.fullmatch(r'[A-Za-z0-9_]+', schema):
raise RuntimeError('Invalid schema name')
values = config_values(config)
if int(values.get('db_port', '0')) != db_port:
raise RuntimeError('Core DB_PORT does not match the requested target')
if db_schemas(db_config) != {'SQL_PLAYER': player, 'SQL_ACCOUNT': account}:
raise RuntimeError('DB config does not match the requested schemas')
ips = ' '.join(v for k, v in values.items() if k.startswith('adminpage_ip')).split()
if '127.0.0.1' not in ips or not values.get('adminpage_password'):
raise RuntimeError('A configured loopback admin endpoint is required')
if '\n' in values['adminpage_password'] or '\r' in values['adminpage_password']:
raise RuntimeError('Invalid admin credential format')
return values
def mysql(sql):
return subprocess.check_output(['mysql', '--batch', '--skip-column-names'],
input=sql.encode()).decode().strip()
def snapshot(player, account):
names = ','.join("'%s'" % k for k in sorted(APPROVED))
rows = mysql('SELECT szName,szState,lValue FROM `%s`.quest '
'WHERE dwPID=0 AND szName IN (%s) ORDER BY szName,szState' % (player, names))
before = {}
for line in rows.splitlines():
name, state, value = line.split('\t')
if state or name in before:
raise RuntimeError('Ambiguous event flag rows: ' + name)
before[name] = int(value)
engines = mysql("SELECT COUNT(*) FROM information_schema.tables WHERE ENGINE='InnoDB' AND "
"((TABLE_SCHEMA='%s' AND TABLE_NAME='port_point_rewards') OR "
"(TABLE_SCHEMA='%s' AND TABLE_NAME='account'))" % (player, account))
if engines != '2':
raise RuntimeError('Transactional reward ledger/wallet prerequisites are missing')
return before
def rollout(before, desired):
if all(before.get(k, 0) == v for k, v in desired.items()):
return []
# Quotas and eligibility must be active before any nonzero award probability.
return ([(k, 0) for k in CHANCES] +
[(k, desired[k]) for k in sorted(desired) if k not in CHANCES] +
[(k, desired[k]) for k in CHANCES])
class Admin:
def __init__(self, values, host):
# Some cores bind only the machine's LAN address. Keep the connection's
# source on loopback so its existing admin IP allowlist still applies.
self.sock = socket.create_connection((host, int(values['port'])), timeout=3,
source_address=('127.0.0.1', 0))
# Drain the normal binary phase/handshake before using text admin commands.
self.sock.settimeout(.2)
try:
while self.sock.recv(4096):
pass
except socket.timeout:
pass
self.sock.settimeout(3)
self.command(values['adminpage_password'], 'UNKNOWN')
def command(self, command, expected):
self.sock.sendall(b'@' + command.encode() + b'\n')
result = b''
while not result.endswith(b'\n'):
part = self.sock.recv(4096)
if not part or len(result) + len(part) > 4096:
raise RuntimeError('Admin response missing or oversized')
result += part
if result.strip() != expected.encode():
raise RuntimeError('Admin command rejected; no credential/response is logged')
def event(self, name, value):
self.command('EVENT %s %d' % (name, value), 'EVENT FLAG CHANGE ' + name)
def close(self):
self.sock.close()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--config', required=True, type=Path)
parser.add_argument('--db-config', required=True, type=Path)
parser.add_argument('--player', required=True)
parser.add_argument('--account', required=True)
parser.add_argument('--db-port', required=True, type=int)
parser.add_argument('--host', default='127.0.0.1', help='local listening address of the core')
parser.add_argument('--apply', action='store_true')
parser.add_argument('--backup', type=Path)
parser.add_argument('--restore', type=Path, help='restore flag values from this backup')
args = parser.parse_args()
values = validate_target(args.config, args.db_config, args.player, args.account, args.db_port)
before = snapshot(args.player, args.account)
desired = dict(APPROVED)
if args.restore:
saved = json.loads(args.restore.read_text())
if (saved['player'], saved['account'], saved['db_port'], saved['config']) != (
args.player, args.account, args.db_port, str(args.config.resolve())):
raise RuntimeError('Backup belongs to a different target')
desired = {k: int(saved['before'].get(k, 0)) for k in APPROVED}
commands = rollout(before, desired)
report = {'config': str(args.config.resolve()), 'player': args.player,
'account': args.account, 'db_port': args.db_port, 'host': args.host,
'created_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'before': before, 'desired': desired, 'commands': commands, 'applied': False}
if args.apply and commands:
if not args.backup:
raise RuntimeError('--apply requires a new --backup path')
args.backup.parent.mkdir(parents=True, exist_ok=True)
with args.backup.open('x') as file:
json.dump(report, file, indent=2)
admin = Admin(values, args.host)
try:
for name, value in commands:
admin.event(name, value)
deadline = time.monotonic() + 5
while snapshot(args.player, args.account) != desired:
if time.monotonic() >= deadline:
raise RuntimeError('Flags not persisted; inspect backup and runtime before retry')
time.sleep(.1)
finally:
admin.close()
report['applied'] = True
args.backup.with_suffix('.result.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, sort_keys=True))
if __name__ == '__main__':
main()
+6 -6
View File
@@ -1,11 +1,11 @@
{
"points_mob_chance": 500,
"points_mob_min": 1,
"points_mob_max": 1,
"points_mob_chance": 5000,
"points_mob_min": 3,
"points_mob_max": 5,
"points_stone_chance": 10000,
"points_stone_min": 3,
"points_stone_max": 8,
"points_stone_min": 15,
"points_stone_max": 30,
"points_min_level": 1,
"points_max_overlevel": 15,
"points_daily_cap": 500
"points_daily_cap": 0
}
+16
View File
@@ -0,0 +1,16 @@
# 材料与消耗品 2000 叠放工具
协议修订为 mt20261030,旧客户端必须升级。材料分类与正式清单由 catalogue.py 生成,所有不可合堆标记继续生效。实际数量协议为 uint16,内部及存档为32位。
- migrate.py --schema NAME 默认检查;--apply 扩展数量列并对比行数、数量总和,不支持缩窄。
- cluster.py inventory --scope test|production 按实际 DB_PORT 分组;CH5 当前使用隔离库。deploy 需要候选路径、备份目录和 QA 登录白名单(逗号分隔),执行正常停服、备份、迁移、双端替换和健康检查;open 正常重启并取消白名单。
- fallback 保留宽协议和宽存档,以环境变量停止超过200的新增长;已有大堆叠可整组移动和扣除,不能换回旧二进制。
- provision_fixture.py 只创建全新的验收账号和角色;warehouse_fixture.py 仅用于 CH5 临时验收入口,验收后 remove 清理。私密文件只存于 build 或远端受限目录,不提交Git。
构建候选必须同时重建配套 libsql,再链接 game 与 db。仓库内预编译 libsql.a 可能与当前 AsyncSQL.h 不一致,不能直接链接后上线。使用候选目录并显式覆盖 Makefile 的 GAMEDIR/DBDIR;原始 Makefile 默认会将构建产物移动到正式服务目录。
上线前必须验证候选SHA、包长断言、真实客户端数量往返、普通仓库、洗练扣除、重启存档和旧版拒绝。部署失败期间保留维护状态与备份,不盲目恢复旧版读取大堆叠。
2026-10-27 已完成203正式上线:14个正式game/auth+db,CH5独立db与两个活动核心;19个配置二进制路径SHA一致,旧协议被拒绝。详见 docs/FEATURE-MATERIAL-STACK-2000.md。新增 port_refine_materials.h 保证强化能使用专用背包材料且全量预检后扣除。stress_fixture.py 仅在停止隔离集群后安装/清理满背包和确定性宝箱测试数据;warehouse_fixture.py 的 production scope 只允许新验收角色的普通仓库入口,禁止扩展发奖菜单,必须验收后移除并重启。所有临时夹具均已清理。
迁移报告额外保存数据完整指纹,比较物品身份和所有存档字段。源码工作区的原有未提交内容已保留,发布二进制以SHA256标识,不能仅用有dirty修改的Git HEAD判断版本。
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Export the active item-proto and recipe-derived 2000-stack coverage."""
import argparse,json,re,subprocess
from pathlib import Path
TYPES={'ITEM_USE','ITEM_AUTOUSE','ITEM_MATERIAL','ITEM_METIN','ITEM_RESOURCE','ITEM_BLEND','ITEM_EXTRACT'}
def catalogue(proto,cube,schema):
if not re.fullmatch('[A-Za-z0-9_]+',schema):raise ValueError('schema')
ingredients=set()
if cube.exists():
for line in cube.read_text(errors='replace').splitlines():
parts=line.split()
if len(parts)>=3 and parts[0]=='item' and parts[1].isdigit():ingredients.add(int(parts[1]))
query=' UNION '.join('SELECT vnum%d FROM `%s`.refine_proto WHERE vnum%d>0'%(i,schema,i) for i in range(5))
result=subprocess.run(['mysql','-N','-e',query],check=True,capture_output=True,text=True)
ingredients.update(int(n) for n in result.stdout.split())
records=[]
for line in proto.read_bytes().splitlines()[1:]:
f=[s.decode('latin1') for s in line.split(b'\t')]
if len(f)<7 or not re.fullmatch(r'\d+(?:~\d+)?',f[0]):continue
span=[int(n) for n in f[0].split('~')];lo=span[0];hi=span[-1]
stackable='ITEM_STACKABLE' in f[6] or 'STACKABLE' in f[6]
anti='ANTI_STACK' in f[5]
for vnum in range(lo,hi+1):
eligible=stackable and not anti and (f[2] in TYPES or vnum in ingredients)
if eligible:records.append(dict(vnum=vnum,type=f[2],old_limit=200,new_limit=2000,recipe_material=vnum in ingredients))
return dict(schema=schema,proto=str(proto),cube=str(cube),covered_items=len(records),items=records)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--proto',type=Path,required=True);p.add_argument('--cube',type=Path,required=True);p.add_argument('--schema',required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
report=catalogue(a.proto,a.cube,a.schema);a.output.write_text(json.dumps(report,indent=2));print(json.dumps({'covered_items':report['covered_items'],'output':str(a.output)}))
+131
View File
@@ -0,0 +1,131 @@
#!/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'}))
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Inspect/expand item quantity columns; never narrows columns or rewrites item rows."""
import argparse
import hashlib
import json
import re
import subprocess
def sql(query):
result = subprocess.run(['mysql', '--batch', '--skip-column-names', '-e', query],
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return [line.split('\t') for line in result.stdout.splitlines()]
def identifier(value):
if not re.fullmatch(r'[A-Za-z0-9_]+', value):
raise ValueError('invalid database identifier')
return '`' + value + '`'
def run(schema, apply=False):
identifier(schema)
rows = sql("SELECT TABLE_NAME,COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT "
"FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='%s' "
"AND COLUMN_NAME IN ('count','item_count')" % schema)
report = []
for table, column, kind, nullable, default in rows:
if not (table in ('item','item_orphan_quarantine','shop_item','item_award') or
'item' in table or 'custody' in table):
continue
target = identifier(schema) + '.' + identifier(table)
field = identifier(column)
before = sql('SELECT COUNT(*),COALESCE(SUM(%s),0) FROM %s' % (field,target))
def fingerprint():
# Data-only canonical dump includes item identities and every saved
# field; column widening must preserve more than aggregate totals.
data=subprocess.check_output(['mysqldump','--no-create-info','--skip-extended-insert',
'--skip-comments','--compact','--order-by-primary','--hex-blob',schema,table],stderr=subprocess.PIPE)
return hashlib.sha256(data).hexdigest()
old_fingerprint=fingerprint()
change = kind.lower().startswith(('tinyint','smallint','mediumint'))
entry = dict(table=table,column=column,old_type=kind,needs_expansion=change,before=before,data_sha256=old_fingerprint)
if change and apply:
if default != 'NULL' and not re.fullmatch(r'\d+',default):
raise RuntimeError('unexpected quantity default for '+table)
declaration = 'INT UNSIGNED ' + ('NULL' if nullable=='YES' else 'NOT NULL')
if default != 'NULL': declaration += ' DEFAULT ' + default
sql('ALTER TABLE %s MODIFY COLUMN %s %s' % (target,field,declaration))
after=sql('SELECT COUNT(*),COALESCE(SUM(%s),0) FROM %s' % (field,target))
if before != after: raise RuntimeError('quantity totals changed: '+table)
after_fingerprint=fingerprint()
if after_fingerprint!=old_fingerprint:raise RuntimeError('item identities/data changed: '+table)
entry.update(after=after,new_type='int unsigned',after_data_sha256=after_fingerprint)
report.append(entry)
if not any(row['table']=='item' for row in report):
raise RuntimeError('item table was not found')
return dict(schema=schema,applied=apply,columns=report)
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--schema',required=True);parser.add_argument('--apply',action='store_true')
args=parser.parse_args();print(json.dumps(run(args.schema,args.apply),indent=2))
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Create a fresh, isolated QA character. Does not edit any existing account or item."""
import argparse,json,re,subprocess
from pathlib import Path
def sql(q):
r=subprocess.run(['mysql','-N','-e',q],check=True,capture_output=True,text=True)
return [row.split('\t') for row in r.stdout.splitlines()]
def ident(s):
if not re.fullmatch(r'[a-zA-Z0-9_]+',s):raise ValueError('identifier')
return '`'+s+'`'
def value(s):return '0x'+s.encode().hex()
def clone(table,overrides,where):
cols=[x[0] for x in sql('SHOW COLUMNS FROM '+table) if x[0]!='id']
fields=','.join(ident(c) for c in cols)
expressions=','.join(overrides.get(c,ident(c)) for c in cols)
sql('INSERT INTO '+table+' ('+fields+') SELECT '+expressions+' FROM '+table+' WHERE '+where+' LIMIT 1')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--player-schema',required=True);p.add_argument('--account-schema',required=True);p.add_argument('--private-file',required=True);a=p.parse_args()
private=Path(a.private_file);secrets=json.loads(private.read_text());login=secrets['login'];name=secrets['name']
if len(secrets['password'])>16:raise ValueError('login UI password limit is 16')
acc=ident(a.account_schema)+'.account';player=ident(a.player_schema)+'.player';index=ident(a.player_schema)+'.player_index'
if sql('SELECT id FROM '+acc+' WHERE login='+value(login)):raise RuntimeError('fixture account already exists')
if sql('SELECT id FROM '+player+' WHERE name='+value(name)):raise RuntimeError('fixture character already exists')
clone(acc,{'login':value(login),'password':'PASSWORD('+value(secrets['password'])+')','status':"'OK'",'create_time':'NOW()'},'1 ORDER BY id')
aid=int(sql('SELECT id FROM '+acc+' WHERE login='+value(login))[0][0])
replacements={'account_id':str(aid),'name':value(name),'job':'0','level':'10','gold':'1000000','exp':'0','map_index':'1','x':'477100','y':'956700','z':'0','exit_map_index':'1','exit_x':'477100','exit_y':'956700','hp':'10000','sp':'10000'}
clone(player,replacements,'job=0 ORDER BY id')
pid=int(sql('SELECT id FROM '+player+' WHERE name='+value(name))[0][0])
sql('INSERT INTO '+index+' (id,pid1,pid2,pid3,pid4,pid5,empire) VALUES (%d,%d,0,0,0,0,1)'%(aid,pid))
item=ident(a.player_schema)+'.item'
for i,count in enumerate([199,200,201,255,256,1999,2000]):
sql("INSERT INTO "+item+" (owner_id,window,pos,count,vnum,port_extra) VALUES (%d,'INVENTORY',%d,%d,30006,%s)"%(pid,180+i,count,'0x'+'00'*69))
for cell,vnum,count in [(192,71085,2000),(193,71084,2000),(194,19,1)]:
sql("INSERT INTO "+item+" (owner_id,window,pos,count,vnum,port_extra) VALUES (%d,'INVENTORY',%d,%d,%d,%s)"%(pid,cell,count,vnum,'0x'+'00'*69))
secrets.update(account_id=aid,player_id=pid,player_schema=a.player_schema,account_schema=a.account_schema)
private.write_text(json.dumps(secrets));private.chmod(0o600)
print(json.dumps({'account_id':aid,'player_id':pid,'schema':a.player_schema,'seeded_count':sql('SELECT SUM(count) FROM '+item+' WHERE owner_id='+str(pid))[0][0]}))
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""CH5 QA-only full inventory / deterministic chest fixture. Run with isolated cores/db stopped."""
import argparse,json,re,subprocess
from pathlib import Path
from cluster import inventory
BASE=Path('/root/deploy-features/20261026-stack2000')
def sql(q):return subprocess.check_output(['mysql','-N','-e',q],text=True).strip()
p=argparse.ArgumentParser();p.add_argument('action',choices=['install','remove']);p.add_argument('--private-file',required=True);a=p.parse_args()
s=inventory('test')
if s['db']['pid'] or any(e['pid'] for e in s['cores']):raise RuntimeError('stop isolated cluster before fixture mutation')
secret=json.loads(Path(a.private_file).read_text());assert secret['player_schema']=='player_sb'
pid=int(secret['player_id']);manifest=BASE/'stress-fixture.json'
if a.action=='remove':
data=json.loads(manifest.read_text())
ids=','.join(map(str,data['fillers']))
if ids:sql('DELETE FROM player_sb.item WHERE owner_id=%d AND vnum=11000 AND id IN (%s)'%(pid,ids))
path=Path(data['group_path']);assert not path.is_symlink();path.unlink();path.symlink_to(data['group_target'])
manifest.unlink();print('QA fillers and isolated chest override removed')
else:
if manifest.exists():raise RuntimeError('fixture already installed')
rows=sql("SELECT i.pos,p.size FROM player_sb.item i JOIN player_sb.item_proto p ON i.vnum=p.vnum WHERE i.owner_id=%d AND i.window='INVENTORY' AND i.pos<225"%pid)
occupied=set()
for row in rows.splitlines():
cell,size=map(int,row.split());occupied.update(cell+5*j for j in range(size))
for cell,vnum,count,size in [(197,16,1,2),(198,50037,2,1)]:
cells={cell+5*j for j in range(size)}
if cells&occupied:raise RuntimeError('QA seed cells occupied')
sql("INSERT INTO player_sb.item(owner_id,window,pos,count,vnum,port_extra) VALUES(%d,'INVENTORY',%d,%d,%d,UNHEX(REPEAT('00',69)))"%(pid,cell,count,vnum));occupied.update(cells)
ids=[]
for cell in range(225):
if cell in occupied:continue
ids.append(int(sql("INSERT INTO player_sb.item(owner_id,window,pos,count,vnum,port_extra) VALUES(%d,'INVENTORY',%d,1,11000,UNHEX(REPEAT('00',69)));SELECT LAST_INSERT_ID()"%(pid,cell))))
path=Path('/usr/metin2/server/sbtest/share/locale/newcibn/special_item_group.txt');assert path.is_symlink();target=str(path.readlink());blob=path.read_bytes()
pattern=rb'(?m)^Group[^\r\n]*\r?\n\{.*?^\}'
def keep(m):return b'' if re.search(rb'\bVnum\s+50037\b',m[0],re.I) else m[0]
blob=re.sub(pattern,keep,blob,flags=re.S)+b'\nGroup STACK2000_QA\n{\n Vnum 50037\n 1 27002 2000 100\n}\n'
data=dict(fillers=ids,group_path=str(path),group_target=target)
manifest.write_text(json.dumps(data));manifest.chmod(0o600);path.unlink();path.write_bytes(blob)
print('QA-only full inventory prepared; filler count',len(ids))
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Temporary CH5-only NPC click fixture for a named QA character; remove after acceptance."""
import argparse,json,pathlib,re,shutil,subprocess
BASE=pathlib.Path('/root/deploy-features/20261026-stack2000')
QUEST=pathlib.Path('/usr/metin2/server/sbtest/share/locale/newcibn/quest')
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('action',choices=['install','remove']);p.add_argument('--private-file',required=True);p.add_argument('--extended',action='store_true');p.add_argument('--scope',choices=['test','production'],default='test');a=p.parse_args()
if a.scope=='production':
if a.extended:raise RuntimeError('extended fixtures are isolated-only')
QUEST=pathlib.Path('/usr/metin2/server/share/locale/newcibn/quest')
manifest=BASE/('warehouse-fixture-files.json' if a.scope=='test' else 'warehouse-fixture-production-files.json')
if a.action=='remove':
if manifest.exists():
for name in json.loads(manifest.read_text()):
path=pathlib.Path(name)
if not path.is_relative_to(QUEST/'object'):raise RuntimeError('unexpected fixture path')
path.unlink(missing_ok=True)
manifest.unlink()
else:
s=json.loads(pathlib.Path(a.private_file).read_text());name=s['name']
if not re.fullmatch('[A-Za-z0-9]+',name):raise ValueError('name')
work=BASE/('warehouse-quest' if a.scope=='test' else 'warehouse-quest-production');work.mkdir(exist_ok=True)
shutil.copy2(QUEST/'quest_functions',work/'quest_functions')
source=work/'stack2000_acceptance.quest'
actions={'STACK2000_QA':'game.open_safebox()'}
if a.extended:actions.update(STACK2000_SHOP='npc.open_shop(65001)',STACK2000_MALL='game.open_mall()',STACK2000_GRANT='pc.give_item2(30007,4001)',STACK2000_CUBE='command("cube open")',STACK2000_CUBE_MATERIAL='pc.give_item2(30008,2000)',STACK2000_FULL='pc.give_item2(27003,2001)',STACK2000_REFINE='pc.give_item2(30053,2000) mob.spawn(20016,pc.get_local_x()+1,pc.get_local_y()+1,0,false,1)')
clauses=['when 9005.chat."'+label+'" with pc.get_name()=="'+name+'" begin\n setskin(NOWINDOW)\n '+action+'\n end' for label,action in actions.items()]
source.write_text('quest stack2000_acceptance begin\n state start begin\n'+'\n'.join(clauses)+'\n end\nend\n')
shutil.rmtree(work/'object',ignore_errors=True)
subprocess.run([str(QUEST/'qc'),str(source)],cwd=work,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
files=[]
for path in (work/'object').rglob('*'):
if not path.is_file():continue
target=QUEST/'object'/path.relative_to(work/'object')
if target.exists():raise RuntimeError('fixture path already exists')
target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,target);files.append(str(target))
manifest.write_text(json.dumps(files));print('fixture files',len(files))