mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-23 03:25:56 +00:00
launcher (Rust): settings, state records, control lock, prepare
First part of moving Scripts/manage.py into coa-core (plan §17, PY-1). Same formats on disk as manage.py so both can run on one server: .state records, the byte-0 control lock msvcrt.locking takes, configuration.json. prepare renders byte-for-byte what manage.py renders (checked against the real script, COA_MANAGE_PY). State files are flushed to disk before they replace the old ones, and a damaged record counts as no process instead of failing every later start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b4dc30b84a
commit
ee43522019
5 files changed
+572
No files matched your search
@@ -0,0 +1,18 @@
|
||||
//! The repack launcher in Rust: what `Scripts/manage.py` does, without Python.
|
||||
//!
|
||||
//! Formats on disk stay exactly those of `manage.py`, so the two can be used on the same server during the move
|
||||
//! (an old `.bat` and a new Manager, or the other way round):
|
||||
//!
|
||||
//! * `.state/<service>.json` process records `{pid, exe, created}` (see [`crate::process::ProcessIdentity`]);
|
||||
//! * `.state/control.lock` one start/stop action at a time: byte 0 locked, as `msvcrt.locking` does;
|
||||
//! * `.state/control-owner.json`, `.state/configuration.json`, `.state/debug-logs.json`;
|
||||
//! * the rendered configs (`Core/configs/*.conf`, `mysql/my.ini`, `mysql/admin-client.ini`) byte for byte.
|
||||
//!
|
||||
//! 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 render;
|
||||
pub mod settings;
|
||||
pub mod state;
|
||||
|
||||
pub use settings::Settings;
|
||||
@@ -0,0 +1,267 @@
|
||||
//! `prepare`: the configuration files a repack runs with, rendered from `Settings/*.template` and
|
||||
//! `Settings/repack.json` (`manage.py prepare()`), byte for byte the same.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::launcher::{settings::Settings, state};
|
||||
|
||||
/// Services whose running process blocks moving the folder or changing ports.
|
||||
const SERVICES: [&str; 5] = ["mysql", "auth", "world", "supervisor", "relay"];
|
||||
|
||||
/// The root as the servers see it: forward slashes, and the short (8.3) form when the real one has non-Latin
|
||||
/// letters, which MySQL and the servers do not read reliably from their config files.
|
||||
pub fn native_root(root: &Path) -> Result<String> {
|
||||
let mut value = root.to_string_lossy().into_owned();
|
||||
if !value.is_ascii() {
|
||||
if let Some(short) = sys::short_path(root) {
|
||||
value = short;
|
||||
}
|
||||
}
|
||||
if !value.is_ascii() {
|
||||
return Err(Error::Invalid(
|
||||
"Extract the repack to a path with Latin letters, such as C:\\Games\\CoA-Repack.".into(),
|
||||
));
|
||||
}
|
||||
Ok(value.replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// Text as Python's text mode reads it: strict UTF-8, Windows and old Mac line ends turned into "\n".
|
||||
fn read_text(path: &Path) -> Result<String> {
|
||||
let bytes = std::fs::read(path)?;
|
||||
let text = String::from_utf8(bytes).map_err(|_| Error::Invalid(format!("{} is not UTF-8 text.", path.display())))?;
|
||||
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
|
||||
}
|
||||
|
||||
/// Text written as Python's text mode writes it on Windows: "\n" becomes "\r\n".
|
||||
fn windows_text(text: &str) -> Vec<u8> {
|
||||
if cfg!(windows) {
|
||||
text.replace('\n', "\r\n").into_bytes()
|
||||
} else {
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholders(line: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let bytes = line.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'@' {
|
||||
let mut j = i + 1;
|
||||
while j < bytes.len() && (bytes[j].is_ascii_alphabetic() || bytes[j] == b'_') {
|
||||
j += 1;
|
||||
}
|
||||
if j < bytes.len() && j > i + 1 && bytes[j] == b'@' {
|
||||
out.push(line[i..=j].to_string());
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn credentials(root: &Path) -> Result<(String, String)> {
|
||||
let v: serde_json::Value = crate::fsx::read_json(&root.join("Settings/database.json"))?;
|
||||
let good = |k: &str| {
|
||||
v.get(k)
|
||||
.and_then(|x| x.as_str())
|
||||
.filter(|s| s.len() == 48 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
.map(str::to_string)
|
||||
};
|
||||
match (good("rootPassword"), good("appPassword")) {
|
||||
(Some(r), Some(a)) => Ok((r, a)),
|
||||
_ => Err(Error::Invalid("Invalid packaged database configuration.".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render every file the repack's services read. Refuses while a service runs and the folder or the ports
|
||||
/// changed since the last render.
|
||||
pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
|
||||
let base = native_root(root)?;
|
||||
let signature = serde_json::json!({
|
||||
"root": root.to_string_lossy(),
|
||||
"ports": serde_json::Value::Object(config.port_map()),
|
||||
});
|
||||
let previous = state::dir(root).join("configuration.json");
|
||||
if previous.exists() {
|
||||
let recorded: Option<serde_json::Value> = crate::fsx::read_json(&previous).ok();
|
||||
if recorded.as_ref() != Some(&signature) && SERVICES.iter().any(|s| state::running(root, s).is_some()) {
|
||||
return Err(Error::Invalid("Stop this repack before moving its folder or changing its ports.".into()));
|
||||
}
|
||||
}
|
||||
let (root_password, app_password) = credentials(root)?;
|
||||
for folder in ["Core/configs/modules", "Core/Logs", "BugReport/reports", "BugReport/Logs", "mysql/logs", ".state"] {
|
||||
std::fs::create_dir_all(root.join(folder))?;
|
||||
}
|
||||
let mysql_port = config.mysql_port;
|
||||
let mut values: Vec<(&str, String)> = vec![
|
||||
("DATA", format!("{base}/Data")),
|
||||
("LOGS", format!("{base}/Core/Logs")),
|
||||
("ASCENSION_DBC", format!("{base}/Data/dbc/Ascension")),
|
||||
("MYSQL_EXE", format!("{base}/mysql/bin/mysql.exe")),
|
||||
("AUTH_PORT", config.auth_port.to_string()),
|
||||
("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")] {
|
||||
values.push((key, format!("127.0.0.1;{mysql_port};acore;{app_password};{db}")));
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
for (name, target) in [
|
||||
("authserver.conf", "Core/configs/authserver.conf"),
|
||||
("worldserver.conf", "Core/configs/worldserver.conf"),
|
||||
("mod_ascension_compat.conf", "Core/configs/modules/mod_ascension_compat.conf"),
|
||||
] {
|
||||
let mut text = read_text(&root.join("Settings").join(format!("{name}.template")))?;
|
||||
for (key, value) in &values {
|
||||
text = text.replace(&format!("@{key}@"), value);
|
||||
}
|
||||
let mut unresolved: Vec<String> = text
|
||||
.split('\n')
|
||||
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
|
||||
.flat_map(placeholders)
|
||||
.collect();
|
||||
unresolved.sort();
|
||||
unresolved.dedup();
|
||||
if !unresolved.is_empty() {
|
||||
return Err(Error::Invalid(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())?;
|
||||
written.push(root.join(target));
|
||||
}
|
||||
let files: [(&str, String); 3] = [
|
||||
(
|
||||
"Core/configs/modules/coa_bugreport.conf",
|
||||
format!(
|
||||
"# Managed by the repack launcher. Enabled whenever worldserver starts.\nCoABugReport.Enable = 1\nCoABugReport.SpoolDirectory = \"{base}/BugReport/reports\"\nCoABugReport.CooldownSeconds = 120\n"
|
||||
),
|
||||
),
|
||||
(
|
||||
"mysql/my.ini",
|
||||
format!(
|
||||
"[mysqld]\nbasedir=\"{base}/mysql\"\ndatadir=\"{base}/mysql/data\"\nport={mysql_port}\nbind-address=127.0.0.1\nmysqlx=0\ncharacter-set-server=utf8mb4\ncollation-server=utf8mb4_unicode_ci\nmax_allowed_packet=128M\ninnodb_buffer_pool_size=256M\nskip-log-bin\nlog-error=\"{base}/mysql/logs/mysql-error.log\"\npid-file=\"{base}/mysql/mysql.pid\"\n"
|
||||
),
|
||||
),
|
||||
(
|
||||
"mysql/admin-client.ini",
|
||||
format!(
|
||||
"[client]\nuser=root\npassword={root_password}\nhost=127.0.0.1\nport={mysql_port}\nprotocol=tcp\ndefault-character-set=utf8mb4\n"
|
||||
),
|
||||
),
|
||||
];
|
||||
for (rel, text) in files {
|
||||
std::fs::write(root.join(rel), windows_text(&text))?;
|
||||
written.push(root.join(rel));
|
||||
}
|
||||
state::write_json(&previous, &signature)?;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod sys {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
|
||||
|
||||
pub fn short_path(path: &Path) -> Option<String> {
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let mut buf = vec![0u16; 32768];
|
||||
let n = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) };
|
||||
(n > 0 && (n as usize) < buf.len()).then(|| String::from_utf16_lossy(&buf[..n as usize]))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod sys {
|
||||
pub fn short_path(_: &std::path::Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
pub(crate) fn fixture(root: &Path) {
|
||||
let w = |rel: &str, text: &[u8]| {
|
||||
let p = root.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, text).unwrap();
|
||||
};
|
||||
w("Settings/repack.json", br#"{"authPort": 3724, "mysqlPort": 3307, "raPassword": "e0c39beaa5c14128", "raPort": 3443, "raUsername": "COAMANAGER", "worldPort": 8085}"#);
|
||||
w("Settings/database.json", format!(r#"{{"rootPassword": "{}", "appPassword": "{}"}}"#, "a".repeat(48), "0123456789abcdef".repeat(3)).as_bytes());
|
||||
w("Settings/authserver.conf.template", b"[authserver]\r\nLoginDatabaseInfo = \"@LoginDatabaseInfo@\"\r\nRealmServerPort = @AUTH_PORT@\r\nLogsDir = \"@LOGS@\"\r\n# @NOT_A_VALUE@ in a comment is fine\r\n");
|
||||
w("Settings/worldserver.conf.template", "[worldserver]\nDataDir = \"@DATA@\"\nWorldServerPort = @WORLD_PORT@\nRa.Port = @RA_PORT@\nWorldDatabaseInfo = \"@WorldDatabaseInfo@\"\nCharacterDatabaseInfo = \"@CharacterDatabaseInfo@\"\nMySQLExecutable = \"@MYSQL_EXE@\"\nMotd = \"Ünïcode stays\"\n".as_bytes());
|
||||
w("Settings/mod_ascension_compat.conf.template", b"Ascension.DbcDir = \"@ASCENSION_DBC@\"\rOld.Mac = 1\r");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholders_left_outside_comments_are_refused() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
fixture(d.path());
|
||||
std::fs::write(d.path().join("Settings/worldserver.conf.template"), "A = @UNKNOWN@\n").unwrap();
|
||||
let cfg = Settings::load(d.path(), 0).unwrap();
|
||||
let err = prepare(d.path(), &cfg).unwrap_err().to_string();
|
||||
assert!(err.contains("worldserver.conf.template: @UNKNOWN@"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_password_file_is_refused() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
fixture(d.path());
|
||||
std::fs::write(d.path().join("Settings/database.json"), r#"{"rootPassword":"short","appPassword":"x"}"#).unwrap();
|
||||
let cfg = Settings::load(d.path(), 0).unwrap();
|
||||
assert!(prepare(d.path(), &cfg).unwrap_err().to_string().contains("Invalid packaged database configuration"));
|
||||
}
|
||||
|
||||
/// Byte-for-byte the same files as the Python launcher. COA_MANAGE_PY = a manage.py to compare with (taken from
|
||||
/// coa-server-build); skipped without it.
|
||||
#[test]
|
||||
fn renders_exactly_what_manage_py_renders() {
|
||||
let Ok(manage) = std::env::var("COA_MANAGE_PY") else { return };
|
||||
let python = std::env::var("COA_PYTHON").unwrap_or_else(|_| "python".into());
|
||||
let rust = tempfile::tempdir().unwrap();
|
||||
let py = tempfile::tempdir().unwrap();
|
||||
for d in [rust.path(), py.path()] {
|
||||
fixture(d);
|
||||
}
|
||||
std::fs::create_dir_all(py.path().join("Scripts")).unwrap();
|
||||
std::fs::copy(&manage, py.path().join("Scripts/manage.py")).unwrap();
|
||||
// manage.py imports squid_playerbots lazily; prepare does not need it.
|
||||
let out = std::process::Command::new(&python)
|
||||
.args(["-I", "-B"])
|
||||
.arg(py.path().join("Scripts/manage.py"))
|
||||
.arg("prepare")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||
let cfg = Settings::load(rust.path(), 0).unwrap();
|
||||
let written = prepare(rust.path(), &cfg).unwrap();
|
||||
let root_text = |p: &Path, base: &Path| {
|
||||
let n = native_root(base).unwrap();
|
||||
String::from_utf8(std::fs::read(p).unwrap()).unwrap().replace(&n, "<ROOT>")
|
||||
};
|
||||
for file in &written {
|
||||
let rel = file.strip_prefix(rust.path()).unwrap();
|
||||
assert_eq!(
|
||||
root_text(file, rust.path()),
|
||||
root_text(&py.path().join(rel), py.path()),
|
||||
"{} differs",
|
||||
rel.display()
|
||||
);
|
||||
}
|
||||
let sig = |base: &Path| -> serde_json::Value {
|
||||
let mut v: serde_json::Value = crate::fsx::read_json(&base.join(".state/configuration.json")).unwrap();
|
||||
v["root"] = serde_json::Value::Null;
|
||||
v
|
||||
};
|
||||
assert_eq!(sig(rust.path()), sig(py.path()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! `Settings/repack.json`: ports and the console login of one repack (`manage.py settings()`).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
pub const PORT_KEYS: [&str; 4] = ["mysqlPort", "authPort", "worldPort", "raPort"];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Settings {
|
||||
pub mysql_port: u16,
|
||||
pub auth_port: u16,
|
||||
pub world_port: u16,
|
||||
pub ra_port: u16,
|
||||
pub ra_username: String,
|
||||
pub ra_password: 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>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// Read `Settings/repack.json`, with every port moved by `offset` (a second world of the same server runs on
|
||||
/// shifted ports). The same checks as `manage.py`: integer ports in 1025..65535 after the offset, all
|
||||
/// different.
|
||||
pub fn load(root: &Path, offset: i32) -> Result<Settings> {
|
||||
let bytes = std::fs::read(root.join("Settings/repack.json"))?;
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
|
||||
let raw: serde_json::Map<String, serde_json::Value> =
|
||||
serde_json::from_str(text).map_err(|e| Error::Invalid(format!("Settings/repack.json: {e}")))?;
|
||||
let mut ports = [0u16; 4];
|
||||
for (i, key) in PORT_KEYS.iter().enumerate() {
|
||||
// Python's `type(value) is not int` refuses booleans and floats alike.
|
||||
let value = raw.get(*key).and_then(|v| v.as_i64()).filter(|_| raw[*key].is_i64() || raw[*key].is_u64());
|
||||
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())),
|
||||
}
|
||||
}
|
||||
let mut unique = ports.to_vec();
|
||||
unique.sort_unstable();
|
||||
unique.dedup();
|
||||
if unique.len() != 4 {
|
||||
return Err(Error::Invalid("Each service needs a different port.".into()));
|
||||
}
|
||||
let text_of = |k: &str| raw.get(k).and_then(|v| v.as_str()).unwrap_or_default().to_string();
|
||||
Ok(Settings {
|
||||
mysql_port: ports[0],
|
||||
auth_port: ports[1],
|
||||
world_port: ports[2],
|
||||
ra_port: ports[3],
|
||||
ra_username: text_of("raUsername"),
|
||||
ra_password: text_of("raPassword"),
|
||||
raw,
|
||||
})
|
||||
}
|
||||
|
||||
/// `{"mysqlPort": .., "authPort": .., "worldPort": .., "raPort": ..}` as `manage.py` records it in
|
||||
/// `.state/configuration.json` (the keys of repack.json ending in "Port", in the file's order).
|
||||
pub fn port_map(&self) -> serde_json::Map<String, serde_json::Value> {
|
||||
let shifted = [self.mysql_port, self.auth_port, self.world_port, self.ra_port];
|
||||
let mut out = serde_json::Map::new();
|
||||
for key in self.raw.keys().filter(|k| k.ends_with("Port")) {
|
||||
let value = PORT_KEYS
|
||||
.iter()
|
||||
.position(|p| p == key)
|
||||
.map(|i| serde_json::Value::from(shifted[i]))
|
||||
.unwrap_or_else(|| self.raw[key].clone());
|
||||
out.insert(key.clone(), value);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(dir: &Path, text: &str) {
|
||||
std::fs::create_dir_all(dir.join("Settings")).unwrap();
|
||||
std::fs::write(dir.join("Settings/repack.json"), text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ports_are_checked_like_the_python_launcher() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
write(d.path(), r#"{"mysqlPort":3307,"authPort":3724,"worldPort":8085,"raPort":3443,"raUsername":"U","raPassword":"P"}"#);
|
||||
let s = Settings::load(d.path(), 0).unwrap();
|
||||
assert_eq!((s.mysql_port, s.auth_port, s.world_port, s.ra_port), (3307, 3724, 8085, 3443));
|
||||
assert_eq!(s.ra_username, "U");
|
||||
let shifted = Settings::load(d.path(), 10).unwrap();
|
||||
assert_eq!(shifted.world_port, 8095);
|
||||
assert_eq!(shifted.port_map()["worldPort"], serde_json::json!(8095));
|
||||
|
||||
for bad in [
|
||||
r#"{"mysqlPort":1024,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||
r#"{"mysqlPort":"3307","authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||
r#"{"mysqlPort":3307.0,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||
r#"{"mysqlPort":true,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||
r#"{"mysqlPort":3307,"authPort":3307,"worldPort":8085,"raPort":3443}"#,
|
||||
r#"{"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||
] {
|
||||
write(d.path(), bad);
|
||||
assert!(Settings::load(d.path(), 0).is_err(), "{bad}");
|
||||
}
|
||||
write(d.path(), "\u{feff}{\"mysqlPort\":3307,\"authPort\":3724,\"worldPort\":8085,\"raPort\":65535}");
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! `.state/`: which processes belong to this repack, and the one-action-at-a-time lock.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
use crate::process::{self, ProcessIdentity};
|
||||
|
||||
pub fn dir(root: &Path) -> PathBuf {
|
||||
root.join(".state")
|
||||
}
|
||||
|
||||
/// Written like `manage.py atomic_json`: two-space JSON and a newline, now flushed to disk before it replaces
|
||||
/// the old file.
|
||||
pub fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<()> {
|
||||
let mut text = serde_json::to_string_pretty(value)?;
|
||||
text.push('\n');
|
||||
fsx::atomic_write(path, text.as_bytes())
|
||||
}
|
||||
|
||||
/// The recorded process of `name` when it is still that process (same executable and start time). A missing,
|
||||
/// empty or damaged record is no process: `manage.py` failed on those, and every later start with it.
|
||||
pub fn running(root: &Path, name: &str) -> Option<ProcessIdentity> {
|
||||
let record = process::read_state_record(root, name)?;
|
||||
process::is_alive(&record).then_some(record)
|
||||
}
|
||||
|
||||
/// Record the process `pid` as `name`. Fails when it has already exited.
|
||||
pub fn record(root: &Path, name: &str, pid: u32) -> Result<ProcessIdentity> {
|
||||
let identity = process::identity(pid)
|
||||
.ok_or_else(|| Error::Invalid(format!("{name} exited during startup; check its log.")))?;
|
||||
write_json(&dir(root).join(format!("{name}.json")), &identity)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
/// Held while one start/stop action runs. Byte 0 of `.state/control.lock` is locked, exactly the region
|
||||
/// `msvcrt.locking(fd, LK_NBLCK, 1)` locks in `manage.py`, so a Python launcher and this one exclude each other.
|
||||
pub struct ControlLock {
|
||||
file: File,
|
||||
owner: PathBuf,
|
||||
}
|
||||
|
||||
impl ControlLock {
|
||||
/// Wait up to `wait` for the lock. `action` is recorded for whoever waits next ("start-all", ...).
|
||||
pub fn acquire(root: &Path, action: &str, wait: Duration, progress: &dyn Fn(&str)) -> Result<ControlLock> {
|
||||
let state = dir(root);
|
||||
std::fs::create_dir_all(&state)?;
|
||||
let mut file = OpenOptions::new().read(true).append(true).create(true).open(state.join("control.lock"))?;
|
||||
if file.seek(SeekFrom::End(0))? == 0 {
|
||||
file.write_all(b"0")?;
|
||||
file.flush()?;
|
||||
}
|
||||
let owner = state.join("control-owner.json");
|
||||
let deadline = Instant::now() + wait;
|
||||
let mut announced = false;
|
||||
loop {
|
||||
if sys::try_lock(&file)? {
|
||||
break;
|
||||
}
|
||||
let detail = match fsx::read_json::<serde_json::Value>(&owner) {
|
||||
Ok(v) if v.get("pid").is_some() && v.get("action").is_some() => {
|
||||
format!(" PID {}, action {}.", v["pid"], v["action"].as_str().unwrap_or(""))
|
||||
}
|
||||
_ => " Owner information is unavailable.".into(),
|
||||
};
|
||||
if Instant::now() >= deadline {
|
||||
return Err(Error::Invalid(format!("Another start/stop action is in progress.{detail}")));
|
||||
}
|
||||
if !announced {
|
||||
progress(&format!("Waiting for the current server action.{detail}"));
|
||||
announced = true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
let started = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs_f64())
|
||||
.unwrap_or(0.0);
|
||||
let lock = ControlLock { file, owner };
|
||||
write_json(
|
||||
&lock.owner,
|
||||
&serde_json::json!({ "pid": std::process::id(), "action": action, "started": started }),
|
||||
)?;
|
||||
Ok(lock)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ControlLock {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.owner);
|
||||
sys::unlock(&self.file);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod sys {
|
||||
use std::fs::File;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::{LockFile, UnlockFile};
|
||||
|
||||
/// `LockFile` on byte 0, length 1: the call `msvcrt.locking` makes. Non-blocking.
|
||||
pub fn try_lock(file: &File) -> std::io::Result<bool> {
|
||||
let ok = unsafe { LockFile(file.as_raw_handle() as _, 0, 0, 1, 0) };
|
||||
if ok != 0 {
|
||||
return Ok(true);
|
||||
}
|
||||
let err = std::io::Error::last_os_error();
|
||||
// ERROR_LOCK_VIOLATION (33): someone else holds it.
|
||||
if err.raw_os_error() == Some(33) {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unlock(file: &File) {
|
||||
unsafe {
|
||||
UnlockFile(file.as_raw_handle() as _, 0, 0, 1, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod sys {
|
||||
use std::fs::File;
|
||||
pub fn try_lock(_: &File) -> std::io::Result<bool> {
|
||||
Ok(true)
|
||||
}
|
||||
pub fn unlock(_: &File) {}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_damaged_record_is_no_process() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir(d.path())).unwrap();
|
||||
std::fs::write(dir(d.path()).join("mysql.json"), [0u8; 116]).unwrap();
|
||||
assert!(running(d.path(), "mysql").is_none());
|
||||
std::fs::write(dir(d.path()).join("auth.json"), b"").unwrap();
|
||||
assert!(running(d.path(), "auth").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_process_is_recorded_and_found_running() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let me = record(d.path(), "probe", std::process::id()).unwrap();
|
||||
assert_eq!(running(d.path(), "probe"), Some(me));
|
||||
let text = std::fs::read_to_string(dir(d.path()).join("probe.json")).unwrap();
|
||||
assert!(text.starts_with("{\n \"pid\": ") && text.ends_with("}\n"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_action_at_a_time() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let first = ControlLock::acquire(d.path(), "start-all", Duration::from_secs(1), &|_| {}).unwrap();
|
||||
let owner: serde_json::Value = fsx::read_json(&dir(d.path()).join("control-owner.json")).unwrap();
|
||||
assert_eq!(owner["action"], "start-all");
|
||||
let said = std::sync::Mutex::new(Vec::new());
|
||||
let second = ControlLock::acquire(d.path(), "stop-all", Duration::from_millis(600), &|m| said.lock().unwrap().push(m.to_string()));
|
||||
if cfg!(windows) {
|
||||
let err = second.err().expect("the second action waits and gives up").to_string();
|
||||
assert!(err.contains("Another start/stop action is in progress") && err.contains("start-all"), "{err}");
|
||||
assert_eq!(said.lock().unwrap().len(), 1);
|
||||
}
|
||||
drop(first);
|
||||
assert!(!dir(d.path()).join("control-owner.json").exists());
|
||||
ControlLock::acquire(d.path(), "stop-all", Duration::from_secs(1), &|_| {}).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ pub mod glue_config;
|
||||
pub mod health;
|
||||
pub mod install;
|
||||
pub mod layout;
|
||||
pub mod launcher;
|
||||
pub mod logging;
|
||||
pub mod server_logging;
|
||||
pub mod manifest;
|
||||
|
||||
Reference in new issue
Block a user