diff --git a/changelog.d/20261028-legacy-world-shutdown.md b/changelog.d/20261028-legacy-world-shutdown.md new file mode 100644 index 0000000..24a4ab2 --- /dev/null +++ b/changelog.d/20261028-legacy-world-shutdown.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Recovery can stop an unfinished world startup after restoring an older launcher +--- +If the world console is unavailable, stop only the verified recorded world process. Keep MySQL running if ownership or shutdown cannot be confirmed. diff --git a/crates/coa-core/src/launcher_bridge.py b/crates/coa-core/src/launcher_bridge.py index 76ff2aa..e5bdadf 100644 --- a/crates/coa-core/src/launcher_bridge.py +++ b/crates/coa-core/src/launcher_bridge.py @@ -15,6 +15,34 @@ def wait_ready(name, port, seconds=180): launcher["start_mysql"].__globals__["wait_ready"] = wait_ready if sys.argv[1] == "stop-all": + shutdown = launcher["stop_all"].__globals__ + if "ra" in shutdown: + original_ra = shutdown["ra"] + + class UnsafeShutdown(Exception): + pass + + def shutdown_command(command, config): + try: + return original_ra(command, config) + except (OSError, RuntimeError): + if not command.startswith("server shutdown "): + raise + world = shutdown["process"]("world") + if not world: + return "Worldserver has already stopped." + expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe" + if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world): + raise UnsafeShutdown("World process ownership could not be verified; the database was left running.") + try: + shutdown["terminate"](world) + except (OSError, RuntimeError) as error: + raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error + if not shutdown["wait_stopped"](world, 90): + raise UnsafeShutdown("Worldserver is still stopping; its database was left running.") + return "Stopped this server's recorded world process without its unavailable console." + + shutdown["ra"] = shutdown_command config = launcher["settings"]() with launcher["control_lock"](): launcher["stop_all"](config) diff --git a/src/data/latest-note-translations.json b/src/data/latest-note-translations.json index 2beabac..e2b2394 100644 --- a/src/data/latest-note-translations.json +++ b/src/data/latest-note-translations.json @@ -4,31 +4,36 @@ "Existing unsupported character records no longer block unrelated server updates": "Старые неподдерживаемые записи персонажей больше не блокируют несвязанные обновления сервера", "New server installation waits for slower database startup": "Установка нового сервера дольше ожидает запуска базы на медленных дисках", "Find and edit CoA options in the existing server settings": "Параметры CoA доступны для поиска и редактирования в настройках сервера", - "Simultaneous update checks share results or wait their turn": "Одновременные проверки обновлений используют общий результат или ожидают своей очереди" + "Simultaneous update checks share results or wait their turn": "Одновременные проверки обновлений используют общий результат или ожидают своей очереди", + "Recovery can stop an unfinished world startup after restoring an older launcher": "Восстановление может остановить зависший запуск мира после возврата старого launcher" }, "de": { "Existing unsupported character records no longer block unrelated server updates": "Bestehende nicht unterstützte Charakterdatensätze blockieren keine unabhängigen Serverupdates mehr", "New server installation waits for slower database startup": "Die Neuinstallation wartet länger auf einen langsamen Datenbankstart", "Find and edit CoA options in the existing server settings": "CoA-Optionen in den bestehenden Servereinstellungen suchen und bearbeiten", - "Simultaneous update checks share results or wait their turn": "Gleichzeitige Updateprüfungen teilen Ergebnisse oder warten aufeinander" + "Simultaneous update checks share results or wait their turn": "Gleichzeitige Updateprüfungen teilen Ergebnisse oder warten aufeinander", + "Recovery can stop an unfinished world startup after restoring an older launcher": "Die Wiederherstellung stoppt einen unvollständigen Weltstart auch mit altem Launcher" }, "fr": { "Existing unsupported character records no longer block unrelated server updates": "Les anciennes fiches de personnage non prises en charge ne bloquent plus les mises à jour sans rapport", "New server installation waits for slower database startup": "L’installation attend le démarrage de la base sur les disques plus lents", "Find and edit CoA options in the existing server settings": "Recherchez et modifiez les options CoA dans les paramètres du serveur", - "Simultaneous update checks share results or wait their turn": "Les vérifications simultanées partagent leurs résultats ou attendent leur tour" + "Simultaneous update checks share results or wait their turn": "Les vérifications simultanées partagent leurs résultats ou attendent leur tour", + "Recovery can stop an unfinished world startup after restoring an older launcher": "La restauration peut arrêter un démarrage du monde inachevé avec un ancien lanceur" }, "es": { "Existing unsupported character records no longer block unrelated server updates": "Los registros antiguos de personajes no compatibles ya no bloquean actualizaciones del servidor no relacionadas", "New server installation waits for slower database startup": "La instalación espera más tiempo al inicio de la base de datos en discos lentos", "Find and edit CoA options in the existing server settings": "Busca y edita opciones de CoA en la configuración actual del servidor", - "Simultaneous update checks share results or wait their turn": "Las comprobaciones simultáneas comparten resultados o esperan su turno" + "Simultaneous update checks share results or wait their turn": "Las comprobaciones simultáneas comparten resultados o esperan su turno", + "Recovery can stop an unfinished world startup after restoring an older launcher": "La recuperación puede detener el inicio del mundo tras restaurar un lanzador antiguo" }, "zh": { "Existing unsupported character records no longer block unrelated server updates": "已有的不受支持角色记录不再阻止无关的服务器更新", "New server installation waits for slower database startup": "安装新服务器时会等待较慢的数据库启动", "Find and edit CoA options in the existing server settings": "在现有服务器设置中查找和编辑 CoA 选项", - "Simultaneous update checks share results or wait their turn": "同时进行的更新检查会共用结果或依次执行" + "Simultaneous update checks share results or wait their turn": "同时进行的更新检查会共用结果或依次执行", + "Recovery can stop an unfinished world startup after restoring an older launcher": "恢复旧版启动器后,恢复流程也能停止未完成启动的世界服务器" } }, "server": {} diff --git a/tools/test_launcher_bridge.py b/tools/test_launcher_bridge.py index de79737..e48b1be 100644 --- a/tools/test_launcher_bridge.py +++ b/tools/test_launcher_bridge.py @@ -1,4 +1,3 @@ -import contextlib import pathlib import runpy import sys @@ -12,10 +11,83 @@ BRIDGE = pathlib.Path(__file__).resolve().parents[1] / 'crates/coa-core/src/laun class LauncherBridgeTests(unittest.TestCase): def launch(self, action, body): with tempfile.TemporaryDirectory() as directory: - script = pathlib.Path(directory) / 'manage.py' + script = pathlib.Path(directory) / 'Scripts/manage.py' + script.parent.mkdir() script.write_text(body, encoding='utf8') - with patch.object(sys, 'argv', ['bridge', str(script), action]): - return runpy.run_path(str(BRIDGE)) + original = runpy.run_path + def capture(*args, **kwargs): + self.launcher = original(*args, **kwargs) + return self.launcher + with patch.object(sys, 'argv', ['bridge', str(script), action]), patch.object(runpy, 'run_path', side_effect=capture): + return original(str(BRIDGE)) + + def shutdown_fixture(self, *, console_error='RuntimeError', stopped=True, foreign=False, same=True, modern=False, terminate_error=False): + return f''' +from pathlib import Path +from contextlib import nullcontext +calls = [] +world = {{'pid': 123, 'created': 456, 'exe': str(Path(__file__).resolve().parents[1] / {'"foreign.exe"' if foreign else '"Core/worldserver.exe"'})}} +def wait_ready(*args): pass +def start_mysql(): raise AssertionError('must not start') +def main(): raise AssertionError('must not prepare') +def settings(): return {{}} +def control_lock(): return nullcontext() +def process(name): return world if name == 'world' else None +def same_process(record): return {same!r} +def ra(command, config): + calls.append('console') + {'raise '+console_error+'("Start this repack worldserver first")' if console_error else 'return "Graceful shutdown"'} +def terminate(record): + assert record is world + calls.append('terminate') + {'raise RuntimeError("identity changed")' if terminate_error else 'pass'} +def wait_stopped(record, seconds): + assert record is world + calls.append('wait') + return {stopped!r} +def stop_all(config): + record = process('world') + if record: + if {modern!r}: + try: ra('server shutdown 1s 0', config) + except (OSError, RuntimeError): terminate(record) + else: + ra('server shutdown 1s 0', config) + if not wait_stopped(record, 60): raise RuntimeError('world still alive') + calls.append('mysql-shutdown') +''' + + def test_unavailable_console_in_restored_legacy_launcher_stops_owned_world_before_mysql(self): + for error in ['RuntimeError', 'OSError']: + with self.subTest(error=error): + result = self.launch('stop-all', self.shutdown_fixture(console_error=error)) + self.assertEqual(result['launcher']['calls'], ['console', 'terminate', 'wait', 'wait', 'mysql-shutdown']) + + def test_healthy_console_keeps_graceful_shutdown(self): + result = self.launch('stop-all', self.shutdown_fixture(console_error=None)) + self.assertEqual(result['launcher']['calls'], ['console', 'wait', 'mysql-shutdown']) + + def test_foreign_or_reused_process_is_never_terminated_even_by_a_modern_launcher_catch(self): + for modern in [False, True]: + for identity in [{'foreign': True}, {'same': False}]: + with self.subTest(modern=modern, **identity): + with self.assertRaisesRegex(Exception, 'ownership could not be verified'): + self.launch('stop-all', self.shutdown_fixture(modern=modern, **identity)) + self.assertEqual(self.launcher['calls'], ['console']) + + def test_world_that_stays_alive_blocks_database_shutdown(self): + for modern in [False, True]: + with self.subTest(modern=modern): + with self.assertRaisesRegex(Exception, 'database was left running'): + self.launch('stop-all', self.shutdown_fixture(stopped=False, modern=modern)) + self.assertEqual(self.launcher['calls'], ['console', 'terminate', 'wait']) + + def test_termination_identity_failure_leaves_mysql_untouched(self): + for modern in [False, True]: + with self.subTest(modern=modern): + with self.assertRaisesRegex(Exception, 'could not be stopped safely'): + self.launch('stop-all', self.shutdown_fixture(terminate_error=True, modern=modern)) + self.assertEqual(self.launcher['calls'], ['console', 'terminate']) def test_slow_mysql_gets_time_to_finish_but_other_waits_are_unchanged(self): result = self.launch('start-mysql', '''