mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 19:25:56 +00:00
Server Migration: real analysis and a real modular copy
The page was a mock: it never read the database (always 0 accounts), showed a hard-coded schema and core version, looked for server files in the wrong folder, and its "transfer" reported accounts, characters and tables as moved without moving anything. Its locale was fixed to "ru". - remove server_migration.rs and its three commands - modular_copy::preview: classic/modular core, version, database state, counts and schemas from a running database (read only), database size, settings files, extra worlds; nothing is started or changed - the page shows that and hands over to the same modular-copy install screen as "Manage another server"; texts in en and ru via i18n - the modular copy now carries world settings changed in Server Configuration (Settings/worldserver.conf.template was not copied) - E2E preview_bare_and_copy_e2e checks the preview and the carried setting; passes against preview core 0.261108.9501 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6091e545f8
commit
fdbf38ee4e
14 files changed
+495
-1260
No files matched your search
@@ -114,9 +114,20 @@ fn copy(work: &Path, reg: &Registry) -> R<()> {
|
||||
let fingerprint = |root: &Path| sql(root, "SELECT CONCAT((SELECT COUNT(*) FROM acore_auth.account),'|',(SELECT COUNT(*) FROM acore_characters.characters),'|',\
|
||||
(SELECT CONCAT(name,':',level,':',money) FROM acore_characters.characters WHERE guid=900001))").trim().to_string();
|
||||
let expected = fingerprint(&old);
|
||||
let counts = sql(&old, "SELECT CONCAT((SELECT COUNT(*) FROM acore_auth.account),'|',(SELECT COUNT(*) FROM acore_characters.characters))").trim().to_string();
|
||||
// A world setting changed on the Server Configuration page lives in the old server's template.
|
||||
let old_meta = coa_core::registry::metadata_dir_for(&old)?;
|
||||
let rate = BTreeMap::from([("Rate.XP.Kill".to_string(), "3".to_string())]);
|
||||
assert_eq!(coa_core::allsettings::save(&old, &old_meta, &rate)?, ["Rate.XP.Kill"]);
|
||||
let _ = coa_core::driver::run(&old, coa_core::driver::Verb::StopAll);
|
||||
println!("old server data: {expected}");
|
||||
assert!(coa_core::modular_copy::is_classic(&old));
|
||||
let before_preview = tree(&old);
|
||||
let p = coa_core::modular_copy::preview(&old)?;
|
||||
println!("preview (stopped): {p:?}");
|
||||
assert!(p.classic && !p.modular && p.database == "stopped" && p.accounts.is_none());
|
||||
assert!(p.database_bytes > 0 && p.config_files.iter().any(|f| f.ends_with("mod-coa-content-scaling.conf")));
|
||||
assert_eq!(tree(&old), before_preview, "the preview changed the old server's files");
|
||||
|
||||
// 2. copy of the stopped server, then the preview core on the copy.
|
||||
let before = tree(&old);
|
||||
@@ -130,6 +141,9 @@ fn copy(work: &Path, reg: &Registry) -> R<()> {
|
||||
assert_eq!(observed.mysql.state, coa_core::process::ServiceState::Stopped, "a database of the copy is still running: {:?}", observed.mysql);
|
||||
assert!(!coa_core::registry::metadata_dir_for(&new)?.join("import").exists(), "the private copy of the old data is removed");
|
||||
assert_eq!(std::fs::read_to_string(new.join("Core/configs/modules/mod-coa-content-scaling.conf"))?, conf_text);
|
||||
assert_eq!(report.world_settings, ["Rate.XP.Kill"], "skipped: {:?}", report.world_settings_skipped);
|
||||
let world_value = |root: &Path| coa_core::allsettings::list(root).unwrap().into_iter().find(|i| i.key == "Rate.XP.Kill").map(|i| i.value);
|
||||
assert_eq!(world_value(&new).as_deref(), Some("3"));
|
||||
let out = preview_core(&new)?;
|
||||
println!("modules on the copy: {:?}", out.modules);
|
||||
let got = fingerprint(&new);
|
||||
@@ -143,6 +157,11 @@ fn copy(work: &Path, reg: &Registry) -> R<()> {
|
||||
assert!(started.ok, "{}", started.output);
|
||||
let data_before: BTreeMap<String, String> = tree(&old).into_iter().filter(|(k, _)| !k.starts_with("mysql/") && !k.starts_with(".state/") && !k.starts_with("Core/configs/")).collect();
|
||||
let rows_before = fingerprint(&old);
|
||||
let p = coa_core::modular_copy::preview(&old)?;
|
||||
println!("preview (running): accounts {:?} characters {:?} schemas {:?}", p.accounts, p.characters, p.schemas);
|
||||
assert_eq!(p.database, "running");
|
||||
assert_eq!(format!("{}|{}", p.accounts.unwrap(), p.characters.unwrap()), counts);
|
||||
assert!(p.schemas.iter().any(|s| s == "acore_characters"));
|
||||
let new2 = work.join("copy-running-fixture");
|
||||
install(&new2, reg)?;
|
||||
let report = coa_core::modular_copy::copy_data(&old, &new2, &|w| println!(" copy: {w}"));
|
||||
@@ -154,6 +173,7 @@ fn copy(work: &Path, reg: &Registry) -> R<()> {
|
||||
let data_after: BTreeMap<String, String> = tree(&old).into_iter().filter(|(k, _)| !k.starts_with("mysql/") && !k.starts_with(".state/") && !k.starts_with("Core/configs/")).collect();
|
||||
assert_eq!(data_after, data_before, "files outside the database changed");
|
||||
assert_eq!(fingerprint(&new2), expected);
|
||||
assert_eq!(world_value(&new2).as_deref(), Some("3"));
|
||||
let _ = coa_core::driver::run(&new2, coa_core::driver::Verb::StopAll);
|
||||
println!("COPY (running) PASS");
|
||||
Ok(())
|
||||
|
||||
@@ -76,7 +76,6 @@ pub mod remote_client;
|
||||
pub mod repair;
|
||||
pub mod report;
|
||||
pub mod schema_check;
|
||||
pub mod server_migration;
|
||||
pub mod signing;
|
||||
pub mod solver;
|
||||
pub mod squid;
|
||||
|
||||
@@ -38,6 +38,84 @@ pub struct CopyReport {
|
||||
pub config_files: Vec<String>,
|
||||
/// How the old data was read: "running database" or "copy of the stopped database".
|
||||
pub read_from: String,
|
||||
/// World settings the owner changed (Server Configuration) that were set on the new server too.
|
||||
pub world_settings: Vec<String>,
|
||||
/// Changed world settings the new server's configuration does not take, with the reason.
|
||||
pub world_settings_skipped: Vec<String>,
|
||||
}
|
||||
|
||||
/// What a modular copy of `old` would take, read without changing anything: the old server is never started,
|
||||
/// and its database is only queried when it is already running.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CopyPreview {
|
||||
pub path: PathBuf,
|
||||
/// The classic core (modules compiled in): the only kind that is copied.
|
||||
pub classic: bool,
|
||||
/// Already a modular core: it is added as it is, not copied.
|
||||
pub modular: bool,
|
||||
pub version: Option<String>,
|
||||
/// "running", "stopped" or "missing" (no database folder).
|
||||
pub database: String,
|
||||
/// Read from the running database; `None` when it is stopped (they are counted while copying).
|
||||
pub accounts: Option<u64>,
|
||||
pub characters: Option<u64>,
|
||||
pub schemas: Vec<String>,
|
||||
/// Size of the old database files; a stopped database is copied once more while it is read.
|
||||
pub database_bytes: u64,
|
||||
/// Settings files that go along (module configs, realm profiles).
|
||||
pub config_files: Vec<String>,
|
||||
/// Extra worlds of the old server (`.realms/<name>`). Their databases are in the same MySQL and go along, and
|
||||
/// the copied realm profile switches them on; the new server prepares their folders when it starts them.
|
||||
pub extra_worlds: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn preview(old: &Path) -> Result<CopyPreview> {
|
||||
if !old.is_dir() {
|
||||
return Err(Error::Invalid(format!("{} is not a folder.", old.display())));
|
||||
}
|
||||
let classic = is_classic(old);
|
||||
let modular = !crate::docker::is_docker(old)
|
||||
&& old.join("Core/worldserver.exe").is_file()
|
||||
&& crate::provenance::realm_host_fingerprint(old).is_some();
|
||||
let version = crate::registry::metadata_dir_for(old)
|
||||
.ok()
|
||||
.and_then(|dir| crate::registry::MetaDir::open(&dir).ok())
|
||||
.and_then(|(_, meta)| meta.core.version);
|
||||
let data = old.join("mysql/data");
|
||||
let has_data = data.join("mysql").is_dir();
|
||||
let observed = crate::process::observe(old, &crate::layout::read_ports(old));
|
||||
let running_db = (has_data && observed.mysql.state == ServiceState::Running)
|
||||
.then(|| Db::from_repack(old, Account::Admin).ok())
|
||||
.flatten()
|
||||
.filter(|db| db.ping())
|
||||
.map(|db| db.for_realm(crate::realms::Mode::Coa));
|
||||
let (database, accounts, characters, schemas) = match &running_db {
|
||||
Some(db) => (
|
||||
"running",
|
||||
Some(count(db, "SELECT COUNT(*) FROM acore_auth.account;")),
|
||||
Some(count(db, "SELECT COUNT(*) FROM acore_characters.characters;")),
|
||||
game_schemas(db).unwrap_or_default(),
|
||||
),
|
||||
None if has_data => ("stopped", None, None, Vec::new()),
|
||||
None => ("missing", None, None, Vec::new()),
|
||||
};
|
||||
let mut extra_worlds: Vec<String> = fs::read_dir(old.join(".realms"))
|
||||
.map(|rd| rd.flatten().filter(|e| e.path().is_dir()).map(|e| e.file_name().to_string_lossy().into_owned()).collect())
|
||||
.unwrap_or_default();
|
||||
extra_worlds.sort();
|
||||
Ok(CopyPreview {
|
||||
path: old.to_path_buf(),
|
||||
classic,
|
||||
modular,
|
||||
version,
|
||||
database: database.into(),
|
||||
accounts,
|
||||
characters,
|
||||
schemas,
|
||||
database_bytes: if has_data { dir_size(&data) } else { 0 },
|
||||
config_files: settings_files(old),
|
||||
extra_worlds,
|
||||
})
|
||||
}
|
||||
|
||||
/// Game schemas of a CoA server: `acore_*` (auth, characters, world, their Wildcard/Reborn variants, bots).
|
||||
@@ -295,13 +373,120 @@ pub fn copy_data(old: &Path, new: &Path, progress: &dyn Fn(&str)) -> Result<Copy
|
||||
}
|
||||
fsx::atomic_write_json(&new.join("Settings/repack.json"), &repack)?;
|
||||
let _ = fs::remove_dir_all(&work);
|
||||
Ok(CopyReport { schemas, accounts, characters, config_files: files, read_from: read_from.into() })
|
||||
progress("Copying world settings");
|
||||
let (world_settings, world_settings_skipped) = carry_world_settings(old, new)?;
|
||||
Ok(CopyReport {
|
||||
schemas,
|
||||
accounts,
|
||||
characters,
|
||||
config_files: files,
|
||||
read_from: read_from.into(),
|
||||
world_settings,
|
||||
world_settings_skipped,
|
||||
})
|
||||
}
|
||||
|
||||
/// The world settings changed on the old server (they live in its `Settings/worldserver.conf.template`, which the new
|
||||
/// server does not take: it keeps the template of its own version) are set on the new server through the same checks
|
||||
/// the Server Configuration page uses. Settings the Manager owns (ports, folders, passwords) are not among them.
|
||||
///
|
||||
/// The shipped template already differs from `worldserver.conf.dist` in many places, so "changed" means "differs from
|
||||
/// what the new server has now": for a copy onto the same version that is exactly what the owner changed. (A value the
|
||||
/// owner never touched but a newer release ships differently cannot be told apart from an owner's change; it keeps the
|
||||
/// old server's value, which is what that server ran with.)
|
||||
fn carry_world_settings(old: &Path, new: &Path) -> Result<(Vec<String>, Vec<String>)> {
|
||||
let current: std::collections::BTreeMap<String, String> =
|
||||
crate::allsettings::list(new)?.into_iter().map(|i| (i.key, i.value)).collect();
|
||||
let mut changes = std::collections::BTreeMap::new();
|
||||
let mut skipped = Vec::new();
|
||||
for item in crate::allsettings::list(old)? {
|
||||
match current.get(&item.key) {
|
||||
Some(now) if *now == item.value => {}
|
||||
Some(_) => {
|
||||
changes.insert(item.key, item.value);
|
||||
}
|
||||
None if item.changed => skipped.push(format!("{}: not a setting of the new version", item.key)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
let meta = crate::registry::metadata_dir_for(new)?;
|
||||
let mut carried = Vec::new();
|
||||
match crate::allsettings::save(new, &meta, &changes) {
|
||||
Ok(set) => carried.extend(set),
|
||||
// One value the new version refuses must not lose the others: set them one at a time.
|
||||
Err(_) => {
|
||||
for (key, value) in changes {
|
||||
match crate::allsettings::save(new, &meta, &std::collections::BTreeMap::from([(key.clone(), value)])) {
|
||||
Ok(set) => carried.extend(set),
|
||||
Err(e) => skipped.push(format!("{key}: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((carried, skipped))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const DIST: &str = "[worldserver]\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Description: Epic drops.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
|
||||
|
||||
fn world(root: &Path, dist: &str, conf: &str) {
|
||||
fs::create_dir_all(root.join("Core/configs")).unwrap();
|
||||
fs::create_dir_all(root.join("Settings")).unwrap();
|
||||
fs::create_dir_all(crate::registry::metadata_dir_for(root).unwrap()).unwrap();
|
||||
fs::write(root.join("Core/configs/worldserver.conf.dist"), dist).unwrap();
|
||||
fs::write(root.join("Settings/worldserver.conf.template"), conf).unwrap();
|
||||
fs::write(root.join("Core/configs/worldserver.conf"), conf).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_world_settings_go_to_the_new_server_and_the_rest_keep_its_defaults() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (old, new) = (dir.path().join("old"), dir.path().join("new"));
|
||||
let old_dist = format!("{DIST}\r\n#\r\n# Old.Only\r\n# Description: gone in the new version.\r\n# Default: 1\r\n#\r\n\r\nOld.Only = 1\r\n");
|
||||
world(&old, &old_dist, "[worldserver]\r\nRate.Drop.Item.Epic = 3\r\nOld.Only = 2\r\nLoginDatabaseInfo = \"old\"\r\n");
|
||||
world(&new, DIST, "[worldserver]\r\nLoginDatabaseInfo = \"new\"\r\n");
|
||||
|
||||
let (carried, skipped) = carry_world_settings(&old, &new).unwrap();
|
||||
assert_eq!(carried, ["Rate.Drop.Item.Epic"]);
|
||||
assert_eq!(skipped.len(), 1, "{skipped:?}");
|
||||
assert!(skipped[0].starts_with("Old.Only"));
|
||||
for f in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
|
||||
let text = fs::read_to_string(new.join(f)).unwrap();
|
||||
assert!(text.contains("Rate.Drop.Item.Epic = 3"), "{f}: {text}");
|
||||
assert!(text.contains("LoginDatabaseInfo = \"new\""), "the Manager's own settings stay: {text}");
|
||||
assert!(!text.contains("Old.Only"), "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_of_a_folder_reads_only_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let classic = dir.path().join("classic");
|
||||
fs::create_dir_all(classic.join("Core/configs/modules")).unwrap();
|
||||
fs::create_dir_all(classic.join("mysql/data/mysql")).unwrap();
|
||||
fs::create_dir_all(classic.join(".realms/secondary")).unwrap();
|
||||
fs::write(classic.join("Core/worldserver.exe"), b"not a plugin host").unwrap();
|
||||
fs::write(classic.join("Core/configs/modules/mod_x.conf"), b"x").unwrap();
|
||||
fs::write(classic.join("mysql/data/ibdata1"), vec![0u8; 2048]).unwrap();
|
||||
let p = preview(&classic).unwrap();
|
||||
assert!(p.classic && !p.modular);
|
||||
assert_eq!(p.database, "stopped");
|
||||
assert_eq!((p.accounts, p.characters), (None, None), "a stopped database is not opened");
|
||||
assert_eq!(p.database_bytes, 2048);
|
||||
assert_eq!(p.config_files, ["Core/configs/modules/mod_x.conf"]);
|
||||
assert_eq!(p.extra_worlds, ["secondary"]);
|
||||
|
||||
let empty = dir.path().join("empty");
|
||||
fs::create_dir_all(&empty).unwrap();
|
||||
let p = preview(&empty).unwrap();
|
||||
assert!(!p.classic && !p.modular);
|
||||
assert_eq!(p.database, "missing");
|
||||
assert!(preview(&dir.path().join("nowhere")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_owner_settings_are_copied() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,595 +0,0 @@
|
||||
//! Server Migration Center (Перенос сервера).
|
||||
//!
|
||||
//! Subsystem for discovering, inspecting, comparing, planning, and executing non-destructive
|
||||
//! server migrations from legacy or external AzerothCore/CoA servers into CSM Modules Preview realms.
|
||||
//!
|
||||
//! Migration Lifecycle:
|
||||
//! Discover -> Inspect -> Classify -> Compare -> Plan -> Backup -> Transfer -> Validate -> Commit.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum SourceClassification {
|
||||
CsmManagedCoa,
|
||||
LegacyEmbeddedCoa,
|
||||
StandardAzerothCore,
|
||||
UnknownCustom,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DetectedModule {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub detected_via: String,
|
||||
pub version: Option<String>,
|
||||
pub has_database_data: bool,
|
||||
pub is_supported_by_preview: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SourceInspectionReport {
|
||||
pub source_path: PathBuf,
|
||||
pub source_type: SourceClassification,
|
||||
pub core_version: Option<String>,
|
||||
pub schema_version: Option<String>,
|
||||
pub accounts_count: usize,
|
||||
pub characters_count: usize,
|
||||
pub detected_modules: Vec<DetectedModule>,
|
||||
pub module_tables: BTreeMap<String, Vec<String>>,
|
||||
pub custom_race_support: bool,
|
||||
pub compatibility_notes: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MigrationScope {
|
||||
pub accounts_and_characters: bool,
|
||||
pub module_owned_data: bool,
|
||||
pub server_configuration: bool,
|
||||
pub selected_modules: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for MigrationScope {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
accounts_and_characters: true,
|
||||
module_owned_data: true,
|
||||
server_configuration: true,
|
||||
selected_modules: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ConflictResolutionPolicy {
|
||||
RemapCollidingGuids,
|
||||
SkipCollidingGuids,
|
||||
OverwriteExisting,
|
||||
}
|
||||
|
||||
impl Default for ConflictResolutionPolicy {
|
||||
fn default() -> Self {
|
||||
ConflictResolutionPolicy::RemapCollidingGuids
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AdapterPlan {
|
||||
pub module_id: String,
|
||||
pub source_tables: Vec<String>,
|
||||
pub dest_tables: Vec<String>,
|
||||
pub data_loss_risks: Vec<String>,
|
||||
pub requires_conversion: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MigrationPlan {
|
||||
pub plan_id: String,
|
||||
pub source_path: PathBuf,
|
||||
pub dest_realm_path: PathBuf,
|
||||
pub source_report: SourceInspectionReport,
|
||||
pub scope: MigrationScope,
|
||||
pub conflict_policy: ConflictResolutionPolicy,
|
||||
pub adapters: Vec<AdapterPlan>,
|
||||
pub tables_to_migrate: Vec<String>,
|
||||
pub quarantined_tables: Vec<String>,
|
||||
pub estimated_disk_mb: u64,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MigrationExecutionReport {
|
||||
pub success: bool,
|
||||
pub backup_path: Option<PathBuf>,
|
||||
pub accounts_transferred: usize,
|
||||
pub characters_transferred: usize,
|
||||
pub items_transferred: usize,
|
||||
pub modules_migrated: Vec<String>,
|
||||
pub tables_migrated: Vec<String>,
|
||||
pub quarantined_tables: Vec<String>,
|
||||
pub warnings: Vec<String>,
|
||||
pub errors: Vec<String>,
|
||||
pub duration_ms: u64,
|
||||
}
|
||||
|
||||
/// Trait implemented by versioned module migration adapters.
|
||||
pub trait ModuleMigrationAdapter: Send + Sync {
|
||||
fn module_id(&self) -> &str;
|
||||
fn source_module_id(&self) -> &str;
|
||||
fn destination_module_id(&self) -> &str;
|
||||
fn owned_tables(&self) -> &[&str];
|
||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan;
|
||||
fn execute(&self, source: &Path, dest: &Path, remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>>;
|
||||
}
|
||||
|
||||
// ---------------- Built-in Module Adapters ----------------
|
||||
|
||||
pub struct CompanionsAdapter;
|
||||
impl ModuleMigrationAdapter for CompanionsAdapter {
|
||||
fn module_id(&self) -> &str { "companions" }
|
||||
fn source_module_id(&self) -> &str { "mod-coa-playerbots" }
|
||||
fn destination_module_id(&self) -> &str { "companions" }
|
||||
fn owned_tables(&self) -> &[&str] {
|
||||
&["mod_coa_playerbots_saved_bots", "mod_coa_playerbots_talents", "mod_coa_playerbots_equipment"]
|
||||
}
|
||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
||||
let matching: Vec<String> = source_tables.iter()
|
||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
||||
.cloned()
|
||||
.collect();
|
||||
AdapterPlan {
|
||||
module_id: "companions".into(),
|
||||
source_tables: matching.clone(),
|
||||
dest_tables: matching,
|
||||
data_loss_risks: vec!["Bot owner character GUIDs will be remapped to target realm GUIDs".into()],
|
||||
requires_conversion: true,
|
||||
}
|
||||
}
|
||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
||||
Ok(vec!["mod_coa_playerbots_saved_bots".into()])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SquidPlayerbotsAdapter;
|
||||
impl ModuleMigrationAdapter for SquidPlayerbotsAdapter {
|
||||
fn module_id(&self) -> &str { "playerbots" }
|
||||
fn source_module_id(&self) -> &str { "mod-playerbots" }
|
||||
fn destination_module_id(&self) -> &str { "squid_playerbots" }
|
||||
fn owned_tables(&self) -> &[&str] {
|
||||
&["playerbots_rnd_bots", "playerbots_rnd_spells", "playerbots_custom_strategy"]
|
||||
}
|
||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
||||
let matching: Vec<String> = source_tables.iter()
|
||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
||||
.cloned()
|
||||
.collect();
|
||||
AdapterPlan {
|
||||
module_id: "playerbots".into(),
|
||||
source_tables: matching.clone(),
|
||||
dest_tables: matching,
|
||||
data_loss_risks: vec![],
|
||||
requires_conversion: false,
|
||||
}
|
||||
}
|
||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
||||
Ok(vec!["playerbots_rnd_bots".into()])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ContentScalingAdapter;
|
||||
impl ModuleMigrationAdapter for ContentScalingAdapter {
|
||||
fn module_id(&self) -> &str { "content-scaling" }
|
||||
fn source_module_id(&self) -> &str { "mod-coa-content-scaling" }
|
||||
fn destination_module_id(&self) -> &str { "content_scaling" }
|
||||
fn owned_tables(&self) -> &[&str] {
|
||||
&["mod_content_scaling_creatures", "mod_content_scaling_maps"]
|
||||
}
|
||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
||||
let matching: Vec<String> = source_tables.iter()
|
||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
||||
.cloned()
|
||||
.collect();
|
||||
AdapterPlan {
|
||||
module_id: "content-scaling".into(),
|
||||
source_tables: matching.clone(),
|
||||
dest_tables: matching,
|
||||
data_loss_risks: vec![],
|
||||
requires_conversion: false,
|
||||
}
|
||||
}
|
||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
||||
Ok(vec!["mod_content_scaling_creatures".into()])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AuctionHouseBotAdapter;
|
||||
impl ModuleMigrationAdapter for AuctionHouseBotAdapter {
|
||||
fn module_id(&self) -> &str { "ah-bot" }
|
||||
fn source_module_id(&self) -> &str { "mod-auctionhousebot" }
|
||||
fn destination_module_id(&self) -> &str { "ah-bot" }
|
||||
fn owned_tables(&self) -> &[&str] {
|
||||
&["mod_auctionhousebot_buyer", "mod_auctionhousebot_seller"]
|
||||
}
|
||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
||||
let matching: Vec<String> = source_tables.iter()
|
||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
||||
.cloned()
|
||||
.collect();
|
||||
AdapterPlan {
|
||||
module_id: "ah-bot".into(),
|
||||
source_tables: matching.clone(),
|
||||
dest_tables: matching,
|
||||
data_loss_risks: vec!["Active temporary auctions will be refreshed by bot".into()],
|
||||
requires_conversion: false,
|
||||
}
|
||||
}
|
||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
||||
Ok(vec!["mod_auctionhousebot_buyer".into()])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NpcEnchanterAdapter;
|
||||
impl ModuleMigrationAdapter for NpcEnchanterAdapter {
|
||||
fn module_id(&self) -> &str { "npc-enchanter" }
|
||||
fn source_module_id(&self) -> &str { "mod-npc-enchanter" }
|
||||
fn destination_module_id(&self) -> &str { "npc-enchanter" }
|
||||
fn owned_tables(&self) -> &[&str] {
|
||||
&["mod_npc_enchanter_item_cost"]
|
||||
}
|
||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
||||
let matching: Vec<String> = source_tables.iter()
|
||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
||||
.cloned()
|
||||
.collect();
|
||||
AdapterPlan {
|
||||
module_id: "npc-enchanter".into(),
|
||||
source_tables: matching.clone(),
|
||||
dest_tables: matching,
|
||||
data_loss_risks: vec![],
|
||||
requires_conversion: false,
|
||||
}
|
||||
}
|
||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
||||
Ok(vec!["mod_npc_enchanter_item_cost".into()])
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Core Migration Functions ----------------
|
||||
|
||||
/// Gets the registry of all built-in module migration adapters.
|
||||
pub fn get_adapters() -> Vec<Box<dyn ModuleMigrationAdapter>> {
|
||||
vec![
|
||||
Box::new(CompanionsAdapter),
|
||||
Box::new(SquidPlayerbotsAdapter),
|
||||
Box::new(ContentScalingAdapter),
|
||||
Box::new(AuctionHouseBotAdapter),
|
||||
Box::new(NpcEnchanterAdapter),
|
||||
]
|
||||
}
|
||||
|
||||
/// Discovers and inspects a source server non-destructively (read-only).
|
||||
pub fn inspect_source(source_path: &Path) -> Result<SourceInspectionReport> {
|
||||
if !source_path.is_dir() {
|
||||
return Err(Error::Invalid(format!(
|
||||
"Source path is not a directory: {}",
|
||||
source_path.display()
|
||||
)));
|
||||
}
|
||||
|
||||
let mut notes = Vec::new();
|
||||
|
||||
// 1. Classify source
|
||||
let has_csm_metadata = source_path.join(".manager").is_dir() || source_path.join("metadata").is_dir();
|
||||
let has_worldserver = source_path.join("worldserver.exe").is_file() || source_path.join("bin/worldserver").is_file();
|
||||
let has_coa_config = source_path.join("configs/modules/coa.conf").is_file()
|
||||
|| source_path.join("configs/modules/coa.conf.dist").is_file()
|
||||
|| source_path.join("etc/coa.conf").is_file();
|
||||
|
||||
let source_type = if has_csm_metadata && has_coa_config {
|
||||
SourceClassification::CsmManagedCoa
|
||||
} else if has_coa_config {
|
||||
SourceClassification::LegacyEmbeddedCoa
|
||||
} else if has_worldserver {
|
||||
SourceClassification::StandardAzerothCore
|
||||
} else {
|
||||
SourceClassification::UnknownCustom
|
||||
};
|
||||
|
||||
if source_type == SourceClassification::UnknownCustom {
|
||||
notes.push("Source directory does not match standard CoA or AzerothCore server layout. Migration will be conservative.".into());
|
||||
}
|
||||
|
||||
// 2. Discover installed modules and configurations
|
||||
let mut detected_modules = Vec::new();
|
||||
let mut module_tables = BTreeMap::new();
|
||||
|
||||
let conf_dirs = [
|
||||
source_path.join("configs/modules"),
|
||||
source_path.join("etc/modules"),
|
||||
source_path.join("configs"),
|
||||
];
|
||||
|
||||
let mut found_confs = BTreeSet::new();
|
||||
for d in &conf_dirs {
|
||||
if let Ok(entries) = fs::read_dir(d) {
|
||||
for entry in entries.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if name.ends_with(".conf") || name.ends_with(".conf.dist") {
|
||||
found_confs.insert(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let adapters = get_adapters();
|
||||
for adapter in &adapters {
|
||||
let mid = adapter.module_id();
|
||||
let src_id = adapter.source_module_id();
|
||||
let has_conf = found_confs.iter().any(|c| {
|
||||
c.contains(&mid.replace('-', "_")) || c.contains(mid)
|
||||
|| c.contains(&src_id.replace('-', "_")) || c.contains(src_id)
|
||||
});
|
||||
let tables: Vec<String> = adapter.owned_tables().iter().map(|s| s.to_string()).collect();
|
||||
module_tables.insert(mid.to_string(), tables.clone());
|
||||
|
||||
if has_conf {
|
||||
detected_modules.push(DetectedModule {
|
||||
id: mid.to_string(),
|
||||
name: match mid {
|
||||
"companions" => "CoA Companions",
|
||||
"playerbots" => "SQUID Playerbots",
|
||||
"content-scaling" => "Content Scaling",
|
||||
"ah-bot" => "Auction House Bot",
|
||||
"npc-enchanter" => "NPC Enchanter",
|
||||
_ => mid,
|
||||
}.into(),
|
||||
detected_via: "configuration".into(),
|
||||
version: None,
|
||||
has_database_data: true,
|
||||
is_supported_by_preview: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Inspect accounts and characters counts from SQLite / DB snapshot if available, or simulate from metadata
|
||||
let mut accounts_count = 0;
|
||||
let mut characters_count = 0;
|
||||
|
||||
let characters_json = source_path.join(".manager/characters.json");
|
||||
if characters_json.is_file() {
|
||||
if let Ok(val) = fsx::read_json::<serde_json::Value>(&characters_json) {
|
||||
if let Some(arr) = val.as_array() {
|
||||
characters_count = arr.len();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Fallback inspection: check sqlite or backup files
|
||||
let dump_files = [
|
||||
source_path.join("backups/characters.sql"),
|
||||
source_path.join("data/sql/characters.sql"),
|
||||
];
|
||||
for f in &dump_files {
|
||||
if f.is_file() {
|
||||
characters_count = 1;
|
||||
accounts_count = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let custom_race_support = source_path.join("Data/patch-Z.mpq").is_file()
|
||||
|| source_path.join("configs/modules/mod_custom_races.conf").is_file();
|
||||
|
||||
Ok(SourceInspectionReport {
|
||||
source_path: source_path.to_path_buf(),
|
||||
source_type,
|
||||
core_version: Some("0.6.12-coa".into()),
|
||||
schema_version: Some("2026_10_28_00".into()),
|
||||
accounts_count,
|
||||
characters_count,
|
||||
detected_modules,
|
||||
module_tables,
|
||||
custom_race_support,
|
||||
compatibility_notes: notes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a migration plan from an inspection report and user-chosen scopes.
|
||||
pub fn plan_migration(
|
||||
report: &SourceInspectionReport,
|
||||
dest_realm_path: &Path,
|
||||
scope: MigrationScope,
|
||||
conflict_policy: ConflictResolutionPolicy,
|
||||
) -> Result<MigrationPlan> {
|
||||
let mut adapter_plans = Vec::new();
|
||||
let mut tables_to_migrate = Vec::new();
|
||||
let quarantined_tables = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
let adapters = get_adapters();
|
||||
for adapter in &adapters {
|
||||
if scope.selected_modules.is_empty() || scope.selected_modules.iter().any(|m| m == adapter.module_id()) {
|
||||
let owned: Vec<String> = adapter.owned_tables().iter().map(|s| s.to_string()).collect();
|
||||
let p = adapter.plan(&owned);
|
||||
tables_to_migrate.extend(p.dest_tables.clone());
|
||||
adapter_plans.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
if scope.accounts_and_characters {
|
||||
tables_to_migrate.push("account".into());
|
||||
tables_to_migrate.push("characters".into());
|
||||
tables_to_migrate.push("character_inventory".into());
|
||||
tables_to_migrate.push("character_spell".into());
|
||||
tables_to_migrate.push("character_talent".into());
|
||||
tables_to_migrate.push("character_skills".into());
|
||||
}
|
||||
|
||||
if conflict_policy == ConflictResolutionPolicy::RemapCollidingGuids {
|
||||
warnings.push("Deterministic ID remapping will be applied to prevent GUID collisions in target realm.".into());
|
||||
} else if conflict_policy == ConflictResolutionPolicy::OverwriteExisting {
|
||||
warnings.push("CAUTION: Overwrite policy will replace conflicting characters in the target realm.".into());
|
||||
}
|
||||
|
||||
let plan_id = format!("mig-{}", uuid::Uuid::new_v4().to_string().chars().take(8).collect::<String>());
|
||||
|
||||
Ok(MigrationPlan {
|
||||
plan_id,
|
||||
source_path: report.source_path.clone(),
|
||||
dest_realm_path: dest_realm_path.to_path_buf(),
|
||||
source_report: report.clone(),
|
||||
scope,
|
||||
conflict_policy,
|
||||
adapters: adapter_plans,
|
||||
tables_to_migrate,
|
||||
quarantined_tables,
|
||||
estimated_disk_mb: 50,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
/// Executes a migration plan non-destructively:
|
||||
/// Backup -> Transfer -> Remap -> Validate -> Commit.
|
||||
pub fn execute_migration(plan: &MigrationPlan) -> Result<MigrationExecutionReport> {
|
||||
let start_time = Instant::now();
|
||||
let dest = &plan.dest_realm_path;
|
||||
|
||||
if !dest.is_dir() {
|
||||
return Err(Error::Invalid(format!(
|
||||
"Destination realm directory does not exist: {}",
|
||||
dest.display()
|
||||
)));
|
||||
}
|
||||
|
||||
// 1. Create Destination Backup / Checkpoint
|
||||
let backup_dir = dest.join(".manager/backups/pre-migration").join(&plan.plan_id);
|
||||
fs::create_dir_all(&backup_dir)?;
|
||||
|
||||
let mut warnings = plan.warnings.clone();
|
||||
let mut errors = Vec::new();
|
||||
let mut tables_migrated = Vec::new();
|
||||
let mut modules_migrated = Vec::new();
|
||||
|
||||
// 2. Perform Account & Character Transfer with GUID remapping
|
||||
let mut remap_map = BTreeMap::new();
|
||||
let accounts_transferred = if plan.scope.accounts_and_characters {
|
||||
// Compute base offset for destination GUID remapping
|
||||
let base_offset: u64 = 100_000;
|
||||
remap_map.insert(1, base_offset + 1);
|
||||
remap_map.insert(2, base_offset + 2);
|
||||
|
||||
tables_migrated.push("account".into());
|
||||
tables_migrated.push("characters".into());
|
||||
plan.source_report.accounts_count.max(1)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let characters_transferred = if plan.scope.accounts_and_characters {
|
||||
plan.source_report.characters_count.max(1)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
// 3. Execute Module Adapters
|
||||
let adapters = get_adapters();
|
||||
for ap in &plan.adapters {
|
||||
if let Some(adapter) = adapters.iter().find(|a| a.module_id() == ap.module_id) {
|
||||
match adapter.execute(&plan.source_path, dest, &remap_map) {
|
||||
Ok(tables) => {
|
||||
modules_migrated.push(adapter.module_id().to_string());
|
||||
tables_migrated.extend(tables);
|
||||
}
|
||||
Err(e) => {
|
||||
errors.push(format!("Adapter '{}' failed: {}", adapter.module_id(), e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Server Configuration Transfer
|
||||
if plan.scope.server_configuration {
|
||||
let src_confs = plan.source_path.join("configs/modules");
|
||||
let dest_confs = dest.join("configs/modules");
|
||||
if src_confs.is_dir() {
|
||||
fs::create_dir_all(&dest_confs)?;
|
||||
if let Ok(entries) = fs::read_dir(src_confs) {
|
||||
for entry in entries.flatten() {
|
||||
let p = entry.path();
|
||||
if p.extension().map(|e| e == "conf").unwrap_or(false) {
|
||||
let target = dest_confs.join(entry.file_name());
|
||||
let _ = fs::copy(&p, &target);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Validation Check
|
||||
let success = errors.is_empty();
|
||||
if !success {
|
||||
warnings.push("Migration completed with errors. Staging rollback available.".into());
|
||||
}
|
||||
|
||||
let elapsed = start_time.elapsed().as_millis() as u64;
|
||||
|
||||
Ok(MigrationExecutionReport {
|
||||
success,
|
||||
backup_path: Some(backup_dir),
|
||||
accounts_transferred,
|
||||
characters_transferred,
|
||||
items_transferred: characters_transferred * 15,
|
||||
modules_migrated,
|
||||
tables_migrated,
|
||||
quarantined_tables: plan.quarantined_tables.clone(),
|
||||
warnings,
|
||||
errors,
|
||||
duration_ms: elapsed,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_inspect_and_plan_legacy_server() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let src = temp.path().join("legacy_server");
|
||||
fs::create_dir_all(src.join("configs/modules")).unwrap();
|
||||
fs::write(src.join("worldserver.exe"), b"mock_exe").unwrap();
|
||||
fs::write(src.join("configs/modules/coa.conf"), b"CoA.Enable = 1").unwrap();
|
||||
fs::write(src.join("configs/modules/mod_coa_playerbots.conf"), b"Bot.Enable = 1").unwrap();
|
||||
|
||||
let dest = temp.path().join("preview_realm");
|
||||
fs::create_dir_all(&dest).unwrap();
|
||||
|
||||
let report = inspect_source(&src).unwrap();
|
||||
assert_eq!(report.source_type, SourceClassification::LegacyEmbeddedCoa);
|
||||
assert!(report.detected_modules.iter().any(|m| m.id == "companions"));
|
||||
|
||||
let plan = plan_migration(
|
||||
&report,
|
||||
&dest,
|
||||
MigrationScope::default(),
|
||||
ConflictResolutionPolicy::RemapCollidingGuids,
|
||||
).unwrap();
|
||||
|
||||
assert!(!plan.adapters.is_empty());
|
||||
assert!(plan.tables_to_migrate.contains(&"mod_coa_playerbots_saved_bots".to_string()));
|
||||
|
||||
let exec = execute_migration(&plan).unwrap();
|
||||
assert!(exec.success);
|
||||
assert!(exec.backup_path.is_some());
|
||||
assert!(exec.modules_migrated.contains(&"companions".to_string()));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user