diff --git a/crates/coa-core/src/config/mod.rs b/crates/coa-core/src/config/mod.rs index 7070eb6..f5c82a8 100644 --- a/crates/coa-core/src/config/mod.rs +++ b/crates/coa-core/src/config/mod.rs @@ -213,9 +213,12 @@ pub fn load(root: &Path, scope: Scope) -> Result { let known: BTreeSet<&str> = schema.settings.iter().map(|s| s.key.as_str()).collect(); let unknown_keys = conf.entries().filter(|(k, _)| !known.contains(k)).count(); + // On a Docker server some settings are fixed by the backend (environment beats the file): not offered. + let docker = scope == Scope::Server && crate::docker::is_docker(root); let settings = schema .settings .iter() + .filter(|s| !(docker && crate::docker::managed_setting(&s.key))) .map(|s| { let raw = conf.get(&s.key); let (value, problem) = match raw { @@ -286,9 +289,13 @@ pub fn validate(root: &Path, scope: Scope, changes: &BTreeMap) -> let schema = scope.schema(); let mut errors = Vec::new(); let mut raws = BTreeMap::new(); + let docker = scope == Scope::Server && crate::docker::is_docker(root); for (key, value) in changes { match schema.get(key) { None => errors.push(FieldError { key: key.clone(), message: "is not a setting the Manager can change".into() }), + Some(_) if docker && crate::docker::managed_setting(key) => { + errors.push(FieldError { key: key.clone(), message: "is set by the Docker backend; changing it in the file would have no effect".into() }) + } Some(s) => match s.to_raw(value) { Ok(raw) => { raws.insert(key.clone(), raw); @@ -736,6 +743,26 @@ Spellbook.New = 5 assert!(list_snapshots(&meta).is_empty(), "no snapshot for a rejected save"); } + #[test] + fn a_docker_server_is_not_offered_the_settings_its_backend_fixes() { + let (_d, root, meta) = fixture(); + let keys = |root: &Path| load(root, Scope::Server).unwrap().settings.into_iter().map(|s| s.meta.key).collect::>(); + for k in ["Ra.Enable", "Ra.IP", "Updates.EnableDatabases", "PlayerLimit"] { + assert!(keys(&root).iter().any(|x| x == k), "a repack offers {k}"); + } + fs::write(root.join("Settings/docker.json"), br#"{"project":"t1"}"#).unwrap(); + let docker = keys(&root); + for k in ["Ra.Enable", "Ra.IP", "Updates.EnableDatabases"] { + assert!(!docker.iter().any(|x| x == k), "a Docker server does not offer {k}: the containers' environment beats the file"); + } + assert!(docker.iter().any(|x| x == "PlayerLimit"), "everything else is still offered"); + // Forcing a change through is refused and says why, instead of being saved and ignored. + let err = save(&root, &meta, Scope::Server, &set(&[("Ra.Enable", json!(0))])).unwrap_err().to_string(); + assert!(err.contains("Docker backend"), "{err}"); + assert!(!fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap().contains("Ra.Enable = 0")); + save(&root, &meta, Scope::Server, &set(&[("PlayerLimit", json!(77))])).unwrap(); + } + #[test] fn missing_key_is_appended_and_noop_saves_do_nothing() { let (_d, root, meta) = fixture(); diff --git a/crates/coa-core/src/docker/lifecycle.rs b/crates/coa-core/src/docker/lifecycle.rs index 642ed36..6620c21 100644 --- a/crates/coa-core/src/docker/lifecycle.rs +++ b/crates/coa-core/src/docker/lifecycle.rs @@ -242,6 +242,10 @@ fn start(d: &dyn Docker, root: &Path, cfg: &Config, with_game: bool, log: &mut L run_container(d, &call, &n.world, log)?; } wait_listening(d, cfg, &n.world, ports.world, WORLD_WAIT, log)?; + // The core leaves with code 2 for `server restart` and expects a supervisor to start it again (the repack has one). Docker + // does that for any non-zero exit, but only once the server has come up: a start that fails must stay failed, not loop. + // A stop by `docker stop` or `server shutdown` (code 0) is never restarted. + let _ = docker(d, &["update", "--restart", "on-failure:3", &n.world], QUICK); if !state.get(&n.auth).is_some_and(Container::running) { remove(d, &n.auth); @@ -388,6 +392,21 @@ fn database_env(s: &Secrets, world: bool, realm: crate::realms::Mode) -> Vec<(St env } +/// Every setting variable (`AC_...`) the containers get, for the check that the screens know which settings are fixed. +#[cfg(test)] +pub(crate) fn forced_variables() -> Vec { + let cfg = Config { project: "t".into(), bind_address: "127.0.0.1".into(), mysql_image: "mysql:8.4".into(), data_dir: None }; + let n = cfg.names(); + let mut found = Vec::new(); + for kind in [GameKind::World, GameKind::Auth] { + let args = game_args(&cfg, &n, kind, Path::new("/s"), Path::new("/d"), 1, 2, None); + found.extend(args.iter().filter_map(|a| a.strip_prefix("AC_").map(|rest| format!("AC_{}", rest.split('=').next().unwrap())))); + } + found.sort(); + found.dedup(); + found +} + /// Realm profiles are only in play once a profile has been chosen on this server (`Settings/realm-profile.json`). fn prepare_realm(root: &Path, log: &mut Log) -> Step { let fail_with = |e: crate::error::Error| Failure { code: ErrorCode::StartupFailed, output: e.to_string() }; @@ -670,6 +689,7 @@ mod tests { } out(0, "containerid\n", "") } + ["update", "--restart", _, _] => out(0, "", ""), ["stop", "--time", _, name] => { self.running.borrow_mut().remove(*name); self.exited.borrow_mut().insert(name.to_string(), (0, false)); @@ -757,6 +777,21 @@ mod tests { assert!(!plain.iter().any(|a| a == "--lower-case-table-names=1" || a == "--user")); } + #[test] + fn the_world_server_is_started_again_when_it_restarts_itself_but_only_once_it_is_up() { + let (_d, root) = server("t1"); + let sim = Sim::new(); + assert!(start_all(&sim, &root).ok); + let world_run = sim.calls_of("run").into_iter().find(|c| c.args.iter().any(|a| a == "coa-t1-world")).unwrap(); + assert!(!world_run.args.iter().any(|a| a == "--restart"), "no restart while it is still starting"); + let updates = sim.calls_of("update"); + assert_eq!(updates.len(), 1); + assert_eq!(updates[0].args, ["update", "--restart", "on-failure:3", "coa-t1-world"]); + let verbs = sim.verbs(); + let pos = |p: &str| verbs.iter().position(|v| v.starts_with(p)).unwrap(); + assert!(pos("run --detach") < pos("update"), "after the container exists and listens"); + } + #[test] fn the_containers_use_the_databases_of_the_selected_realm() { let s = Secrets { root: "r".into(), app: "apppw".into() }; diff --git a/crates/coa-core/src/docker/mod.rs b/crates/coa-core/src/docker/mod.rs index fae61d9..d668bf1 100644 --- a/crates/coa-core/src/docker/mod.rs +++ b/crates/coa-core/src/docker/mod.rs @@ -140,6 +140,52 @@ pub fn ensure_main_configs(root: &Path) -> Result> { Ok(created) } +/// Settings the Docker backend gives the containers as environment variables. The core reads `AC_` before the +/// configuration file, so a value written to the file for one of these keys is silently ignored. They are what makes the +/// containers work (where things are inside them, listening on every interface, the console, no built-in database +/// updater, the databases); the owner has no use for them and the screens do not offer them. +pub(crate) const FORCED_KEYS: [&str; 12] = [ + "BindIP", + "WorldServerPort", + "RealmServerPort", + "LogsDir", + "DataDir", + "Updates.EnableDatabases", + "Ra.Enable", + "Ra.IP", + "Ra.Port", + "LoginDatabaseInfo", + "WorldDatabaseInfo", + "CharacterDatabaseInfo", +]; + +/// Is this setting fixed by the Docker backend (see `FORCED_KEYS`)? +pub fn managed_setting(key: &str) -> bool { + FORCED_KEYS.iter().any(|k| k.eq_ignore_ascii_case(key)) +} + +/// The environment variable the core reads for a setting: `AC_` and the key in upper snake case, a `_` between a lower-case +/// letter and a capital, and at letter / digit boundaries (the core's `IniKeyToEnvVarKey`). +#[cfg(test)] +pub(crate) fn env_name(key: &str) -> String { + let chars: Vec = key.chars().collect(); + let mut out = String::from("AC_"); + for (i, &c) in chars.iter().enumerate() { + if matches!(c, ' ' | '.' | '-') { + out.push('_'); + continue; + } + out.push(c.to_ascii_uppercase()); + if let Some(&next) = chars.get(i + 1) { + let split = (!c.is_ascii_uppercase() && next.is_ascii_uppercase()) || (!c.is_ascii_digit() && next.is_ascii_digit()) || (c.is_ascii_digit() && !next.is_ascii_digit() && !matches!(next, ' ' | '.' | '-')); + if split { + out.push('_'); + } + } + } + out +} + /// Name of the runtime image: it follows the content of its Dockerfile, so changing the libraries builds a new image. pub(crate) fn runtime_image() -> String { format!("coa-runtime:{}", &fsx::sha256_bytes(RUNTIME_DOCKERFILE.as_bytes())[..12]) @@ -206,6 +252,33 @@ mod tests { use super::*; use std::fs; + #[test] + fn setting_names_become_the_variables_the_core_reads() { + for (key, var) in [ + ("BindIP", "AC_BIND_IP"), + ("Ra.Enable", "AC_RA_ENABLE"), + ("Ra.IP", "AC_RA_IP"), + ("Updates.EnableDatabases", "AC_UPDATES_ENABLE_DATABASES"), + ("WorldServerPort", "AC_WORLD_SERVER_PORT"), + ("LoginDatabaseInfo", "AC_LOGIN_DATABASE_INFO"), + ("DataDir", "AC_DATA_DIR"), + ("Dynamic.XP.Reminder.Interval", "AC_DYNAMIC_XP_REMINDER_INTERVAL"), + ("EtherealBazaar.Enable", "AC_ETHEREAL_BAZAAR_ENABLE"), + ] { + assert_eq!(env_name(key), var, "{key}"); + } + } + + #[test] + fn the_settings_called_managed_are_exactly_the_variables_the_containers_get() { + // If a variable is added to the containers without being listed here (or the other way round), a screen would + // offer a setting that does nothing, or hide one that works. + let given: std::collections::BTreeSet = lifecycle::forced_variables().into_iter().collect(); + let listed: std::collections::BTreeSet = FORCED_KEYS.iter().map(|k| env_name(k)).collect(); + assert_eq!(given, listed); + assert!(managed_setting("ra.enable") && managed_setting("Updates.EnableDatabases") && !managed_setting("PlayerLimit")); + } + #[test] fn the_main_configs_are_created_from_their_templates_and_never_overwritten() { let d = tempfile::tempdir().unwrap();