mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 19:25:56 +00:00
Manager starts and stops servers through the Rust launcher
driver::run now calls coa-core::launcher::ops::run in-process instead of running Scripts/manage.py through launcher_bridge.py. Failures carry a typed code (Error::Service) instead of being guessed from stderr text. Moved into the launcher: realm profiles (realm id, name and databases from Settings/realm-profile.json), extra worlds sharing the main database, the shared world startup deadline and console readiness check, the owned-world check on shutdown, force-stop-all, and an environment block without AC_REALM_SERVER_PORT for update validation. The world supervisor is Scripts/coa-launcher.exe when the repack ships it, otherwise manage.py watch-world. Extra worlds get an unmodified manage.py. The realm patch of manage.py stays for the repack's own .bat files. Verified with examples/manager_launcher_e2e on a disposable repack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1211de5a77
commit
a822bfc99b
15 files changed
+545
-446
No files matched your search
@@ -0,0 +1,141 @@
|
||||
//! The Manager's start/stop (`driver`) on the Rust launcher, on a DISPOSABLE repack:
|
||||
//!
|
||||
//! 1. driver start-all: every service runs, the console answers, manage.py is not touched and sees the services;
|
||||
//! 2. driver stop-all stops everything;
|
||||
//! 3. manage.py start-all, then driver stop-all stops what Python started;
|
||||
//! 4. a taken world port fails with the typed "port in use" code (no stderr parsing), then stop-all;
|
||||
//! 5. driver start-all, then the forced stop;
|
||||
//! 6. with a realm profile: the realm row gets the profile's name, the .bat launcher is adapted as before;
|
||||
//! 7. nothing of the repack is left running.
|
||||
//!
|
||||
//! usage: manager_launcher_e2e <existing folder ending in -fixture>
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Instant;
|
||||
|
||||
use coa_core::driver::{self, Verb};
|
||||
use coa_core::error::ErrorCode;
|
||||
use coa_core::launcher::{services, settings::Settings, state};
|
||||
|
||||
fn indent(s: &str) -> String {
|
||||
s.lines().map(|l| format!(" {l}")).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
fn drive(root: &Path, verb: Verb) -> driver::DriverOutcome {
|
||||
let t = Instant::now();
|
||||
let out = driver::run(root, verb).expect("driver");
|
||||
println!("[driver {verb:?}] ok={} code={:?} in {:?}\n{}", out.ok, out.code, t.elapsed(), indent(&out.output));
|
||||
out
|
||||
}
|
||||
|
||||
fn manage(root: &Path, action: &str) -> (bool, String) {
|
||||
let python = root.join("Runtime/python/python.exe");
|
||||
let script = root.join("Scripts/manage.py").to_string_lossy().into_owned();
|
||||
let t = Instant::now();
|
||||
let out = Command::new(python).args(["-B", &script, action]).output().unwrap();
|
||||
let text = String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
|
||||
println!("[manage.py {action}] ok={} in {:?}\n{}", out.status.success(), t.elapsed(), indent(&text));
|
||||
(out.status.success(), text)
|
||||
}
|
||||
|
||||
fn python_status(root: &Path) -> serde_json::Value {
|
||||
let (ok, out) = manage(root, "status-json");
|
||||
assert!(ok);
|
||||
let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).expect("a JSON status line");
|
||||
serde_json::from_str(line).unwrap()
|
||||
}
|
||||
|
||||
fn all(v: &serde_json::Value, running: bool) -> bool {
|
||||
["mysql", "auth", "world", "relay"].iter().all(|k| v[*k] == running)
|
||||
}
|
||||
|
||||
fn nothing_running(root: &Path) -> bool {
|
||||
["mysql", "auth", "world", "supervisor", "relay"].iter().all(|n| state::running(root, n).is_none())
|
||||
&& ["mysql/bin/mysqld.exe", "Core/authserver.exe", "Core/worldserver.exe"]
|
||||
.iter()
|
||||
.all(|exe| coa_core::process::find_by_exe(&root.join(exe)).is_empty())
|
||||
}
|
||||
|
||||
fn console(root: &Path) -> String {
|
||||
let cfg = Settings::load(root, 0).unwrap();
|
||||
let mut ra = coa_core::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).unwrap();
|
||||
ra.run("server info").unwrap()
|
||||
}
|
||||
|
||||
fn realm_name(root: &Path) -> String {
|
||||
services::mysql(root, Some("SELECT name FROM acore_auth.realmlist WHERE id=1;"), None).unwrap()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||
let root = Path::new(&a[0]);
|
||||
assert!(a[0].ends_with("-fixture"), "a folder ending in -fixture is required");
|
||||
assert!(nothing_running(root), "the fixture must be stopped before the test");
|
||||
let manage_py = root.join("Scripts/manage.py");
|
||||
let original = std::fs::read(&manage_py).unwrap();
|
||||
let profile = root.join("Settings/realm-profile.json");
|
||||
assert!(!profile.exists(), "the fixture starts without a realm profile");
|
||||
|
||||
// 1
|
||||
let started = drive(root, Verb::StartAll);
|
||||
assert!(started.ok, "start-all");
|
||||
assert!(all(&python_status(root), true), "manage.py sees what the Manager started");
|
||||
let info = console(root);
|
||||
println!("[console] {}", info.lines().next().unwrap_or(""));
|
||||
assert_eq!(std::fs::read(&manage_py).unwrap(), original, "manage.py is not rewritten");
|
||||
assert_eq!(realm_name(root), "AzerothCore", "no profile: the launcher's own realm name");
|
||||
|
||||
// 2
|
||||
assert!(drive(root, Verb::StopAll).ok, "stop-all");
|
||||
assert!(nothing_running(root), "1-2 left something running");
|
||||
|
||||
// 3
|
||||
assert!(manage(root, "start-all").0);
|
||||
assert!(drive(root, Verb::StopAll).ok, "driver stops what manage.py started");
|
||||
assert!(nothing_running(root), "3 left something running");
|
||||
|
||||
// 4
|
||||
let cfg = Settings::load(root, 0).unwrap();
|
||||
let blocker = std::net::TcpListener::bind(("127.0.0.1", cfg.world_port)).unwrap();
|
||||
let refused = drive(root, Verb::StartAll);
|
||||
assert!(!refused.ok);
|
||||
assert_eq!(refused.code, Some(ErrorCode::PortInUse), "typed port error");
|
||||
assert!(refused.output.contains(&format!("Port {}", cfg.world_port)));
|
||||
drop(blocker);
|
||||
assert!(drive(root, Verb::StopAll).ok);
|
||||
assert!(nothing_running(root), "4 left something running");
|
||||
|
||||
// 5
|
||||
assert!(drive(root, Verb::StartAll).ok);
|
||||
let t = Instant::now();
|
||||
let forced = driver::force_stop(root).expect("force stop");
|
||||
println!("[driver force_stop] ok={} in {:?}\n{}", forced.ok, t.elapsed(), indent(&forced.output));
|
||||
assert!(forced.ok && forced.output.contains("Force-stopped"));
|
||||
assert!(nothing_running(root), "5 left something running");
|
||||
|
||||
// 6
|
||||
std::fs::write(&profile, br#"{"active":"coa","wildcard_created":false}"#).unwrap();
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
assert!(drive(root, Verb::StartAll).ok, "start-all with a realm profile");
|
||||
assert_eq!(realm_name(root), "Conquest of Azeroth");
|
||||
let patched = std::fs::read_to_string(&manage_py).unwrap();
|
||||
assert!(patched.contains("# coa-manager-realm-profiles-v2"), "the .bat launcher still follows the realm");
|
||||
let fix = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
|
||||
assert_eq!(
|
||||
patched.matches(fix).count(),
|
||||
String::from_utf8_lossy(&original).matches(fix).count(),
|
||||
"no bridge import fix added"
|
||||
);
|
||||
assert!(drive(root, Verb::StopAll).ok);
|
||||
});
|
||||
std::fs::remove_file(&profile).unwrap();
|
||||
std::fs::write(&manage_py, &original).unwrap();
|
||||
if result.is_err() {
|
||||
let _ = driver::run(root, Verb::StopAll);
|
||||
panic!("step 6 failed");
|
||||
}
|
||||
|
||||
// 7
|
||||
assert!(nothing_running(root), "something of the repack is still running");
|
||||
println!("PASS: the Manager starts and stops through the Rust launcher, interoperates with manage.py, typed errors");
|
||||
}
|
||||
+56
-247
@@ -1,11 +1,10 @@
|
||||
//! Start/stop of a repack-shaped installation by delegating to the repack's own supervisor
|
||||
//! (`Runtime\python\python.exe Scripts\manage.py <verb>`), which already implements config rendering, the
|
||||
//! bug-report relay, RA graceful shutdown and readiness. Observation stays native (see `process`).
|
||||
//! Start/stop of a repack-shaped installation through the repack launcher in this crate
|
||||
//! ([`crate::launcher`]): config rendering, the services, the world supervisor, graceful shutdown and readiness.
|
||||
//! It writes the same `.state` records as the repack's `Scripts/manage.py`, so the server's own `.bat` files and
|
||||
//! this Manager can be used on the same folder. Observation stays native (see `process`).
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -22,22 +21,13 @@ pub enum Verb {
|
||||
}
|
||||
|
||||
impl Verb {
|
||||
fn arg(self) -> &'static str {
|
||||
fn action(self) -> crate::launcher::ops::Action {
|
||||
use crate::launcher::ops::Action;
|
||||
match self {
|
||||
Verb::StartAll => "start-all",
|
||||
Verb::StartMysql => "start-mysql",
|
||||
Verb::StartWorld => "start-world",
|
||||
Verb::StopAll => "stop-all",
|
||||
}
|
||||
}
|
||||
|
||||
fn timeout(self, _root: &Path) -> Duration {
|
||||
match self {
|
||||
// Includes database startup, optional bot provisioning and the shared 25-minute
|
||||
// world/console wait in launcher_bridge.py, even for older installed scripts.
|
||||
Verb::StartAll | Verb::StartWorld => Duration::from_secs(3600),
|
||||
Verb::StartMysql => Duration::from_secs(360),
|
||||
Verb::StopAll => Duration::from_secs(240),
|
||||
Verb::StartAll => Action::StartAll,
|
||||
Verb::StartMysql => Action::StartMysql,
|
||||
Verb::StartWorld => Action::StartWorld,
|
||||
Verb::StopAll => Action::StopAll,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,41 +42,14 @@ pub struct DriverOutcome {
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
/// Map the launcher's own messages onto stable error codes. Unknown text stays `Unknown` (details remain visible).
|
||||
pub fn translate(output: &str) -> ErrorCode {
|
||||
let o = output.to_lowercase();
|
||||
if o.contains("is already used") {
|
||||
ErrorCode::PortInUse
|
||||
} else if o.contains("another start/stop action is in progress")
|
||||
|| o.contains("shutdown is still finishing")
|
||||
{
|
||||
ErrorCode::OperationInProgress
|
||||
} else if o.contains("packaged database is missing")
|
||||
|| o.contains("extract the complete repack")
|
||||
{
|
||||
ErrorCode::ServerFilesIncomplete
|
||||
} else if o.contains("stopped during startup")
|
||||
|| o.contains("is still starting")
|
||||
|| o.contains("world startup failed")
|
||||
{
|
||||
ErrorCode::StartupFailed
|
||||
} else if o.contains("invalid port") || o.contains("unresolved placeholder") {
|
||||
ErrorCode::InvalidConfigValue
|
||||
} else {
|
||||
ErrorCode::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
fn launcher(root: &Path) -> Result<(PathBuf, PathBuf)> {
|
||||
let python = root.join("Runtime/python/python.exe");
|
||||
let script = root.join("Scripts/manage.py");
|
||||
if !python.is_file() || !script.is_file() {
|
||||
fn has_launcher_settings(root: &Path) -> Result<()> {
|
||||
if !root.join("Settings/repack.json").is_file() {
|
||||
return Err(Error::Invalid(
|
||||
"This server has no CoA Repack launcher; start/stop is not available for it yet."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
Ok((python, script))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a launcher verb to completion (blocking; call from a worker thread).
|
||||
@@ -205,108 +168,51 @@ fn run_inner_mode(
|
||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
crate::modules::ensure_bot_exclusivity(&root)?;
|
||||
}
|
||||
let (python, script) = launcher(&root)?;
|
||||
has_launcher_settings(&root)?;
|
||||
prepare_headless_world(&root, verb)?;
|
||||
let original = std::fs::read_to_string(&script)?;
|
||||
let patched = patch_launcher_imports(&original)?;
|
||||
if original != patched {
|
||||
fsx::atomic_write(&script, patched.as_bytes())?;
|
||||
if let Ok(dir) = crate::registry::metadata_dir_for(&root) {
|
||||
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
|
||||
if meta.original_hashes.get("Scripts/manage.py")
|
||||
== Some(&fsx::sha256_bytes(original.as_bytes()))
|
||||
{
|
||||
meta.original_hashes.insert(
|
||||
"Scripts/manage.py".into(),
|
||||
fsx::sha256_bytes(patched.as_bytes()),
|
||||
);
|
||||
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
discard_damaged_launcher_state(&root);
|
||||
if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) {
|
||||
recover_mysql_launcher_state(&root, verb != Verb::StopAll)?;
|
||||
}
|
||||
if force {
|
||||
recover_world_for_forced_stop(&root)?;
|
||||
}
|
||||
let mut cmd = Command::new(&python);
|
||||
if validating_update {
|
||||
// Isolated startup must use the port from its temporary auth config.
|
||||
cmd.env_remove("AC_REALM_SERVER_PORT");
|
||||
}
|
||||
cmd.arg("-B")
|
||||
.arg("-c")
|
||||
.arg(LAUNCH_SCRIPT)
|
||||
.arg(&script)
|
||||
.arg(if force { "force-stop-all" } else { verb.arg() })
|
||||
.current_dir(&root)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
tracing::info!(?verb, root = %root.display(), "driver: starting launcher verb");
|
||||
let mut child = cmd.spawn()?;
|
||||
let mut stdout = child.stdout.take().expect("piped");
|
||||
let mut stderr = child.stderr.take().expect("piped");
|
||||
let out_t = std::thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
let _ = stdout.read_to_string(&mut s);
|
||||
s
|
||||
});
|
||||
let err_t = std::thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
let _ = stderr.read_to_string(&mut s);
|
||||
s
|
||||
});
|
||||
let deadline = Instant::now() + verb.timeout(&root);
|
||||
let status = loop {
|
||||
if let Some(st) = child.try_wait()? {
|
||||
break Some(st);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
// Never kill the servers themselves: only abandon the launcher process we spawned.
|
||||
let _ = child.kill();
|
||||
break None;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
};
|
||||
let mut output = out_t.join().unwrap_or_default();
|
||||
output.push_str(&err_t.join().unwrap_or_default());
|
||||
let mut output = output.trim().to_string();
|
||||
if status.is_none() {
|
||||
output.push_str(&format!(
|
||||
"\nLauncher {} exceeded its {} second deadline; check the server logs.",
|
||||
verb.arg(),
|
||||
verb.timeout(&root).as_secs()
|
||||
));
|
||||
}
|
||||
let (ok, exit_code) = match status {
|
||||
Some(st) => (st.success(), st.code()),
|
||||
None => (false, None),
|
||||
};
|
||||
let code = if ok {
|
||||
None
|
||||
let action = if force {
|
||||
crate::launcher::ops::Action::ForceStopAll
|
||||
} else {
|
||||
// Log evidence beats the launcher's generic "stopped during startup" message.
|
||||
let base = if status.is_none() {
|
||||
ErrorCode::StartupFailed
|
||||
} else {
|
||||
translate(&output)
|
||||
};
|
||||
match base {
|
||||
ErrorCode::StartupFailed | ErrorCode::Unknown => {
|
||||
Some(crate::health::diagnose_installation(&root).unwrap_or(base))
|
||||
verb.action()
|
||||
};
|
||||
tracing::info!(?verb, root = %root.display(), "driver: starting launcher action");
|
||||
let lines = Mutex::new(Vec::<String>::new());
|
||||
let progress = |line: &str| {
|
||||
tracing::info!(?verb, "launcher: {line}");
|
||||
lines.lock().unwrap_or_else(|e| e.into_inner()).push(line.to_string());
|
||||
};
|
||||
let result = crate::launcher::Settings::load(&root, 0).and_then(|mut cfg| {
|
||||
if validating_update {
|
||||
// Isolated startup must use the port from its temporary auth config.
|
||||
cfg.env_remove.push("AC_REALM_SERVER_PORT".into());
|
||||
}
|
||||
crate::launcher::ops::run(&root, &cfg, 0, action, None, &progress)
|
||||
});
|
||||
let mut output = lines.into_inner().unwrap_or_else(|e| e.into_inner()).join("\n");
|
||||
let ok = result.is_ok();
|
||||
let code = match &result {
|
||||
Ok(()) => None,
|
||||
Err(error) => {
|
||||
if !output.is_empty() {
|
||||
output.push('\n');
|
||||
}
|
||||
output.push_str(&format!("ERROR: {error}"));
|
||||
// Log evidence beats a generic "stopped during startup".
|
||||
match error.code() {
|
||||
ErrorCode::StartupFailed | ErrorCode::Unknown => Some(
|
||||
crate::health::diagnose_installation(&root).unwrap_or(error.code()),
|
||||
),
|
||||
other => Some(other),
|
||||
}
|
||||
other => Some(other),
|
||||
}
|
||||
};
|
||||
let exit_code = Some(if ok { 0 } else { 1 });
|
||||
if code == Some(ErrorCode::PortInUse) {
|
||||
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
|
||||
for service in [&observed.mysql, &observed.auth, &observed.world]
|
||||
@@ -374,35 +280,6 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The launcher keeps one JSON record per service in `.state`. A crash or power loss while it writes one can leave
|
||||
/// a file of the right length that holds only zero bytes (NTFS keeps the length but not the data), and the launcher
|
||||
/// then dies on every start with an unreadable record. Such a file carries no information, so remove it: the
|
||||
/// launcher treats a missing record as "not running". Only empty or all-zero `*.json` files are touched.
|
||||
pub(crate) fn discard_damaged_launcher_state(root: &Path) -> Vec<PathBuf> {
|
||||
let mut removed = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(root.join(".state")) else {
|
||||
return removed;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path
|
||||
.extension()
|
||||
.is_none_or(|e| !e.eq_ignore_ascii_case("json"))
|
||||
|| !path.is_file()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(&path) else {
|
||||
continue;
|
||||
};
|
||||
if bytes.iter().all(|b| *b == 0) && std::fs::remove_file(&path).is_ok() {
|
||||
tracing::warn!(file = %path.display(), bytes = bytes.len(), "driver: removed a launcher state file damaged by an interrupted write");
|
||||
removed.push(path);
|
||||
}
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
/// A lost launcher record must not hide this installation's running MySQL from
|
||||
/// graceful shutdown. Adopt only the exact executable owning its configured port.
|
||||
fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()> {
|
||||
@@ -453,8 +330,8 @@ fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const LAUNCH_SCRIPT: &str = include_str!("launcher_bridge.py");
|
||||
|
||||
/// The import fix older Managers wrote into `Scripts/manage.py` (needed only to run it through their bridge). It
|
||||
/// is no longer applied; it stays so that file checks still recognise a file it changed.
|
||||
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
|
||||
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
|
||||
if !text.contains("from squid_playerbots import") || text.contains(line) {
|
||||
@@ -608,7 +485,7 @@ mod tests {
|
||||
text.contains("launcher request failed before completion")
|
||||
&& text.contains("in progress")
|
||||
);
|
||||
assert!(!text.contains("starting launcher verb"));
|
||||
assert!(!text.contains("starting launcher action"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -665,78 +542,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slow_world_startup_has_time_with_either_bot_system_without_extending_shutdown() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let modules = folder.path().join("Core/configs/modules");
|
||||
std::fs::create_dir_all(&modules).unwrap();
|
||||
std::fs::write(
|
||||
modules.join("playerbots.conf.dist"),
|
||||
"AiPlayerbot.Enabled = 1\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
Verb::StartAll.timeout(folder.path()),
|
||||
Duration::from_secs(3600)
|
||||
);
|
||||
assert_eq!(
|
||||
Verb::StopAll.timeout(folder.path()),
|
||||
Duration::from_secs(240)
|
||||
);
|
||||
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
|
||||
assert_eq!(
|
||||
Verb::StartWorld.timeout(folder.path()),
|
||||
Duration::from_secs(3600)
|
||||
);
|
||||
assert_eq!(
|
||||
Verb::StartMysql.timeout(folder.path()),
|
||||
Duration::from_secs(360)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_filled_launcher_state_is_discarded_and_valid_state_is_kept() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let state = folder.path().join(".state");
|
||||
std::fs::create_dir_all(&state).unwrap();
|
||||
std::fs::write(state.join("mysql.json"), vec![0u8; 116]).unwrap();
|
||||
std::fs::write(state.join("configuration.json"), Vec::<u8>::new()).unwrap();
|
||||
std::fs::write(state.join("world.json"), "{\"pid\": 4}\n").unwrap();
|
||||
std::fs::write(state.join("stop-relay"), Vec::<u8>::new()).unwrap();
|
||||
std::fs::write(state.join("auth.json"), "{\"pid\": 0}").unwrap();
|
||||
let mut removed: Vec<_> = discard_damaged_launcher_state(folder.path())
|
||||
.iter()
|
||||
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
removed.sort();
|
||||
assert_eq!(removed, ["configuration.json", "mysql.json"]);
|
||||
assert!(
|
||||
state.join("world.json").exists()
|
||||
&& state.join("auth.json").exists()
|
||||
&& state.join("stop-relay").exists()
|
||||
);
|
||||
assert!(discard_damaged_launcher_state(folder.path()).is_empty());
|
||||
assert!(discard_damaged_launcher_state(&folder.path().join("missing")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_known_launcher_messages() {
|
||||
assert_eq!(
|
||||
translate("RuntimeError: Port 8085 is already used. Stop the other server"),
|
||||
ErrorCode::PortInUse
|
||||
);
|
||||
assert_eq!(
|
||||
translate("Another start/stop action is in progress."),
|
||||
ErrorCode::OperationInProgress
|
||||
);
|
||||
assert_eq!(
|
||||
translate("The packaged database is missing. Extract the complete repack."),
|
||||
ErrorCode::ServerFilesIncomplete
|
||||
);
|
||||
assert_eq!(
|
||||
translate("world stopped during startup. Check its log."),
|
||||
ErrorCode::StartupFailed
|
||||
);
|
||||
assert_eq!(translate("Exit code -1073741819"), ErrorCode::Unknown);
|
||||
fn launcher_failures_carry_their_error_code() {
|
||||
let e = Error::Service(ErrorCode::PortInUse, "Port 8085 is already used (PID 4).".into());
|
||||
assert_eq!(e.code(), ErrorCode::PortInUse);
|
||||
assert_eq!(e.to_string(), "Port 8085 is already used (PID 4).");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -24,6 +24,9 @@ pub enum Error {
|
||||
UnknownInstallation(String),
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
/// A server start or stop failed for a reason the UI can explain (the repack launcher's own errors).
|
||||
#[error("{1}")]
|
||||
Service(ErrorCode, String),
|
||||
#[error("package not published: {0}")]
|
||||
PackageNotPublished(String),
|
||||
#[error("download server unreachable: {0}")]
|
||||
@@ -199,6 +202,7 @@ impl Error {
|
||||
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
|
||||
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
|
||||
Error::BotModulesConflict => ErrorCode::BotModulesConflict,
|
||||
Error::Service(code, _) => *code,
|
||||
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
|
||||
Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported,
|
||||
_ => ErrorCode::Unknown,
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
//! State files are written with a flush to disk before they replace the old ones (`manage.py` did not, and a
|
||||
//! power cut could leave a zero-filled record that stopped every later start).
|
||||
|
||||
pub mod ops;
|
||||
pub mod render;
|
||||
pub mod services;
|
||||
pub mod settings;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! One start/stop action of a repack, with the control lock held (`manage.py main()`): the entry point of both
|
||||
//! `coa-launcher.exe` and the Manager.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::launcher::services::{self, Progress};
|
||||
use crate::launcher::world::{self, Supervisor};
|
||||
use crate::launcher::{render, settings::Settings, squid, state};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Action {
|
||||
StartAll,
|
||||
StartMysql,
|
||||
StartAuth,
|
||||
StartWorld,
|
||||
StopAll,
|
||||
/// Stop the world without its console first (unsaved progress is lost), then everything else.
|
||||
ForceStopAll,
|
||||
Prepare,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
/// The command name, as the `.bat` files and `manage.py` call it.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Action::StartAll => "start-all",
|
||||
Action::StartMysql => "start-mysql",
|
||||
Action::StartAuth => "start-auth",
|
||||
Action::StartWorld => "start-world",
|
||||
Action::StopAll => "stop-all",
|
||||
Action::ForceStopAll => "force-stop-all",
|
||||
Action::Prepare => "prepare",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(name: &str) -> Option<Action> {
|
||||
[
|
||||
Action::StartAll,
|
||||
Action::StartMysql,
|
||||
Action::StartAuth,
|
||||
Action::StartWorld,
|
||||
Action::StopAll,
|
||||
Action::ForceStopAll,
|
||||
Action::Prepare,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|a| a.name() == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `action`. A started world is supervised by `supervisor`, or by what the repack ships when it is `None`.
|
||||
pub fn run(root: &Path, cfg: &Settings, offset: i32, action: Action, supervisor: Option<&Supervisor>, progress: Progress) -> Result<()> {
|
||||
let _lock = state::ControlLock::acquire(root, action.name(), Duration::from_secs(30), progress)?;
|
||||
match action {
|
||||
// Shutdown uses the existing client and console settings: the templates may be exactly what a recovery
|
||||
// needs to replace, so nothing is rendered.
|
||||
Action::StopAll => return services::stop_all(root, cfg, progress),
|
||||
Action::ForceStopAll => return services::force_stop_all(root, cfg, progress),
|
||||
_ => {}
|
||||
}
|
||||
if matches!(action, Action::StartAll | Action::StartWorld) {
|
||||
squid::validate_bots(root)?;
|
||||
}
|
||||
render::prepare(root, cfg)?;
|
||||
if action == Action::Prepare {
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(action, Action::StartAll | Action::StartMysql) {
|
||||
services::start_mysql(root, cfg, progress)?;
|
||||
}
|
||||
if matches!(action, Action::StartAll | Action::StartAuth) {
|
||||
services::start_auth(root, cfg, progress)?;
|
||||
}
|
||||
if matches!(action, Action::StartAll | Action::StartWorld) {
|
||||
let shipped;
|
||||
let supervisor = match supervisor {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
shipped = Supervisor::of(root)?;
|
||||
&shipped
|
||||
}
|
||||
};
|
||||
world::start_world(root, cfg, offset, supervisor, progress)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -106,7 +106,11 @@ pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
|
||||
("WORLD_PORT", config.world_port.to_string()),
|
||||
("RA_PORT", config.ra_port.to_string()),
|
||||
];
|
||||
for (key, db) in [("LoginDatabaseInfo", "acore_auth"), ("WorldDatabaseInfo", "acore_world"), ("CharacterDatabaseInfo", "acore_characters")] {
|
||||
for (key, db) in [
|
||||
("LoginDatabaseInfo", "acore_auth"),
|
||||
("WorldDatabaseInfo", config.realm.world_db),
|
||||
("CharacterDatabaseInfo", config.realm.characters_db),
|
||||
] {
|
||||
values.push((key, format!("127.0.0.1;{mysql_port};acore;{app_password};{db}")));
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
@@ -127,10 +131,10 @@ pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
|
||||
unresolved.sort();
|
||||
unresolved.dedup();
|
||||
if !unresolved.is_empty() {
|
||||
return Err(Error::Invalid(format!(
|
||||
"An unresolved placeholder remains in Settings/{name}.template: {}",
|
||||
unresolved.join(", ")
|
||||
)));
|
||||
return Err(Error::Service(
|
||||
crate::error::ErrorCode::InvalidConfigValue,
|
||||
format!("An unresolved placeholder remains in Settings/{name}.template: {}", unresolved.join(", ")),
|
||||
));
|
||||
}
|
||||
// these three keep "\n" (Python wrote them with newline="\n")
|
||||
std::fs::write(root.join(target), text.as_bytes())?;
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::error::{Error, ErrorCode, Result};
|
||||
use crate::launcher::{settings::Settings, state};
|
||||
use crate::process::ProcessIdentity;
|
||||
|
||||
@@ -24,9 +24,10 @@ fn hidden(cmd: &mut Command) -> &mut Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Start `exe` with its output appended to `log`, and record it as `name`.
|
||||
pub fn spawn(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path) -> Result<ProcessIdentity> {
|
||||
let child = crate::launcher::spawn::start(exe, args, cwd, log)?;
|
||||
/// Start `exe` with its output appended to `log`, and record it as `name`. `env_remove` are variables of this
|
||||
/// process the service must not see.
|
||||
pub fn spawn(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path, env_remove: &[String]) -> Result<ProcessIdentity> {
|
||||
let child = crate::launcher::spawn::start(exe, args, cwd, log, env_remove)?;
|
||||
state::record(root, name, child.pid)
|
||||
}
|
||||
|
||||
@@ -50,10 +51,10 @@ pub fn ensure_free(port: u16, progress: Progress) -> Result<()> {
|
||||
owners.dedup();
|
||||
if owners.iter().any(|p| *p != 0) {
|
||||
let list: Vec<String> = owners.iter().map(u32::to_string).collect();
|
||||
return Err(Error::Invalid(format!(
|
||||
"Port {port} is already used (PID {}). Stop the other server or change Settings/repack.json.",
|
||||
list.join(", ")
|
||||
)));
|
||||
return Err(Error::Service(
|
||||
ErrorCode::PortInUse,
|
||||
format!("Port {port} is already used (PID {}). Stop the other server or change Settings/repack.json.", list.join(", ")),
|
||||
));
|
||||
}
|
||||
match sys::exclusive_bind(port) {
|
||||
Ok(()) => return Ok(()),
|
||||
@@ -111,13 +112,14 @@ pub fn wait_ready(root: &Path, name: &str, port: u16, seconds: u64) -> Result<()
|
||||
return Ok(());
|
||||
}
|
||||
if state::running(root, name).is_none() {
|
||||
return Err(Error::Invalid(format!("{name} stopped during startup. Check its log.")));
|
||||
return Err(Error::Service(ErrorCode::StartupFailed, format!("{name} stopped during startup. Check its log.")));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
Err(Error::Invalid(format!(
|
||||
"{name} is still starting: its expected TCP listener on port {port} was not found; check its log."
|
||||
)))
|
||||
Err(Error::Service(
|
||||
ErrorCode::StartupFailed,
|
||||
format!("{name} is still starting: its expected TCP listener on port {port} was not found; check its log."),
|
||||
))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
@@ -191,6 +193,12 @@ pub fn mysql(root: &Path, sql: Option<&str>, admin: Option<&str>) -> Result<Stri
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
pub fn start_mysql(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||
if cfg.shared_database {
|
||||
// An extra world uses the main folder's database; it must already run.
|
||||
return mysql(root, None, Some("ping")).map(|_| ()).map_err(|e| {
|
||||
Error::Service(ErrorCode::DatabaseNotRunning, format!("The main server's database is not running. {e}"))
|
||||
});
|
||||
}
|
||||
if state::running(root, "mysql").is_some() {
|
||||
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
|
||||
mysql(root, None, Some("ping"))?;
|
||||
@@ -199,18 +207,18 @@ pub fn start_mysql(root: &Path, cfg: &Settings, progress: Progress) -> Result<()
|
||||
}
|
||||
ensure_free(cfg.mysql_port, progress)?;
|
||||
if !root.join("mysql/data/mysql").is_dir() {
|
||||
return Err(Error::Invalid("The packaged database is missing. Extract the complete repack.".into()));
|
||||
return Err(Error::Service(ErrorCode::ServerFilesIncomplete, "The packaged database is missing. Extract the complete repack.".into()));
|
||||
}
|
||||
progress("Starting MySQL...");
|
||||
let ini = format!("--defaults-file={}", root.join("mysql/my.ini").display());
|
||||
spawn(root, "mysql", &root.join("mysql/bin/mysqld.exe"), &[&ini, "--no-monitor"], &root.join("mysql"), &root.join("mysql/logs/startup.log"))?;
|
||||
spawn(root, "mysql", &root.join("mysql/bin/mysqld.exe"), &[&ini, "--no-monitor"], &root.join("mysql"), &root.join("mysql/logs/startup.log"), &cfg.env_remove)?;
|
||||
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
|
||||
mysql(root, None, Some("ping"))?;
|
||||
mysql(
|
||||
root,
|
||||
Some(&format!(
|
||||
"UPDATE acore_auth.realmlist SET name='AzerothCore',address='127.0.0.1',localAddress='127.0.0.1',port={} WHERE id=1;",
|
||||
cfg.world_port
|
||||
"UPDATE acore_auth.realmlist SET name='{}',address='127.0.0.1',localAddress='127.0.0.1',port={} WHERE id={};",
|
||||
cfg.realm.name, cfg.world_port, cfg.realm.id
|
||||
)),
|
||||
None,
|
||||
)?;
|
||||
@@ -226,9 +234,9 @@ pub fn start_auth(root: &Path, cfg: &Settings, progress: Progress) -> Result<()>
|
||||
}
|
||||
ensure_free(cfg.auth_port, progress)?;
|
||||
// An interrupted world startup can leave flag 3, which authserver excludes.
|
||||
mysql(root, Some("UPDATE acore_auth.realmlist SET flag=0 WHERE id=1;"), None)?;
|
||||
mysql(root, Some(&format!("UPDATE acore_auth.realmlist SET flag=0 WHERE id={};", cfg.realm.id)), None)?;
|
||||
progress("Starting authserver...");
|
||||
spawn(root, "auth", &root.join("Core/authserver.exe"), &["-c", "configs/authserver.conf"], &root.join("Core"), &root.join("Core/Logs/auth-console.log"))?;
|
||||
spawn(root, "auth", &root.join("Core/authserver.exe"), &["-c", "configs/authserver.conf"], &root.join("Core"), &root.join("Core/Logs/auth-console.log"), &cfg.env_remove)?;
|
||||
wait_ready(root, "auth", cfg.auth_port, 60)
|
||||
}
|
||||
|
||||
@@ -248,9 +256,40 @@ pub fn wait_stopped(record: &ProcessIdentity, seconds: u64) -> bool {
|
||||
!crate::process::is_alive(record)
|
||||
}
|
||||
|
||||
/// Stop everything of this repack, world first (gracefully through its console), its database last.
|
||||
/// The recorded world, when it is this folder's own `Core/worldserver.exe` (never stop a process only because a
|
||||
/// record names it).
|
||||
fn owned_world(root: &Path) -> Result<Option<ProcessIdentity>> {
|
||||
let Some(world) = state::running(root, "world") else { return Ok(None) };
|
||||
let expected = root.join("Core/worldserver.exe");
|
||||
let same = std::fs::canonicalize(&world.exe).ok().zip(std::fs::canonicalize(&expected).ok()).is_some_and(|(a, b)| a == b);
|
||||
if !same {
|
||||
return Err(Error::Invalid("World process ownership could not be verified; the database was left running.".into()));
|
||||
}
|
||||
Ok(Some(world))
|
||||
}
|
||||
|
||||
/// Stop this folder's world without its console (unsaved progress since the last save is lost).
|
||||
fn stop_world_process(world: &ProcessIdentity) -> Result<()> {
|
||||
terminate(world).map_err(|_| Error::Invalid("Worldserver could not be stopped safely; its database was left running.".into()))?;
|
||||
if !wait_stopped(world, 90) {
|
||||
return Err(Error::Invalid("Worldserver is still stopping; its database was left running.".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop the world at once, then everything else as [`stop_all`] does. Only when the user asked for it.
|
||||
pub fn force_stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||
if let Some(world) = owned_world(root)? {
|
||||
stop_world_process(&world)?;
|
||||
progress("Force-stopped this server's verified world process; unsaved progress may be lost.");
|
||||
}
|
||||
stop_all(root, cfg, progress)
|
||||
}
|
||||
|
||||
/// Stop everything of this repack, world first (gracefully through its console), its database last. An extra
|
||||
/// world leaves the shared database alone.
|
||||
pub fn stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||
if let Some(world) = state::running(root, "world") {
|
||||
if let Some(world) = owned_world(root)? {
|
||||
let asked = ready(root, "world", cfg.ra_port)
|
||||
.then(|| crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password))
|
||||
.and_then(|r| r.ok())
|
||||
@@ -259,7 +298,7 @@ pub fn stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||
Some(Ok(())) => progress("Graceful world shutdown requested."),
|
||||
_ => {
|
||||
progress("World console unavailable; stopping this repack's recorded world process.");
|
||||
terminate(&world)?;
|
||||
stop_world_process(&world)?;
|
||||
}
|
||||
}
|
||||
if !wait_stopped(&world, 90) {
|
||||
@@ -283,7 +322,7 @@ pub fn stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||
return Err(Error::Invalid("Authserver did not stop.".into()));
|
||||
}
|
||||
}
|
||||
if let Some(database) = state::running(root, "mysql") {
|
||||
if let Some(database) = state::running(root, "mysql").filter(|_| !cfg.shared_database) {
|
||||
let shutdown = mysql(root, None, Some("shutdown"));
|
||||
if !wait_stopped(&database, 60) {
|
||||
shutdown?;
|
||||
|
||||
@@ -6,6 +6,40 @@ use crate::error::{Error, Result};
|
||||
|
||||
pub const PORT_KEYS: [&str; 4] = ["mysqlPort", "authPort", "worldPort", "raPort"];
|
||||
|
||||
/// The realm a folder runs: its row in `acore_auth.realmlist` and its two game databases.
|
||||
///
|
||||
/// Without `Settings/realm-profile.json` this is what the repack launcher always did (realm 1 "AzerothCore" on
|
||||
/// `acore_world`/`acore_characters`). With it, the active profile decides, as the Manager's realm patch of
|
||||
/// `manage.py` did.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Realm {
|
||||
pub id: u32,
|
||||
pub name: &'static str,
|
||||
pub world_db: &'static str,
|
||||
pub characters_db: &'static str,
|
||||
}
|
||||
|
||||
impl Realm {
|
||||
pub fn load(root: &Path) -> Result<Realm> {
|
||||
let path = root.join("Settings/realm-profile.json");
|
||||
if !path.exists() {
|
||||
return Ok(Realm { id: 1, name: "AzerothCore", world_db: "acore_world", characters_db: "acore_characters" });
|
||||
}
|
||||
let v: serde_json::Value = crate::fsx::read_json(&path)?;
|
||||
Ok(match v.get("active").and_then(|a| a.as_str()).unwrap_or("coa") {
|
||||
"wildcard" => Realm { id: 2, name: "Wildcard", world_db: "acore_world_wildcard", characters_db: "acore_characters_wildcard" },
|
||||
"reborn" => Realm { id: 3, name: "Warcraft Reborn", world_db: "acore_world_reborn", characters_db: "acore_characters_reborn" },
|
||||
_ => Realm { id: 1, name: "Conquest of Azeroth", world_db: "acore_world", characters_db: "acore_characters" },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An extra world of a server (`<server>/.realms/<name>`): it shares the main folder's database and never
|
||||
/// starts or stops it.
|
||||
pub fn is_extra_world(root: &Path) -> bool {
|
||||
root.parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".realms")
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Settings {
|
||||
pub mysql_port: u16,
|
||||
@@ -14,6 +48,12 @@ pub struct Settings {
|
||||
pub ra_port: u16,
|
||||
pub ra_username: String,
|
||||
pub ra_password: String,
|
||||
pub realm: Realm,
|
||||
/// The database belongs to the main folder of this server (an extra world): it is only checked, never
|
||||
/// started.
|
||||
pub shared_database: bool,
|
||||
/// Environment variables the started services must not see (for example a port override of the caller).
|
||||
pub env_remove: Vec<String>,
|
||||
/// The whole document, for keys this code does not know (kept when it is written back).
|
||||
pub raw: serde_json::Map<String, serde_json::Value>,
|
||||
}
|
||||
@@ -35,7 +75,7 @@ impl Settings {
|
||||
let shifted = value.map(|v| v + i64::from(offset));
|
||||
match shifted {
|
||||
Some(p) if p > 1024 && p < 65536 => ports[i] = p as u16,
|
||||
_ => return Err(Error::Invalid("Invalid port in Settings/repack.json".into())),
|
||||
_ => return Err(Error::Service(crate::error::ErrorCode::InvalidConfigValue, "Invalid port in Settings/repack.json".into())),
|
||||
}
|
||||
}
|
||||
let mut unique = ports.to_vec();
|
||||
@@ -52,6 +92,9 @@ impl Settings {
|
||||
ra_port: ports[3],
|
||||
ra_username: text_of("raUsername"),
|
||||
ra_password: text_of("raPassword"),
|
||||
realm: Realm::load(root)?,
|
||||
shared_database: is_extra_world(root),
|
||||
env_remove: Vec::new(),
|
||||
raw,
|
||||
})
|
||||
}
|
||||
@@ -108,4 +151,18 @@ mod tests {
|
||||
assert!(Settings::load(d.path(), 1).is_err(), "65536 after the offset");
|
||||
assert!(Settings::load(d.path(), 0).is_ok(), "a byte order mark is accepted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_realm_follows_the_active_profile() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
assert_eq!(Realm::load(d.path()).unwrap().name, "AzerothCore");
|
||||
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
|
||||
for (active, id, db) in [("coa", 1, "acore_world"), ("wildcard", 2, "acore_world_wildcard"), ("reborn", 3, "acore_world_reborn")] {
|
||||
std::fs::write(d.path().join("Settings/realm-profile.json"), format!("{{\"active\":\"{active}\"}}")).unwrap();
|
||||
let r = Realm::load(d.path()).unwrap();
|
||||
assert_eq!((r.id, r.world_db), (id, db));
|
||||
}
|
||||
assert!(is_extra_world(&d.path().join(".realms/secondary")));
|
||||
assert!(!is_extra_world(d.path()));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -67,7 +67,7 @@ impl ControlLock {
|
||||
_ => " Owner information is unavailable.".into(),
|
||||
};
|
||||
if Instant::now() >= deadline {
|
||||
return Err(Error::Invalid(format!("Another start/stop action is in progress.{detail}")));
|
||||
return Err(Error::Service(crate::error::ErrorCode::OperationInProgress, format!("Another start/stop action is in progress.{detail}")));
|
||||
}
|
||||
if !announced {
|
||||
progress(&format!("Waiting for the current server action.{detail}"));
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
//! and the detailed-logging switch (`debug_logs`).
|
||||
//!
|
||||
//! A world is started through a supervisor process that outlives the caller: it starts `worldserver.exe`, keeps
|
||||
//! the relay running while the world runs, and stops the relay when the world ends. The relay itself is still
|
||||
//! the Python `BugReport/relay.py`, run through the repack's Python, until it is ported too.
|
||||
//! the relay running while the world runs, and stops the relay when the world ends. The supervisor is
|
||||
//! `coa-launcher.exe watch-world`, or `manage.py watch-world` on a repack that does not ship it yet (both write
|
||||
//! the same records). The relay itself is still the Python `BugReport/relay.py`, run through the repack's
|
||||
//! Python, until it is ported too.
|
||||
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::error::{Error, ErrorCode, Result};
|
||||
use crate::launcher::services::{self, ensure_free, mysql, spawn, start_mysql, wait_ready, Progress};
|
||||
use crate::launcher::spawn::Proc;
|
||||
use crate::launcher::{settings::Settings, squid, state};
|
||||
@@ -31,54 +33,120 @@ pub fn wait_relay(root: &Path) -> Result<()> {
|
||||
Err(Error::Invalid("Bug-report relay is not ready; check BugReport/Logs/relay.log.".into()))
|
||||
}
|
||||
|
||||
/// Start the world (and its database). `supervisor` is the launcher executable that runs `watch-world`.
|
||||
pub fn start_world(root: &Path, cfg: &Settings, offset: i32, supervisor: &Path, progress: Progress) -> Result<()> {
|
||||
/// The process that runs `watch-world` for a started world.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Supervisor {
|
||||
/// `coa-launcher.exe` (this crate's launcher).
|
||||
Launcher(PathBuf),
|
||||
/// The repack's Python with `Scripts/manage.py`.
|
||||
Python { python: PathBuf, script: PathBuf },
|
||||
}
|
||||
|
||||
impl Supervisor {
|
||||
/// The supervisor a repack ships: `Scripts/coa-launcher.exe` when present, otherwise its Python launcher.
|
||||
pub fn of(root: &Path) -> Result<Supervisor> {
|
||||
let exe = root.join("Scripts/coa-launcher.exe");
|
||||
if exe.is_file() {
|
||||
return Ok(Supervisor::Launcher(exe));
|
||||
}
|
||||
let python = squid::package_root(root).join("Runtime/python/python.exe");
|
||||
let script = root.join("Scripts/manage.py");
|
||||
if python.is_file() && script.is_file() {
|
||||
return Ok(Supervisor::Python { python, script });
|
||||
}
|
||||
Err(Error::Service(
|
||||
ErrorCode::ServerFilesIncomplete,
|
||||
"This server has no world supervisor (Scripts/coa-launcher.exe or Scripts/manage.py). Repair its program files.".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a world may take to open both of its listeners, together: slow worlds (many bots, a cold disk) are
|
||||
/// common, and the limit must not depend on the bot module.
|
||||
const WORLD_STARTUP_SECONDS: u64 = 1500;
|
||||
|
||||
/// Wait until the world's console answers a command (it can listen before it accepts logins).
|
||||
fn wait_console(root: &Path, cfg: &Settings, until: Instant) -> Result<()> {
|
||||
let mut last = String::new();
|
||||
while Instant::now() < until {
|
||||
if state::running(root, "world").is_none() {
|
||||
return Err(Error::Service(
|
||||
ErrorCode::StartupFailed,
|
||||
"World startup failed: worldserver stopped before its console accepted commands.".into(),
|
||||
));
|
||||
}
|
||||
match crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).and_then(|mut ra| ra.run("server info")) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) => last = e.to_string(),
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
Err(Error::Service(ErrorCode::StartupFailed, format!("World startup failed: its console is still starting. {last}")))
|
||||
}
|
||||
|
||||
fn seconds_until(until: Instant) -> u64 {
|
||||
until.saturating_duration_since(Instant::now()).as_secs()
|
||||
}
|
||||
|
||||
/// Start the world (and its database, unless it is shared), and wait until its console accepts commands.
|
||||
pub fn start_world(root: &Path, cfg: &Settings, offset: i32, supervisor: &Supervisor, progress: Progress) -> Result<()> {
|
||||
start_mysql(root, cfg, progress)?;
|
||||
squid::validate_bots(root)?;
|
||||
let seconds = squid::startup_timeout(root);
|
||||
let until = Instant::now() + Duration::from_secs(squid::startup_timeout(root).max(WORLD_STARTUP_SECONDS));
|
||||
if state::running(root, "world").is_some() {
|
||||
if state::running(root, "supervisor").is_none() {
|
||||
return Err(Error::Invalid("Worldserver has no repack supervisor. Use Stop_All_Server.bat before restarting it.".into()));
|
||||
return Err(Error::Service(
|
||||
ErrorCode::WorldserverAlreadyRunning,
|
||||
"Worldserver has no repack supervisor. Use Stop_All_Server.bat before restarting it.".into(),
|
||||
));
|
||||
}
|
||||
wait_ready(root, "world", cfg.world_port, seconds)?;
|
||||
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
|
||||
wait_relay(root)?;
|
||||
wait_console(root, cfg, until)?;
|
||||
progress("Worldserver and bug-report relay are already running.");
|
||||
return Ok(());
|
||||
}
|
||||
ensure_free(cfg.world_port, progress)?;
|
||||
ensure_free(cfg.ra_port, progress)?;
|
||||
if state::running(root, "supervisor").is_some() || state::running(root, "relay").is_some() {
|
||||
return Err(Error::Invalid("The previous world/relay shutdown is still finishing. Try again shortly.".into()));
|
||||
return Err(Error::Service(
|
||||
ErrorCode::OperationInProgress,
|
||||
"The previous world/relay shutdown is still finishing. Try again shortly.".into(),
|
||||
));
|
||||
}
|
||||
squid::prepare_playerbots(root, cfg.mysql_port, &|sql| mysql(root, Some(sql), None), progress)?;
|
||||
progress("Starting worldserver and its bug-report relay...");
|
||||
let _ = std::fs::remove_file(stop_relay_flag(root));
|
||||
let offset_text = offset.to_string();
|
||||
let root_text = root.to_string_lossy().into_owned();
|
||||
spawn(
|
||||
root,
|
||||
"supervisor",
|
||||
supervisor,
|
||||
&["--root", &root_text, "--port-offset", &offset_text, "watch-world"],
|
||||
root,
|
||||
&root.join("Core/Logs/supervisor.log"),
|
||||
)?;
|
||||
let until = Instant::now() + Duration::from_secs(20);
|
||||
while state::running(root, "world").is_none() && Instant::now() < until {
|
||||
let log = root.join("Core/Logs/supervisor.log");
|
||||
match supervisor {
|
||||
Supervisor::Launcher(exe) => {
|
||||
spawn(root, "supervisor", exe, &["--root", &root_text, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
|
||||
}
|
||||
Supervisor::Python { python, script } => {
|
||||
let script = script.to_string_lossy().into_owned();
|
||||
spawn(root, "supervisor", python, &["-B", &script, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
|
||||
}
|
||||
};
|
||||
let first = Instant::now() + Duration::from_secs(20);
|
||||
while state::running(root, "world").is_none() && Instant::now() < first {
|
||||
if state::running(root, "supervisor").is_none() {
|
||||
return Err(Error::Invalid("World startup failed; check Core/Logs/supervisor.log.".into()));
|
||||
return Err(Error::Service(ErrorCode::StartupFailed, "World startup failed; check Core/Logs/supervisor.log.".into()));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
wait_ready(root, "world", cfg.world_port, seconds)?;
|
||||
wait_ready(root, "world", cfg.ra_port, seconds)?;
|
||||
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
|
||||
wait_ready(root, "world", cfg.ra_port, seconds_until(until))?;
|
||||
wait_relay(root)?;
|
||||
wait_console(root, cfg, until)?;
|
||||
progress("Worldserver and automatic bug reporting are ready.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_child(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path) -> Result<Proc> {
|
||||
let child = crate::launcher::spawn::start(exe, args, cwd, log)?;
|
||||
// The supervisor was started with the environment its services should have.
|
||||
let child = crate::launcher::spawn::start(exe, args, cwd, log, &[])?;
|
||||
state::record(root, name, child.pid)?;
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
import runpy
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
script = sys.argv[1]
|
||||
sys.path.insert(0, str(Path(script).resolve().parent))
|
||||
sys.argv = sys.argv[1:]
|
||||
launcher = runpy.run_path(script, run_name="coa_manager_launcher")
|
||||
original_wait = launcher["wait_ready"]
|
||||
world_deadline = None
|
||||
|
||||
|
||||
def wait_ready(name, port, seconds=180):
|
||||
global world_deadline
|
||||
if name == "mysql":
|
||||
seconds = max(seconds, 300)
|
||||
elif name == "world":
|
||||
# Both game and console listeners belong to one startup, including on old repacks.
|
||||
# Ordinary CoA worlds can load slowly too; this must not depend on SQUID.
|
||||
if world_deadline is None:
|
||||
world_deadline = time.monotonic() + max(seconds, 1500)
|
||||
seconds = max(0, world_deadline - time.monotonic())
|
||||
return original_wait(name, port, seconds)
|
||||
|
||||
|
||||
launcher["start_mysql"].__globals__["wait_ready"] = wait_ready
|
||||
if sys.argv[1] in ("stop-all", "force-stop-all"):
|
||||
shutdown = launcher["stop_all"].__globals__
|
||||
class UnsafeShutdown(Exception):
|
||||
pass
|
||||
|
||||
def stop_owned_world(world):
|
||||
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.")
|
||||
|
||||
if "ra" in shutdown:
|
||||
original_ra = shutdown["ra"]
|
||||
|
||||
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."
|
||||
stop_owned_world(world)
|
||||
return "Stopped this server's recorded world process without its unavailable console."
|
||||
|
||||
shutdown["ra"] = shutdown_command
|
||||
config = launcher["settings"]()
|
||||
with launcher["control_lock"]():
|
||||
if sys.argv[1] == "force-stop-all":
|
||||
world = shutdown["process"]("world")
|
||||
if world:
|
||||
stop_owned_world(world)
|
||||
print("Force-stopped this server's verified world process; unsaved progress may be lost.", flush=True)
|
||||
launcher["stop_all"](config)
|
||||
else:
|
||||
launcher["main"]()
|
||||
if sys.argv[1] in ("start-all", "start-world"):
|
||||
config = launcher["settings"]()
|
||||
deadline = world_deadline if world_deadline is not None else time.monotonic() + 1500
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
if not launcher["process"]("world"):
|
||||
raise RuntimeError("World startup failed: worldserver stopped before its console accepted commands.")
|
||||
try:
|
||||
launcher["ra"]("server info", config)
|
||||
print("World console is accepting commands.", flush=True)
|
||||
break
|
||||
except (OSError, RuntimeError) as error:
|
||||
last_error = error
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise RuntimeError(f"World startup failed: its console is still starting. {last_error}")
|
||||
@@ -176,7 +176,6 @@ fn set_tree(main: &Path, tree: Tree, enabled: bool) -> Result<realms::View> {
|
||||
}
|
||||
}
|
||||
}
|
||||
secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?;
|
||||
}
|
||||
let status = process::observe(main, &crate::layout::read_ports(main));
|
||||
if status.world.state != ServiceState::Stopped
|
||||
@@ -349,25 +348,18 @@ fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
let source = fs::read_to_string(main.join("Scripts/manage.py"))?;
|
||||
let source = secondary_launcher(&source)?;
|
||||
fsx::atomic_write(&second.join("Scripts/manage.py"), source.as_bytes())?;
|
||||
Ok(second)
|
||||
}
|
||||
|
||||
fn secondary_launcher(source: &str) -> Result<String> {
|
||||
let marker = "def start_world(config, offset):\n start_mysql(config)";
|
||||
let source = source.replace("\r\n", "\n");
|
||||
if !source.contains(marker) {
|
||||
return Err(Error::Invalid(
|
||||
"The launcher does not support a shared database world. Update the server first."
|
||||
.into(),
|
||||
));
|
||||
// The world supervisor and the bug-report relay of the extra world (the launcher itself runs in the Manager
|
||||
// and knows that this world shares the main database).
|
||||
for script in ["Scripts/coa-launcher.exe", "Scripts/manage.py"] {
|
||||
let target = second.join(script);
|
||||
if main.join(script).is_file() {
|
||||
fs::create_dir_all(second.join("Scripts"))?;
|
||||
fsx::atomic_write(&target, &fs::read(main.join(script))?)?;
|
||||
} else if target.exists() {
|
||||
fs::remove_file(&target)?;
|
||||
}
|
||||
}
|
||||
Ok(source.replace(
|
||||
marker,
|
||||
"def start_world(config, offset):\n mysql(admin=\"ping\")",
|
||||
))
|
||||
Ok(second)
|
||||
}
|
||||
|
||||
fn start_tree(main: &Path, tree: Tree) -> Result<()> {
|
||||
@@ -408,7 +400,7 @@ pub fn start(main: &Path) -> Result<()> {
|
||||
|
||||
fn stop_tree(main: &Path, tree: Tree) -> Result<()> {
|
||||
let second = tree_root(main, tree);
|
||||
if !second.join("Scripts/manage.py").exists() {
|
||||
if !second.join("Settings/repack.json").exists() {
|
||||
if tree_running(main, tree) {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The running {}'s launcher is missing. The shared database was left running.",
|
||||
@@ -505,12 +497,4 @@ mod tests {
|
||||
assert!(err.contains(expected), "{err}");
|
||||
assert!(!realms::state(t.path()).unwrap().with_reborn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secondary_never_starts_the_shared_database() {
|
||||
let patched = secondary_launcher("def start_world(config, offset):\r\n start_mysql(config)\r\n wait_ready('world', 8086)\r\n").unwrap();
|
||||
assert!(patched.contains("mysql(admin=\"ping\")"));
|
||||
assert!(!patched.contains("start_mysql(config)"));
|
||||
assert!(secondary_launcher("def start_world(): pass").is_err());
|
||||
}
|
||||
}
|
||||
@@ -614,7 +614,12 @@ pub fn prepare_launcher(root: &Path) -> Result<()> {
|
||||
if crate::docker::is_docker(root) {
|
||||
return Ok(());
|
||||
}
|
||||
// The Manager starts servers itself; this keeps the repack's own Python launcher (its .bat files) on the
|
||||
// active realm. A repack without that launcher has nothing to adapt.
|
||||
let path = root.join("Scripts/manage.py");
|
||||
if !path.is_file() {
|
||||
return Ok(());
|
||||
}
|
||||
let source = fs::read_to_string(&path)?;
|
||||
let patched = patch_launcher(&source)?;
|
||||
if patched != source {
|
||||
@@ -1161,8 +1166,9 @@ CoA.GameModeMask = 0
|
||||
fn a_docker_server_has_no_launcher_to_adapt() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(d.path().join("Settings")).unwrap();
|
||||
// No Scripts/manage.py anywhere: on a repack this fails, on a Docker server there is nothing to do.
|
||||
assert!(prepare_launcher(d.path()).is_err());
|
||||
// No Scripts/manage.py anywhere: neither a repack without the Python launcher nor a Docker server has
|
||||
// anything to adapt.
|
||||
assert!(prepare_launcher(d.path()).is_ok());
|
||||
fs::write(
|
||||
d.path().join("Settings/docker.json"),
|
||||
br#"{"project":"t1"}"#,
|
||||
|
||||
@@ -8,10 +8,11 @@ use std::io::{BufRead, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use coa_core::launcher::{render, services, settings::Settings, state, world};
|
||||
use coa_core::launcher::ops::{self, Action};
|
||||
use coa_core::launcher::{services, settings::Settings, state, world};
|
||||
|
||||
const ACTIONS: [&str; 17] = [
|
||||
"start-all", "start-mysql", "start-auth", "start-world", "stop-all", "status", "status-json", "create-account",
|
||||
const ACTIONS: [&str; 18] = [
|
||||
"start-all", "start-mysql", "start-auth", "start-world", "stop-all", "force-stop-all", "status", "status-json", "create-account",
|
||||
"create-account-once", "console", "ra-once", "prepare", "watch-world", "relay-worker", "debug-logs-on",
|
||||
"debug-logs-off", "debug-logs-status",
|
||||
];
|
||||
@@ -184,10 +185,12 @@ fn run(args: Args) -> Result<(), String> {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
{
|
||||
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
|
||||
match args.action.as_str() {
|
||||
"status" => {
|
||||
match args.action.as_str() {
|
||||
"status" | "status-json" => {
|
||||
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
|
||||
if args.action == "status-json" {
|
||||
say(&services::status(root).to_string());
|
||||
} else {
|
||||
for name in ["mysql", "auth", "world", "relay"] {
|
||||
let line = match state::running(root, name) {
|
||||
Some(r) => format!("{name:12} running (PID {})", r.pid),
|
||||
@@ -195,34 +198,14 @@ fn run(args: Args) -> Result<(), String> {
|
||||
};
|
||||
say(&line);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
"status-json" => {
|
||||
say(&services::status(root).to_string());
|
||||
return Ok(());
|
||||
}
|
||||
"stop-all" => return services::stop_all(root, &cfg, &|m| say(m)).map_err(e),
|
||||
_ => {}
|
||||
}
|
||||
if matches!(args.action.as_str(), "start-all" | "start-world") {
|
||||
coa_core::launcher::squid::validate_bots(root).map_err(e)?;
|
||||
}
|
||||
render::prepare(root, &cfg).map_err(e)?;
|
||||
if args.action == "prepare" {
|
||||
return Ok(());
|
||||
}
|
||||
let progress = |m: &str| say(m);
|
||||
if matches!(args.action.as_str(), "start-all" | "start-mysql") {
|
||||
services::start_mysql(root, &cfg, &progress).map_err(e)?;
|
||||
}
|
||||
if matches!(args.action.as_str(), "start-all" | "start-auth") {
|
||||
services::start_auth(root, &cfg, &progress).map_err(e)?;
|
||||
}
|
||||
if matches!(args.action.as_str(), "start-all" | "start-world") {
|
||||
let me = std::env::current_exe().map_err(|x| x.to_string())?;
|
||||
world::start_world(root, &cfg, args.offset, &me, &progress).map_err(e)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let action = Action::parse(&args.action).ok_or_else(usage)?;
|
||||
let me = world::Supervisor::Launcher(std::env::current_exe().map_err(|x| x.to_string())?);
|
||||
ops::run(root, &cfg, args.offset, action, Some(&me), &|m| say(m)).map_err(e)?;
|
||||
if args.action.starts_with("start-") {
|
||||
say("Use Stop_All_Server.bat to shut down this repack safely.");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user