Files
WoW-Hybrid-gateway/ops/start_native_client.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

134 lines
8.7 KiB
Python

#!/usr/bin/env python3
"""Start/reuse the journaled private native client; never types credentials.
No rebuild, server restart, gateway, Lua registration or automatic process kill.
The existing debug owner validates executable/dependency identities and owns all
native setup. This wrapper only replaces repetitive detached startup commands.
"""
import argparse,datetime,json,os,subprocess,sys,time
from pathlib import Path
from client_installation import client_debug_socket
from client_installation import COPY,running_clients
from client_session import Session
from native_engine_character_test import ROOT,local_listeners
from native_test_guard import require_local_turtle_ports
from local_tortoise import db
def wait_local_character_shutdown(timeout=15,*,character_guid=None):
"""Wait for an actual saved offline state; never clear online flags."""
if type(timeout)not in(int,float)or not 0<timeout<=15:raise ValueError('Shutdown readiness bound0..15seconds')
if character_guid is not None and(type(character_guid)is not int or not 0<character_guid<2**32):raise ValueError('Positive uint32 character GUID required')
query='SELECT COUNT(*) FROM tw_char.characters WHERE online<>0'+(' AND guid='+str(character_guid)if character_guid is not None else'')+';'
deadline=time.monotonic()+timeout
while True:
count=db(query)
if count=='0':return
if not isinstance(count,str)or not count.isascii()or not count.isdecimal():raise RuntimeError('Invalid local online-state response; preserve state')
if time.monotonic()>=deadline:raise RuntimeError('Local character shutdown/save still pending; no relaunch or DB edit')
time.sleep(.25)
def startup_graphics_failure(log,not_before):
"""Explain a fresh, unrecovered Present fault without changing client state."""
try:
if log.stat().st_mtime<not_before:return None
with log.open('rb') as source:
source.seek(max(0,log.stat().st_size-65536));text=source.read(65536).decode(errors='replace')
except OSError:return None
text=text.rsplit('LogOpen',1)[-1]
failure=text.rfind('Exception caught in SwapChain::Present: code 0xC0000005')
if failure<0 or 'Dx11 Device Create Successful' in text[failure:]:return None
return 'Fresh gx.log reports a SwapChain::Present access violation; graphics recovery has not logged a successful device recreation. Client and logs preserved; inspect graphics before retrying input.'
def owned_queue_entry_executable(pid):
# Same pinned original queue entry checked again by the owner before any
# observer installation. A mapped window may precede natural unpacking.
address=0x141e53d80
for line in (Path('/proc')/str(pid)/'maps').read_text().splitlines():
fields=line.split();lo,hi=(int(value,16) for value in fields[0].split('-'))
if lo<=address<hi:return 'x' in fields[1]
return False
def wait_background_native_window(pid,timeout=25):
"""Wait for the owned main surface using metadata only.
The owner/reuse path establishes process identity before this transition.
Login readiness is established later by the controller's idle/listener/ABI
proof and original callback arm; a preset screen is never clicked here.
"""
from Xlib import display
import client_ui
deadline=time.monotonic()+timeout
d=display.Display()
try:
while True:
if not (Path('/proc')/str(pid)).exists():raise ProcessLookupError('Owned native client closed during startup')
try:row=client_ui.choose_main_window(client_ui.window_rows(d),pid)
except client_ui.ClientWindowBlocked:raise
except RuntimeError as error:
if str(error)!='No real WowB.exe main window found':raise
else:
if row['mapped'] and owned_queue_entry_executable(pid):return 'native-main-window-ready'
if time.monotonic()>=deadline:raise RuntimeError('Native startup readiness timed out while pending (main window or original queue entry not executable); client preserved')
time.sleep(.1)
finally:d.close()
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--endpoint-profile',choices=('local','octo'),default='local')
parser.add_argument('--realm-registration-observer',action='store_true',help='Observe original C_Login/C_RealmList registrations during this necessary startup')
parser.add_argument('--character-guid',type=int,help='Wait for this local character save when other isolated clients intentionally remain online')
parser.add_argument('--background-manual-arm',action='store_true',help='Launcher manual mode: metadata-only main-window readiness, no focus, capture or input')
args=parser.parse_args()
os.umask(0o077);started=time.monotonic();launched_at=time.time();ports=local_listeners()
if args.endpoint_profile=='local':
require_local_turtle_ports(ports)
# The existing login handoff checks this again at submission. Check it
# before starting the client as well, so a non-local modern fallback is
# rejected before the local test owner can launch the engine.
from engine_login_input_binding import isolated_modern_fallback
isolated_modern_fallback()
elif 19085 in ports:raise RuntimeError('Stop external gateway before direct Octo startup')
clients=running_clients(owned_only=True);pid_file=ROOT/'runtime/native-client.pid';socket=client_debug_socket(ROOT);owner_file=ROOT/'runtime/native-owner-detached.pid'
if clients:
if len(clients)!=1 or not pid_file.exists() or clients!=[int(pid_file.read_text())]:raise RuntimeError('Unowned/multiple client preserved; no duplicate launch')
pid=clients[0];command=(Path('/proc')/str(pid)/'cmdline').read_bytes().split(b'\0');expected=str(COPY/'_classic_beta_/WowB.exe')
if not any(p.encode() in command for p in (expected,'Z:'+expected.replace('/','\\'))) or not socket.exists():raise RuntimeError('Private owner identity differs; active client preserved')
if args.background_manual_arm:state=wait_background_native_window(pid)
else:
with Session(pid) as session:state=session.state()
binding_path=ROOT/'runtime/engine-poll-binding.json';active_profile=None
if binding_path.exists():
binding=json.loads(binding_path.read_text())
if binding.get('pid')==pid and not binding.get('restored'):active_profile=binding.get('endpoint_profile')
print(json.dumps(dict(reused=True,client_pid=pid,state=state,requested_endpoint_profile=args.endpoint_profile,
active_endpoint_profile=active_profile,authentication_started=False,
elapsed_seconds=round(time.monotonic()-started,3))));return
if socket.exists():raise RuntimeError('Pending/stale owner socket preserved; inspect before retry')
if owner_file.exists() and (Path('/proc')/owner_file.read_text().strip()).exists():raise RuntimeError('Previous owner still alive; no duplicate launch')
if args.endpoint_profile=='local':wait_local_character_shutdown(character_guid=args.character_guid)
log=ROOT/'runtime'/('native-owner-'+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')+'.log')
with log.open('xb') as output:
child=subprocess.Popen([sys.executable,'-u',str(ROOT/'ops/debug_client_owner.py'),'serve-poll-host-realm-registration' if args.realm_registration_observer else 'serve-poll-host'],cwd=ROOT,stdout=output,stderr=output,start_new_session=True)
owner_file.write_text(str(child.pid)+'\n');(ROOT/'runtime/native-owner-current-log.txt').write_text(str(log)+'\n')
deadline=time.monotonic()+15
while 'owner ready' not in log.read_text(errors='replace'):
if child.poll() is not None:raise RuntimeError('Owner exited; inspect private startup log (not exported)')
if time.monotonic()>=deadline:raise RuntimeError('Owner readiness timed out; preserve child and journal')
time.sleep(.1)
state='login'
try:
if args.background_manual_arm:
state=wait_background_native_window(int(pid_file.read_text()))
else:
with Session(startup_pid=child.pid) as session:
deadline=time.monotonic()+25
while session.state()!='login':
if time.monotonic()>=deadline:raise RuntimeError('Login readiness timed out; client preserved')
time.sleep(.1)
except RuntimeError as error:
diagnostic=startup_graphics_failure(COPY/'_classic_beta_/Logs/gx.log',launched_at)
if diagnostic:raise RuntimeError(diagnostic+' Readiness error: '+str(error)) from error
raise
print(json.dumps(dict(reused=False,owner_pid=child.pid,client_pid=int(pid_file.read_text()),state=state,startup_seconds=round(time.monotonic()-started,3))))
if __name__=='__main__':main()