Merge perf/sp-open-to-lan (with main) into perf/sp-server-state
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -109,18 +109,18 @@ jobs:
|
||||
- name: ALSA and udev headers
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
|
||||
- name: Build the client, horizon-ctl and horizon-prepare
|
||||
run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
|
||||
- name: Build the client, horizon-ctl, horizon-prepare and horizon-server
|
||||
run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server
|
||||
- name: Every program the release folder takes was built
|
||||
run: |
|
||||
for binary in horizon-client horizon-ctl horizon-prepare; do
|
||||
for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do
|
||||
test -f "target/release/$binary${{ matrix.exe }}" || { echo "::error::target/release/$binary${{ matrix.exe }} is missing"; exit 1; }
|
||||
done
|
||||
- name: Only system libraries
|
||||
# Windows: no non-system DLL (a "DLL not found" dialog on some players' machines). Linux: the standard
|
||||
# loader and libraries every desktop distribution has. macOS: only the system's own libraries.
|
||||
run: |
|
||||
for binary in horizon-client horizon-ctl horizon-prepare; do
|
||||
for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do
|
||||
file="target/release/$binary${{ matrix.exe }}"
|
||||
if [[ "$RUNNER_OS" == macOS ]]; then
|
||||
others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true)
|
||||
@@ -137,6 +137,7 @@ jobs:
|
||||
"$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null
|
||||
"$bin/horizon-prepare${{ matrix.exe }}" --version
|
||||
"$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir'
|
||||
"$bin/horizon-server${{ matrix.exe }}" --version
|
||||
- name: Tools from the runner
|
||||
if: runner.environment == 'self-hosted'
|
||||
run: bash tools/ci/runner-env.sh
|
||||
|
||||
Generated
+35
@@ -1398,6 +1398,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-bots"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-protocol",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-client"
|
||||
version = "0.1.0"
|
||||
@@ -1417,6 +1425,7 @@ dependencies = [
|
||||
"horizon-friends",
|
||||
"horizon-mods",
|
||||
"horizon-protocol",
|
||||
"horizon-server-files",
|
||||
"horizon-shaderpack",
|
||||
"horizon-telemetry",
|
||||
"horizon-theme",
|
||||
@@ -1541,6 +1550,31 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-server"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-bench",
|
||||
"horizon-server-files",
|
||||
"libc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml",
|
||||
"toml_edit",
|
||||
"windows-sys 0.61.2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-server-files"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-core",
|
||||
"horizon-protocol",
|
||||
"horizon-world",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "horizon-shaderpack"
|
||||
version = "0.1.0"
|
||||
@@ -3739,6 +3773,7 @@ dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
exclude = ["launcher", "crates/horizon-telemetry-server"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
|
||||
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "horizon-bots"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Load-test bots for Minecraft Java Edition 26.3 servers (docs/server.md, section 9)"
|
||||
|
||||
[dependencies]
|
||||
horizon-protocol = { path = "../horizon-protocol" }
|
||||
serde_json = "1.0.151"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,589 @@
|
||||
//! `horizon-bots`: load-test bots for any Minecraft Java Edition 26.3 server, vanilla, Paper or Horizon
|
||||
//! (docs/server.md, section 9). Each bot logs in offline, goes through configuration as vanilla's client
|
||||
//! does, answers keep-alives and pings, accepts teleports, acknowledges chunk batches, and moves at 20 Hz.
|
||||
//!
|
||||
//! Bots fly a little above the ground, so the server must give them creative mode (`gamemode=creative`
|
||||
//! and `force-gamemode=true`): they never touch blocks, so they need no world of their own, and no server
|
||||
//! can refuse their moves for walking into terrain. Every behaviour is deterministic from `--seed`.
|
||||
//!
|
||||
//! horizon-bots --server 127.0.0.1:25565 --bots 25 --behaviour mixed --seconds 360 --report bots.json
|
||||
//!
|
||||
//! It prints one JSON line a second (bots online, chunks received) and writes a summary with `--report`.
|
||||
|
||||
use horizon_protocol::{
|
||||
PROTOCOL_VERSION,
|
||||
buf::{Reader, Writer},
|
||||
connection::{ConnWriter, Connection},
|
||||
crypto::offline_uuid,
|
||||
ids,
|
||||
packets::{
|
||||
Empty, configuration,
|
||||
handshake::{self, Intention},
|
||||
login::{self, ServerHello},
|
||||
play,
|
||||
},
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const HELP: &str = "\
|
||||
horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline mode, creative)
|
||||
|
||||
--server HOST:PORT default 127.0.0.1:25565
|
||||
--bots N default 10
|
||||
--behaviour B idle, walk, explore or mixed (60 % walk, 20 % explore, 20 % idle); default mixed
|
||||
--join-every SECONDS default 1
|
||||
--seconds N how long to run after the first bot joins; default 60
|
||||
--view-distance N what the bots ask for; default 10
|
||||
--seed N default 12345
|
||||
--name PREFIX bot names: PREFIX0, PREFIX1...; default Bot
|
||||
--report FILE a JSON summary at the end
|
||||
";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Behaviour {
|
||||
Idle,
|
||||
Walk,
|
||||
Explore,
|
||||
}
|
||||
|
||||
impl Behaviour {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Idle => "idle",
|
||||
Self::Walk => "walk",
|
||||
Self::Explore => "explore",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Options {
|
||||
host: String,
|
||||
port: u16,
|
||||
bots: usize,
|
||||
behaviour: String,
|
||||
join_every: f64,
|
||||
seconds: u64,
|
||||
view_distance: i8,
|
||||
seed: u64,
|
||||
name: String,
|
||||
report: Option<String>,
|
||||
}
|
||||
|
||||
fn options() -> Result<Options, String> {
|
||||
let mut o = Options {
|
||||
host: "127.0.0.1".into(),
|
||||
port: 25565,
|
||||
bots: 10,
|
||||
behaviour: "mixed".into(),
|
||||
join_every: 1.0,
|
||||
seconds: 60,
|
||||
view_distance: 10,
|
||||
seed: 12345,
|
||||
name: "Bot".into(),
|
||||
report: None,
|
||||
};
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "-h" || arg == "--help" {
|
||||
print!("{HELP}");
|
||||
std::process::exit(0);
|
||||
}
|
||||
let value = args.next().ok_or(format!("{arg} needs a value"))?;
|
||||
let number = |what: &str| format!("{arg} needs {what}, not {value:?}");
|
||||
match arg.as_str() {
|
||||
"--server" => {
|
||||
let (host, port) = value.rsplit_once(':').unwrap_or((&value, "25565"));
|
||||
o.host = host.into();
|
||||
o.port = port.parse().map_err(|_| number("a port"))?;
|
||||
}
|
||||
"--bots" => o.bots = value.parse().map_err(|_| number("a number"))?,
|
||||
"--behaviour" => o.behaviour = value,
|
||||
"--join-every" => o.join_every = value.parse().map_err(|_| number("seconds"))?,
|
||||
"--seconds" => o.seconds = value.parse().map_err(|_| number("seconds"))?,
|
||||
"--view-distance" => o.view_distance = value.parse().map_err(|_| number("2 to 32"))?,
|
||||
"--seed" => o.seed = value.parse().map_err(|_| number("a number"))?,
|
||||
"--name" => o.name = value,
|
||||
"--report" => o.report = Some(value),
|
||||
_ => return Err(format!("unknown option {arg}; --help lists them")),
|
||||
}
|
||||
}
|
||||
if !["idle", "walk", "explore", "mixed"].contains(&o.behaviour.as_str()) {
|
||||
return Err(format!(
|
||||
"--behaviour {}: use idle, walk, explore or mixed",
|
||||
o.behaviour
|
||||
));
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// What one bot is doing, shared between its reader and its ticks.
|
||||
#[derive(Default)]
|
||||
struct Bot {
|
||||
online: AtomicBool,
|
||||
chunks: AtomicU64,
|
||||
/// Where the server last put the bot (a teleport), to start from.
|
||||
teleport: Mutex<Option<[f64; 3]>>,
|
||||
error: Mutex<Option<String>>,
|
||||
joined_after_ms: AtomicU64,
|
||||
}
|
||||
|
||||
/// A small deterministic generator (SplitMix64), so every run moves the bots the same way.
|
||||
struct Random(u64);
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
fn unit(&mut self) -> f64 {
|
||||
(self.next() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
fn raw(id: i32, write: impl FnOnce(&mut Writer)) -> Vec<u8> {
|
||||
let mut w = Writer::new();
|
||||
w.varint(id);
|
||||
write(&mut w);
|
||||
w.data
|
||||
}
|
||||
|
||||
fn err(e: impl std::fmt::Display) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
/// Handshake, offline login and configuration; returns the connection in the play state.
|
||||
fn join(o: &Options, name: &str) -> Result<Connection, String> {
|
||||
let mut c = Connection::connect(&o.host, o.port, Duration::from_secs(10)).map_err(err)?;
|
||||
c.send(
|
||||
&handshake::Serverbound::Intention(Intention {
|
||||
protocol: PROTOCOL_VERSION,
|
||||
host: o.host.clone(),
|
||||
port: o.port,
|
||||
intent: handshake::LOGIN,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?;
|
||||
c.send(
|
||||
&login::Serverbound::Hello(ServerHello {
|
||||
name: name.into(),
|
||||
uuid: offline_uuid(name),
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?;
|
||||
loop {
|
||||
let (id, body) = c.recv().map_err(err)?;
|
||||
match login::Clientbound::decode(id, &body).map_err(err)? {
|
||||
login::Clientbound::Compression(p) => c.set_compression(p.threshold),
|
||||
login::Clientbound::LoginFinished(_) => {
|
||||
c.send(&login::Serverbound::LoginAcknowledged(Empty).encode())
|
||||
.map_err(err)?;
|
||||
break;
|
||||
}
|
||||
login::Clientbound::Disconnect(p) => return Err(format!("refused: {}", p.reason_json)),
|
||||
login::Clientbound::Hello(_) => {
|
||||
return Err("the server is in online mode; bots need online-mode=false".into());
|
||||
}
|
||||
login::Clientbound::CustomQuery(p) => c
|
||||
.send(
|
||||
&login::Serverbound::CustomQueryAnswer(login::CustomQueryAnswer {
|
||||
transaction: p.transaction,
|
||||
payload: None,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?,
|
||||
login::Clientbound::CookieRequest(p) => c
|
||||
.send(
|
||||
&login::Serverbound::CookieResponse(login::CookieResponse {
|
||||
key: p.key,
|
||||
payload: None,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?,
|
||||
login::Clientbound::Unknown(..) => {}
|
||||
}
|
||||
}
|
||||
use ids::configuration::clientbound as cb;
|
||||
c.send(
|
||||
&configuration::Serverbound::ClientInformation(configuration::ClientInformation::new(
|
||||
o.view_distance,
|
||||
))
|
||||
.encode(),
|
||||
)
|
||||
.map_err(err)?;
|
||||
loop {
|
||||
let (id, body) = c.recv().map_err(err)?;
|
||||
let reply = match id {
|
||||
cb::SELECT_KNOWN_PACKS
|
||||
| cb::KEEP_ALIVE
|
||||
| cb::PING
|
||||
| cb::CODE_OF_CONDUCT
|
||||
| cb::COOKIE_REQUEST
|
||||
| cb::DISCONNECT
|
||||
| cb::FINISH_CONFIGURATION => {
|
||||
match configuration::Clientbound::decode(id, &body).map_err(err)? {
|
||||
configuration::Clientbound::SelectKnownPacks(p) => {
|
||||
configuration::Serverbound::SelectKnownPacks(p)
|
||||
}
|
||||
configuration::Clientbound::KeepAlive(p) => {
|
||||
configuration::Serverbound::KeepAlive(p)
|
||||
}
|
||||
configuration::Clientbound::Ping(p) => configuration::Serverbound::Pong(p),
|
||||
configuration::Clientbound::CodeOfConduct(_) => {
|
||||
configuration::Serverbound::AcceptCodeOfConduct(Empty)
|
||||
}
|
||||
configuration::Clientbound::CookieRequest(p) => {
|
||||
configuration::Serverbound::CookieResponse(configuration::CookieResponse {
|
||||
key: p.key,
|
||||
payload: None,
|
||||
})
|
||||
}
|
||||
configuration::Clientbound::Disconnect(_) => {
|
||||
return Err("disconnected during configuration".into());
|
||||
}
|
||||
configuration::Clientbound::FinishConfiguration(_) => {
|
||||
c.send(&configuration::Serverbound::FinishConfiguration(Empty).encode())
|
||||
.map_err(err)?;
|
||||
return Ok(c);
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
c.send(&reply.encode()).map_err(err)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the play state: answers what a client must answer, counts chunks, records teleports.
|
||||
fn read(
|
||||
mut reader: horizon_protocol::connection::ConnReader,
|
||||
writer: Arc<Mutex<ConnWriter>>,
|
||||
bot: Arc<Bot>,
|
||||
) {
|
||||
use ids::play::clientbound as cb;
|
||||
use ids::play::serverbound as sb;
|
||||
let send = |body: Vec<u8>| writer.lock().unwrap().send(&body);
|
||||
loop {
|
||||
let (id, body) = match reader.recv() {
|
||||
Ok(packet) => packet,
|
||||
Err(e) => {
|
||||
if bot.online.swap(false, Ordering::SeqCst) {
|
||||
*bot.error.lock().unwrap() = Some(e.to_string());
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut r = Reader::new(&body);
|
||||
let sent = match id {
|
||||
cb::KEEP_ALIVE => match r.i64() {
|
||||
Ok(v) => send(raw(sb::KEEP_ALIVE, |w| w.i64(v))),
|
||||
Err(_) => Ok(()),
|
||||
},
|
||||
cb::PING => match r.i32() {
|
||||
Ok(v) => send(raw(sb::PONG, |w| w.i32(v))),
|
||||
Err(_) => Ok(()),
|
||||
},
|
||||
cb::LEVEL_CHUNK_WITH_LIGHT => {
|
||||
bot.chunks.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
cb::CHUNK_BATCH_FINISHED => send(
|
||||
play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived {
|
||||
chunks_per_tick: 25.0,
|
||||
})
|
||||
.encode(),
|
||||
),
|
||||
cb::PLAYER_POSITION => match play::Clientbound::decode(id, &body) {
|
||||
Ok(play::Clientbound::PlayerPosition(p)) => {
|
||||
let mut at = bot.teleport.lock().unwrap();
|
||||
let previous = at.unwrap_or([0.0; 3]);
|
||||
// Relative flags: X 1, Y 2, Z 4.
|
||||
let pos: [f64; 3] = std::array::from_fn(|i| {
|
||||
if p.relatives & (1 << i) != 0 {
|
||||
previous[i] + p.position[i]
|
||||
} else {
|
||||
p.position[i]
|
||||
}
|
||||
});
|
||||
*at = Some(pos);
|
||||
send(
|
||||
play::Serverbound::AcceptTeleportation(play::AcceptTeleportation {
|
||||
id: p.teleport,
|
||||
x: pos[0],
|
||||
y: pos[1],
|
||||
z: pos[2],
|
||||
yaw: p.yaw,
|
||||
pitch: p.pitch,
|
||||
})
|
||||
.encode(),
|
||||
)
|
||||
}
|
||||
_ => Ok(()),
|
||||
},
|
||||
cb::DISCONNECT | cb::START_CONFIGURATION => {
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
*bot.error.lock().unwrap() = Some(if id == cb::DISCONNECT {
|
||||
format!(
|
||||
"disconnected: {}",
|
||||
String::from_utf8_lossy(&body)
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.collect::<String>()
|
||||
)
|
||||
} else {
|
||||
"sent back to configuration".into()
|
||||
});
|
||||
return;
|
||||
}
|
||||
_ => Ok(()),
|
||||
};
|
||||
if sent.is_err() {
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One bot: join, then move every 50 ms until `until`.
|
||||
fn run_bot(
|
||||
o: Arc<Options>,
|
||||
index: usize,
|
||||
behaviour: Behaviour,
|
||||
bot: Arc<Bot>,
|
||||
until: Arc<Mutex<Option<Instant>>>,
|
||||
) {
|
||||
let name = format!("{}{index}", o.name);
|
||||
let asked = Instant::now();
|
||||
let connection = match join(&o, &name) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
*bot.error.lock().unwrap() = Some(e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (reader, writer) = connection.split();
|
||||
let writer = Arc::new(Mutex::new(writer));
|
||||
bot.online.store(true, Ordering::SeqCst);
|
||||
{
|
||||
let (writer, bot) = (writer.clone(), bot.clone());
|
||||
thread::spawn(move || read(reader, writer, bot));
|
||||
}
|
||||
use ids::play::serverbound as sb;
|
||||
// Wait for the spawn position.
|
||||
let spawn = loop {
|
||||
if let Some(at) = *bot.teleport.lock().unwrap() {
|
||||
break at;
|
||||
}
|
||||
if !bot.online.load(Ordering::SeqCst) || asked.elapsed() > Duration::from_secs(60) {
|
||||
if bot.error.lock().unwrap().is_none() {
|
||||
*bot.error.lock().unwrap() = Some("no spawn position within 60 s".into());
|
||||
}
|
||||
return;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
bot.joined_after_ms
|
||||
.store(asked.elapsed().as_millis() as u64, Ordering::SeqCst);
|
||||
let send = |body: Vec<u8>| writer.lock().unwrap().send(&body).is_ok();
|
||||
send(raw(sb::PLAYER_LOADED, |_| {}));
|
||||
let mut random = Random(o.seed ^ (index as u64).wrapping_mul(0x2545_F491_4F6C_DD1D));
|
||||
let mut pos = spawn;
|
||||
let cruise = spawn[1] + 24.0;
|
||||
let heading = random.unit() * std::f64::consts::TAU;
|
||||
let mut target = pos;
|
||||
let mut next = Instant::now();
|
||||
loop {
|
||||
if until.lock().unwrap().is_some_and(|u| Instant::now() >= u)
|
||||
|| !bot.online.load(Ordering::SeqCst)
|
||||
{
|
||||
break;
|
||||
}
|
||||
// A teleport from the server wins over where the bot thought it was.
|
||||
if let Some(at) = bot.teleport.lock().unwrap().take() {
|
||||
pos = at;
|
||||
}
|
||||
if pos[1] < cruise {
|
||||
pos[1] = (pos[1] + 0.5).min(cruise);
|
||||
} else {
|
||||
match behaviour {
|
||||
Behaviour::Idle => {}
|
||||
Behaviour::Walk => {
|
||||
let (dx, dz) = (target[0] - pos[0], target[2] - pos[2]);
|
||||
let distance = dx.hypot(dz);
|
||||
if distance < 1.0 {
|
||||
let angle = random.unit() * std::f64::consts::TAU;
|
||||
let reach = 8.0 + random.unit() * 40.0;
|
||||
target = [
|
||||
spawn[0] + angle.cos() * reach,
|
||||
cruise,
|
||||
spawn[2] + angle.sin() * reach,
|
||||
];
|
||||
} else {
|
||||
// Sprinting: 5.6 blocks a second.
|
||||
let step = 0.28_f64.min(distance);
|
||||
pos[0] += dx / distance * step;
|
||||
pos[2] += dz / distance * step;
|
||||
}
|
||||
}
|
||||
Behaviour::Explore => {
|
||||
// Flying fast in creative: about 22 blocks a second, which keeps new chunks coming.
|
||||
pos[0] += heading.cos() * 1.1;
|
||||
pos[2] += heading.sin() * 1.1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let ok = send(
|
||||
play::Serverbound::MovePlayerPos(play::MovePlayerPos {
|
||||
x: pos[0],
|
||||
y: pos[1],
|
||||
z: pos[2],
|
||||
flags: 0,
|
||||
})
|
||||
.encode(),
|
||||
) && send(raw(sb::CLIENT_TICK_END, |_| {}));
|
||||
if !ok {
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
next += Duration::from_millis(50);
|
||||
let now = Instant::now();
|
||||
if next > now {
|
||||
thread::sleep(next - now);
|
||||
} else if now - next > Duration::from_secs(1) {
|
||||
next = now;
|
||||
}
|
||||
}
|
||||
// Offline first, so the reader doesn't count the closed connection as a failure.
|
||||
bot.online.store(false, Ordering::SeqCst);
|
||||
writer.lock().unwrap().shutdown();
|
||||
}
|
||||
|
||||
fn behaviour_of(mode: &str, index: usize) -> Behaviour {
|
||||
match mode {
|
||||
"idle" => Behaviour::Idle,
|
||||
"walk" => Behaviour::Walk,
|
||||
"explore" => Behaviour::Explore,
|
||||
// mixed: of every five bots, three walk, one explores, one stands.
|
||||
_ => match index % 5 {
|
||||
0 | 2 | 4 => Behaviour::Walk,
|
||||
1 => Behaviour::Explore,
|
||||
_ => Behaviour::Idle,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let o = match options() {
|
||||
Ok(o) => Arc::new(o),
|
||||
Err(e) => {
|
||||
eprintln!("horizon-bots: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let start = Instant::now();
|
||||
let until: Arc<Mutex<Option<Instant>>> = Arc::new(Mutex::new(None));
|
||||
let bots: Vec<Arc<Bot>> = (0..o.bots).map(|_| Arc::new(Bot::default())).collect();
|
||||
let launcher = {
|
||||
let (o, bots, until) = (o.clone(), bots.clone(), until.clone());
|
||||
thread::spawn(move || {
|
||||
let mut handles = Vec::new();
|
||||
for (i, bot) in bots.iter().enumerate() {
|
||||
let (o2, bot, until) = (o.clone(), bot.clone(), until.clone());
|
||||
let behaviour = behaviour_of(&o.behaviour, i);
|
||||
handles.push(thread::spawn(move || run_bot(o2, i, behaviour, bot, until)));
|
||||
thread::sleep(Duration::from_secs_f64(o.join_every));
|
||||
}
|
||||
handles
|
||||
})
|
||||
};
|
||||
// The run lasts --seconds after the first bot is in.
|
||||
let mut previous_chunks = 0;
|
||||
let mut first = None;
|
||||
loop {
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
let online = bots
|
||||
.iter()
|
||||
.filter(|b| b.online.load(Ordering::SeqCst))
|
||||
.count();
|
||||
let chunks: u64 = bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum();
|
||||
let failed = bots
|
||||
.iter()
|
||||
.filter(|b| b.error.lock().unwrap().is_some())
|
||||
.count();
|
||||
if first.is_none() && online > 0 {
|
||||
first = Some(Instant::now());
|
||||
*until.lock().unwrap() = Some(Instant::now() + Duration::from_secs(o.seconds));
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"t": start.elapsed().as_secs(),
|
||||
"online": online,
|
||||
"failed": failed,
|
||||
"chunks": chunks,
|
||||
"chunks_per_second": chunks - previous_chunks,
|
||||
})
|
||||
);
|
||||
previous_chunks = chunks;
|
||||
let over = until.lock().unwrap().is_some_and(|u| Instant::now() >= u);
|
||||
let all_failed = failed == o.bots;
|
||||
if over || all_failed || (first.is_none() && start.elapsed() > Duration::from_secs(120)) {
|
||||
*until.lock().unwrap() = Some(Instant::now());
|
||||
break;
|
||||
}
|
||||
}
|
||||
for handle in launcher.join().unwrap_or_default() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
let summary = json!({
|
||||
"server": format!("{}:{}", o.host, o.port),
|
||||
"bots": o.bots,
|
||||
"behaviour": o.behaviour,
|
||||
"seed": o.seed,
|
||||
"view_distance": o.view_distance,
|
||||
"seconds": o.seconds,
|
||||
"joined": bots.iter().filter(|b| b.joined_after_ms.load(Ordering::SeqCst) > 0).count(),
|
||||
"chunks": bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum::<u64>(),
|
||||
"per_bot": bots.iter().enumerate().map(|(i, b)| json!({
|
||||
"name": format!("{}{i}", o.name),
|
||||
"behaviour": behaviour_of(&o.behaviour, i).name(),
|
||||
"joined_after_ms": b.joined_after_ms.load(Ordering::SeqCst),
|
||||
"chunks": b.chunks.load(Ordering::Relaxed),
|
||||
"error": *b.error.lock().unwrap(),
|
||||
})).collect::<Vec<_>>(),
|
||||
});
|
||||
if let Some(path) = &o.report {
|
||||
if let Err(e) = std::fs::write(path, format!("{summary:#}\n")) {
|
||||
eprintln!("horizon-bots: {path}: {e}");
|
||||
}
|
||||
}
|
||||
let errors: Vec<String> = bots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, b)| {
|
||||
b.error
|
||||
.lock()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.map(|e| format!("{}{i}: {e}", o.name))
|
||||
})
|
||||
.collect();
|
||||
for e in errors.iter().take(10) {
|
||||
eprintln!("horizon-bots: {e}");
|
||||
}
|
||||
std::process::exit(if errors.is_empty() { 0 } else { 1 });
|
||||
}
|
||||
@@ -12,6 +12,8 @@ horizon-assets = { path = "../horizon-assets" }
|
||||
horizon-core = { path = "../horizon-core" }
|
||||
horizon-world = { path = "../horizon-world" }
|
||||
horizon-protocol = { path = "../horizon-protocol" }
|
||||
# server.properties, eula.txt and the user lists, shared with horizon-server.
|
||||
horizon-server-files = { path = "../horizon-server-files" }
|
||||
horizon-friends = { path = "../horizon-friends" }
|
||||
# Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md).
|
||||
horizon-mods = { path = "../horizon-mods" }
|
||||
|
||||
@@ -74,6 +74,10 @@ pub struct DebugCharts {
|
||||
pub bandwidth: SampleLogger,
|
||||
/// `MinecraftServer.smoothedTickTimeMillis`.
|
||||
pub smoothed_tick_ms: f32,
|
||||
/// Connection's smoothed packets per second, sent then received.
|
||||
pub packet_rates: [f32; 2],
|
||||
packet_totals: [i64; 2],
|
||||
packet_tick: u8,
|
||||
previous_tick: Option<Instant>,
|
||||
bytes_seen: Option<i64>,
|
||||
}
|
||||
@@ -113,6 +117,9 @@ impl DebugCharts {
|
||||
self.previous_tick = None;
|
||||
self.bytes_seen = None;
|
||||
self.smoothed_tick_ms = 0.0;
|
||||
self.packet_rates = [0.0; 2];
|
||||
self.packet_totals = [0; 2];
|
||||
self.packet_tick = 0;
|
||||
}
|
||||
/// One integrated server tick that started at `started` and ran its
|
||||
/// tick method for `method` (`MinecraftServer.logFullTickTime` and
|
||||
@@ -136,6 +143,17 @@ impl DebugCharts {
|
||||
}
|
||||
self.bytes_seen = Some(total);
|
||||
}
|
||||
/// `Connection.tickSecond`: sampled on the first tick, then every 20 ticks.
|
||||
pub fn log_packets(&mut self, totals: [i64; 2]) {
|
||||
if self.packet_tick == 0 {
|
||||
for (i, total) in totals.into_iter().enumerate() {
|
||||
let count = (total - self.packet_totals[i]).max(0) as f32;
|
||||
self.packet_rates[i] = count + 0.75 * (self.packet_rates[i] - count);
|
||||
}
|
||||
self.packet_totals = totals;
|
||||
}
|
||||
self.packet_tick = (self.packet_tick + 1) % 20;
|
||||
}
|
||||
/// The charts along the bottom of the screen (`extractRenderState`):
|
||||
/// frame times left and tick times right, or bandwidth left (remote
|
||||
/// servers only) and ping right. `mspt` is the level's milliseconds
|
||||
@@ -524,6 +542,27 @@ mod tests {
|
||||
assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packet_rates_follow_connection_smoothing_and_reset_between_worlds() {
|
||||
let mut charts = DebugCharts::default();
|
||||
charts.log_packets([80, 400]);
|
||||
assert_eq!(charts.packet_rates, [20.0, 100.0]);
|
||||
for _ in 1..20 {
|
||||
charts.log_packets([180, 800]);
|
||||
}
|
||||
assert_eq!(charts.packet_rates, [20.0, 100.0]);
|
||||
charts.log_packets([180, 800]);
|
||||
assert_eq!(charts.packet_rates, [40.0, 175.0]);
|
||||
for _ in 0..20 {
|
||||
charts.log_packets([180, 800]);
|
||||
}
|
||||
assert_eq!(charts.packet_rates, [30.0, 131.25]);
|
||||
charts.reset();
|
||||
assert_eq!(charts.packet_rates, [0.0, 0.0]);
|
||||
charts.log_packets([4, 8]);
|
||||
assert_eq!(charts.packet_rates, [1.0, 2.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticks_and_bandwidth_log_their_differences() {
|
||||
let mut c = DebugCharts::default();
|
||||
|
||||
@@ -1046,12 +1046,15 @@ pub fn arrow_from_nbt(
|
||||
}
|
||||
|
||||
/// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn falling_block_to_nbt(
|
||||
state: Tag,
|
||||
position: Vec3,
|
||||
motion: Vec3,
|
||||
time: i32,
|
||||
drop_item: bool,
|
||||
damage: crate::falling_block::Damage,
|
||||
fall_distance: f64,
|
||||
uuid: [i32; 4],
|
||||
) -> Tag {
|
||||
let base = Base {
|
||||
@@ -1061,29 +1064,27 @@ pub fn falling_block_to_nbt(
|
||||
motion,
|
||||
rotation: [0.0, 0.0],
|
||||
on_ground: false,
|
||||
fall_distance: 0.0,
|
||||
fall_distance,
|
||||
};
|
||||
let mut tag = base.tag(None);
|
||||
for (key, value) in [
|
||||
("BlockState", state),
|
||||
("Time", Tag::Int(time)),
|
||||
("DropItem", Tag::Byte(i8::from(drop_item))),
|
||||
("HurtEntities", Tag::Byte(0)),
|
||||
("CancelDrop", Tag::Byte(0)),
|
||||
("FallHurtAmount", Tag::Float(0)),
|
||||
("FallHurtMax", Tag::Int(40)),
|
||||
] {
|
||||
put(&mut tag, key, value);
|
||||
}
|
||||
damage.save(&mut tag);
|
||||
tag
|
||||
}
|
||||
/// (block state tag, position, motion, time)
|
||||
pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32)> {
|
||||
/// (block state tag, position, motion, time, fall distance)
|
||||
pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32, f64)> {
|
||||
Some((
|
||||
tag.get("BlockState")?.clone(),
|
||||
position(tag)?,
|
||||
motion(tag),
|
||||
number(tag.get("Time")).unwrap_or(0) as i32,
|
||||
float(tag.get("fall_distance")).unwrap_or(0.0),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -1493,6 +1494,36 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::items::ItemStack;
|
||||
|
||||
#[test]
|
||||
fn falling_block_round_trip_keeps_impact_distance_and_settings() {
|
||||
let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]);
|
||||
let position = Vec3::new(3.5, 100.0, -7.5);
|
||||
let velocity = Vec3::new(0.0, -1.25, 0.0);
|
||||
let damage = crate::falling_block::Damage {
|
||||
cancel_drop: true,
|
||||
..crate::falling_block::Damage::anvil()
|
||||
};
|
||||
let tag = falling_block_to_nbt(
|
||||
state.clone(),
|
||||
position,
|
||||
velocity,
|
||||
30,
|
||||
false,
|
||||
damage,
|
||||
19.75,
|
||||
[1, 2, 3, 4],
|
||||
);
|
||||
let (loaded_state, pos, motion, age, distance) = falling_block_from_nbt(&tag).unwrap();
|
||||
assert_eq!(loaded_state, state);
|
||||
assert_eq!(
|
||||
(pos, motion, age, distance),
|
||||
(position, velocity, 30, 19.75)
|
||||
);
|
||||
assert_eq!(falling_block_flags(&tag), (false, false));
|
||||
assert_eq!(crate::falling_block::Damage::from_nbt(&tag, true), damage);
|
||||
assert_eq!(uuid(&tag), Some([1, 2, 3, 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_entities_round_trip() {
|
||||
let e = ItemEntity {
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
//! FallingBlockEntity's impact damage, anvil wear and saved impact settings.
|
||||
use crate::{
|
||||
mobs::{Damage as MobDamage, DamageKind, Mob},
|
||||
save::{float, number, put},
|
||||
};
|
||||
use horizon_core::geometry::{Aabb, Vec3};
|
||||
use horizon_world::{chunk::BlockState, nbt::Tag};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Damage {
|
||||
pub hurt_entities: bool,
|
||||
pub cancel_drop: bool,
|
||||
pub per_distance: f32,
|
||||
pub max: i32,
|
||||
}
|
||||
impl Default for Damage {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hurt_entities: false,
|
||||
cancel_drop: false,
|
||||
per_distance: 0.0,
|
||||
max: 40,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Damage {
|
||||
pub fn anvil() -> Self {
|
||||
Self {
|
||||
hurt_entities: true,
|
||||
per_distance: 2.0,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
pub fn from_nbt(tag: &Tag, anvil: bool) -> Self {
|
||||
Self {
|
||||
hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0),
|
||||
cancel_drop: number(tag.get("CancelDrop")).is_some_and(|v| v != 0),
|
||||
per_distance: float(tag.get("FallHurtAmount")).unwrap_or(0.0) as f32,
|
||||
max: number(tag.get("FallHurtMax")).unwrap_or(40) as i32,
|
||||
}
|
||||
}
|
||||
pub fn save(self, tag: &mut Tag) {
|
||||
for (key, value) in [
|
||||
("HurtEntities", Tag::Byte(i8::from(self.hurt_entities))),
|
||||
("CancelDrop", Tag::Byte(i8::from(self.cancel_drop))),
|
||||
("FallHurtAmount", Tag::Float(self.per_distance.to_bits())),
|
||||
("FallHurtMax", Tag::Int(self.max)),
|
||||
] {
|
||||
put(tag, key, value);
|
||||
}
|
||||
}
|
||||
pub fn impact(self, fall_distance: f64) -> Option<Impact> {
|
||||
if !self.hurt_entities {
|
||||
return None;
|
||||
}
|
||||
let steps = (fall_distance - 1.0).ceil() as i32;
|
||||
if steps < 0 {
|
||||
return None;
|
||||
}
|
||||
let amount = ((steps as f32 * self.per_distance).floor() as i32).min(self.max) as f32;
|
||||
Some(Impact {
|
||||
amount,
|
||||
wear_chance: if amount > 0.0 {
|
||||
0.05 + steps as f32 * 0.05
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Impact {
|
||||
pub amount: f32,
|
||||
pub wear_chance: f32,
|
||||
}
|
||||
|
||||
/// AnvilBlock.damage: advance wear without changing facing; false means broken.
|
||||
pub fn wear_anvil(state: &mut BlockState) -> bool {
|
||||
state.name = match state.name.as_str() {
|
||||
"minecraft:anvil" => "minecraft:chipped_anvil",
|
||||
"minecraft:chipped_anvil" => "minecraft:damaged_anvil",
|
||||
_ => return false,
|
||||
}
|
||||
.into();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn bounds(position: Vec3) -> Aabb {
|
||||
let size = f64::from(0.98_f32);
|
||||
Aabb::new(
|
||||
Vec3::new(position.x - size / 2.0, position.y, position.z - size / 2.0),
|
||||
Vec3::new(
|
||||
position.x + size / 2.0,
|
||||
position.y + size,
|
||||
position.z + size / 2.0,
|
||||
),
|
||||
)
|
||||
}
|
||||
pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) {
|
||||
if amount <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let bounds = bounds(position);
|
||||
let source = MobDamage {
|
||||
kind: DamageKind::FallingBlock,
|
||||
attacker: None,
|
||||
from: Some([position.x, position.y, position.z]),
|
||||
};
|
||||
for mob in mobs
|
||||
.iter_mut()
|
||||
.filter(|m| m.alive() && bounds.intersects(m.bounds()))
|
||||
{
|
||||
mob.damage(amount, source);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() {
|
||||
let damage = Damage::anvil();
|
||||
assert!(Damage::default().impact(50.0).is_none());
|
||||
assert!(damage.impact(0.0).is_none());
|
||||
let short = damage.impact(1.0).unwrap();
|
||||
assert_eq!((short.amount, short.wear_chance), (0.0, 0.0));
|
||||
assert_eq!(damage.impact(1.01).unwrap().amount, 2.0);
|
||||
assert_eq!(damage.impact(5.0).unwrap().amount, 8.0);
|
||||
assert_eq!(damage.impact(100.0).unwrap().amount, 40.0);
|
||||
assert!(damage.impact(21.0).unwrap().wear_chance > 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn damage_settings_round_trip_and_keep_vanilla_load_defaults() {
|
||||
let empty = Tag::Compound(Default::default());
|
||||
assert_eq!(Damage::from_nbt(&empty, false), Damage::default());
|
||||
let loaded_anvil = Damage::from_nbt(&empty, true);
|
||||
assert!(loaded_anvil.hurt_entities);
|
||||
assert_eq!(loaded_anvil.per_distance, 0.0);
|
||||
let damage = Damage {
|
||||
hurt_entities: true,
|
||||
cancel_drop: true,
|
||||
per_distance: 3.5,
|
||||
max: 17,
|
||||
};
|
||||
let mut tag = empty;
|
||||
damage.save(&mut tag);
|
||||
assert_eq!(Damage::from_nbt(&tag, false), damage);
|
||||
}
|
||||
#[test]
|
||||
fn anvil_wears_twice_then_breaks_preserving_facing() {
|
||||
for facing in ["north", "south", "east", "west"] {
|
||||
let mut state = BlockState {
|
||||
name: "minecraft:anvil".into(),
|
||||
properties: [("facing".into(), facing.into())].into(),
|
||||
};
|
||||
for name in ["minecraft:chipped_anvil", "minecraft:damaged_anvil"] {
|
||||
assert!(wear_anvil(&mut state));
|
||||
assert_eq!(state.name, name);
|
||||
assert_eq!(state.properties["facing"], facing);
|
||||
}
|
||||
assert!(!wear_anvil(&mut state));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires prepared entity models/data in HORIZON_TEST_RESOURCES"]
|
||||
fn impact_hurts_only_living_intersecting_noninvulnerable_mobs() {
|
||||
use crate::mobs::{Mob, MobTypes};
|
||||
use std::{path::Path, sync::Arc};
|
||||
let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES");
|
||||
let types = MobTypes::load(Path::new(&root)).unwrap();
|
||||
let cow = Arc::new(types.types["minecraft:cow"].clone());
|
||||
let mut mobs = vec![
|
||||
Mob::new(1, cow.clone(), Vec3::ZERO, 0.0),
|
||||
Mob::new(2, cow.clone(), Vec3::new(3.0, 0.0, 0.0), 0.0),
|
||||
Mob::new(3, cow.clone(), Vec3::ZERO, 0.0),
|
||||
Mob::new(4, cow, Vec3::ZERO, 0.0),
|
||||
];
|
||||
mobs[2].invulnerable_flag = true;
|
||||
mobs[3].extra.head = Some("minecraft:carved_pumpkin".into());
|
||||
let initial = mobs.iter().map(|m| m.health).collect::<Vec<_>>();
|
||||
hurt_mobs(
|
||||
&mut mobs,
|
||||
Vec3::ZERO,
|
||||
Damage::anvil().impact(5.0).unwrap().amount,
|
||||
);
|
||||
assert_eq!(mobs[0].health, initial[0] - 8.0);
|
||||
assert_eq!(mobs[1].health, initial[1]);
|
||||
assert_eq!(mobs[2].health, initial[2]);
|
||||
assert_eq!(mobs[3].health, initial[3] - 6.0);
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,7 @@ impl Title {
|
||||
x: f32,
|
||||
y: f32,
|
||||
) -> Action {
|
||||
self.remember_direct_address();
|
||||
if self.skip_opening() {
|
||||
return Action::None;
|
||||
}
|
||||
@@ -472,7 +473,7 @@ impl Title {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(id) = id {
|
||||
match screen.click(Some(id), 0.0, 0.0, (0.0, 0.0), &saves) {
|
||||
match self.multiplayer_click(Some(id), 0.0, 0.0, (0.0, 0.0)) {
|
||||
Outcome::Back => self.mode = Mode::Main,
|
||||
Outcome::Connect(address) => return Action::Connect { address },
|
||||
Outcome::None => {}
|
||||
@@ -1432,6 +1433,28 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizon_direct_connection_remembers_the_address_after_leaving() {
|
||||
let atlas =
|
||||
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap();
|
||||
let saves =
|
||||
std::env::temp_dir().join(format!("horizon-front-direct-{}", std::process::id()));
|
||||
let mut title = Title::new(saves.clone(), &saves);
|
||||
title.last_server = "localhost:25566".into();
|
||||
title.mode = Mode::Multiplayer(Screen::list(&saves));
|
||||
press(&mut title, &atlas, DIRECT);
|
||||
assert_eq!(title.focused_field().unwrap().1, "localhost:25566");
|
||||
*title.focused_field().unwrap().1 = "example.org:25567".into();
|
||||
press(&mut title, &atlas, BACK);
|
||||
press(&mut title, &atlas, DIRECT);
|
||||
assert_eq!(title.focused_field().unwrap().1, "example.org:25567");
|
||||
*title.focused_field().unwrap().1 = "localhost:25568".into();
|
||||
press(&mut title, &atlas, NAV);
|
||||
press(&mut title, &atlas, NAV + 2);
|
||||
press(&mut title, &atlas, DIRECT);
|
||||
assert_eq!(title.focused_field().unwrap().1, "localhost:25568");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizon_world_delete_confirms_and_keeps_the_selection_in_place() {
|
||||
let atlas =
|
||||
|
||||
@@ -41,6 +41,7 @@ mod entity_culling;
|
||||
mod events;
|
||||
mod explosion;
|
||||
mod extras;
|
||||
mod falling_damage;
|
||||
mod fangs;
|
||||
mod fireworks;
|
||||
mod fishing;
|
||||
@@ -652,6 +653,7 @@ struct FallingBlock {
|
||||
drop_item: bool,
|
||||
/// `Entity.fallDistance` (powder snow holds a block that fell far at 0.9).
|
||||
fall_distance: f64,
|
||||
damage: horizon_client::falling_block::Damage,
|
||||
/// The UUID and compound it was loaded with, kept while it moves.
|
||||
saved: Option<Box<([i32; 4], horizon_world::nbt::Tag)>>,
|
||||
}
|
||||
@@ -1970,6 +1972,7 @@ impl Game<'_> {
|
||||
1009 => Some(("minecraft:block.fire.extinguish", 0.5)),
|
||||
1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)),
|
||||
1030 => Some(("minecraft:block.anvil.use", 1.0)),
|
||||
1029 => Some(("minecraft:block.anvil.destroy", 1.0)),
|
||||
1031 => Some(("minecraft:block.anvil.land", 0.3)),
|
||||
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
|
||||
_ => None,
|
||||
@@ -2022,6 +2025,11 @@ impl Game<'_> {
|
||||
no_gravity: false,
|
||||
drop_item: true,
|
||||
fall_distance: 0.0,
|
||||
damage: if self.res.facts.get(state).name.ends_with("anvil") {
|
||||
horizon_client::falling_block::Damage::anvil()
|
||||
} else {
|
||||
Default::default()
|
||||
},
|
||||
saved: None,
|
||||
});
|
||||
}
|
||||
@@ -2277,14 +2285,19 @@ impl Game<'_> {
|
||||
return false;
|
||||
}
|
||||
if solid {
|
||||
landed.push((
|
||||
f.state,
|
||||
[
|
||||
next.x.floor() as i32,
|
||||
next.y.floor() as i32 + i32::from(!sunk),
|
||||
next.z.floor() as i32,
|
||||
],
|
||||
));
|
||||
let pos = [
|
||||
next.x.floor() as i32,
|
||||
next.y.floor() as i32 + i32::from(!sunk),
|
||||
next.z.floor() as i32,
|
||||
];
|
||||
let landing_y = if sunk {
|
||||
next.y.floor() + f64::from(0.9_f32)
|
||||
} else {
|
||||
f64::from(pos[1])
|
||||
};
|
||||
f.fall_distance += (f.position.y - landing_y).max(0.0);
|
||||
f.position = Vec3::new(next.x, landing_y, next.z);
|
||||
landed.push((f.clone(), pos));
|
||||
return false;
|
||||
}
|
||||
if next.y < f.position.y {
|
||||
@@ -2318,30 +2331,8 @@ impl Game<'_> {
|
||||
self.spawn_item(stack, [at.x, at.y, at.z], v, 10);
|
||||
}
|
||||
}
|
||||
for (state, pos) in landed {
|
||||
let landing = self.with_level(|b, level, ticks| {
|
||||
b.falling_block_landed(
|
||||
level,
|
||||
ticks,
|
||||
BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
state,
|
||||
false,
|
||||
)
|
||||
});
|
||||
if matches!(landing, Landing::Broken) {
|
||||
let item = self.res.facts.get(state).item.clone();
|
||||
if &*item != "minecraft:air" {
|
||||
self.pop_resource(
|
||||
pos,
|
||||
ItemStack {
|
||||
item,
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
for (block, pos) in landed {
|
||||
self.finish_falling_block(block, pos);
|
||||
}
|
||||
self.process_level_events()
|
||||
}
|
||||
@@ -3659,6 +3650,9 @@ impl Game<'_> {
|
||||
) || self.book.is_some())
|
||||
}
|
||||
fn capture(&mut self, capture: bool) {
|
||||
if !capture {
|
||||
self.stop_mining();
|
||||
}
|
||||
// The real pointer takes over from an agent's.
|
||||
self.agent_pointer = false;
|
||||
let Some(window) = &self.window else { return };
|
||||
@@ -6648,6 +6642,9 @@ impl Game<'_> {
|
||||
std::env::current_dir()?.join("saves"),
|
||||
&self.options.resources,
|
||||
));
|
||||
if let Some(title) = &mut self.title {
|
||||
title.last_server = self.settings.file.string("lastServer");
|
||||
}
|
||||
self.capture(false);
|
||||
Ok(())
|
||||
}
|
||||
@@ -9301,6 +9298,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
clicked
|
||||
}
|
||||
});
|
||||
self.save_title_options();
|
||||
if sound {
|
||||
self.audio.play_button_click();
|
||||
}
|
||||
@@ -9539,6 +9537,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
if let Some(t) = self.title.as_mut() {
|
||||
t.escape();
|
||||
}
|
||||
self.save_title_options();
|
||||
}
|
||||
_ => self.title_edit(event.text.as_deref(), false),
|
||||
}
|
||||
@@ -10323,10 +10322,11 @@ pub fn run() -> Result<()> {
|
||||
game.open_world(&folder, None, Some(seed), creative, None)?;
|
||||
}
|
||||
None => {
|
||||
let title = Title::new(
|
||||
let mut title = Title::new(
|
||||
std::env::current_dir()?.join("saves"),
|
||||
&game.options.resources,
|
||||
);
|
||||
title.last_server = game.settings.file.string("lastServer");
|
||||
// The launcher's opening, once per session and only in Horizon's style.
|
||||
if horizon_client::ui_theme::horizon() && game.options.frames.is_none() {
|
||||
title
|
||||
|
||||
@@ -2985,6 +2985,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
|
||||
K::Explosion if player => "minecraft:player_explosion",
|
||||
K::Explosion => "minecraft:explosion",
|
||||
K::Fall => "minecraft:fall",
|
||||
K::FallingBlock => "minecraft:falling_block",
|
||||
K::OnFire => "minecraft:on_fire",
|
||||
K::InFire => "minecraft:in_fire",
|
||||
K::Lava => "minecraft:lava",
|
||||
|
||||
@@ -194,15 +194,17 @@ impl Game<'_> {
|
||||
}
|
||||
return;
|
||||
};
|
||||
let received = r
|
||||
.session
|
||||
.counters
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed));
|
||||
if let Some(total) = received {
|
||||
self.debug_charts.log_bandwidth(total);
|
||||
let received = r.session.counters.lock().unwrap().as_ref().map(|c| {
|
||||
let order = std::sync::atomic::Ordering::Relaxed;
|
||||
[
|
||||
c.bytes_in.load(order),
|
||||
c.sent.load(order),
|
||||
c.received.load(order),
|
||||
]
|
||||
});
|
||||
if let Some([bytes, sent, received]) = received {
|
||||
self.debug_charts.log_bandwidth(bytes);
|
||||
self.debug_charts.log_packets([sent, received]);
|
||||
}
|
||||
if shown {
|
||||
use horizon_protocol::packets::{play::Serverbound, status::Ping};
|
||||
@@ -403,8 +405,9 @@ impl Game<'_> {
|
||||
],
|
||||
);
|
||||
}
|
||||
// tps: DebugEntryTps for the integrated server (it counts no packets).
|
||||
if self.player.is_some() && self.remote.is_none() {
|
||||
// tps: DebugEntryTps for local and remote connections.
|
||||
if self.player.is_some() {
|
||||
let [tx, rx] = self.debug_charts.packet_rates.map(|n| n.round() as i64);
|
||||
let (target, status) = if self.clock.sprinting() {
|
||||
("-".to_owned(), " (sprinting)")
|
||||
} else if self.clock.stepping() {
|
||||
@@ -417,10 +420,22 @@ impl Game<'_> {
|
||||
} else {
|
||||
(format!("{:.1}", 1000.0 / self.clock.rate()), "")
|
||||
};
|
||||
d.line(format!(
|
||||
"Integrated server @ {:.1}/{target} ms{status}, 0 tx, 0 rx",
|
||||
self.debug_charts.smoothed_tick_ms
|
||||
));
|
||||
if self.remote.is_none() || self.integrated.is_some() {
|
||||
let tick_ms = self
|
||||
.integrated
|
||||
.as_ref()
|
||||
.map_or(self.debug_charts.smoothed_tick_ms, |server| {
|
||||
server.smoothed_tick_ms()
|
||||
});
|
||||
d.line(format!(
|
||||
"Integrated server @ {tick_ms:.1}/{target} ms{status}, {tx} tx, {rx} rx",
|
||||
));
|
||||
} else if let Some(remote) = &self.remote {
|
||||
d.line(format!(
|
||||
"\"{}\" server{status}, {tx} tx, {rx} rx",
|
||||
remote.brand
|
||||
));
|
||||
}
|
||||
}
|
||||
let (left, right) = d.columns(&self.debug_chart_lines());
|
||||
let atlas = &self.atlas;
|
||||
|
||||
@@ -29,6 +29,8 @@ use std::{
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
mod status;
|
||||
|
||||
/// Double.toString for the magnitudes positions have (no exponent form
|
||||
/// between 1e-3 and 1e7).
|
||||
pub(super) fn java_double(v: f64) -> String {
|
||||
@@ -64,6 +66,11 @@ pub(super) fn log(level: &str, message: &str) {
|
||||
_ => ::log::Level::Info,
|
||||
};
|
||||
horizon_client::logging::write_only(file_level, message);
|
||||
CAPTURE.with_borrow_mut(|lines| {
|
||||
if let Some(lines) = lines {
|
||||
lines.push(message.to_owned());
|
||||
}
|
||||
});
|
||||
let secs = now_millis().div_euclid(1000).rem_euclid(86_400);
|
||||
println!(
|
||||
"[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}",
|
||||
@@ -73,6 +80,18 @@ pub(super) fn log(level: &str, message: &str) {
|
||||
);
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The lines logged while a control request runs a console command.
|
||||
static CAPTURE: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` and returns the lines it logged.
|
||||
fn capture_log(f: impl FnOnce()) -> Vec<String> {
|
||||
CAPTURE.set(Some(Vec::new()));
|
||||
f();
|
||||
CAPTURE.take().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Main.main up to the server start: arguments, server.properties (stored
|
||||
/// back at once), eula.txt. False when the process should stop here.
|
||||
pub(super) fn preflight(options: &mut Options) -> Result<bool> {
|
||||
@@ -289,6 +308,9 @@ struct ServerState {
|
||||
stop: bool,
|
||||
autosave: bool,
|
||||
empty_ticks: i32,
|
||||
/// When the last passes of the loop ended, for the tick rate horizon-server shows.
|
||||
ticks: std::collections::VecDeque<Instant>,
|
||||
paused: bool,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
@@ -471,14 +493,18 @@ impl Game<'_> {
|
||||
stop: false,
|
||||
autosave: true,
|
||||
empty_ticks: 0,
|
||||
ticks: Default::default(),
|
||||
paused: false,
|
||||
};
|
||||
let pause_after = props.pause_when_empty_seconds * 20;
|
||||
let idle_timeout = props.player_idle_timeout;
|
||||
let mut next = Instant::now();
|
||||
while !state.stop {
|
||||
let tick_start = Instant::now();
|
||||
while let Ok(line) = state.console.try_recv() {
|
||||
self.console_command(&mut state, &line);
|
||||
}
|
||||
self.poll_server_control(&mut state);
|
||||
let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len());
|
||||
if pause_after > 0 {
|
||||
if players == 0 {
|
||||
@@ -488,6 +514,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
let paused = pause_after > 0 && state.empty_ticks >= pause_after;
|
||||
state.paused = paused;
|
||||
if paused && state.empty_ticks == pause_after {
|
||||
log(
|
||||
"INFO",
|
||||
@@ -513,6 +540,9 @@ impl Game<'_> {
|
||||
if idle_timeout > 0 {
|
||||
self.kick_idle(idle_timeout);
|
||||
}
|
||||
// MinecraftServer.tickServer records each tick's time, for /tick query (and the status).
|
||||
self.clock.record(tick_start.elapsed());
|
||||
state.ticked(Instant::now());
|
||||
let rate = self.clock.rate().max(1.0);
|
||||
next += Duration::from_secs_f64(1.0 / f64::from(rate));
|
||||
let now = Instant::now();
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
//! What `horizon-server` asks the dedicated server on its control endpoint (`--control-socket`, docs/server.md
|
||||
//! section 2): `server-status` answers with the tick rate, the tick times `/tick query` reports, the players
|
||||
//! and the loaded chunks; `console <line>` runs a console command and answers with the lines it logged.
|
||||
use super::{ServerState, capture_log};
|
||||
use crate::game::Game;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
sync::atomic::Ordering,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// The window the tick rate is measured over.
|
||||
const TPS_WINDOW: Duration = Duration::from_secs(5);
|
||||
|
||||
impl ServerState {
|
||||
/// One pass of the server loop ended.
|
||||
pub(super) fn ticked(&mut self, at: Instant) {
|
||||
self.ticks.push_back(at);
|
||||
while self
|
||||
.ticks
|
||||
.front()
|
||||
.is_some_and(|t| at.duration_since(*t) > TPS_WINDOW)
|
||||
{
|
||||
self.ticks.pop_front();
|
||||
}
|
||||
}
|
||||
/// Ticks per second over the last few seconds.
|
||||
fn tps(&self) -> f64 {
|
||||
match (self.ticks.front(), self.ticks.back()) {
|
||||
(Some(first), Some(last)) if self.ticks.len() > 1 => {
|
||||
(self.ticks.len() - 1) as f64 / last.duration_since(*first).as_secs_f64().max(1e-9)
|
||||
}
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Answers the requests waiting on the control endpoint.
|
||||
pub(super) fn poll_server_control(&mut self, state: &mut ServerState) {
|
||||
while let Some(request) = self.control.as_ref().and_then(|c| c.try_recv()) {
|
||||
let reply = match request.line.trim().split_once(' ') {
|
||||
_ if request.line.trim() == "server-status" => self.server_status(state),
|
||||
Some(("console", line)) => {
|
||||
// Command feedback is logged as system chat; the reply carries the text alone.
|
||||
let output: Vec<String> = capture_log(|| self.console_command(state, line))
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
l.strip_prefix("System chat: ")
|
||||
.map_or(l.clone(), str::to_owned)
|
||||
})
|
||||
.collect();
|
||||
json!({ "output": output })
|
||||
}
|
||||
_ => json!({ "error": format!("unknown request {:?}", request.line) }),
|
||||
};
|
||||
let _ = request.reply.send(reply.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn server_status(&self, state: &ServerState) -> Value {
|
||||
let millis = |nanos: u64| nanos as f64 / 1e6;
|
||||
let samples = self.clock.sorted_samples();
|
||||
// The percentiles `/tick query` prints (TickCommand.percentileToString).
|
||||
let at = |q: f64| {
|
||||
let i = ((samples.len() as f64 * q) as usize).min(samples.len().saturating_sub(1));
|
||||
samples.get(i).copied().map_or(0.0, millis)
|
||||
};
|
||||
let (players, max_players) = self.lan.as_ref().map_or((Vec::new(), 0), |h| {
|
||||
let players = h
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.map(|g| {
|
||||
json!({
|
||||
"name": g.name,
|
||||
"uuid": horizon_protocol::crypto::uuid_string(g.uuid),
|
||||
"address": g.address.ip().to_string(),
|
||||
"ping_ms": g.latency.load(Ordering::Relaxed),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(players, h.hub.lan.shared.max_players())
|
||||
});
|
||||
json!({
|
||||
"tps": state.tps(),
|
||||
"target_tps": self.clock.rate(),
|
||||
"mspt": {
|
||||
"average": millis(self.clock.average_nanos()),
|
||||
"p50": at(0.5),
|
||||
"p95": at(0.95),
|
||||
"p99": at(0.99),
|
||||
},
|
||||
"players": players,
|
||||
"max_players": max_players,
|
||||
"chunks": self.world.chunks.len(),
|
||||
"paused": state.paused,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Landing impacts for falling blocks, before their placement/drop decision.
|
||||
use super::{FallingBlock, Game, Landing};
|
||||
use horizon_client::{falling_block, items::ItemStack};
|
||||
use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
|
||||
use horizon_world::level::LevelEvent;
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) {
|
||||
let anvil = self.res.facts.get(block.state).name.ends_with("anvil");
|
||||
if let Some(impact) = block.damage.impact(block.fall_distance) {
|
||||
if impact.amount > 0.0 {
|
||||
falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount);
|
||||
let kind = if anvil {
|
||||
"minecraft:falling_anvil"
|
||||
} else {
|
||||
"minecraft:falling_block"
|
||||
};
|
||||
self.falling_hurt_player(block.position, impact.amount, kind);
|
||||
if let Some(mut host) = self.lan.take() {
|
||||
let bounds = falling_block::bounds(block.position);
|
||||
let conns = host
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| {
|
||||
g.placed
|
||||
&& g.loaded
|
||||
&& !g.dead
|
||||
&& !g.creative()
|
||||
&& !g.spectator()
|
||||
&& bounds.intersects(super::lan_mobs::guest_bounds(g))
|
||||
})
|
||||
.map(|g| g.conn)
|
||||
.collect::<Vec<_>>();
|
||||
for conn in conns {
|
||||
self.guest_hit_by(&mut host, conn, |g| {
|
||||
g.falling_hurt_player(block.position, impact.amount, kind)
|
||||
});
|
||||
}
|
||||
self.lan = Some(host);
|
||||
}
|
||||
}
|
||||
if anvil
|
||||
&& impact.wear_chance > 0.0
|
||||
&& self.world.random.next_float() < impact.wear_chance
|
||||
&& let Some(mut state) = self.pack.assets.registry.state(block.state).cloned()
|
||||
{
|
||||
if falling_block::wear_anvil(&mut state) {
|
||||
block.state = self
|
||||
.pack
|
||||
.assets
|
||||
.registry
|
||||
.resolve(&state)
|
||||
.unwrap_or(block.state);
|
||||
} else {
|
||||
block.damage.cancel_drop = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if block.damage.cancel_drop {
|
||||
if anvil {
|
||||
self.level_events.push(LevelEvent::LevelEvent {
|
||||
id: 1029,
|
||||
pos: BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
data: 0,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
let landing = self.with_level(|b, level, ticks| {
|
||||
b.falling_block_landed(
|
||||
level,
|
||||
ticks,
|
||||
BlockPos::new(pos[0], pos[1], pos[2]),
|
||||
block.state,
|
||||
false,
|
||||
)
|
||||
});
|
||||
if matches!(landing, Landing::Broken)
|
||||
&& block.drop_item
|
||||
&& self.ui.rules.bool("entity_drops")
|
||||
{
|
||||
let item = self.res.facts.get(block.state).item.clone();
|
||||
if &*item != "minecraft:air" {
|
||||
self.pop_resource(
|
||||
pos,
|
||||
ItemStack {
|
||||
item,
|
||||
count: 1,
|
||||
damage: 0,
|
||||
extra: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn falling_hurt_player(&mut self, position: Vec3, amount: f32, kind: &str) {
|
||||
if self.creative || self.spectator() {
|
||||
return;
|
||||
}
|
||||
if self.player.as_ref().is_none_or(|p| {
|
||||
p.health.dead_or_dying() || !falling_block::bounds(position).intersects(p.bounds())
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
let amount = if self.armor[0].is_some() {
|
||||
amount * 0.75
|
||||
} else {
|
||||
amount
|
||||
};
|
||||
let hurt = if let Some(p) = self.player.as_mut()
|
||||
&& let Some(id) = self.motion.health.damage.id(kind)
|
||||
{
|
||||
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if hurt {
|
||||
self.hurt_armor(amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,18 @@ fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: boo
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Opening a screen stops breaking before the next game tick (which may pause).
|
||||
pub(super) fn stop_mining(&mut self) {
|
||||
let mut destroying = std::mem::take(&mut self.clicks.destroying);
|
||||
destroying.stop(&mut GameHands {
|
||||
game: self,
|
||||
error: None,
|
||||
});
|
||||
self.clicks.destroying = destroying;
|
||||
self.attack_clicks = 0;
|
||||
self.stop_remote_mining();
|
||||
self.mining = None;
|
||||
}
|
||||
/// `LivingEntity.swing` with `getModifiedSwingDuration`.
|
||||
pub(super) fn swing_hand(&mut self, hand: Hand, animation: SwingAnimation) {
|
||||
let effects = &self.potions.effects;
|
||||
|
||||
@@ -31,7 +31,7 @@ use std::{
|
||||
path::Path,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicU16, Ordering},
|
||||
atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering},
|
||||
mpsc::{Receiver, Sender, channel, sync_channel},
|
||||
},
|
||||
thread::JoinHandle,
|
||||
@@ -47,6 +47,7 @@ struct Flags {
|
||||
/// `IntegratedServer.getPort`: the port it is open to the LAN on, 0
|
||||
/// while it is not.
|
||||
published: AtomicU16,
|
||||
smoothed_tick_ms: AtomicU32,
|
||||
}
|
||||
|
||||
/// Work the window hands its server thread (`MinecraftServer.execute`).
|
||||
@@ -61,6 +62,9 @@ pub(super) struct Integrated {
|
||||
pub world_name: String,
|
||||
}
|
||||
impl Integrated {
|
||||
pub fn smoothed_tick_ms(&self) -> f32 {
|
||||
f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed))
|
||||
}
|
||||
/// `IntegratedServer.tickServer` skips the world while the game is paused.
|
||||
pub fn set_paused(&self, paused: bool) {
|
||||
self.flags.paused.store(paused, Ordering::Relaxed);
|
||||
@@ -322,7 +326,13 @@ impl Game<'_> {
|
||||
// Only the connections run.
|
||||
self.tick_lan();
|
||||
} else {
|
||||
let started = Instant::now();
|
||||
self.tick()?;
|
||||
self.debug_charts.log_tick(started, started.elapsed());
|
||||
flags.smoothed_tick_ms.store(
|
||||
self.debug_charts.smoothed_tick_ms.to_bits(),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
}
|
||||
self.apply_publish();
|
||||
let rate = self.clock.rate().max(1.0);
|
||||
|
||||
@@ -17,6 +17,17 @@ pub(super) const CONTROL_HELP: &[&str] = &[
|
||||
];
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn save_title_options(&mut self) {
|
||||
if let Some(title) = &self.title
|
||||
&& title.last_server != self.settings.file.string("lastServer")
|
||||
{
|
||||
self.settings.file.set(
|
||||
"lastServer",
|
||||
horizon_client::options_file::V::Str(title.last_server.clone()),
|
||||
);
|
||||
self.settings.save(&Self::options_path());
|
||||
}
|
||||
}
|
||||
/// `options-get` and `options-set`; None for other commands.
|
||||
pub(super) fn options_control(&mut self, words: &[&str], line: &str) -> Result<Option<Value>> {
|
||||
match words[0] {
|
||||
|
||||
@@ -354,6 +354,7 @@ impl Game<'_> {
|
||||
}
|
||||
if let Some(title) = self.title.as_mut() {
|
||||
title.escape();
|
||||
self.save_title_options();
|
||||
return Ok(());
|
||||
}
|
||||
if self.sign_edit.is_some() {
|
||||
|
||||
@@ -49,16 +49,7 @@ fn with_raw(modelled: Tag, raw: Option<&Tag>) -> Tag {
|
||||
// Defaults Horizon invents for fields it does not simulate give way to the save.
|
||||
let invented = matches!(
|
||||
k.to_string_lossy().as_str(),
|
||||
"Fire"
|
||||
| "Air"
|
||||
| "Invulnerable"
|
||||
| "PortalCooldown"
|
||||
| "HasBeenShot"
|
||||
// FallingBlockEntity fields Horizon does not simulate.
|
||||
| "HurtEntities"
|
||||
| "CancelDrop"
|
||||
| "FallHurtAmount"
|
||||
| "FallHurtMax"
|
||||
"Fire" | "Air" | "Invulnerable" | "PortalCooldown" | "HasBeenShot"
|
||||
);
|
||||
if !(invented && out.contains_key(k)) {
|
||||
out.insert(k.clone(), v.clone());
|
||||
@@ -199,7 +190,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
"minecraft:falling_block" => {
|
||||
if let Some((state, position, velocity, age)) =
|
||||
if let Some((state, position, velocity, age, fall_distance)) =
|
||||
entity_nbt::falling_block_from_nbt(&tag)
|
||||
&& let Some(state) = self.state_from_nbt(&state)
|
||||
{
|
||||
@@ -214,7 +205,11 @@ impl Game<'_> {
|
||||
age,
|
||||
no_gravity,
|
||||
drop_item,
|
||||
fall_distance: 0.0,
|
||||
fall_distance,
|
||||
damage: horizon_client::falling_block::Damage::from_nbt(
|
||||
&tag,
|
||||
self.res.facts.get(state).name.ends_with("anvil"),
|
||||
),
|
||||
saved: uuid.map(|u| Box::new((u, tag.clone()))),
|
||||
});
|
||||
}
|
||||
@@ -620,6 +615,8 @@ impl Game<'_> {
|
||||
f.velocity,
|
||||
f.age,
|
||||
f.drop_item,
|
||||
f.damage,
|
||||
f.fall_distance,
|
||||
uuid,
|
||||
);
|
||||
out.entry(chunk_of(f.position))
|
||||
|
||||
@@ -68,6 +68,7 @@ struct Lerp {
|
||||
|
||||
pub(super) struct Remote {
|
||||
pub session: Session,
|
||||
pub brand: String,
|
||||
builtin: Arc<Builtin>,
|
||||
lang: Arc<Language>,
|
||||
registries: Arc<Dynamic>,
|
||||
@@ -153,7 +154,20 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
|
||||
impl Game<'_> {
|
||||
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
|
||||
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
|
||||
self.join_server(address, name, None)
|
||||
if let Err(error) = self.join_server(address, name, None) {
|
||||
log::warn!("Horizon: could not join server: {error}");
|
||||
if self.title.is_none() {
|
||||
self.title = Some(horizon_client::title::Title::new(
|
||||
std::env::current_dir()?.join("saves"),
|
||||
&self.options.resources,
|
||||
));
|
||||
}
|
||||
if let Some(title) = &mut self.title {
|
||||
title.failed(error);
|
||||
}
|
||||
self.capture(false);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Join single player's integrated server through memory.
|
||||
pub(super) fn connect_local(
|
||||
@@ -173,7 +187,7 @@ impl Game<'_> {
|
||||
let root = self.options.resources.clone();
|
||||
let builtin = Builtin::find(&root)
|
||||
.and_then(|p| Builtin::load(&p).ok())
|
||||
.ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?;
|
||||
.ok_or("Resources are incomplete: registries.json is missing or invalid. Click \"Prepare again\" in the launcher (or run horizon-prepare), then try again.")?;
|
||||
let lang = Arc::new(horizon_client::net::load_language(&root));
|
||||
let view = self.settings.render_distance.clamp(2, 32) as i8;
|
||||
if local.is_none() {
|
||||
@@ -238,6 +252,7 @@ impl Game<'_> {
|
||||
self.apply_settings();
|
||||
self.remote = Some(Remote {
|
||||
session,
|
||||
brand: "unknown".into(),
|
||||
builtin: Arc::new(builtin),
|
||||
lang,
|
||||
registries: Arc::new(Dynamic::default()),
|
||||
@@ -330,6 +345,7 @@ impl Game<'_> {
|
||||
}
|
||||
let saves = std::env::current_dir()?.join("saves");
|
||||
let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources);
|
||||
title.last_server = self.settings.file.string("lastServer");
|
||||
if single_player && reason.is_none() {
|
||||
self.title = Some(title);
|
||||
self.capture(false);
|
||||
@@ -467,6 +483,11 @@ impl Game<'_> {
|
||||
r.status = format!("Joined as {name}; loading terrain...");
|
||||
}
|
||||
}
|
||||
Event::Brand(brand) => {
|
||||
if let Some(remote) = &mut self.remote {
|
||||
remote.brand = brand;
|
||||
}
|
||||
}
|
||||
Event::Reconfigured(registries) => self.set_registries(registries),
|
||||
Event::DecodeError(e) => {
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
@@ -2101,6 +2122,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stop_remote_mining(&mut self) {
|
||||
if let Some((pos, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) {
|
||||
self.send(S::PlayerAction(play::PlayerAction {
|
||||
action: 2,
|
||||
pos,
|
||||
direction: 0,
|
||||
sequence: 0,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock.
|
||||
fn remote_mining(&mut self) {
|
||||
let Some(r) = self.remote.as_mut() else {
|
||||
@@ -2111,14 +2143,7 @@ impl Game<'_> {
|
||||
}
|
||||
let chatting = r.chat_input.is_some();
|
||||
if !self.left || self.screen != Screen::Playing || chatting {
|
||||
if let Some((pos, _, _)) = r.destroying.take() {
|
||||
self.send(S::PlayerAction(play::PlayerAction {
|
||||
action: 2,
|
||||
pos,
|
||||
direction: 0,
|
||||
sequence: 0,
|
||||
}));
|
||||
}
|
||||
self.stop_remote_mining();
|
||||
self.mining = None;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -146,9 +146,6 @@ impl Game<'_> {
|
||||
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
|
||||
.map(|b| b.4)
|
||||
};
|
||||
if hit.is_some() && !horizon_client::ui_theme::horizon() {
|
||||
self.audio.play_button_click();
|
||||
}
|
||||
match hit {
|
||||
Some(0) => {
|
||||
self.screen = Screen::Playing;
|
||||
@@ -168,6 +165,9 @@ impl Game<'_> {
|
||||
Some(2) => self.close_world()?,
|
||||
_ => {}
|
||||
}
|
||||
if hit.is_some() && !horizon_client::ui_theme::horizon() {
|
||||
self.audio.play_button_click();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// DeathScreen: gradient, the title at double size, the cause and score.
|
||||
@@ -260,9 +260,6 @@ impl Game<'_> {
|
||||
.into_iter()
|
||||
.find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0))
|
||||
.map(|d| d.3);
|
||||
if hit.is_some() {
|
||||
self.audio.play_button_click();
|
||||
}
|
||||
match hit {
|
||||
Some(0) if self.remote.is_some() => {
|
||||
self.ui.death_text = None;
|
||||
@@ -292,6 +289,9 @@ impl Game<'_> {
|
||||
Some(1) => self.close_world()?,
|
||||
_ => {}
|
||||
}
|
||||
if hit.is_some() {
|
||||
self.audio.play_button_click();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ pub mod entity_nbt;
|
||||
pub mod environment;
|
||||
pub mod extras;
|
||||
pub mod extras_hud;
|
||||
pub mod falling_block;
|
||||
pub mod fast_hash;
|
||||
pub mod fastutil_order;
|
||||
pub mod fire_render;
|
||||
@@ -147,7 +148,7 @@ pub mod screen_draw;
|
||||
pub mod screen_effects;
|
||||
pub mod screen_layout;
|
||||
pub mod sculk;
|
||||
pub mod server;
|
||||
pub use horizon_server_files as server;
|
||||
pub mod settings;
|
||||
pub mod shader_pack;
|
||||
pub mod shadows;
|
||||
|
||||
@@ -509,6 +509,7 @@ pub enum DamageKind {
|
||||
Fireball,
|
||||
Explosion,
|
||||
Fall,
|
||||
FallingBlock,
|
||||
OnFire,
|
||||
InFire,
|
||||
Lava,
|
||||
@@ -1614,6 +1615,12 @@ impl Mob {
|
||||
return false;
|
||||
}
|
||||
let mut amount = amount;
|
||||
if source.kind == DamageKind::FallingBlock
|
||||
&& !species::body_slot(self.species())
|
||||
&& self.extra.head.is_some()
|
||||
{
|
||||
amount *= 0.75;
|
||||
}
|
||||
let (worn, worn_toughness) = self.worn_armor();
|
||||
if !source.bypasses_armor() && self.kind.armor + worn > 0.0 {
|
||||
// CombatRules.getDamageAfterAbsorb
|
||||
|
||||
@@ -29,6 +29,8 @@ use std::{
|
||||
pub enum Event {
|
||||
/// Progress text for the connecting screen.
|
||||
Status(String),
|
||||
/// The server's `minecraft:brand` custom payload.
|
||||
Brand(String),
|
||||
/// Configuration finished: the play state begins with these registries.
|
||||
Joined {
|
||||
registries: Arc<Dynamic>,
|
||||
@@ -374,7 +376,7 @@ fn run(
|
||||
.map_err(e)?;
|
||||
let (mut reader, writer) = c.split();
|
||||
*shared_writer.lock().unwrap() = Some(writer);
|
||||
let registries = configure(&mut reader, shared_writer, lang)?;
|
||||
let registries = configure(&mut reader, shared_writer, lang, send)?;
|
||||
let _ = send.send(Event::Joined {
|
||||
registries: Arc::new(registries),
|
||||
uuid: profile.uuid,
|
||||
@@ -413,10 +415,13 @@ fn run(
|
||||
}
|
||||
play::Clientbound::StartConfiguration(_) => {
|
||||
reply(play::Serverbound::ConfigurationAcknowledged(Empty));
|
||||
let registries = configure(&mut reader, shared_writer, lang)?;
|
||||
let registries = configure(&mut reader, shared_writer, lang, send)?;
|
||||
let _ = send.send(Event::Reconfigured(Arc::new(registries)));
|
||||
}
|
||||
play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)),
|
||||
play::Clientbound::CustomPayload(p) if p.channel == "minecraft:brand" => {
|
||||
receive_brand(&p, send);
|
||||
}
|
||||
other => {
|
||||
if send.send(Event::Packet(Box::new(other))).is_err() {
|
||||
return Ok("Disconnected".into());
|
||||
@@ -432,6 +437,7 @@ fn configure(
|
||||
reader: &mut ConnReader,
|
||||
writer: &Mutex<Option<ConnWriter>>,
|
||||
lang: &Language,
|
||||
send: &Sender<Event>,
|
||||
) -> Result<Dynamic, String> {
|
||||
let mut registries = Dynamic::default();
|
||||
let reply = |p: cfg::Serverbound| -> Result<(), String> {
|
||||
@@ -444,6 +450,7 @@ fn configure(
|
||||
let (id, payload) = reader.recv().map_err(|e| e.to_string())?;
|
||||
match cfg::Clientbound::decode(id, &payload).map_err(|e| e.to_string())? {
|
||||
cfg::Clientbound::KeepAlive(k) => reply(cfg::Serverbound::KeepAlive(k))?,
|
||||
cfg::Clientbound::CustomPayload(p) => receive_brand(&p, send),
|
||||
cfg::Clientbound::Ping(p) => reply(cfg::Serverbound::Pong(p))?,
|
||||
// Know no packs: the server then sends every registry entry in full.
|
||||
cfg::Clientbound::SelectKnownPacks(_) => {
|
||||
@@ -477,6 +484,14 @@ fn configure(
|
||||
}
|
||||
}
|
||||
|
||||
fn receive_brand(payload: &cfg::CustomPayload, send: &Sender<Event>) {
|
||||
if payload.channel == "minecraft:brand"
|
||||
&& let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767)
|
||||
{
|
||||
let _ = send.send(Event::Brand(brand));
|
||||
}
|
||||
}
|
||||
|
||||
/// The minecraft:brand payload: a string naming the client.
|
||||
fn brand() -> Vec<u8> {
|
||||
let mut w = horizon_protocol::buf::Writer::new();
|
||||
@@ -565,3 +580,28 @@ pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128
|
||||
let _ = c.recv().map_err(e)?;
|
||||
Ok((json, start.elapsed().as_millis()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() {
|
||||
let (send, events) = channel();
|
||||
let mut writer = horizon_protocol::buf::Writer::new();
|
||||
writer.string("vanilla");
|
||||
let mut payload = cfg::CustomPayload {
|
||||
channel: "minecraft:brand".into(),
|
||||
data: writer.data,
|
||||
};
|
||||
receive_brand(&payload, &send);
|
||||
assert!(matches!(events.try_recv(), Ok(Event::Brand(brand)) if brand == "vanilla"));
|
||||
payload.channel = "example:other".into();
|
||||
receive_brand(&payload, &send);
|
||||
assert!(events.try_recv().is_err());
|
||||
payload.channel = "minecraft:brand".into();
|
||||
payload.data = vec![0xff];
|
||||
receive_brand(&payload, &send);
|
||||
assert!(events.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +125,8 @@ pub enum Action {
|
||||
}
|
||||
pub struct Title {
|
||||
pub mode: Mode,
|
||||
/// Direct Connection's address, synchronized with `options.txt`'s `lastServer`.
|
||||
pub last_server: String,
|
||||
pub saves: PathBuf,
|
||||
pub started: std::time::Instant,
|
||||
search: String,
|
||||
@@ -232,6 +234,7 @@ impl Title {
|
||||
Self {
|
||||
shown: std::cell::Cell::new((std::mem::discriminant(&mode), now)),
|
||||
mode,
|
||||
last_server: String::new(),
|
||||
saves,
|
||||
started: now,
|
||||
search: String::new(),
|
||||
@@ -397,7 +400,7 @@ impl Title {
|
||||
scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content);
|
||||
self.scroll.set(scroll);
|
||||
}
|
||||
fn failed(&mut self, error: impl std::fmt::Display) {
|
||||
pub fn failed(&mut self, error: impl std::fmt::Display) {
|
||||
let return_to = Box::new(self.mode.clone());
|
||||
self.mode = Mode::Error {
|
||||
message: error.to_string(),
|
||||
@@ -1162,6 +1165,7 @@ impl Title {
|
||||
/// The action and whether to play `AbstractWidget.playButtonClickSound`.
|
||||
/// Navigation buttons can return `Action::None` while still sounding.
|
||||
pub fn click(&mut self, x: f32, y: f32, size: (f32, f32)) -> (Action, bool) {
|
||||
self.remember_direct_address();
|
||||
let (w, h) = (size.0.ceil(), size.1.ceil());
|
||||
// MenuTabBar: a new tab clears the focus and clicks.
|
||||
if let Mode::Create { focus, options, .. } = &mut self.mode
|
||||
@@ -1195,16 +1199,14 @@ impl Title {
|
||||
self.mode = Mode::Multiplayer(crate::multiplayer::Screen::list(&self.saves));
|
||||
Action::None
|
||||
}
|
||||
(Mode::Multiplayer(screen), hit) => {
|
||||
match screen.click(hit, x, y, (w, h), &self.saves) {
|
||||
crate::multiplayer::Outcome::Back => {
|
||||
self.mode = Mode::Main;
|
||||
Action::None
|
||||
}
|
||||
crate::multiplayer::Outcome::Connect(address) => Action::Connect { address },
|
||||
crate::multiplayer::Outcome::None => Action::None,
|
||||
(Mode::Multiplayer(_), hit) => match self.multiplayer_click(hit, x, y, (w, h)) {
|
||||
crate::multiplayer::Outcome::Back => {
|
||||
self.mode = Mode::Main;
|
||||
Action::None
|
||||
}
|
||||
}
|
||||
crate::multiplayer::Outcome::Connect(address) => Action::Connect { address },
|
||||
crate::multiplayer::Outcome::None => Action::None,
|
||||
},
|
||||
(Mode::Main, Some(3)) => Action::Options,
|
||||
(Mode::Main, Some(7)) => Action::Accessibility,
|
||||
(Mode::Main, Some(6)) => Action::Language,
|
||||
@@ -1512,7 +1514,31 @@ impl Title {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(crate) fn remember_direct_address(&mut self) {
|
||||
if let Mode::Multiplayer(crate::multiplayer::Screen::Direct { address }) = &self.mode {
|
||||
self.last_server.clone_from(address);
|
||||
}
|
||||
}
|
||||
pub(crate) fn multiplayer_click(
|
||||
&mut self,
|
||||
hit: Option<u8>,
|
||||
x: f32,
|
||||
y: f32,
|
||||
size: (f32, f32),
|
||||
) -> crate::multiplayer::Outcome {
|
||||
let Mode::Multiplayer(screen) = &mut self.mode else {
|
||||
return crate::multiplayer::Outcome::None;
|
||||
};
|
||||
let outcome = screen.click(hit, x, y, size, &self.saves);
|
||||
if hit == Some(41)
|
||||
&& let crate::multiplayer::Screen::Direct { address } = screen
|
||||
{
|
||||
address.clone_from(&self.last_server);
|
||||
}
|
||||
outcome
|
||||
}
|
||||
pub fn escape(&mut self) {
|
||||
self.remember_direct_address();
|
||||
if let Mode::Multiplayer(screen) = &mut self.mode
|
||||
&& !screen.escape(&self.saves)
|
||||
{
|
||||
|
||||
@@ -82,6 +82,41 @@ impl Drop for Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_connection_remembers_the_address_on_cancel_escape_and_join() {
|
||||
let mut f = Fixture::new();
|
||||
f.title.last_server = "localhost:25566".into();
|
||||
f.click("Multiplayer");
|
||||
f.click("Direct Connection");
|
||||
assert_eq!(f.title.focused_field().unwrap().1, "localhost:25566");
|
||||
|
||||
*f.title.focused_field().unwrap().1 = "example.org:25567".into();
|
||||
f.click("Cancel");
|
||||
f.click("Direct Connection");
|
||||
assert_eq!(f.title.focused_field().unwrap().1, "example.org:25567");
|
||||
|
||||
*f.title.focused_field().unwrap().1 = "[::1]:25568".into();
|
||||
f.title.escape();
|
||||
f.title.escape();
|
||||
f.click("Multiplayer");
|
||||
f.click("Direct Connection");
|
||||
assert_eq!(f.title.focused_field().unwrap().1, "[::1]:25568");
|
||||
|
||||
*f.title.focused_field().unwrap().1 = "localhost:25569".into();
|
||||
assert_eq!(
|
||||
f.click("Join Server"),
|
||||
Action::Connect {
|
||||
address: "localhost:25569".into(),
|
||||
}
|
||||
);
|
||||
assert_eq!(f.title.last_server, "localhost:25569");
|
||||
|
||||
f.title.focused_field().unwrap().1.clear();
|
||||
f.title.escape();
|
||||
f.click("Direct Connection");
|
||||
assert!(f.title.focused_field().unwrap().1.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_singleplayer_opens_creation_and_cancel_returns_to_title() {
|
||||
let mut f = Fixture::new();
|
||||
|
||||
@@ -762,8 +762,7 @@ fn steps(
|
||||
"behaviour-export.log",
|
||||
)?;
|
||||
|
||||
let items = root.join("items.json");
|
||||
if !items.exists() || !run.same("server_sha256") {
|
||||
if datagen_reports_missing(root) || !run.same("server_sha256") {
|
||||
// Vanilla's own data generator reports every item's default components.
|
||||
(run.log)("Running vanilla's data generator reports");
|
||||
let datagen = run.local.join("datagen");
|
||||
@@ -785,21 +784,7 @@ fn steps(
|
||||
)
|
||||
.map_err(|e| format!("{e} in the data generator; see {}", log_path.display()))?;
|
||||
let reports = datagen.join("out").join("reports");
|
||||
let mut components = Value::Object(Vec::new());
|
||||
for file in json_files(&reports.join("minecraft/components/item"))? {
|
||||
let stem = file.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
let report = read_json(&file)?;
|
||||
let component = report
|
||||
.get("components")
|
||||
.ok_or_else(|| format!("{} has no components", file.display()))?;
|
||||
components.insert(&format!("minecraft:{stem}"), component.clone());
|
||||
}
|
||||
write_text(&items, &pyjson::dumps(&components, &pyjson::DEFAULT))?;
|
||||
let biome_parameters = root.join("biome-parameters");
|
||||
mkdir(&biome_parameters)?;
|
||||
for file in json_files(&reports.join("biome_parameters/minecraft"))? {
|
||||
copy(&file, &biome_parameters.join(file.file_name().unwrap()))?;
|
||||
}
|
||||
install_datagen_reports(root, &reports)?;
|
||||
}
|
||||
|
||||
// Biome parameter tables come from the data generator reports above.
|
||||
@@ -925,6 +910,37 @@ fn steps(
|
||||
)
|
||||
}
|
||||
|
||||
fn datagen_reports_missing(root: &Path) -> bool {
|
||||
["items.json", "registries.json", "commands.json"]
|
||||
.iter()
|
||||
.any(|name| !root.join(name).is_file())
|
||||
}
|
||||
|
||||
fn install_datagen_reports(root: &Path, reports: &Path) -> Result<(), String> {
|
||||
for name in ["registries.json", "commands.json"] {
|
||||
copy(&reports.join(name), &root.join(name))?;
|
||||
}
|
||||
let mut components = Value::Object(Vec::new());
|
||||
for file in json_files(&reports.join("minecraft/components/item"))? {
|
||||
let stem = file.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
let report = read_json(&file)?;
|
||||
let component = report
|
||||
.get("components")
|
||||
.ok_or_else(|| format!("{} has no components", file.display()))?;
|
||||
components.insert(&format!("minecraft:{stem}"), component.clone());
|
||||
}
|
||||
write_text(
|
||||
&root.join("items.json"),
|
||||
&pyjson::dumps(&components, &pyjson::DEFAULT),
|
||||
)?;
|
||||
let biome_parameters = root.join("biome-parameters");
|
||||
mkdir(&biome_parameters)?;
|
||||
for file in json_files(&reports.join("biome_parameters/minecraft"))? {
|
||||
copy(&file, &biome_parameters.join(file.file_name().unwrap()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `sorted(directory.glob('*.json'))`: glob skips names starting with a dot.
|
||||
fn json_files(directory: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut files: Vec<PathBuf> = fs::read_dir(directory)
|
||||
@@ -1124,6 +1140,54 @@ fn export_block_behavior(run: &Run, export: &Path) -> Result<(), String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn datagen_reports_are_installed_beside_resources_and_missing_reports_need_repair() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("horizon-prepare-reports-{}", std::process::id()));
|
||||
let root = dir.join("resources");
|
||||
let reports = dir.join("reports");
|
||||
mkdir(&root).unwrap();
|
||||
mkdir(&reports.join("minecraft/components/item")).unwrap();
|
||||
mkdir(&reports.join("biome_parameters/minecraft")).unwrap();
|
||||
write_text(&root.join("items.json"), "{}").unwrap();
|
||||
assert!(datagen_reports_missing(&root));
|
||||
write_text(
|
||||
&reports.join("registries.json"),
|
||||
"{\"minecraft:item\":{\"entries\":{}}}",
|
||||
)
|
||||
.unwrap();
|
||||
write_text(&reports.join("commands.json"), "{\"type\":\"root\"}").unwrap();
|
||||
write_text(
|
||||
&reports.join("minecraft/components/item/stone.json"),
|
||||
"{\"components\":{\"minecraft:max_stack_size\":64}}",
|
||||
)
|
||||
.unwrap();
|
||||
write_text(
|
||||
&reports.join("biome_parameters/minecraft/overworld.json"),
|
||||
"{}",
|
||||
)
|
||||
.unwrap();
|
||||
install_datagen_reports(&root, &reports).unwrap();
|
||||
assert!(!datagen_reports_missing(&root));
|
||||
for name in ["registries.json", "commands.json"] {
|
||||
assert_eq!(
|
||||
read(&root.join(name)).unwrap(),
|
||||
read(&reports.join(name)).unwrap()
|
||||
);
|
||||
}
|
||||
assert!(read_json(&root.join("items.json"))
|
||||
.unwrap()
|
||||
.get("minecraft:stone")
|
||||
.is_some());
|
||||
assert!(root.join("biome-parameters/overworld.json").is_file());
|
||||
for name in ["registries.json", "commands.json", "items.json"] {
|
||||
fs::remove_file(root.join(name)).unwrap();
|
||||
assert!(datagen_reports_missing(&root), "{name}");
|
||||
install_datagen_reports(&root, &reports).unwrap();
|
||||
}
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_source_digest_is_the_one_build_rs_computed() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -359,6 +359,8 @@ mod tests {
|
||||
big.extend(std::iter::repeat_n(3u8, 1000));
|
||||
c.send(&big).unwrap();
|
||||
assert_eq!(c.recv().unwrap(), (9, vec![1, 2]));
|
||||
assert_eq!(c.reader.counters.sent.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(c.reader.counters.received.load(Ordering::Relaxed), 1);
|
||||
server.join().unwrap();
|
||||
assert!(c.recv().is_err());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "horizon-server-files"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.90"
|
||||
description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans"
|
||||
|
||||
[dependencies]
|
||||
horizon-core = { path = "../horizon-core" }
|
||||
horizon-protocol = { path = "../horizon-protocol" }
|
||||
horizon-world = { path = "../horizon-world" }
|
||||
log = "0.4"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -9,8 +9,13 @@ pub const EULA_LINK: &str = "https://aka.ms/MinecraftEULA";
|
||||
|
||||
/// The default file, as Properties.store(OutputStream) writes it.
|
||||
pub fn default_file(millis: i64) -> String {
|
||||
file(millis, false)
|
||||
}
|
||||
|
||||
/// The file with `eula` set: what the owner's agreement writes (horizon-server init).
|
||||
pub fn file(millis: i64, agreed: bool) -> String {
|
||||
let mut p = Properties::default();
|
||||
p.put("eula", "false".into());
|
||||
p.put("eula", agreed.to_string());
|
||||
p.store(
|
||||
Some(&format!(
|
||||
"By changing the setting below to TRUE you are indicating your agreement to our EULA ({EULA_LINK})."
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The dedicated server's files and settings, ported from
|
||||
//! net.minecraft.server.dedicated and net.minecraft.server.players:
|
||||
//! server.properties, eula.txt and the four user lists. The server itself
|
||||
//! runs the game's own world, simulation and LAN hub headless
|
||||
//! (`horizon-client --dedicated`, see the game's `dedicated` module).
|
||||
//! server.properties, eula.txt and the four user lists. The game's dedicated
|
||||
//! server (`horizon-client --dedicated`) reads them, and `horizon-server`
|
||||
//! manages them; this crate needs neither a window nor the game.
|
||||
pub mod eula;
|
||||
pub mod java_properties;
|
||||
pub mod json;
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "horizon-server"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.90"
|
||||
description = "Host a Horizon server: server.toml, the CLI and the supervisor that runs the game headless (docs/server.md)"
|
||||
|
||||
[dependencies]
|
||||
horizon-server-files = { path = "../horizon-server-files" }
|
||||
# The game process's RAM and CPU (the same probes the benchmark reports use).
|
||||
horizon-bench = { path = "../horizon-bench" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
toml = "1.1"
|
||||
# Edits server.toml in place, keeping the owner's comments and order.
|
||||
toml_edit = "0.25"
|
||||
# Backups: one zip anyone can open, Windows included.
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
# SIGINT/SIGTERM/SIGHUP: stop the game cleanly when the terminal or the service manager asks.
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console", "Win32_System_Threading"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,78 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>Horizon server</title>
|
||||
<link rel="stylesheet" href="/panel.css">
|
||||
<script src="/panel.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="title">
|
||||
<h1>Horizon server</h1>
|
||||
<span id="phase" class="pill">…</span>
|
||||
<span id="summary" class="muted"></span>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button id="restart" type="button">Restart</button>
|
||||
<button id="stop" type="button" class="danger">Stop</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="app" hidden>
|
||||
<section class="charts" aria-label="Last 10 minutes">
|
||||
<figure><figcaption>TPS <b id="tps-now">–</b></figcaption><canvas id="tps" width="320" height="96"></canvas></figure>
|
||||
<figure><figcaption>MSPT <b id="mspt-now">–</b></figcaption><canvas id="mspt" width="320" height="96"></canvas></figure>
|
||||
<figure><figcaption>RAM <b id="ram-now">–</b></figcaption><canvas id="ram" width="320" height="96"></canvas></figure>
|
||||
<figure><figcaption>CPU <b id="cpu-now">–</b></figcaption><canvas id="cpu" width="320" height="96"></canvas></figure>
|
||||
</section>
|
||||
|
||||
<div class="columns">
|
||||
<section>
|
||||
<h2>Players <span id="player-count" class="muted"></span></h2>
|
||||
<table>
|
||||
<thead><tr><th>Name</th><th>Ping</th><th></th></tr></thead>
|
||||
<tbody id="players"></tbody>
|
||||
</table>
|
||||
<p id="no-players" class="muted">Nobody is online.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Backups</h2>
|
||||
<form id="backup-form" class="row">
|
||||
<input id="backup-name" placeholder="Name (optional)" maxlength="40" pattern="[A-Za-z0-9_.\-]*" autocomplete="off">
|
||||
<button type="submit">Back up now</button>
|
||||
</form>
|
||||
<table>
|
||||
<thead><tr><th>Backup</th><th>Size</th><th></th></tr></thead>
|
||||
<tbody id="backups"></tbody>
|
||||
</table>
|
||||
<p id="no-backups" class="muted">No backups yet.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h2>Console</h2>
|
||||
<pre id="log" tabindex="0" aria-live="off"></pre>
|
||||
<form id="command-form" class="row">
|
||||
<input id="command" placeholder="A console command, like list or say Hello" autocomplete="off" spellcheck="false">
|
||||
<button type="submit">Run</button>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<main id="signed-out" class="message" hidden>
|
||||
<p>Sign in with a link from the server: run <code>horizon-server panel</code> in the server's folder and open
|
||||
the link it prints. Links work once, for 10 minutes.</p>
|
||||
</main>
|
||||
|
||||
<main id="gone" class="message" hidden>
|
||||
<p>The server isn't answering. It may have stopped: start it again with <code>horizon-server start</code>,
|
||||
then reload this page.</p>
|
||||
</main>
|
||||
|
||||
<div id="toast" role="status" hidden></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,128 @@
|
||||
/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (website/src/tokens.css). */
|
||||
:root {
|
||||
--page: #fafafc;
|
||||
--plate-soft: #f3f3f8;
|
||||
--plate: #ebecf4;
|
||||
--surface: #ffffff;
|
||||
--rule: #e2e3ea;
|
||||
--ink: #16181f;
|
||||
--ink-soft: #3b3e49;
|
||||
--muted: #646875;
|
||||
--accent: #5b3fd6;
|
||||
--on-accent: #ffffff;
|
||||
--danger: #b4372a;
|
||||
--success: #1d7a48;
|
||||
--font: "Geist", ui-sans-serif, system-ui, sans-serif;
|
||||
--mono: "Geist Mono", ui-monospace, monospace;
|
||||
--radius: 8px;
|
||||
--radius-plate: 12px;
|
||||
color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--page: #0d0e13;
|
||||
--plate-soft: #181a22;
|
||||
--plate: #20222c;
|
||||
--surface: #16181f;
|
||||
--rule: #24262f;
|
||||
--ink: #ecedf3;
|
||||
--ink-soft: #c5c7d1;
|
||||
--muted: #8b8f9c;
|
||||
--accent: #9a86ff;
|
||||
--on-accent: #0d0e13;
|
||||
--danger: #f07a68;
|
||||
--success: #45c27a;
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--page);
|
||||
color: var(--ink);
|
||||
font: 14px/1.5 var(--font);
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 24px;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
background: var(--surface);
|
||||
}
|
||||
.title { display: flex; flex-wrap: wrap; gap: 12px; align-items: baseline; }
|
||||
h1 { font-size: 18px; font-weight: 500; margin: 0; letter-spacing: -0.01em; }
|
||||
h2 { font-size: 13px; font-weight: 500; margin: 0 0 8px; color: var(--ink-soft); }
|
||||
main { padding: 24px; max-width: 1200px; margin: 0 auto; display: grid; gap: 24px; }
|
||||
section { background: var(--surface); border: 1px solid var(--rule); border-radius: var(--radius-plate); padding: 16px; }
|
||||
.muted { color: var(--muted); }
|
||||
.pill {
|
||||
font-size: 12px;
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
background: var(--plate);
|
||||
color: var(--ink-soft);
|
||||
}
|
||||
.pill.running { background: color-mix(in srgb, var(--success) 18%, transparent); color: var(--success); }
|
||||
.pill.stopping, .pill.restarting, .pill.starting { background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); }
|
||||
.pill.down { background: color-mix(in srgb, var(--danger) 16%, transparent); color: var(--danger); }
|
||||
|
||||
.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; }
|
||||
figure { margin: 0; }
|
||||
figcaption { font-size: 12px; color: var(--muted); display: flex; justify-content: space-between; }
|
||||
figcaption b { color: var(--ink); font-weight: 500; font-variant-numeric: tabular-nums; }
|
||||
canvas { width: 100%; height: 96px; display: block; }
|
||||
|
||||
.columns { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 24px; }
|
||||
table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
|
||||
th { text-align: left; font-weight: 400; font-size: 12px; color: var(--muted); padding: 4px 0; }
|
||||
td { padding: 6px 0; border-top: 1px solid var(--rule); }
|
||||
td:last-child { text-align: right; white-space: nowrap; }
|
||||
td button { margin-left: 4px; }
|
||||
|
||||
button, input {
|
||||
font: inherit;
|
||||
height: 32px;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--rule);
|
||||
background: var(--plate-soft);
|
||||
color: var(--ink);
|
||||
padding: 0 12px;
|
||||
}
|
||||
button { cursor: pointer; }
|
||||
button:hover { background: var(--plate); }
|
||||
button:disabled { opacity: 0.5; cursor: default; }
|
||||
button[type="submit"] { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
|
||||
button.danger { color: var(--danger); }
|
||||
input { background: var(--surface); flex: 1; min-width: 0; }
|
||||
input:focus, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
.row { display: flex; gap: 8px; margin: 8px 0; }
|
||||
|
||||
pre {
|
||||
font: 12px/1.5 var(--mono);
|
||||
background: var(--plate-soft);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px;
|
||||
margin: 0;
|
||||
height: 320px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
.message { max-width: 560px; }
|
||||
code { font-family: var(--mono); font-size: 13px; }
|
||||
#toast {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--ink);
|
||||
color: var(--page);
|
||||
padding: 8px 16px;
|
||||
border-radius: var(--radius);
|
||||
max-width: 90vw;
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
// The Horizon server panel (docs/server.md, section 6). It polls the control API once a second through
|
||||
// the panel's session; every change is a POST with the X-Horizon header. Text from the server is only
|
||||
// ever set with textContent.
|
||||
"use strict";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let logNext = 0;
|
||||
let metricsSince = 0;
|
||||
const samples = [];
|
||||
let lastStatus = null;
|
||||
let backupsShown = "";
|
||||
|
||||
class SignedOut extends Error {}
|
||||
|
||||
async function api(method, path, body) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(path, {
|
||||
method,
|
||||
credentials: "same-origin",
|
||||
headers: { "X-Horizon": "1", "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new Error("the server isn't answering");
|
||||
}
|
||||
if (response.status === 401) throw new SignedOut();
|
||||
const value = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(value.error || `error ${response.status}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function show(view) {
|
||||
for (const id of ["app", "signed-out", "gone"]) $(id).hidden = id !== view;
|
||||
for (const id of ["restart", "stop"]) $(id).disabled = view !== "app";
|
||||
}
|
||||
|
||||
let toastTimer;
|
||||
function toast(text) {
|
||||
$("toast").textContent = text;
|
||||
$("toast").hidden = false;
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => ($("toast").hidden = true), 5000);
|
||||
}
|
||||
|
||||
function duration(seconds) {
|
||||
if (seconds == null) return "";
|
||||
const d = Math.floor(seconds / 86400), h = Math.floor(seconds / 3600) % 24, m = Math.floor(seconds / 60) % 60;
|
||||
if (d) return `${d} d ${h} h`;
|
||||
if (h) return `${h} h ${m} min`;
|
||||
return m ? `${m} min` : `${seconds} s`;
|
||||
}
|
||||
|
||||
function bytes(n) {
|
||||
if (n == null) return "–";
|
||||
if (n >= 1e9) return `${(n / 1e9).toFixed(2)} GB`;
|
||||
if (n >= 1e6) return `${(n / 1e6).toFixed(1)} MB`;
|
||||
return `${Math.ceil(n / 1e3)} kB`;
|
||||
}
|
||||
|
||||
function cell(text) {
|
||||
const td = document.createElement("td");
|
||||
td.textContent = text;
|
||||
return td;
|
||||
}
|
||||
|
||||
function button(label, action, danger) {
|
||||
const b = document.createElement("button");
|
||||
b.type = "button";
|
||||
b.textContent = label;
|
||||
if (danger) b.className = "danger";
|
||||
b.addEventListener("click", action);
|
||||
return b;
|
||||
}
|
||||
|
||||
async function run(line) {
|
||||
const reply = await api("POST", "/api/v1/command", { line });
|
||||
return (reply.output || []).join("\n");
|
||||
}
|
||||
|
||||
function renderStatus(status) {
|
||||
lastStatus = status;
|
||||
const phase = $("phase");
|
||||
phase.textContent = status.phase;
|
||||
phase.className = `pill ${status.phase}`;
|
||||
const game = status.sample && status.sample.game;
|
||||
const parts = [`up ${duration(status.engine_uptime_seconds)}`, `horizon-server ${status.version}`];
|
||||
if (status.crashes) parts.push(`${status.crashes} crash${status.crashes > 1 ? "es" : ""}`);
|
||||
$("summary").textContent = parts.join(" · ");
|
||||
|
||||
const players = (game && game.players) || [];
|
||||
$("player-count").textContent = game ? `${players.length} of ${game.max_players}` : "";
|
||||
$("no-players").hidden = players.length > 0;
|
||||
const body = $("players");
|
||||
body.replaceChildren(
|
||||
...players.map((p) => {
|
||||
const tr = document.createElement("tr");
|
||||
const actions = cell("");
|
||||
actions.append(
|
||||
button("Op", async () => toast(await run(`op ${p.name}`).catch((e) => e.message))),
|
||||
button("Kick", async () => {
|
||||
if (confirm(`Kick ${p.name}?`)) toast(await run(`kick ${p.name}`).catch((e) => e.message));
|
||||
}, true),
|
||||
);
|
||||
tr.append(cell(p.name), cell(p.ping_ms == null ? "–" : `${p.ping_ms} ms`), actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function renderBackups(list) {
|
||||
const key = JSON.stringify(list);
|
||||
if (key === backupsShown) return;
|
||||
backupsShown = key;
|
||||
$("no-backups").hidden = list.length > 0;
|
||||
$("backups").replaceChildren(
|
||||
...list.map((b) => {
|
||||
const tr = document.createElement("tr");
|
||||
const actions = cell("");
|
||||
actions.append(
|
||||
button("Restore", async () => {
|
||||
if (!confirm(`Restore ${b.name}? The server restarts with that world; the current one is kept in backups/.`)) return;
|
||||
try {
|
||||
await api("POST", "/api/v1/restore", { name: b.name });
|
||||
toast(`Restoring ${b.name}: the server is restarting.`);
|
||||
} catch (e) {
|
||||
toast(e.message);
|
||||
}
|
||||
}, true),
|
||||
);
|
||||
tr.append(cell(b.name), cell(bytes(b.bytes)), actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function appendLog(lines) {
|
||||
if (!lines.length) return;
|
||||
const log = $("log");
|
||||
const atBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 8;
|
||||
log.append(document.createTextNode(lines.join("\n") + "\n"));
|
||||
// Keep the page light: the last 2000 lines, as the server does.
|
||||
const text = log.textContent;
|
||||
const all = text.split("\n");
|
||||
if (all.length > 2100) log.textContent = all.slice(-2000).join("\n");
|
||||
if (atBottom) log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function chart(id, values, { max, unit, line, decimals = 1 }) {
|
||||
const canvas = $(id);
|
||||
const ratio = window.devicePixelRatio || 1;
|
||||
const width = canvas.clientWidth, height = canvas.clientHeight;
|
||||
if (canvas.width !== width * ratio) {
|
||||
canvas.width = width * ratio;
|
||||
canvas.height = height * ratio;
|
||||
}
|
||||
const g = canvas.getContext("2d");
|
||||
g.setTransform(ratio, 0, 0, ratio, 0, 0);
|
||||
g.clearRect(0, 0, width, height);
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
const known = values.filter((v) => v != null);
|
||||
const top = Math.max(max || 0, ...known, 1e-9) * 1.1;
|
||||
if (line != null) {
|
||||
g.strokeStyle = style.getPropertyValue("--rule");
|
||||
g.setLineDash([4, 4]);
|
||||
g.beginPath();
|
||||
const y = height - (line / top) * height;
|
||||
g.moveTo(0, y);
|
||||
g.lineTo(width, y);
|
||||
g.stroke();
|
||||
g.setLineDash([]);
|
||||
}
|
||||
g.strokeStyle = style.getPropertyValue("--accent");
|
||||
g.lineWidth = 1.5;
|
||||
g.beginPath();
|
||||
const span = 600;
|
||||
let drawing = false;
|
||||
values.forEach((v, i) => {
|
||||
if (v == null) {
|
||||
drawing = false;
|
||||
return;
|
||||
}
|
||||
const x = width - ((values.length - 1 - i) / (span - 1)) * width;
|
||||
const y = height - (v / top) * height;
|
||||
if (drawing) g.lineTo(x, y);
|
||||
else g.moveTo(x, y);
|
||||
drawing = true;
|
||||
});
|
||||
g.stroke();
|
||||
const last = values[values.length - 1];
|
||||
$(`${id}-now`).textContent = last == null ? "–" : `${last.toFixed(decimals)}${unit}`;
|
||||
}
|
||||
|
||||
function renderCharts() {
|
||||
chart("tps", samples.map((s) => s.tps), { max: 20, unit: "", line: 20 });
|
||||
chart("mspt", samples.map((s) => s.mspt), { max: 50, unit: " ms", line: 50 });
|
||||
chart("ram", samples.map((s) => (s.rss_bytes == null ? null : s.rss_bytes / 1e9)), { unit: " GB", decimals: 2 });
|
||||
chart("cpu", samples.map((s) => s.cpu_percent), { max: 100, unit: " %", decimals: 0 });
|
||||
$("ram-now").textContent = bytes(samples.length ? samples[samples.length - 1].rss_bytes : null);
|
||||
}
|
||||
|
||||
let ticks = 0;
|
||||
async function poll() {
|
||||
try {
|
||||
const [status, metrics, logs] = await Promise.all([
|
||||
api("GET", "/api/v1/status"),
|
||||
api("GET", `/api/v1/metrics?since=${metricsSince}`),
|
||||
api("GET", `/api/v1/logs?since=${logNext}`),
|
||||
]);
|
||||
show("app");
|
||||
renderStatus(status);
|
||||
for (const s of metrics.samples) {
|
||||
samples.push(s);
|
||||
metricsSince = s.t;
|
||||
}
|
||||
samples.splice(0, Math.max(0, samples.length - 600));
|
||||
renderCharts();
|
||||
logNext = logs.next;
|
||||
appendLog(logs.lines);
|
||||
if (ticks++ % 10 === 0) renderBackups((await api("GET", "/api/v1/backups")).backups);
|
||||
} catch (e) {
|
||||
if (e instanceof SignedOut) show("signed-out");
|
||||
else if (lastStatus) {
|
||||
show("gone");
|
||||
$("phase").textContent = "down";
|
||||
$("phase").className = "pill down";
|
||||
} else show("gone");
|
||||
}
|
||||
}
|
||||
|
||||
function setUp() {
|
||||
$("command-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const line = $("command").value.trim();
|
||||
if (!line) return;
|
||||
$("command").value = "";
|
||||
try {
|
||||
const output = await run(line);
|
||||
appendLog([`> ${line}`]);
|
||||
if (!output) toast("Done.");
|
||||
} catch (e) {
|
||||
toast(e.message);
|
||||
}
|
||||
});
|
||||
$("backup-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const name = $("backup-name").value.trim();
|
||||
toast("Backing up…");
|
||||
try {
|
||||
const made = await api("POST", "/api/v1/backups", name ? { name } : {});
|
||||
toast(`Backed up to backups/${made.name}`);
|
||||
$("backup-name").value = "";
|
||||
renderBackups((await api("GET", "/api/v1/backups")).backups);
|
||||
} catch (e) {
|
||||
toast(e.message);
|
||||
}
|
||||
});
|
||||
$("restart").addEventListener("click", async () => {
|
||||
if (!confirm("Restart the game? Players are disconnected for a moment.")) return;
|
||||
await api("POST", "/api/v1/restart").then(() => toast("Restarting…"), (e) => toast(e.message));
|
||||
});
|
||||
$("stop").addEventListener("click", async () => {
|
||||
if (!confirm("Stop the server? The panel stops with it; start it again on the server.")) return;
|
||||
await api("POST", "/api/v1/stop").then(() => toast("Stopping…"), (e) => toast(e.message));
|
||||
});
|
||||
poll();
|
||||
setInterval(poll, 1000);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", setUp);
|
||||
@@ -0,0 +1,497 @@
|
||||
//! The control API (docs/server.md, section 8): HTTP and JSON on 127.0.0.1, with a random token in
|
||||
//! `.horizon/api.json` that only the server's own user can read. The CLI manages a running server through
|
||||
//! it; the web panel and the MCP server will too.
|
||||
//!
|
||||
//! - `GET /api/v1/status`: the supervisor's state, the game's status (TPS, MSPT, players), RAM and CPU.
|
||||
//! - `GET /api/v1/logs?since=N`: the log lines after the Nth.
|
||||
//! - `POST /api/v1/command {"line": "..."}`: a console command; the lines it logged.
|
||||
//! - `POST /api/v1/stop`, `POST /api/v1/restart`.
|
||||
//! - `GET /api/v1/metrics?since=T`: the samples taken after T (seconds since 1970), up to 10 minutes.
|
||||
//! - `GET /api/v1/backups`; `POST /api/v1/backups {"name": "..."}` backs up now; `POST /api/v1/restore
|
||||
//! {"name": "..."}` restarts the game with that backup's world.
|
||||
//! - `POST /api/v1/panel/login`: a one-time login link for the web panel (with the token only).
|
||||
|
||||
use crate::{
|
||||
backup,
|
||||
config::Config,
|
||||
engine,
|
||||
http::{self, Request, Response},
|
||||
panel,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io::Write,
|
||||
net::{SocketAddr, TcpListener},
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const ENDPOINT: &str = ".horizon/api.json";
|
||||
/// The log lines kept for `logs` and the panel's console.
|
||||
const LOG_LINES: usize = 2000;
|
||||
/// The samples kept for the panel's graphs: 10 minutes, one a second.
|
||||
const METRICS: usize = 600;
|
||||
|
||||
/// What the supervisor is doing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
Starting,
|
||||
Running,
|
||||
Stopping,
|
||||
/// Stopping the game to start it again (`restart`), or waiting to after a crash.
|
||||
Restarting,
|
||||
}
|
||||
|
||||
impl Phase {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Starting => "starting",
|
||||
Self::Running => "running",
|
||||
Self::Stopping => "stopping",
|
||||
Self::Restarting => "restarting",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub phase: Phase,
|
||||
pub engine_pid: Option<u32>,
|
||||
pub engine_started: Option<Instant>,
|
||||
pub crashes: u32,
|
||||
pub last_crash: Option<String>,
|
||||
/// The latest sample (`sample`): the game's status, RAM and CPU.
|
||||
pub sample: Value,
|
||||
}
|
||||
|
||||
/// The log, numbered from the first line since the supervisor started.
|
||||
#[derive(Default)]
|
||||
pub struct Log {
|
||||
lines: VecDeque<String>,
|
||||
first: u64,
|
||||
}
|
||||
|
||||
impl Log {
|
||||
pub fn push(&mut self, line: String) {
|
||||
if self.lines.len() == LOG_LINES {
|
||||
self.lines.pop_front();
|
||||
self.first += 1;
|
||||
}
|
||||
self.lines.push_back(line);
|
||||
}
|
||||
/// The lines after the `since`th, and the number to ask from next.
|
||||
pub fn since(&self, since: u64) -> (u64, Vec<String>) {
|
||||
let skip = since.saturating_sub(self.first) as usize;
|
||||
let next = self.first + self.lines.len() as u64;
|
||||
(next, self.lines.iter().skip(skip).cloned().collect())
|
||||
}
|
||||
}
|
||||
|
||||
/// What the supervisor and the API threads share.
|
||||
pub struct Shared {
|
||||
pub dir: PathBuf,
|
||||
pub state: Mutex<State>,
|
||||
pub log: Mutex<Log>,
|
||||
pub stop: AtomicBool,
|
||||
pub restart: AtomicBool,
|
||||
/// The backup to put in place before the game starts again (`restore`).
|
||||
pub restore: Mutex<Option<String>>,
|
||||
/// Held while a backup is written: one at a time.
|
||||
pub backing_up: Mutex<()>,
|
||||
pub started: Instant,
|
||||
/// The last samples, oldest first, for the panel's graphs.
|
||||
pub metrics: Mutex<VecDeque<Value>>,
|
||||
/// The panel's address, login links and sessions.
|
||||
pub panel: Mutex<panel::Auth>,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
pub fn new(dir: &Path) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
dir: dir.to_owned(),
|
||||
state: Mutex::new(State {
|
||||
phase: Phase::Starting,
|
||||
engine_pid: None,
|
||||
engine_started: None,
|
||||
crashes: 0,
|
||||
last_crash: None,
|
||||
sample: Value::Null,
|
||||
}),
|
||||
log: Mutex::new(Log::default()),
|
||||
stop: AtomicBool::new(false),
|
||||
restart: AtomicBool::new(false),
|
||||
restore: Mutex::new(None),
|
||||
backing_up: Mutex::new(()),
|
||||
started: Instant::now(),
|
||||
metrics: Mutex::new(VecDeque::new()),
|
||||
panel: Mutex::new(panel::Auth::default()),
|
||||
})
|
||||
}
|
||||
/// Keeps one sample for the graphs.
|
||||
pub fn record(&self, sample: Value) {
|
||||
let mut metrics = self.metrics.lock().unwrap();
|
||||
if metrics.len() == METRICS {
|
||||
metrics.pop_front();
|
||||
}
|
||||
metrics.push_back(sample);
|
||||
}
|
||||
pub fn set_phase(&self, phase: Phase) {
|
||||
self.state.lock().unwrap().phase = phase;
|
||||
}
|
||||
fn phase(&self) -> Phase {
|
||||
self.state.lock().unwrap().phase
|
||||
}
|
||||
|
||||
/// A backup while the server runs: the game saves everything and stops writing while the zip is made.
|
||||
pub fn back_up(&self, file_name: &str) -> Result<PathBuf, String> {
|
||||
let _one = self.backing_up.lock().unwrap();
|
||||
let config = Config::load(&self.dir)?;
|
||||
let mut game = match self.phase() {
|
||||
Phase::Running => Some(
|
||||
engine::Control::connect(&self.dir)
|
||||
.map_err(|e| format!("the game didn't answer: {e}"))?,
|
||||
),
|
||||
// Between a crash and the restart nothing writes the world.
|
||||
Phase::Restarting => None,
|
||||
Phase::Starting | Phase::Stopping => {
|
||||
return Err("the game is starting or stopping: try again in a moment".into());
|
||||
}
|
||||
};
|
||||
if let Some(game) = game.as_mut() {
|
||||
for command in ["console save-off", "console save-all flush"] {
|
||||
game.ask(command)
|
||||
.map_err(|e| format!("the game didn't save: {e}"))?;
|
||||
}
|
||||
}
|
||||
let result = backup::create(&self.dir, &config, file_name);
|
||||
if let Some(game) = game.as_mut() {
|
||||
let _ = game.ask("console save-on");
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn status(shared: &Shared) -> Value {
|
||||
let state = shared.state.lock().unwrap();
|
||||
json!({
|
||||
"phase": state.phase.name(),
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"pid": std::process::id(),
|
||||
"uptime_seconds": shared.started.elapsed().as_secs(),
|
||||
"engine_pid": state.engine_pid,
|
||||
"engine_uptime_seconds": state.engine_started.map(|t| t.elapsed().as_secs()),
|
||||
"crashes": state.crashes,
|
||||
"last_crash": state.last_crash,
|
||||
"sample": state.sample,
|
||||
})
|
||||
}
|
||||
|
||||
/// A random token: two 64-bit hashes keyed by the OS's random hasher seeds, the time and the process.
|
||||
pub fn random_token() -> String {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
(0..2u64)
|
||||
.map(|i| {
|
||||
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
|
||||
h.write_u64(i);
|
||||
h.write_u128(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_nanos()),
|
||||
);
|
||||
h.write_u32(std::process::id());
|
||||
format!("{:016x}", h.finish())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn same_token(a: &str, b: &str) -> bool {
|
||||
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
/// Writes a file only its owner can read.
|
||||
pub fn write_private(path: &Path, text: &str) -> std::io::Result<()> {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
options.open(path)?.write_all(text.as_bytes())
|
||||
}
|
||||
|
||||
/// Removes the endpoint file when the supervisor ends.
|
||||
pub struct Endpoint(PathBuf);
|
||||
impl Drop for Endpoint {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the API on a free port of 127.0.0.1 and writes where it is and its token.
|
||||
pub fn start(shared: Arc<Shared>) -> Result<Endpoint, String> {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").map_err(|e| format!("control API: {e}"))?;
|
||||
let address = listener.local_addr().map_err(|e| e.to_string())?;
|
||||
let token = random_token();
|
||||
let path = shared.dir.join(ENDPOINT);
|
||||
write_private(
|
||||
&path,
|
||||
&json!({ "address": address.to_string(), "token": token, "pid": std::process::id() })
|
||||
.to_string(),
|
||||
)
|
||||
.map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let hosts = [address.to_string(), format!("localhost:{}", address.port())];
|
||||
http::serve(listener, move |request| {
|
||||
// A page in a browser can't send the token, and a rebound DNS name can't pass as this address.
|
||||
let authorised = request
|
||||
.header("authorization")
|
||||
.and_then(|h| h.strip_prefix("Bearer "))
|
||||
.is_some_and(|t| same_token(t.trim(), &token));
|
||||
if !authorised {
|
||||
return Response::error(401, "missing or wrong token (see .horizon/api.json)");
|
||||
}
|
||||
if !request
|
||||
.header("host")
|
||||
.is_some_and(|h| hosts.iter().any(|a| a == h))
|
||||
{
|
||||
return Response::error(403, "wrong Host");
|
||||
}
|
||||
if (request.method.as_str(), request.path.as_str()) == ("POST", "/api/v1/panel/login") {
|
||||
return match shared.panel.lock().unwrap().login_link() {
|
||||
Some(url) => Response::json(200, &json!({ "url": url })),
|
||||
None => Response::error(
|
||||
409,
|
||||
"the panel is off: set [panel] bind in server.toml and restart",
|
||||
),
|
||||
};
|
||||
}
|
||||
route(&shared, request)
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Endpoint(path))
|
||||
}
|
||||
|
||||
/// The API's routes, for the CLI (with the token) and the panel (with a session).
|
||||
pub fn route(shared: &Shared, request: &Request) -> Response {
|
||||
match (request.method.as_str(), request.path.as_str()) {
|
||||
("GET", "/api/v1/status") => Response::json(200, &status(shared)),
|
||||
("GET", "/api/v1/metrics") => {
|
||||
let since: u64 = request
|
||||
.param("since")
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let samples: Vec<Value> = shared
|
||||
.metrics
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|m| m["t"].as_u64().is_some_and(|t| t > since))
|
||||
.cloned()
|
||||
.collect();
|
||||
Response::json(200, &json!({ "samples": samples }))
|
||||
}
|
||||
("GET", "/api/v1/logs") => {
|
||||
let since = request
|
||||
.param("since")
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let (next, lines) = shared.log.lock().unwrap().since(since);
|
||||
Response::json(200, &json!({ "next": next, "lines": lines }))
|
||||
}
|
||||
("POST", "/api/v1/command") => {
|
||||
let line = serde_json::from_slice::<Value>(&request.body)
|
||||
.ok()
|
||||
.and_then(|v| v["line"].as_str().map(str::to_owned));
|
||||
let Some(line) = line.filter(|l| !l.trim().is_empty() && !l.contains('\n')) else {
|
||||
return Response::error(400, "the body must be {\"line\": \"<one command>\"}");
|
||||
};
|
||||
if shared.state.lock().unwrap().phase != Phase::Running {
|
||||
return Response::error(409, "the game isn't running right now");
|
||||
}
|
||||
match engine::Control::connect(&shared.dir)
|
||||
.and_then(|mut c| c.ask(&format!("console {}", line.trim_start_matches('/'))))
|
||||
{
|
||||
Ok(reply) => Response::json(200, &reply),
|
||||
Err(e) => Response::error(409, &format!("the game didn't answer: {e}")),
|
||||
}
|
||||
}
|
||||
("POST", "/api/v1/stop") => {
|
||||
shared.stop.store(true, Ordering::SeqCst);
|
||||
Response::json(200, &json!({ "ok": true }))
|
||||
}
|
||||
("POST", "/api/v1/restart") => {
|
||||
shared.restart.store(true, Ordering::SeqCst);
|
||||
Response::json(200, &json!({ "ok": true }))
|
||||
}
|
||||
("GET", "/api/v1/backups") => {
|
||||
let list: Vec<Value> = backup::list(&shared.dir)
|
||||
.into_iter()
|
||||
.map(|b| json!({ "name": b.name, "bytes": b.bytes }))
|
||||
.collect();
|
||||
Response::json(200, &json!({ "backups": list }))
|
||||
}
|
||||
("POST", "/api/v1/backups") => {
|
||||
let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
|
||||
let made = backup::file_name(std::time::SystemTime::now(), body["name"].as_str())
|
||||
.and_then(|name| shared.back_up(&name));
|
||||
match made {
|
||||
Ok(path) => Response::json(
|
||||
200,
|
||||
&json!({ "name": path.file_name().map(|n| n.to_string_lossy()) }),
|
||||
),
|
||||
Err(e) => Response::error(409, &e),
|
||||
}
|
||||
}
|
||||
("POST", "/api/v1/restore") => {
|
||||
let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
|
||||
match backup::find(&shared.dir, body["name"].as_str().unwrap_or_default()) {
|
||||
Ok(name) => {
|
||||
*shared.restore.lock().unwrap() = Some(name.clone());
|
||||
shared.restart.store(true, Ordering::SeqCst);
|
||||
Response::json(200, &json!({ "name": name }))
|
||||
}
|
||||
Err(e) => Response::error(404, &e),
|
||||
}
|
||||
}
|
||||
(
|
||||
_,
|
||||
"/api/v1/status" | "/api/v1/logs" | "/api/v1/command" | "/api/v1/stop"
|
||||
| "/api/v1/restart" | "/api/v1/backups" | "/api/v1/restore" | "/api/v1/metrics",
|
||||
) => Response::error(405, "wrong method"),
|
||||
_ => Response::error(404, "no such endpoint"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The API of the server running in a folder, for the CLI.
|
||||
pub struct Client {
|
||||
address: SocketAddr,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// The running server's API; `None` when no server runs in `dir`.
|
||||
pub fn open(dir: &Path) -> Result<Option<Self>, String> {
|
||||
if crate::supervisor::lock(dir).is_ok() {
|
||||
return Ok(None);
|
||||
}
|
||||
// The supervisor writes the endpoint just after taking the lock: give it a moment.
|
||||
let path = dir.join(ENDPOINT);
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let text = loop {
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(text) => break text,
|
||||
Err(_) if Instant::now() < deadline => {
|
||||
std::thread::sleep(Duration::from_millis(100))
|
||||
}
|
||||
Err(e) => return Err(format!("{}: {e}", path.display())),
|
||||
}
|
||||
};
|
||||
let v: Value =
|
||||
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let address = v["address"]
|
||||
.as_str()
|
||||
.and_then(|a| a.parse().ok())
|
||||
.ok_or_else(|| format!("{}: no address", path.display()))?;
|
||||
let token = v["token"].as_str().unwrap_or_default().to_owned();
|
||||
Ok(Some(Self { address, token }))
|
||||
}
|
||||
|
||||
pub fn call(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value, String> {
|
||||
self.call_within(method, path, body, Duration::from_secs(60))
|
||||
}
|
||||
|
||||
/// A call that may take long (a backup of a big world).
|
||||
pub fn call_within(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&Value>,
|
||||
timeout: Duration,
|
||||
) -> Result<Value, String> {
|
||||
let (status, text) = http::request(self.address, &self.token, method, path, body, timeout)
|
||||
.map_err(|e| format!("the server didn't answer: {e}"))?;
|
||||
let value: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
|
||||
if status == 200 {
|
||||
Ok(value)
|
||||
} else {
|
||||
Err(value["error"].as_str().unwrap_or(&text).to_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn log_keeps_the_last_lines_numbered() {
|
||||
let mut log = Log::default();
|
||||
for i in 0..LOG_LINES + 10 {
|
||||
log.push(i.to_string());
|
||||
}
|
||||
let (next, lines) = log.since(0);
|
||||
assert_eq!(next, (LOG_LINES + 10) as u64);
|
||||
assert_eq!(lines.len(), LOG_LINES);
|
||||
assert_eq!(lines[0], "10");
|
||||
let (next2, tail) = log.since(next - 2);
|
||||
assert_eq!(
|
||||
(next2, tail),
|
||||
(
|
||||
next,
|
||||
vec![(LOG_LINES + 8).to_string(), (LOG_LINES + 9).to_string()]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_api_wants_its_token() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-server-api-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join(".horizon")).unwrap();
|
||||
let shared = Shared::new(&dir);
|
||||
let _endpoint = start(shared.clone()).unwrap();
|
||||
let v: Value =
|
||||
serde_json::from_str(&std::fs::read_to_string(dir.join(ENDPOINT)).unwrap()).unwrap();
|
||||
let address: SocketAddr = v["address"].as_str().unwrap().parse().unwrap();
|
||||
let token = v["token"].as_str().unwrap();
|
||||
let get = |token: &str| {
|
||||
http::request(
|
||||
address,
|
||||
token,
|
||||
"GET",
|
||||
"/api/v1/status",
|
||||
None,
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(get("nope").0, 401);
|
||||
let (status, body) = get(token);
|
||||
assert_eq!(status, 200);
|
||||
let status: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(status["phase"], "starting");
|
||||
let (code, _) = http::request(
|
||||
address,
|
||||
token,
|
||||
"POST",
|
||||
"/api/v1/stop",
|
||||
None,
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(code, 200);
|
||||
assert!(shared.stop.load(Ordering::SeqCst));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(dir.join(ENDPOINT))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
}
|
||||
drop(_endpoint);
|
||||
assert!(!dir.join(ENDPOINT).exists());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
//! Backups and restore (docs/server.md, section 7). A backup is one zip in `backups/`: the world folder and
|
||||
//! the server's settings and lists. On a running server the game first saves everything and stops writing
|
||||
//! (`save-off`, `save-all`), and writes again once the zip is done (`save-on`), so players stay online.
|
||||
//! A restore puts the backup's world in place of the current one, which is moved aside, never deleted.
|
||||
|
||||
use crate::config::Config;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufWriter, Write},
|
||||
path::{Path, PathBuf},
|
||||
time::SystemTime,
|
||||
};
|
||||
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
|
||||
|
||||
pub const DIR: &str = "backups";
|
||||
/// The settings and lists a backup holds beside the world.
|
||||
const FILES: [&str; 6] = [
|
||||
"server.toml",
|
||||
"server.properties",
|
||||
"ops.json",
|
||||
"whitelist.json",
|
||||
"banned-players.json",
|
||||
"banned-ips.json",
|
||||
];
|
||||
/// Automatic backups are named `<time>-auto.zip`; only those are pruned.
|
||||
const AUTO: &str = "auto";
|
||||
|
||||
/// `2026-10-16_18-30-05`, in UTC: sorts by time, and is valid in a file name everywhere.
|
||||
fn stamp(time: SystemTime) -> String {
|
||||
let secs = time
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as i64);
|
||||
let (y, m, d) = horizon_server_files::java_properties::civil_from_days(secs.div_euclid(86_400));
|
||||
let s = secs.rem_euclid(86_400);
|
||||
format!(
|
||||
"{y:04}-{m:02}-{d:02}_{:02}-{:02}-{:02}",
|
||||
s / 3600,
|
||||
s / 60 % 60,
|
||||
s % 60
|
||||
)
|
||||
}
|
||||
|
||||
/// A backup's file name: the time, and a name the owner gave (letters, digits, `-` and `_` only).
|
||||
pub fn file_name(time: SystemTime, name: Option<&str>) -> Result<String, String> {
|
||||
let name = name.unwrap_or("manual");
|
||||
if name.is_empty()
|
||||
|| name.len() > 64
|
||||
|| !name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
{
|
||||
return Err(format!(
|
||||
"backup names use letters, digits, - and _ only (got {name:?})"
|
||||
));
|
||||
}
|
||||
Ok(format!("{}-{name}.zip", stamp(time)))
|
||||
}
|
||||
|
||||
/// Adds a folder to the zip, under `prefix`, skipping the game's session lock.
|
||||
fn add_dir(zip: &mut ZipWriter<BufWriter<File>>, dir: &Path, prefix: &str) -> Result<(), String> {
|
||||
let options = SimpleFileOptions::default()
|
||||
.compression_method(CompressionMethod::Deflated)
|
||||
.large_file(true);
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)
|
||||
.map_err(|e| format!("{}: {e}", dir.display()))?
|
||||
.flatten()
|
||||
.collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let path = entry.path();
|
||||
let inner = format!("{prefix}/{name}");
|
||||
if path.is_dir() {
|
||||
add_dir(zip, &path, &inner)?;
|
||||
} else if name != "session.lock" {
|
||||
zip.start_file(inner.as_str(), options)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut file = File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
std::io::copy(&mut file, zip).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Zips the world and the settings into `backups/<file_name>`. The zip is written under a temporary name
|
||||
/// and renamed when complete, so a backup that looks finished is one.
|
||||
pub fn create(dir: &Path, config: &Config, file_name: &str) -> Result<PathBuf, String> {
|
||||
let backups = dir.join(DIR);
|
||||
std::fs::create_dir_all(&backups).map_err(|e| format!("{}: {e}", backups.display()))?;
|
||||
let path = backups.join(file_name);
|
||||
let part = backups.join(format!("{file_name}.part"));
|
||||
let result = (|| {
|
||||
let file = File::create(&part).map_err(|e| format!("{}: {e}", part.display()))?;
|
||||
let mut zip = ZipWriter::new(BufWriter::new(file));
|
||||
let world = dir.join(&config.world.name);
|
||||
if world.is_dir() {
|
||||
add_dir(&mut zip, &world, &config.world.name)?;
|
||||
}
|
||||
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
|
||||
for name in FILES {
|
||||
if let Ok(bytes) = std::fs::read(dir.join(name)) {
|
||||
zip.start_file(name, options).map_err(|e| e.to_string())?;
|
||||
zip.write_all(&bytes).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
zip.finish()
|
||||
.map_err(|e| e.to_string())?
|
||||
.into_inner()
|
||||
.map_err(|e| e.to_string())?
|
||||
.sync_all()
|
||||
.map_err(|e| e.to_string())
|
||||
})();
|
||||
match result {
|
||||
Ok(()) => {
|
||||
std::fs::rename(&part, &path).map_err(|e| e.to_string())?;
|
||||
Ok(path)
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Backup {
|
||||
pub name: String,
|
||||
pub bytes: u64,
|
||||
}
|
||||
|
||||
/// The finished backups, newest first.
|
||||
pub fn list(dir: &Path) -> Vec<Backup> {
|
||||
let mut out: Vec<Backup> = std::fs::read_dir(dir.join(DIR))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
name.ends_with(".zip").then(|| Backup {
|
||||
bytes: e.metadata().map_or(0, |m| m.len()),
|
||||
name,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| b.name.cmp(&a.name));
|
||||
out
|
||||
}
|
||||
|
||||
/// Deletes the oldest automatic backups beyond `keep`. Backups made by hand are never deleted.
|
||||
pub fn prune(dir: &Path, keep: usize) -> Vec<String> {
|
||||
let auto_suffix = format!("-{AUTO}.zip");
|
||||
list(dir)
|
||||
.into_iter()
|
||||
.filter(|b| b.name.ends_with(&auto_suffix))
|
||||
.skip(keep)
|
||||
.filter(|b| std::fs::remove_file(dir.join(DIR).join(&b.name)).is_ok())
|
||||
.map(|b| b.name)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn auto_name(time: SystemTime) -> String {
|
||||
file_name(time, Some(AUTO)).expect("the automatic name is valid")
|
||||
}
|
||||
|
||||
/// The backup a name points at: a file in `backups/`, by its full name or the start of it.
|
||||
pub fn find(dir: &Path, name: &str) -> Result<String, String> {
|
||||
let all = list(dir);
|
||||
if let Some(b) = all
|
||||
.iter()
|
||||
.find(|b| b.name == name || b.name == format!("{name}.zip"))
|
||||
{
|
||||
return Ok(b.name.clone());
|
||||
}
|
||||
let matches: Vec<&Backup> = all.iter().filter(|b| b.name.starts_with(name)).collect();
|
||||
match matches.as_slice() {
|
||||
[one] => return Ok(one.name.clone()),
|
||||
[] => {}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"{name:?} matches {} backups: be more precise",
|
||||
matches.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
// The name given to `backup NAME` (or `auto`, `manual`): the newest backup with it.
|
||||
let label = format!("-{name}.zip");
|
||||
all.iter()
|
||||
.find(|b| b.name.ends_with(&label))
|
||||
.map(|b| b.name.clone())
|
||||
.ok_or_else(|| {
|
||||
format!("no backup {name:?} in {DIR}/ (`horizon-server backups` lists them)")
|
||||
})
|
||||
}
|
||||
|
||||
/// Puts the backup's world in place of the current one, which goes to `backups/replaced-<time>/`. The
|
||||
/// server must be stopped. Returns where the old world went.
|
||||
pub fn restore(dir: &Path, config: &Config, name: &str) -> Result<Option<PathBuf>, String> {
|
||||
let zip_path = dir.join(DIR).join(name);
|
||||
let scratch = dir.join(".horizon/restore");
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
std::fs::create_dir_all(&scratch).map_err(|e| e.to_string())?;
|
||||
let file = File::open(&zip_path).map_err(|e| format!("{}: {e}", zip_path.display()))?;
|
||||
ZipArchive::new(file)
|
||||
.and_then(|mut z| z.extract(&scratch))
|
||||
.map_err(|e| format!("{name}: {e}"))?;
|
||||
let world = &config.world.name;
|
||||
let restored = scratch.join(world);
|
||||
if !restored.join("level.dat").is_file() {
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
return Err(format!(
|
||||
"{name} holds no world named {world:?} (no {world}/level.dat)"
|
||||
));
|
||||
}
|
||||
let current = dir.join(world);
|
||||
let moved = if current.exists() {
|
||||
let aside = dir
|
||||
.join(DIR)
|
||||
.join(format!("replaced-{}", stamp(SystemTime::now())));
|
||||
std::fs::create_dir_all(&aside).map_err(|e| e.to_string())?;
|
||||
let target = aside.join(world);
|
||||
std::fs::rename(¤t, &target)
|
||||
.map_err(|e| format!("moving the current world aside: {e}"))?;
|
||||
Some(target)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
std::fs::rename(&restored, ¤t)
|
||||
.map_err(|e| format!("putting the backup in place: {e}"))?;
|
||||
let _ = std::fs::remove_dir_all(&scratch);
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
/// `every` from server.toml: `"6h"`, `"30m"`, `"1d"`, or `"0"` for no automatic backups.
|
||||
pub fn interval(every: &str) -> Result<Option<std::time::Duration>, String> {
|
||||
let every = every.trim();
|
||||
if every == "0" || every.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let (number, unit) = every.split_at(every.len() - 1);
|
||||
let n: u64 = number.trim().parse().map_err(|_| {
|
||||
format!("backups.every is {every:?}: use a number and m, h or d, like \"6h\"")
|
||||
})?;
|
||||
let secs = match unit {
|
||||
"m" => 60,
|
||||
"h" => 3600,
|
||||
"d" => 86_400,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"backups.every is {every:?}: use a number and m, h or d, like \"6h\""
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok((n > 0).then(|| std::time::Duration::from_secs(n * secs)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_sort_by_time() {
|
||||
let t = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_792_000_000);
|
||||
assert_eq!(
|
||||
file_name(t, Some("before-update")).unwrap(),
|
||||
"2026-10-14_17-46-40-before-update.zip"
|
||||
);
|
||||
assert!(file_name(t, Some("../x")).is_err());
|
||||
assert_eq!(auto_name(t), "2026-10-14_17-46-40-auto.zip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intervals() {
|
||||
assert_eq!(
|
||||
interval("6h").unwrap(),
|
||||
Some(std::time::Duration::from_secs(21_600))
|
||||
);
|
||||
assert_eq!(
|
||||
interval("30m").unwrap(),
|
||||
Some(std::time::Duration::from_secs(1800))
|
||||
);
|
||||
assert_eq!(interval("0").unwrap(), None);
|
||||
assert!(interval("6 hours").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn back_up_and_restore() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("horizon-server-backup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let config = Config::default();
|
||||
let world = dir.join("world");
|
||||
std::fs::create_dir_all(world.join("region")).unwrap();
|
||||
std::fs::write(world.join("level.dat"), b"before").unwrap();
|
||||
std::fs::write(world.join("region/r.0.0.mca"), vec![7u8; 10_000]).unwrap();
|
||||
std::fs::write(world.join("session.lock"), b"x").unwrap();
|
||||
std::fs::write(dir.join("server.toml"), crate::config::TEMPLATE).unwrap();
|
||||
let t = SystemTime::now();
|
||||
let name = file_name(t, None).unwrap();
|
||||
create(&dir, &config, &name).unwrap();
|
||||
assert_eq!(list(&dir).len(), 1);
|
||||
// The world changes, then the backup comes back.
|
||||
std::fs::write(world.join("level.dat"), b"after").unwrap();
|
||||
let moved = restore(&dir, &config, &find(&dir, &name[..10]).unwrap())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(world.join("level.dat")).unwrap(), b"before");
|
||||
assert_eq!(
|
||||
std::fs::read(world.join("region/r.0.0.mca")).unwrap().len(),
|
||||
10_000
|
||||
);
|
||||
assert!(!world.join("session.lock").exists());
|
||||
assert_eq!(std::fs::read(moved.join("level.dat")).unwrap(), b"after");
|
||||
// Only automatic backups are pruned.
|
||||
for i in 0..3 {
|
||||
let later = t + std::time::Duration::from_secs(10 + i);
|
||||
create(&dir, &config, &auto_name(later)).unwrap();
|
||||
}
|
||||
assert_eq!(prune(&dir, 1).len(), 2);
|
||||
let left: Vec<String> = list(&dir).into_iter().map(|b| b.name).collect();
|
||||
assert_eq!(left.len(), 2);
|
||||
assert!(left.iter().any(|n| n.ends_with("-manual.zip")));
|
||||
// A backup is found by its name, or the newest with a label.
|
||||
assert_eq!(find(&dir, "manual").unwrap(), name);
|
||||
assert_eq!(find(&dir, &left[0]).unwrap(), left[0]);
|
||||
assert_eq!(
|
||||
find(&dir, left[0].trim_end_matches(".zip")).unwrap(),
|
||||
left[0]
|
||||
);
|
||||
assert_eq!(find(&dir, "auto").unwrap(), left[0]);
|
||||
assert!(find(&dir, "nothing").is_err());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
//! The commands that manage a server in the background (docs/server.md, section 5): `start`, `stop`,
|
||||
//! `restart`, `status`, `cmd` and `logs`. They talk to the running supervisor through the control API.
|
||||
|
||||
use crate::{api::Client, backup, signals, supervisor};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
path::Path,
|
||||
process::{Command, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// How long `start` waits for the game's `Done`, and `stop` for the server to end.
|
||||
const START_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
const STOP_TIMEOUT: Duration = Duration::from_secs(180);
|
||||
|
||||
fn running(dir: &Path) -> Result<Client, String> {
|
||||
Client::open(dir)?.ok_or_else(|| format!("no server is running in {}", dir.display()))
|
||||
}
|
||||
|
||||
/// `start`: `run` in the background, its output in logs/supervisor.log; returns once the game is up.
|
||||
pub fn start(dir: &Path) -> Result<(), String> {
|
||||
if Client::open(dir)?.is_some() {
|
||||
return Err(format!("a server is already running in {}", dir.display()));
|
||||
}
|
||||
crate::config::Config::load(dir)?;
|
||||
// Left by a supervisor that was killed: the new one writes its own.
|
||||
let endpoint = dir.join(".horizon/api.json");
|
||||
let _ = std::fs::remove_file(&endpoint);
|
||||
let logs = dir.join("logs");
|
||||
std::fs::create_dir_all(&logs).map_err(|e| e.to_string())?;
|
||||
let log_path = logs.join("supervisor.log");
|
||||
let log = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&log_path)
|
||||
.map_err(|e| format!("{}: {e}", log_path.display()))?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let mut command = Command::new(exe);
|
||||
command
|
||||
.arg("--dir")
|
||||
.arg(dir)
|
||||
.arg("run")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(log.try_clone().map_err(|e| e.to_string())?)
|
||||
.stderr(log);
|
||||
// Its own process group: closing this terminal doesn't stop the server.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::process::CommandExt::process_group(&mut command, 0);
|
||||
#[cfg(windows)]
|
||||
std::os::windows::process::CommandExt::creation_flags(
|
||||
&mut command,
|
||||
windows_sys::Win32::System::Threading::DETACHED_PROCESS
|
||||
| windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP,
|
||||
);
|
||||
let mut child = command.spawn().map_err(|e| e.to_string())?;
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
print!("Starting");
|
||||
loop {
|
||||
if let Ok(Some(status)) = child.try_wait() {
|
||||
println!();
|
||||
return Err(format!(
|
||||
"the server stopped ({status}); see {}",
|
||||
log_path.display()
|
||||
));
|
||||
}
|
||||
// Only once the new supervisor holds the folder (its endpoint is there) may we look: probing the
|
||||
// lock any earlier could take it from under it.
|
||||
if endpoint.exists()
|
||||
&& let Ok(Some(client)) = Client::open(dir)
|
||||
&& let Ok(status) = client.call("GET", "/api/v1/status", None)
|
||||
&& status["phase"] == "running"
|
||||
{
|
||||
println!(
|
||||
"\nThe server is running (pid {}). `horizon-server status` shows how it does, \
|
||||
`horizon-server stop` stops it.",
|
||||
child.id()
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
println!();
|
||||
return Err(format!(
|
||||
"the game isn't up after {} s; it may still be starting: see {}",
|
||||
START_TIMEOUT.as_secs(),
|
||||
log_path.display()
|
||||
));
|
||||
}
|
||||
print!(".");
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
|
||||
/// `stop` and `restart`.
|
||||
pub fn stop(dir: &Path, restart: bool) -> Result<(), String> {
|
||||
let client = running(dir)?;
|
||||
if restart {
|
||||
let before = client.call("GET", "/api/v1/status", None)?["engine_pid"].as_u64();
|
||||
client.call("POST", "/api/v1/restart", None)?;
|
||||
print!("Restarting");
|
||||
wait_running(&client, before)?;
|
||||
println!("\nThe game is running again.");
|
||||
return Ok(());
|
||||
}
|
||||
client.call("POST", "/api/v1/stop", None)?;
|
||||
let deadline = Instant::now() + STOP_TIMEOUT;
|
||||
while supervisor::lock(dir).is_err() {
|
||||
if Instant::now() > deadline {
|
||||
return Err("the server is still stopping".into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
println!("Stopped.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits until the game is up: a new one when `replaced` is the engine's pid before a restart.
|
||||
fn wait_running(client: &Client, replaced: Option<u64>) -> Result<(), String> {
|
||||
let deadline = Instant::now() + START_TIMEOUT;
|
||||
loop {
|
||||
let status = client.call("GET", "/api/v1/status", None)?;
|
||||
if status["phase"] == "running" && status["engine_pid"].as_u64() != replaced {
|
||||
return Ok(());
|
||||
}
|
||||
if status["phase"] == "stopped" || status["phase"] == "stopping" {
|
||||
return Err("the server is stopping".into());
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
return Err(format!(
|
||||
"the game isn't up after {} s; `horizon-server logs` shows why",
|
||||
START_TIMEOUT.as_secs()
|
||||
));
|
||||
}
|
||||
if replaced.is_some() {
|
||||
print!(".");
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
|
||||
/// `cmd`: one console command, and what it printed.
|
||||
pub fn command(dir: &Path, words: &[String]) -> Result<(), String> {
|
||||
if words.is_empty() {
|
||||
return Err("cmd needs a console command, for example: horizon-server cmd list".into());
|
||||
}
|
||||
let client = running(dir)?;
|
||||
// A game that is starting or restarting takes the command once it is up.
|
||||
wait_running(&client, None)?;
|
||||
let reply = client.call(
|
||||
"POST",
|
||||
"/api/v1/command",
|
||||
Some(&json!({ "line": words.join(" ") })),
|
||||
)?;
|
||||
for line in reply["output"].as_array().into_iter().flatten() {
|
||||
println!("{}", line.as_str().unwrap_or_default());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `panel`: a one-time login link for the web panel.
|
||||
pub fn panel(dir: &Path) -> Result<(), String> {
|
||||
let reply = running(dir)?.call("POST", "/api/v1/panel/login", None)?;
|
||||
let url = reply["url"].as_str().unwrap_or_default();
|
||||
println!(
|
||||
"Open this link in your browser (it works once, for 10 minutes):\n {url}\n\
|
||||
From another computer: put a tailnet address in [panel] bind, or forward the port first:\n \
|
||||
ssh -L {port}:{target} <this server>",
|
||||
port = url
|
||||
.split('/')
|
||||
.nth(2)
|
||||
.and_then(|h| h.rsplit_once(':'))
|
||||
.map_or("8130", |(_, p)| p),
|
||||
target = url.split('/').nth(2).unwrap_or("127.0.0.1:8130"),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `status [--json]`.
|
||||
pub fn status(dir: &Path, as_json: bool) -> Result<(), String> {
|
||||
let Some(client) = Client::open(dir)? else {
|
||||
if as_json {
|
||||
println!("{}", json!({ "phase": "stopped" }));
|
||||
} else {
|
||||
println!("Stopped.");
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
let status = client.call("GET", "/api/v1/status", None)?;
|
||||
if as_json {
|
||||
println!("{status}");
|
||||
} else {
|
||||
print!("{}", describe(&status));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The status for people: three short lines.
|
||||
fn describe(status: &Value) -> String {
|
||||
let mut out = String::new();
|
||||
let phase = status["phase"].as_str().unwrap_or("?");
|
||||
let uptime = status["engine_uptime_seconds"]
|
||||
.as_u64()
|
||||
.or(status["uptime_seconds"].as_u64())
|
||||
.map_or_else(String::new, |s| format!(", up {}", duration(s)));
|
||||
let crashes = match status["crashes"].as_u64() {
|
||||
Some(0) | None => String::new(),
|
||||
Some(n) => format!(
|
||||
", {n} crash{} (last: {})",
|
||||
if n == 1 { "" } else { "es" },
|
||||
status["last_crash"].as_str().unwrap_or("?")
|
||||
),
|
||||
};
|
||||
out += &format!("{}{uptime}{crashes}\n", capitalised(phase));
|
||||
let sample = &status["sample"];
|
||||
let game = &sample["game"];
|
||||
if let Some(tps) = game["tps"].as_f64() {
|
||||
let mspt = &game["mspt"];
|
||||
out += &format!(
|
||||
"TPS {tps:.1}, MSPT {:.1} ms average, {:.1} ms P95{}\n",
|
||||
mspt["average"].as_f64().unwrap_or(0.0),
|
||||
mspt["p95"].as_f64().unwrap_or(0.0),
|
||||
if game["paused"] == true {
|
||||
" (paused: nobody online)"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
let names: Vec<&str> = game["players"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|p| p["name"].as_str())
|
||||
.collect();
|
||||
out += &format!(
|
||||
"{} of {} players{}{}, {} chunks loaded\n",
|
||||
names.len(),
|
||||
game["max_players"].as_u64().unwrap_or(0),
|
||||
if names.is_empty() { "" } else { ": " },
|
||||
names.join(", "),
|
||||
game["chunks"].as_u64().unwrap_or(0)
|
||||
);
|
||||
}
|
||||
let ram = sample["rss_bytes"]
|
||||
.as_f64()
|
||||
.map(|b| format!("RAM {:.2} GB", b / 1e9));
|
||||
let cpu = sample["cpu_percent"]
|
||||
.as_f64()
|
||||
.map(|c| format!("CPU {c:.0} % of a core"));
|
||||
let usage: Vec<String> = ram.into_iter().chain(cpu).collect();
|
||||
if !usage.is_empty() {
|
||||
out += &format!("{}\n", usage.join(", "));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn capitalised(s: &str) -> String {
|
||||
let mut c = s.chars();
|
||||
c.next()
|
||||
.map(|f| f.to_uppercase().chain(c).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn duration(secs: u64) -> String {
|
||||
match secs {
|
||||
0..60 => format!("{secs} s"),
|
||||
60..3600 => format!("{} min", secs / 60),
|
||||
3600..86_400 => format!("{} h {:02} min", secs / 3600, secs / 60 % 60),
|
||||
_ => format!("{} d {} h", secs / 86_400, secs / 3600 % 24),
|
||||
}
|
||||
}
|
||||
|
||||
/// `backup [NAME]`: through the running server (it saves first), or straight from the files.
|
||||
pub fn backup(dir: &Path, name: Option<&str>) -> Result<(), String> {
|
||||
let made = match Client::open(dir)? {
|
||||
Some(client) => client.call_within(
|
||||
"POST",
|
||||
"/api/v1/backups",
|
||||
Some(&json!({ "name": name })),
|
||||
Duration::from_secs(3600),
|
||||
)?["name"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
None => {
|
||||
let _lock = supervisor::lock(dir)?;
|
||||
let config = crate::config::Config::load(dir)?;
|
||||
let file = backup::file_name(std::time::SystemTime::now(), name)?;
|
||||
backup::create(dir, &config, &file)?;
|
||||
file
|
||||
}
|
||||
};
|
||||
println!("Backed up to {}/{made}", backup::DIR);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `backups`: the backups, newest first.
|
||||
pub fn backups(dir: &Path) -> Result<(), String> {
|
||||
let all = backup::list(dir);
|
||||
if all.is_empty() {
|
||||
println!("No backups yet: `horizon-server backup` makes one.");
|
||||
}
|
||||
for b in all {
|
||||
println!("{:>10} {}", size(b.bytes), b.name);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn size(bytes: u64) -> String {
|
||||
match bytes {
|
||||
0..1_000_000 => format!("{} kB", bytes.div_ceil(1000)),
|
||||
1_000_000..1_000_000_000 => format!("{:.1} MB", bytes as f64 / 1e6),
|
||||
_ => format!("{:.2} GB", bytes as f64 / 1e9),
|
||||
}
|
||||
}
|
||||
|
||||
/// `restore NAME [--yes]`: the backup's world in place of the current one (moved aside, not deleted). A
|
||||
/// running server restarts with it.
|
||||
pub fn restore(dir: &Path, name: &str, yes: bool) -> Result<(), String> {
|
||||
let name = backup::find(dir, name)?;
|
||||
if !yes {
|
||||
if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
|
||||
return Err("restore replaces the world: pass --yes to confirm".into());
|
||||
}
|
||||
print!(
|
||||
"Replace the world with {name}? The current world is kept in {}/. [y/N] ",
|
||||
backup::DIR
|
||||
);
|
||||
let _ = std::io::Write::flush(&mut std::io::stdout());
|
||||
let mut answer = String::new();
|
||||
let _ = std::io::stdin().read_line(&mut answer);
|
||||
if !answer.trim().eq_ignore_ascii_case("y") && !answer.trim().eq_ignore_ascii_case("yes") {
|
||||
println!("Nothing changed.");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Some(client) = Client::open(dir)? {
|
||||
let before = client.call("GET", "/api/v1/status", None)?["engine_pid"].as_u64();
|
||||
client.call("POST", "/api/v1/restore", Some(&json!({ "name": name })))?;
|
||||
print!("Restoring {name}: restarting the game with it");
|
||||
wait_running(&client, before)?;
|
||||
println!(
|
||||
"\nThe game is running on the restored world; `horizon-server logs` has the details."
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let _lock = supervisor::lock(dir)?;
|
||||
let config = crate::config::Config::load(dir)?;
|
||||
match backup::restore(dir, &config, &name)? {
|
||||
Some(old) => println!(
|
||||
"Restored {name}; the world it replaced is in {}",
|
||||
old.display()
|
||||
),
|
||||
None => println!("Restored {name}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `logs [-f] [-n N]`: the last lines, from the running server or else from logs/latest.log.
|
||||
pub fn logs(dir: &Path, follow: bool, count: usize) -> Result<(), String> {
|
||||
let Some(client) = Client::open(dir)? else {
|
||||
if follow {
|
||||
return Err("no server is running to follow".into());
|
||||
}
|
||||
let path = dir.join("logs/latest.log");
|
||||
let text =
|
||||
std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
for line in &lines[lines.len().saturating_sub(count)..] {
|
||||
println!("{line}");
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
let reply = client.call("GET", "/api/v1/logs?since=0", None)?;
|
||||
let lines = reply["lines"].as_array().cloned().unwrap_or_default();
|
||||
for line in &lines[lines.len().saturating_sub(count)..] {
|
||||
println!("{}", line.as_str().unwrap_or_default());
|
||||
}
|
||||
if !follow {
|
||||
return Ok(());
|
||||
}
|
||||
signals::install();
|
||||
let mut next = reply["next"].as_u64().unwrap_or(0);
|
||||
while signals::requests() == 0 {
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
let Ok(reply) = client.call("GET", &format!("/api/v1/logs?since={next}"), None) else {
|
||||
break;
|
||||
};
|
||||
for line in reply["lines"].as_array().into_iter().flatten() {
|
||||
println!("{}", line.as_str().unwrap_or_default());
|
||||
}
|
||||
next = reply["next"].as_u64().unwrap_or(next);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn status_reads_well() {
|
||||
let status = json!({
|
||||
"phase": "running",
|
||||
"engine_uptime_seconds": 7380,
|
||||
"crashes": 1,
|
||||
"last_crash": "signal: 9 (SIGKILL)",
|
||||
"sample": {
|
||||
"rss_bytes": 1_420_000_000u64,
|
||||
"cpu_percent": 12.4,
|
||||
"game": {
|
||||
"tps": 20.0,
|
||||
"mspt": { "average": 3.12, "p95": 7.9 },
|
||||
"players": [{ "name": "Alex" }, { "name": "Steve" }],
|
||||
"max_players": 20,
|
||||
"chunks": 1234,
|
||||
"paused": false
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(
|
||||
describe(&status),
|
||||
"Running, up 2 h 03 min, 1 crash (last: signal: 9 (SIGKILL))\n\
|
||||
TPS 20.0, MSPT 3.1 ms average, 7.9 ms P95\n\
|
||||
2 of 20 players: Alex, Steve, 1234 chunks loaded\n\
|
||||
RAM 1.42 GB, CPU 12 % of a core\n"
|
||||
);
|
||||
assert_eq!(
|
||||
describe(&json!({ "phase": "starting", "uptime_seconds": 4 })),
|
||||
"Starting, up 4 s\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
//! `server.toml`, the one file an owner edits (docs/server.md, section 4).
|
||||
//!
|
||||
//! It has typed sections for what owners change and `[properties]` for any other vanilla key. Before every
|
||||
//! start the supervisor writes them into `server.properties`, which the game reads exactly as vanilla's
|
||||
//! server does; what the game changes there itself (`/whitelist on`) is copied back afterwards.
|
||||
|
||||
use horizon_server_files::{
|
||||
java_properties::{Properties, date_string, now_millis},
|
||||
properties::{DIFFICULTIES, GAME_MODES, ServerProperties, SystemEntropy},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
pub const FILE: &str = "server.toml";
|
||||
pub const PROPERTIES: &str = "server.properties";
|
||||
|
||||
/// What `init` writes: every typed setting, with vanilla 26.3's defaults and what it means.
|
||||
pub const TEMPLATE: &str = r##"# Horizon server settings (docs/server.md). The server writes them into server.properties before
|
||||
# every start: edit this file, not that one.
|
||||
|
||||
[server]
|
||||
motd = "A Minecraft Server"
|
||||
port = 25565
|
||||
bind = "" # listen on every address, or only on this one (server-ip)
|
||||
max_players = 20
|
||||
online_mode = true # not supported by Horizon yet: the server runs offline and says so
|
||||
whitelist = true # only whitelisted players and operators can join
|
||||
enforce_whitelist = false # kick online players taken off the whitelist
|
||||
view_distance = 10
|
||||
simulation_distance = 10
|
||||
|
||||
[world]
|
||||
name = "world" # the world folder
|
||||
seed = "" # empty: a random seed on the first start
|
||||
game_mode = "survival" # survival, creative, adventure or spectator
|
||||
difficulty = "easy" # peaceful, easy, normal or hard
|
||||
hardcore = false
|
||||
|
||||
# Any other server.properties key, spelled as vanilla spells it, for example:
|
||||
# spawn-protection = 16
|
||||
[properties]
|
||||
|
||||
[engine]
|
||||
path = "" # the game program; empty: the one installed beside horizon-server
|
||||
resources = "" # the prepared game files; empty: resources/ here, else the usual places
|
||||
restart_on_crash = true
|
||||
|
||||
[backups]
|
||||
every = "6h" # automatic backups while the server runs: 30m, 6h, 1d...; "0" turns them off
|
||||
keep = 12 # automatic backups kept (backups made by hand are never deleted)
|
||||
|
||||
[panel]
|
||||
bind = "127.0.0.1:8130" # the web panel: this computer only, or a tailnet address (100.x); "" turns it off
|
||||
allow_public = false # true lets bind be any address; never put the panel on the open internet
|
||||
"##;
|
||||
|
||||
/// Each typed setting: its section, its name, and the vanilla key it writes.
|
||||
const TYPED: [(&str, &str, &str); 14] = [
|
||||
("server", "motd", "motd"),
|
||||
("server", "port", "server-port"),
|
||||
("server", "bind", "server-ip"),
|
||||
("server", "max_players", "max-players"),
|
||||
("server", "online_mode", "online-mode"),
|
||||
("server", "whitelist", "white-list"),
|
||||
("server", "enforce_whitelist", "enforce-whitelist"),
|
||||
("server", "view_distance", "view-distance"),
|
||||
("server", "simulation_distance", "simulation-distance"),
|
||||
("world", "name", "level-name"),
|
||||
("world", "seed", "level-seed"),
|
||||
("world", "game_mode", "gamemode"),
|
||||
("world", "difficulty", "difficulty"),
|
||||
("world", "hardcore", "hardcore"),
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
pub server: Server,
|
||||
#[serde(default)]
|
||||
pub world: World,
|
||||
#[serde(default)]
|
||||
pub properties: BTreeMap<String, toml::Value>,
|
||||
#[serde(default)]
|
||||
pub engine: Engine,
|
||||
#[serde(default)]
|
||||
pub backups: Backups,
|
||||
#[serde(default)]
|
||||
pub panel: Panel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Server {
|
||||
pub motd: String,
|
||||
pub port: u16,
|
||||
pub bind: String,
|
||||
pub max_players: u32,
|
||||
pub online_mode: bool,
|
||||
pub whitelist: bool,
|
||||
pub enforce_whitelist: bool,
|
||||
pub view_distance: u32,
|
||||
pub simulation_distance: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct World {
|
||||
pub name: String,
|
||||
/// A number or any text (vanilla hashes text); empty for a random seed.
|
||||
#[serde(deserialize_with = "text_or_number")]
|
||||
pub seed: String,
|
||||
pub game_mode: String,
|
||||
pub difficulty: String,
|
||||
pub hardcore: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Engine {
|
||||
pub path: String,
|
||||
pub resources: String,
|
||||
pub restart_on_crash: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Panel {
|
||||
pub bind: String,
|
||||
pub allow_public: bool,
|
||||
}
|
||||
|
||||
impl Default for Panel {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bind: "127.0.0.1:8130".into(),
|
||||
allow_public: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// Where the panel listens; `None` when it is off.
|
||||
pub fn address(&self) -> Result<Option<std::net::SocketAddr>, String> {
|
||||
if self.bind.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let address: std::net::SocketAddr = self.bind.trim().parse().map_err(|_| {
|
||||
format!(
|
||||
"panel.bind is \"{}\": use an address and a port, like 127.0.0.1:8130",
|
||||
self.bind
|
||||
)
|
||||
})?;
|
||||
if !self.allow_public && !private(address.ip()) {
|
||||
return Err(format!(
|
||||
"panel.bind is \"{}\": the panel listens only on this computer (127.0.0.1) or a tailnet \
|
||||
address (100.64.0.0/10, fd7a:115c:a1e0::/48); reach it from elsewhere over Tailscale or SSH",
|
||||
self.bind
|
||||
));
|
||||
}
|
||||
Ok(Some(address))
|
||||
}
|
||||
}
|
||||
|
||||
/// Loopback, or a Tailscale address: reachable only from this computer or the owner's tailnet.
|
||||
pub fn private(ip: std::net::IpAddr) -> bool {
|
||||
match ip {
|
||||
std::net::IpAddr::V4(v4) => {
|
||||
v4.is_loopback() || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64)
|
||||
}
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
v6.is_loopback() || v6.segments()[..3] == [0xfd7a, 0x115c, 0xa1e0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Backups {
|
||||
pub every: String,
|
||||
pub keep: u32,
|
||||
}
|
||||
|
||||
impl Default for Server {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
motd: "A Minecraft Server".into(),
|
||||
port: 25565,
|
||||
bind: String::new(),
|
||||
max_players: 20,
|
||||
online_mode: true,
|
||||
whitelist: true,
|
||||
enforce_whitelist: false,
|
||||
view_distance: 10,
|
||||
simulation_distance: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for World {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: "world".into(),
|
||||
seed: String::new(),
|
||||
game_mode: "survival".into(),
|
||||
difficulty: "easy".into(),
|
||||
hardcore: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for Engine {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
path: String::new(),
|
||||
resources: String::new(),
|
||||
restart_on_crash: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Backups {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
every: "6h".into(),
|
||||
keep: 12,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_or_number<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Seed {
|
||||
Text(String),
|
||||
Number(i64),
|
||||
}
|
||||
Ok(match Seed::deserialize(d)? {
|
||||
Seed::Text(s) => s,
|
||||
Seed::Number(n) => n.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn parse(text: &str) -> Result<Self, String> {
|
||||
let config: Self = toml::from_str(text).map_err(|e| e.to_string())?;
|
||||
config.check()?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn load(dir: &Path) -> Result<Self, String> {
|
||||
let path = dir.join(FILE);
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("{}: {e} (run `horizon-server init` first)", path.display()))?;
|
||||
Self::parse(&text).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn check(&self) -> Result<(), String> {
|
||||
let w = &self.world;
|
||||
if !GAME_MODES.contains(&w.game_mode.as_str()) {
|
||||
return Err(format!(
|
||||
"world.game_mode is \"{}\": use {}",
|
||||
w.game_mode,
|
||||
GAME_MODES.join(", ")
|
||||
));
|
||||
}
|
||||
if !DIFFICULTIES.contains(&w.difficulty.as_str()) {
|
||||
return Err(format!(
|
||||
"world.difficulty is \"{}\": use {}",
|
||||
w.difficulty,
|
||||
DIFFICULTIES.join(", ")
|
||||
));
|
||||
}
|
||||
if w.name.is_empty() || w.name.contains(['/', '\\']) || w.name == ".." {
|
||||
return Err(format!(
|
||||
"world.name \"{}\" must be a folder name, without slashes",
|
||||
w.name
|
||||
));
|
||||
}
|
||||
crate::backup::interval(&self.backups.every)?;
|
||||
self.panel.address()?;
|
||||
if self.server.port == 0 {
|
||||
return Err("server.port must be a port number from 1 to 65535".into());
|
||||
}
|
||||
if let Some((section, field, key)) =
|
||||
TYPED.iter().find(|t| self.properties.contains_key(t.2))
|
||||
{
|
||||
return Err(format!(
|
||||
"[properties] sets {key}: set {section}.{field} instead"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The vanilla keys and values this configuration sets, typed settings first.
|
||||
pub fn vanilla(&self) -> Vec<(String, String)> {
|
||||
let table = toml::Table::try_from(self).expect("a configuration is a table");
|
||||
let mut out: Vec<(String, String)> = TYPED
|
||||
.iter()
|
||||
.map(|(section, field, key)| {
|
||||
((*key).to_owned(), property_text(&table[*section][*field]))
|
||||
})
|
||||
.collect();
|
||||
out.extend(
|
||||
self.properties
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), property_text(v))),
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
/// Writes this configuration into `server.properties`, keeping the keys it doesn't set. Returns what it
|
||||
/// wrote, for [`sync_back`].
|
||||
pub fn write_properties(&self, dir: &Path) -> std::io::Result<Vec<(String, String)>> {
|
||||
let path = dir.join(PROPERTIES);
|
||||
let mut properties = read_properties(&path).unwrap_or_default();
|
||||
let written = self.vanilla();
|
||||
for (key, value) in &written {
|
||||
properties.put(key, value.clone());
|
||||
}
|
||||
let text = properties.store(
|
||||
Some("Minecraft server properties"),
|
||||
&date_string(now_millis()),
|
||||
false,
|
||||
);
|
||||
std::fs::write(path, text)?;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// A configuration from a vanilla `server.properties`: typed settings from their keys, and every other
|
||||
/// key the file sets to something other than vanilla's default under `[properties]`.
|
||||
pub fn import(source: &Properties) -> Result<Self, String> {
|
||||
let parsed = ServerProperties::new(source.clone(), &mut SystemEntropy::default())?;
|
||||
let defaults = ServerProperties::new(Properties::default(), &mut SystemEntropy::default())?;
|
||||
let mut table = toml::Table::try_from(Self::default()).map_err(|e| e.to_string())?;
|
||||
for (section, field, key) in TYPED {
|
||||
let (Some(text), Some(slot)) = (
|
||||
parsed.raw.get(key),
|
||||
table
|
||||
.get_mut(section)
|
||||
.and_then(|s| s.as_table_mut())
|
||||
.and_then(|s| s.get_mut(field)),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(value) = typed_value(text, slot) {
|
||||
*slot = value;
|
||||
}
|
||||
}
|
||||
let mut extra = toml::Table::new();
|
||||
let mut keys: Vec<&String> = source.map.keys().collect();
|
||||
keys.sort();
|
||||
for key in keys {
|
||||
let value = parsed.raw.get(key).unwrap_or_default();
|
||||
if TYPED.iter().any(|t| t.2 == key) || defaults.raw.get(key) == Some(value) {
|
||||
continue;
|
||||
}
|
||||
extra.insert(key.clone(), loose_value(value));
|
||||
}
|
||||
table.insert("properties".into(), toml::Value::Table(extra));
|
||||
let config: Self = table.try_into().map_err(|e| e.to_string())?;
|
||||
config.check()?;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
||||
/// `server.toml` for a configuration: the template's comments with this configuration's values.
|
||||
pub fn render(config: &Config) -> String {
|
||||
let mut doc: toml_edit::DocumentMut = TEMPLATE.parse().expect("the template parses");
|
||||
let table = toml::Table::try_from(config).expect("a configuration is a table");
|
||||
for (section, field, _) in TYPED {
|
||||
set(&mut doc, section, field, &table[section][field]);
|
||||
}
|
||||
for (key, value) in &config.properties {
|
||||
set(&mut doc, "properties", key, value);
|
||||
}
|
||||
for (section, field) in [
|
||||
("engine", "path"),
|
||||
("engine", "resources"),
|
||||
("engine", "restart_on_crash"),
|
||||
("backups", "every"),
|
||||
("backups", "keep"),
|
||||
("panel", "bind"),
|
||||
("panel", "allow_public"),
|
||||
] {
|
||||
set(&mut doc, section, field, &table[section][field]);
|
||||
}
|
||||
doc.to_string()
|
||||
}
|
||||
|
||||
/// After the game stopped: copies into `server.toml` the keys it wrote that the game changed in
|
||||
/// `server.properties` (`/whitelist on` stores `white-list`), keeping the owner's comments. Returns the keys
|
||||
/// copied.
|
||||
pub fn sync_back(dir: &Path, written: &[(String, String)]) -> Result<Vec<String>, String> {
|
||||
let Ok(now) = read_properties(&dir.join(PROPERTIES)) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let changed: Vec<(&str, &str)> = written
|
||||
.iter()
|
||||
.filter_map(|(key, value)| {
|
||||
now.get(key)
|
||||
.filter(|v| v != value)
|
||||
.map(|v| (key.as_str(), v))
|
||||
})
|
||||
.collect();
|
||||
if changed.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let path = dir.join(FILE);
|
||||
let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
|
||||
let mut doc: toml_edit::DocumentMut = text.parse().map_err(|e| format!("{e}"))?;
|
||||
let defaults = toml::Table::try_from(Config::default()).map_err(|e| e.to_string())?;
|
||||
for (key, value) in &changed {
|
||||
match TYPED.iter().find(|t| t.2 == *key) {
|
||||
Some((section, field, _)) => {
|
||||
if let Some(v) = typed_value(value, &defaults[*section][*field]) {
|
||||
set(&mut doc, section, field, &v);
|
||||
}
|
||||
}
|
||||
None => set(&mut doc, "properties", key, &loose_value(value)),
|
||||
}
|
||||
}
|
||||
let updated = doc.to_string();
|
||||
Config::parse(&updated)?;
|
||||
std::fs::write(&path, updated).map_err(|e| e.to_string())?;
|
||||
Ok(changed.iter().map(|(k, _)| (*k).to_owned()).collect())
|
||||
}
|
||||
|
||||
/// Sets one typed setting in `server.toml` (`whitelist on`), keeping the owner's comments.
|
||||
pub fn update(dir: &Path, section: &str, field: &str, value: toml::Value) -> Result<(), String> {
|
||||
let path = dir.join(FILE);
|
||||
let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let mut doc: toml_edit::DocumentMut = text.parse().map_err(|e| format!("{e}"))?;
|
||||
set(&mut doc, section, field, &value);
|
||||
let updated = doc.to_string();
|
||||
Config::parse(&updated)?;
|
||||
std::fs::write(&path, updated).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn read_properties(path: &Path) -> Result<Properties, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
Properties::load_file(&bytes).map_err(|e| format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Sets one value in a TOML document, keeping the comment after the old value.
|
||||
fn set(doc: &mut toml_edit::DocumentMut, section: &str, key: &str, value: &toml::Value) {
|
||||
let Some(table) = doc
|
||||
.entry(section)
|
||||
.or_insert_with(toml_edit::table)
|
||||
.as_table_mut()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut new = match value {
|
||||
toml::Value::String(s) => toml_edit::value(s.as_str()),
|
||||
toml::Value::Integer(n) => toml_edit::value(*n),
|
||||
toml::Value::Float(f) => toml_edit::value(*f),
|
||||
toml::Value::Boolean(b) => toml_edit::value(*b),
|
||||
other => toml_edit::value(other.to_string()),
|
||||
};
|
||||
if let (Some(old), Some(v)) = (
|
||||
table.get(key).and_then(|i| i.as_value()),
|
||||
new.as_value_mut(),
|
||||
) {
|
||||
*v.decor_mut() = old.decor().clone();
|
||||
}
|
||||
table.insert(key, new);
|
||||
}
|
||||
|
||||
/// How a TOML value reads in server.properties.
|
||||
fn property_text(value: &toml::Value) -> String {
|
||||
match value {
|
||||
toml::Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A server.properties value as the TOML type of `like`.
|
||||
fn typed_value(text: &str, like: &toml::Value) -> Option<toml::Value> {
|
||||
Some(match like {
|
||||
toml::Value::Boolean(_) => toml::Value::Boolean(text.eq_ignore_ascii_case("true")),
|
||||
toml::Value::Integer(_) => toml::Value::Integer(text.trim().parse().ok()?),
|
||||
_ => toml::Value::String(text.to_owned()),
|
||||
})
|
||||
}
|
||||
|
||||
/// A server.properties value for `[properties]`: a boolean or a number when it reads back the same.
|
||||
fn loose_value(text: &str) -> toml::Value {
|
||||
match text {
|
||||
"true" => toml::Value::Boolean(true),
|
||||
"false" => toml::Value::Boolean(false),
|
||||
_ => match text.parse::<i64>() {
|
||||
Ok(n) if n.to_string() == text => toml::Value::Integer(n),
|
||||
_ => toml::Value::String(text.to_owned()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn properties(pairs: &[(&str, &str)]) -> Properties {
|
||||
let mut p = Properties::default();
|
||||
for (k, v) in pairs {
|
||||
p.put(k, (*v).to_owned());
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_is_the_default() {
|
||||
assert_eq!(Config::parse(TEMPLATE).unwrap(), Config::default());
|
||||
assert_eq!(render(&Config::default()), TEMPLATE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_are_vanilla() {
|
||||
// Every typed default is what vanilla 26.3 writes for a missing key.
|
||||
let vanilla =
|
||||
ServerProperties::new(Properties::default(), &mut SystemEntropy::default()).unwrap();
|
||||
for (key, value) in Config::default().vanilla() {
|
||||
assert_eq!(vanilla.raw.get(&key), Some(value.as_str()), "{key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_keeps_what_differs() {
|
||||
let source = properties(&[
|
||||
("motd", "Hello"),
|
||||
("server-port", "25600"),
|
||||
("white-list", "false"),
|
||||
("gamemode", "1"),
|
||||
("level-seed", "12345"),
|
||||
("spawn-protection", "0"),
|
||||
("allow-flight", "false"),
|
||||
("rate-limit", "10"),
|
||||
]);
|
||||
let c = Config::import(&source).unwrap();
|
||||
assert_eq!(c.server.motd, "Hello");
|
||||
assert_eq!(c.server.port, 25600);
|
||||
assert!(!c.server.whitelist);
|
||||
assert_eq!(c.world.game_mode, "creative");
|
||||
assert_eq!(c.world.seed, "12345");
|
||||
// allow-flight=false is vanilla's default: dropped.
|
||||
assert_eq!(
|
||||
c.properties,
|
||||
BTreeMap::from([
|
||||
("rate-limit".to_owned(), toml::Value::Integer(10)),
|
||||
("spawn-protection".to_owned(), toml::Value::Integer(0)),
|
||||
])
|
||||
);
|
||||
let text = render(&c);
|
||||
assert!(text.contains("spawn-protection = 0"), "{text}");
|
||||
assert!(text.contains("port = 25600"), "{text}");
|
||||
assert_eq!(Config::parse(&text).unwrap(), c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panel_stays_private() {
|
||||
let panel = |bind: &str, allow_public| Panel {
|
||||
bind: bind.into(),
|
||||
allow_public,
|
||||
};
|
||||
assert!(panel("127.0.0.1:8130", false).address().unwrap().is_some());
|
||||
assert!(panel("[::1]:8130", false).address().unwrap().is_some());
|
||||
assert!(
|
||||
panel("100.101.102.103:8130", false)
|
||||
.address()
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
panel("[fd7a:115c:a1e0::1]:8130", false)
|
||||
.address()
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(panel("", false).address().unwrap(), None);
|
||||
assert!(panel("0.0.0.0:8130", false).address().is_err());
|
||||
assert!(panel("100.128.0.1:8130", false).address().is_err());
|
||||
assert!(panel("192.168.1.2:8130", false).address().is_err());
|
||||
assert!(panel("192.168.1.2:8130", true).address().unwrap().is_some());
|
||||
assert!(panel("localhost", false).address().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_may_be_a_number() {
|
||||
let c = Config::parse("[world]\nseed = -42\n").unwrap();
|
||||
assert_eq!(c.world.seed, "-42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_mistakes() {
|
||||
assert!(Config::parse("[world]\ngame_mode = \"creatve\"\n").is_err());
|
||||
assert!(Config::parse("[server]\nprot = 1\n").is_err());
|
||||
assert!(Config::parse("[properties]\nmotd = \"x\"\n").is_err());
|
||||
assert!(Config::parse("[world]\nname = \"../x\"\n").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_properties_and_syncs_back() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("horizon-server-config-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut c = Config::default();
|
||||
c.properties
|
||||
.insert("spawn-protection".into(), toml::Value::Integer(0));
|
||||
std::fs::write(dir.join(FILE), render(&c)).unwrap();
|
||||
std::fs::write(dir.join(PROPERTIES), "rcon.port=25576\nmotd=old\n").unwrap();
|
||||
let written = c.write_properties(&dir).unwrap();
|
||||
let p = read_properties(&dir.join(PROPERTIES)).unwrap();
|
||||
assert_eq!(p.get("motd"), Some("A Minecraft Server"));
|
||||
assert_eq!(p.get("rcon.port"), Some("25576"), "other keys are kept");
|
||||
assert_eq!(p.get("spawn-protection"), Some("0"));
|
||||
// The game turns the whitelist off and changes spawn protection.
|
||||
let mut p = p;
|
||||
p.put("white-list", "false".into());
|
||||
p.put("spawn-protection", "4".into());
|
||||
std::fs::write(dir.join(PROPERTIES), p.store(None, "date", false)).unwrap();
|
||||
let mut changed = sync_back(&dir, &written).unwrap();
|
||||
changed.sort();
|
||||
assert_eq!(changed, ["spawn-protection", "white-list"]);
|
||||
let text = std::fs::read_to_string(dir.join(FILE)).unwrap();
|
||||
assert!(
|
||||
text.contains("whitelist = false # only whitelisted"),
|
||||
"the comment stays: {text}"
|
||||
);
|
||||
let back = Config::parse(&text).unwrap();
|
||||
assert!(!back.server.whitelist);
|
||||
assert_eq!(back.properties["spawn-protection"], toml::Value::Integer(4));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! The engine: the game itself, run headless (`horizon-client --dedicated`, crates/horizon-client
|
||||
//! game/dedicated.rs). It reads the vanilla files the supervisor writes, takes console commands on stdin and
|
||||
//! logs on stdout.
|
||||
|
||||
use crate::config::Config;
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Write},
|
||||
net::{Ipv4Addr, TcpStream},
|
||||
path::{Path, PathBuf},
|
||||
process::{Child, Command, Stdio},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
/// The game's program names, most specific first: a headless engine once there is one, else the game.
|
||||
const PROGRAMS: [&str; 2] = ["horizon-engine", "horizon-client"];
|
||||
|
||||
fn exe(name: &str) -> String {
|
||||
format!("{name}{}", std::env::consts::EXE_SUFFIX)
|
||||
}
|
||||
|
||||
/// The game program: `engine.path`, else one installed beside `horizon-server`, else one on the PATH.
|
||||
pub fn program(config: &Config, dir: &Path) -> Result<PathBuf, String> {
|
||||
if !config.engine.path.is_empty() {
|
||||
let path = dir.join(&config.engine.path);
|
||||
return path
|
||||
.is_file()
|
||||
.then_some(path)
|
||||
.ok_or_else(|| format!("engine.path {} is not a file", config.engine.path));
|
||||
}
|
||||
let beside = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|e| e.parent().map(Path::to_path_buf));
|
||||
let path_dirs = std::env::var_os("PATH")
|
||||
.map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
PROGRAMS
|
||||
.iter()
|
||||
.flat_map(|name| {
|
||||
beside
|
||||
.iter()
|
||||
.chain(&path_dirs)
|
||||
.map(move |d| d.join(exe(name)))
|
||||
})
|
||||
.find(|p| p.is_file())
|
||||
.ok_or_else(|| {
|
||||
"the game program (horizon-client) is neither beside horizon-server nor on the PATH: \
|
||||
install it there, or set engine.path in server.toml"
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the prepared game files may be, in the order they are tried.
|
||||
pub fn resource_candidates(config: &Config, dir: &Path, program: Option<&Path>) -> Vec<PathBuf> {
|
||||
if !config.engine.resources.is_empty() {
|
||||
return vec![dir.join(&config.engine.resources)];
|
||||
}
|
||||
let version = "26.3";
|
||||
let mut out = vec![dir.join("resources")];
|
||||
// A release folder or a checkout: .local/horizon-client/<version> beside the program or above it.
|
||||
if let Some(program) = program {
|
||||
for ancestor in program.ancestors().skip(1).take(4) {
|
||||
out.push(ancestor.join(".local/horizon-client").join(version));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The prepared game files: a folder holding the asset index `horizon-prepare` writes.
|
||||
pub fn resources(config: &Config, dir: &Path, program: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let candidates = resource_candidates(config, dir, program);
|
||||
candidates
|
||||
.iter()
|
||||
.find(|d| d.join("asset-index.json").is_file())
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
let tried: Vec<String> = candidates
|
||||
.iter()
|
||||
.map(|d| format!(" {}", d.display()))
|
||||
.collect();
|
||||
format!(
|
||||
"no prepared game files. Horizon reads them from your own copy of Minecraft 26.3:\n\
|
||||
prepare them with `horizon-prepare --prepare --server-jar PATH` (or the launcher) and copy \
|
||||
the folder to resources/ here, or set engine.resources in server.toml. Looked in:\n{}",
|
||||
tried.join("\n")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts the engine in the server folder, with its console and log piped to the supervisor and its status
|
||||
/// on the control endpoint.
|
||||
pub fn spawn(program: &Path, resources: &Path, dir: &Path) -> std::io::Result<Child> {
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
.arg("--resources")
|
||||
.arg(resources)
|
||||
.arg("--control-socket")
|
||||
.arg(control_path(dir))
|
||||
.args(["--dedicated", "--nogui"])
|
||||
.current_dir(dir)
|
||||
.env("HORIZON_NO_AUDIO", "1")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
// The terminal's Ctrl-C reaches the supervisor alone, which then stops the game cleanly.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::process::CommandExt::process_group(&mut command, 0);
|
||||
#[cfg(windows)]
|
||||
std::os::windows::process::CommandExt::creation_flags(
|
||||
&mut command,
|
||||
windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP,
|
||||
);
|
||||
command.spawn()
|
||||
}
|
||||
|
||||
/// The game's control endpoint in a server folder (`--control-socket`): TCP on 127.0.0.1 with a token, on every OS.
|
||||
pub fn control_path(dir: &Path) -> PathBuf {
|
||||
dir.join(".horizon/engine.json")
|
||||
}
|
||||
|
||||
/// A connection to the game's control endpoint: one JSON line asked, one answered.
|
||||
pub struct Control {
|
||||
writer: TcpStream,
|
||||
reader: BufReader<TcpStream>,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
pub fn connect(dir: &Path) -> std::io::Result<Self> {
|
||||
let text = std::fs::read_to_string(control_path(dir))?;
|
||||
let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "not a control endpoint");
|
||||
let v: serde_json::Value = serde_json::from_str(&text).map_err(|_| bad())?;
|
||||
let port = v["port"]
|
||||
.as_u64()
|
||||
.and_then(|p| u16::try_from(p).ok())
|
||||
.ok_or_else(bad)?;
|
||||
let token = v["token"].as_str().ok_or_else(bad)?;
|
||||
let writer = TcpStream::connect((Ipv4Addr::LOCALHOST, port))?;
|
||||
writer.set_read_timeout(Some(Duration::from_secs(30)))?;
|
||||
let mut control = Self {
|
||||
reader: BufReader::new(writer.try_clone()?),
|
||||
writer,
|
||||
};
|
||||
let reply = control.ask(&format!("auth {token}"))?;
|
||||
if reply["ok"] != true {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"the game refused the token",
|
||||
));
|
||||
}
|
||||
Ok(control)
|
||||
}
|
||||
|
||||
pub fn ask(&mut self, line: &str) -> std::io::Result<serde_json::Value> {
|
||||
writeln!(self.writer, "{line}")?;
|
||||
self.writer.flush()?;
|
||||
let mut reply = String::new();
|
||||
if self.reader.read_line(&mut reply)? == 0 {
|
||||
return Err(std::io::ErrorKind::UnexpectedEof.into());
|
||||
}
|
||||
serde_json::from_str(&reply)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resources_are_searched_in_order() {
|
||||
let mut config = Config::default();
|
||||
let dir = Path::new("/srv/mc");
|
||||
let program = Path::new("/opt/horizon/target/release/horizon-client");
|
||||
let found = resource_candidates(&config, dir, Some(program));
|
||||
assert_eq!(found[0], Path::new("/srv/mc/resources"));
|
||||
assert!(found.contains(&PathBuf::from("/opt/horizon/.local/horizon-client/26.3")));
|
||||
config.engine.resources = "/data/res".into();
|
||||
assert_eq!(
|
||||
resource_candidates(&config, dir, Some(program)),
|
||||
[PathBuf::from("/data/res")]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Just enough HTTP/1.1 for the control API on 127.0.0.1 and the web panel (docs/server.md, sections 6 and
|
||||
//! 8): one request per connection, bodies with a Content-Length. No async runtime and no dependency: a
|
||||
//! thread per connection is plenty for a CLI, a panel tab and an MCP client.
|
||||
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
net::{SocketAddr, TcpListener, TcpStream},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
/// The largest request body the API takes (a console command, a settings change).
|
||||
const MAX_BODY: usize = 1 << 20;
|
||||
|
||||
pub struct Request {
|
||||
pub method: String,
|
||||
pub path: String,
|
||||
pub query: String,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case(name))
|
||||
.map(|(_, v)| v.as_str())
|
||||
}
|
||||
/// One `key=value` from the query string (no percent-decoding: the API's values are numbers and
|
||||
/// tokens).
|
||||
pub fn param(&self, key: &str) -> Option<&str> {
|
||||
self.query
|
||||
.split('&')
|
||||
.filter_map(|p| p.split_once('='))
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
/// One cookie the browser sent.
|
||||
pub fn cookie(&self, name: &str) -> Option<&str> {
|
||||
self.headers
|
||||
.iter()
|
||||
.filter(|(k, _)| k.eq_ignore_ascii_case("cookie"))
|
||||
.flat_map(|(_, v)| v.split(';'))
|
||||
.filter_map(|c| c.trim().split_once('='))
|
||||
.find(|(k, _)| *k == name)
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Response {
|
||||
pub status: u16,
|
||||
pub content_type: &'static str,
|
||||
pub headers: Vec<(&'static str, String)>,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
pub fn json(status: u16, value: &serde_json::Value) -> Self {
|
||||
Self::text(status, "application/json", value.to_string())
|
||||
}
|
||||
pub fn error(status: u16, message: &str) -> Self {
|
||||
Self::json(status, &serde_json::json!({ "error": message }))
|
||||
}
|
||||
pub fn text(status: u16, content_type: &'static str, body: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
content_type,
|
||||
headers: Vec::new(),
|
||||
body: body.into(),
|
||||
}
|
||||
}
|
||||
pub fn with(mut self, header: &'static str, value: impl Into<String>) -> Self {
|
||||
self.headers.push((header, value.into()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn reason(status: u16) -> &'static str {
|
||||
match status {
|
||||
200 => "OK",
|
||||
303 => "See Other",
|
||||
400 => "Bad Request",
|
||||
401 => "Unauthorized",
|
||||
403 => "Forbidden",
|
||||
404 => "Not Found",
|
||||
405 => "Method Not Allowed",
|
||||
409 => "Conflict",
|
||||
413 => "Payload Too Large",
|
||||
429 => "Too Many Requests",
|
||||
_ => "Error",
|
||||
}
|
||||
}
|
||||
|
||||
fn read_request(stream: &TcpStream) -> Result<Request, Response> {
|
||||
let bad = |m: &str| Response::error(400, m);
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).map_err(|_| bad("no request"))?;
|
||||
let mut parts = line.split_whitespace();
|
||||
let (Some(method), Some(target)) = (parts.next(), parts.next()) else {
|
||||
return Err(bad("malformed request line"));
|
||||
};
|
||||
let (path, query) = target.split_once('?').unwrap_or((target, ""));
|
||||
let mut headers = Vec::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).map_err(|_| bad("headers"))? == 0 || line.trim().is_empty() {
|
||||
break;
|
||||
}
|
||||
if headers.len() > 64 {
|
||||
return Err(bad("too many headers"));
|
||||
}
|
||||
if let Some((k, v)) = line.split_once(':') {
|
||||
headers.push((k.trim().to_owned(), v.trim().to_owned()));
|
||||
}
|
||||
}
|
||||
let length = headers
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
|
||||
.map_or(Ok(0), |(_, v)| v.parse::<usize>())
|
||||
.map_err(|_| bad("bad Content-Length"))?;
|
||||
if length > MAX_BODY {
|
||||
return Err(Response::error(413, "the body is too large"));
|
||||
}
|
||||
let mut body = vec![0; length];
|
||||
reader
|
||||
.read_exact(&mut body)
|
||||
.map_err(|_| bad("the body is shorter than its Content-Length"))?;
|
||||
Ok(Request {
|
||||
method: method.to_owned(),
|
||||
path: path.to_owned(),
|
||||
query: query.to_owned(),
|
||||
headers,
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
fn write_response(mut stream: &TcpStream, response: &Response) {
|
||||
let mut head = format!(
|
||||
"HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n",
|
||||
response.status,
|
||||
reason(response.status),
|
||||
response.content_type,
|
||||
response.body.len(),
|
||||
);
|
||||
for (name, value) in &response.headers {
|
||||
head.push_str(&format!("{name}: {value}\r\n"));
|
||||
}
|
||||
head.push_str("\r\n");
|
||||
let _ = stream
|
||||
.write_all(head.as_bytes())
|
||||
.and_then(|()| stream.write_all(response.body.as_bytes()));
|
||||
let _ = stream.flush();
|
||||
}
|
||||
|
||||
/// Serves `handle` on `listener` until the process ends, a thread per connection.
|
||||
pub fn serve(
|
||||
listener: TcpListener,
|
||||
handle: impl Fn(&Request) -> Response + Send + Sync + 'static,
|
||||
) -> std::io::Result<()> {
|
||||
let handle = std::sync::Arc::new(handle);
|
||||
std::thread::Builder::new()
|
||||
.name("api".into())
|
||||
.spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
let handle = handle.clone();
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("api-client".into())
|
||||
.spawn(move || {
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
|
||||
let response = match read_request(&stream) {
|
||||
Ok(request) => handle(&request),
|
||||
Err(response) => response,
|
||||
};
|
||||
write_response(&stream, &response);
|
||||
});
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One request to `address`, with a bearer token; the status and the body.
|
||||
pub fn request(
|
||||
address: SocketAddr,
|
||||
token: &str,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<&serde_json::Value>,
|
||||
timeout: Duration,
|
||||
) -> std::io::Result<(u16, String)> {
|
||||
let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(5))?;
|
||||
stream.set_read_timeout(Some(timeout))?;
|
||||
let body = body.map(ToString::to_string).unwrap_or_default();
|
||||
write!(
|
||||
stream,
|
||||
"{method} {path} HTTP/1.1\r\nHost: {address}\r\nAuthorization: Bearer {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)?;
|
||||
stream.flush()?;
|
||||
let mut text = String::new();
|
||||
stream.read_to_string(&mut text)?;
|
||||
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
|
||||
let status = head
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or_else(|| std::io::Error::other("not an HTTP response"))?;
|
||||
Ok((status, body.to_owned()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trip() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
serve(listener, |r| {
|
||||
Response::json(
|
||||
200,
|
||||
&serde_json::json!({
|
||||
"method": r.method,
|
||||
"path": r.path,
|
||||
"since": r.param("since"),
|
||||
"auth": r.header("authorization"),
|
||||
"body": String::from_utf8_lossy(&r.body),
|
||||
}),
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let (status, body) = request(
|
||||
address,
|
||||
"t0k",
|
||||
"POST",
|
||||
"/api/v1/command?since=7",
|
||||
Some(&serde_json::json!({ "line": "list" })),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(status, 200);
|
||||
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(v["method"], "POST");
|
||||
assert_eq!(v["path"], "/api/v1/command");
|
||||
assert_eq!(v["since"], "7");
|
||||
assert_eq!(v["auth"], "Bearer t0k");
|
||||
assert_eq!(v["body"], r#"{"line":"list"}"#);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! `horizon-server init`: the first run (docs/server.md, section 3). It asks about the EULA, the world, the
|
||||
//! port and who may join, imports an existing `server.properties`, finds the game, and writes `server.toml`.
|
||||
//! Every question has a flag, so it also runs unattended (Docker, scripts).
|
||||
|
||||
use crate::{config, config::Config, engine};
|
||||
use horizon_server_files::{
|
||||
eula,
|
||||
java_properties::now_millis,
|
||||
user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList},
|
||||
};
|
||||
use std::{
|
||||
io::{BufRead, IsTerminal, Write},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
/// The answers given as flags; what is missing is asked, or defaulted with `yes`.
|
||||
#[derive(Default)]
|
||||
pub struct Answers {
|
||||
pub eula: bool,
|
||||
pub world: Option<String>,
|
||||
pub seed: Option<String>,
|
||||
pub port: Option<u16>,
|
||||
pub whitelist: Option<bool>,
|
||||
pub players: Vec<String>,
|
||||
pub op: Option<String>,
|
||||
/// Take the default for every question not answered by a flag.
|
||||
pub yes: bool,
|
||||
}
|
||||
|
||||
impl Answers {
|
||||
/// The answers in the environment, for containers: `HORIZON_EULA=true`, `HORIZON_WORLD`,
|
||||
/// `HORIZON_SEED`, `HORIZON_PORT`, `HORIZON_WHITELIST=true|false`, `HORIZON_PLAYERS` (names separated by
|
||||
/// commas) and `HORIZON_OP`. Flags given on the command line win.
|
||||
pub fn from_env() -> Result<Self, String> {
|
||||
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
|
||||
let flag = |name: &str| var(name).map(|v| v.eq_ignore_ascii_case("true"));
|
||||
Ok(Self {
|
||||
eula: flag("HORIZON_EULA").unwrap_or(false),
|
||||
world: var("HORIZON_WORLD"),
|
||||
seed: var("HORIZON_SEED"),
|
||||
port: var("HORIZON_PORT")
|
||||
.map(|p| {
|
||||
p.parse()
|
||||
.map_err(|_| format!("HORIZON_PORT is {p:?}: use a port number"))
|
||||
})
|
||||
.transpose()?,
|
||||
whitelist: flag("HORIZON_WHITELIST"),
|
||||
players: var("HORIZON_PLAYERS")
|
||||
.map(|p| {
|
||||
p.split([',', ' '])
|
||||
.filter(|n| !n.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
op: var("HORIZON_OP"),
|
||||
yes: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Prompt {
|
||||
interactive: bool,
|
||||
}
|
||||
|
||||
impl Prompt {
|
||||
fn ask(&self, question: &str, default: &str) -> String {
|
||||
if !self.interactive {
|
||||
return default.to_owned();
|
||||
}
|
||||
if default.is_empty() {
|
||||
print!("{question}: ");
|
||||
} else {
|
||||
print!("{question} [{default}]: ");
|
||||
}
|
||||
let _ = std::io::stdout().flush();
|
||||
let mut line = String::new();
|
||||
if std::io::stdin().lock().read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return default.to_owned();
|
||||
}
|
||||
match line.trim() {
|
||||
"" => default.to_owned(),
|
||||
answer => answer.to_owned(),
|
||||
}
|
||||
}
|
||||
fn yes(&self, question: &str, default: bool) -> bool {
|
||||
let answer = self.ask(
|
||||
&format!("{question} ({})", if default { "Y/n" } else { "y/N" }),
|
||||
"",
|
||||
);
|
||||
match answer.to_ascii_lowercase().as_str() {
|
||||
"" => default,
|
||||
a => a.starts_with('y'),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(dir: &Path, answers: Answers) -> Result<(), String> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let toml_path = dir.join(config::FILE);
|
||||
if toml_path.exists() {
|
||||
return Err(format!(
|
||||
"{} already exists: this server is set up. Edit it, or start the server with `horizon-server run`",
|
||||
toml_path.display()
|
||||
));
|
||||
}
|
||||
let prompt = Prompt {
|
||||
interactive: !answers.yes && std::io::stdin().is_terminal(),
|
||||
};
|
||||
|
||||
// An existing vanilla server folder: its settings become server.toml.
|
||||
let properties = dir.join(config::PROPERTIES);
|
||||
let mut cfg = if properties.exists() {
|
||||
let source = config::read_properties(&properties)?;
|
||||
let cfg = Config::import(&source)?;
|
||||
let kept = dir.join("server.properties.imported");
|
||||
std::fs::copy(&properties, &kept).map_err(|e| e.to_string())?;
|
||||
println!(
|
||||
"Imported server.properties into server.toml (the original is kept as {}).",
|
||||
kept.display()
|
||||
);
|
||||
cfg
|
||||
} else {
|
||||
Config::default()
|
||||
};
|
||||
|
||||
// 1. The EULA: only a yes writes eula=true.
|
||||
let eula_path = dir.join("eula.txt");
|
||||
let agreed = eula::agreed(&eula_path).unwrap_or(false);
|
||||
if !agreed {
|
||||
println!(
|
||||
"Minecraft's End User License Agreement applies to running a server: {}",
|
||||
eula::EULA_LINK
|
||||
);
|
||||
let yes = answers.eula || (prompt.interactive && prompt.yes("Do you agree to it?", false));
|
||||
if !yes {
|
||||
let _ = std::fs::write(&eula_path, eula::file(now_millis(), false));
|
||||
return Err(
|
||||
"the server can't run until you agree to the EULA: run init again and answer yes, \
|
||||
or pass --eula"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
std::fs::write(&eula_path, eula::file(now_millis(), true)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
// 2. The world: an existing one keeps its seed.
|
||||
cfg.world.name = answers
|
||||
.world
|
||||
.unwrap_or_else(|| prompt.ask("World name", &cfg.world.name));
|
||||
if dir.join(&cfg.world.name).join("level.dat").exists() {
|
||||
println!("Using the existing world in {}.", cfg.world.name);
|
||||
} else {
|
||||
cfg.world.seed = answers
|
||||
.seed
|
||||
.unwrap_or_else(|| prompt.ask("Seed (empty for a random one)", &cfg.world.seed));
|
||||
}
|
||||
|
||||
// 3. The port, checked free now rather than at the first start.
|
||||
cfg.server.port = match answers.port {
|
||||
Some(port) => port,
|
||||
None => prompt
|
||||
.ask("Port", &cfg.server.port.to_string())
|
||||
.parse()
|
||||
.map_err(|_| "the port must be a number from 1 to 65535".to_owned())?,
|
||||
};
|
||||
if std::net::TcpListener::bind(("0.0.0.0", cfg.server.port)).is_err() {
|
||||
println!(
|
||||
"Port {} is in use right now: stop what uses it, or change server.port in server.toml.",
|
||||
cfg.server.port
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Who may join.
|
||||
cfg.server.whitelist = answers.whitelist.unwrap_or_else(|| {
|
||||
prompt.yes(
|
||||
"Only let in players you list (whitelist)?",
|
||||
cfg.server.whitelist,
|
||||
)
|
||||
});
|
||||
let mut players = answers.players;
|
||||
if players.is_empty() && cfg.server.whitelist {
|
||||
players = prompt
|
||||
.ask("Players to let in (names, separated by commas)", "")
|
||||
.split([',', ' '])
|
||||
.filter(|n| !n.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
}
|
||||
let op = answers.op.or_else(|| {
|
||||
let first = players.first()?;
|
||||
prompt
|
||||
.yes(&format!("Make {first} an operator?"), true)
|
||||
.then(|| first.clone())
|
||||
});
|
||||
add_players(dir, &players, op.as_deref())?;
|
||||
|
||||
// 5. The game and its files.
|
||||
match engine::program(&cfg, dir) {
|
||||
Ok(program) => {
|
||||
println!("Game: {}", program.display());
|
||||
match engine::resources(&cfg, dir, Some(&program)) {
|
||||
Ok(resources) => println!("Game files: {}", resources.display()),
|
||||
Err(e) => println!("{e}"),
|
||||
}
|
||||
}
|
||||
Err(e) => println!("{e}"),
|
||||
}
|
||||
|
||||
std::fs::write(&toml_path, config::render(&cfg)).map_err(|e| e.to_string())?;
|
||||
println!(
|
||||
"Wrote {}. Start the server with: horizon-server run --dir {}",
|
||||
toml_path.display(),
|
||||
dir.display()
|
||||
);
|
||||
if cfg.server.online_mode {
|
||||
println!(
|
||||
"Note: Horizon's server doesn't check Mojang accounts yet (online mode), so it runs offline: \
|
||||
keep the whitelist on, or play on a LAN or a tailnet."
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds players to the whitelist (and one as an operator) in vanilla's files, with offline UUIDs as the
|
||||
/// server runs offline.
|
||||
fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), String> {
|
||||
if !players.is_empty() {
|
||||
let mut white = WhiteList::new(dir.join("whitelist.json"));
|
||||
let _ = white.load();
|
||||
for name in players {
|
||||
white.add(WhiteEntry {
|
||||
user: NameAndId::offline(name),
|
||||
});
|
||||
}
|
||||
println!("Whitelisted: {}", players.join(", "));
|
||||
}
|
||||
if let Some(name) = op {
|
||||
let mut ops = OpList::new(dir.join("ops.json"));
|
||||
let _ = ops.load();
|
||||
ops.add(OpEntry {
|
||||
user: NameAndId::offline(name),
|
||||
level: 4,
|
||||
bypasses_player_limit: false,
|
||||
});
|
||||
println!("Operator: {name}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unattended_init_writes_everything() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-server-init-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let answers = Answers {
|
||||
eula: true,
|
||||
world: Some("survival".into()),
|
||||
seed: Some("12345".into()),
|
||||
port: Some(25599),
|
||||
whitelist: Some(true),
|
||||
players: vec!["Alex".into(), "Steve".into()],
|
||||
op: Some("Alex".into()),
|
||||
yes: true,
|
||||
};
|
||||
run(&dir, answers).unwrap();
|
||||
let cfg = Config::load(&dir).unwrap();
|
||||
assert_eq!(
|
||||
(
|
||||
cfg.world.name.as_str(),
|
||||
cfg.world.seed.as_str(),
|
||||
cfg.server.port
|
||||
),
|
||||
("survival", "12345", 25599)
|
||||
);
|
||||
assert!(eula::agreed(&dir.join("eula.txt")).unwrap());
|
||||
let white = std::fs::read_to_string(dir.join("whitelist.json")).unwrap();
|
||||
assert!(
|
||||
white.contains("\"Alex\"") && white.contains("\"Steve\""),
|
||||
"{white}"
|
||||
);
|
||||
let ops = std::fs::read_to_string(dir.join("ops.json")).unwrap();
|
||||
assert!(
|
||||
ops.contains("\"Alex\"") && ops.contains("\"level\": 4"),
|
||||
"{ops}"
|
||||
);
|
||||
// A second init refuses to overwrite the configuration.
|
||||
assert!(run(&dir, Answers::default()).is_err());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_eula_no_server() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-server-eula-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let answers = Answers {
|
||||
yes: true,
|
||||
..Answers::default()
|
||||
};
|
||||
assert!(run(&dir, answers).unwrap_err().contains("EULA"));
|
||||
assert!(!dir.join(config::FILE).exists());
|
||||
assert!(!eula::agreed(&dir.join("eula.txt")).unwrap());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! `op`, `deop` and `whitelist`. While the server runs, the game owns the lists: the command goes to its
|
||||
//! console. While it is stopped, they edit vanilla's files with the code the game reads them with
|
||||
//! (horizon-server-files) and answer with vanilla's console messages.
|
||||
|
||||
use crate::{config, supervisor};
|
||||
use horizon_server_files::user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList};
|
||||
use std::path::Path;
|
||||
|
||||
pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> {
|
||||
let config = config::Config::load(dir)?;
|
||||
// Holding the folder's lock keeps the server from starting halfway through.
|
||||
let Ok(_lock) = supervisor::lock(dir) else {
|
||||
let mut words = vec![command.to_owned()];
|
||||
words.extend_from_slice(args);
|
||||
return crate::cli::command(dir, &words);
|
||||
};
|
||||
let args: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
let ops_path = dir.join("ops.json");
|
||||
let white_path = dir.join("whitelist.json");
|
||||
let message = match (command, args.as_slice()) {
|
||||
("op", [name]) => {
|
||||
let mut ops = load(OpList::new(ops_path))?;
|
||||
let user = NameAndId::offline(name);
|
||||
if ops.contains(&user) {
|
||||
"Nothing changed. The player already is an operator".to_owned()
|
||||
} else {
|
||||
ops.add(OpEntry {
|
||||
user,
|
||||
level: 4,
|
||||
bypasses_player_limit: false,
|
||||
});
|
||||
format!("Made {name} a server operator")
|
||||
}
|
||||
}
|
||||
("deop", [name]) => {
|
||||
let mut ops = load(OpList::new(ops_path))?;
|
||||
if ops.remove(&NameAndId::offline(name)) {
|
||||
format!("Made {name} no longer a server operator")
|
||||
} else {
|
||||
"Nothing changed. The player is not an operator".to_owned()
|
||||
}
|
||||
}
|
||||
("whitelist", ["add", name]) => {
|
||||
let mut white = load(WhiteList::new(white_path))?;
|
||||
let user = NameAndId::offline(name);
|
||||
if white.contains(&user) {
|
||||
"Player is already whitelisted".to_owned()
|
||||
} else {
|
||||
white.add(WhiteEntry { user });
|
||||
format!("Added {name} to the whitelist")
|
||||
}
|
||||
}
|
||||
("whitelist", ["remove", name]) => {
|
||||
let mut white = load(WhiteList::new(white_path))?;
|
||||
if white.remove(&NameAndId::offline(name)) {
|
||||
format!("Removed {name} from the whitelist")
|
||||
} else {
|
||||
"Player is not whitelisted".to_owned()
|
||||
}
|
||||
}
|
||||
("whitelist", [state @ ("on" | "off")]) => {
|
||||
let on = *state == "on";
|
||||
match (on, config.server.whitelist) {
|
||||
(true, true) => "Whitelist is already turned on".to_owned(),
|
||||
(false, false) => "Whitelist is already turned off".to_owned(),
|
||||
_ => {
|
||||
config::update(dir, "server", "whitelist", toml::Value::Boolean(on))?;
|
||||
format!("Whitelist is now turned {state}")
|
||||
}
|
||||
}
|
||||
}
|
||||
("whitelist", ["list"]) => {
|
||||
let white = load(WhiteList::new(white_path))?;
|
||||
let names: Vec<String> = white
|
||||
.entries()
|
||||
.iter()
|
||||
.map(|e| e.user.name.clone())
|
||||
.collect();
|
||||
let state = if config.server.whitelist { "on" } else { "off" };
|
||||
if names.is_empty() {
|
||||
format!("There are no whitelisted players (the whitelist is {state})")
|
||||
} else {
|
||||
format!(
|
||||
"There are {} whitelisted player(s): {} (the whitelist is {state})",
|
||||
names.len(),
|
||||
names.join(", ")
|
||||
)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(
|
||||
"use: op NAME, deop NAME, whitelist on|off|list, whitelist add|remove NAME".into(),
|
||||
);
|
||||
}
|
||||
};
|
||||
println!("{message}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A list from its file; a missing file is an empty list, a broken one an error (vanilla would replace it).
|
||||
fn load<E: horizon_server_files::user_lists::Entry>(
|
||||
mut list: horizon_server_files::user_lists::UserList<E>,
|
||||
) -> Result<horizon_server_files::user_lists::UserList<E>, String> {
|
||||
if list.file.exists() {
|
||||
list.load()
|
||||
.map_err(|e| format!("{}: {e}", list.file.display()))?;
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn edits_the_lists_while_stopped() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-server-lists-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join(config::FILE), config::TEMPLATE).unwrap();
|
||||
let s = |v: &[&str]| v.iter().map(|a| (*a).to_owned()).collect::<Vec<_>>();
|
||||
run(&dir, "op", &s(&["Alex"])).unwrap();
|
||||
run(&dir, "whitelist", &s(&["add", "Steve"])).unwrap();
|
||||
run(&dir, "whitelist", &s(&["off"])).unwrap();
|
||||
assert!(
|
||||
std::fs::read_to_string(dir.join("ops.json"))
|
||||
.unwrap()
|
||||
.contains("Alex")
|
||||
);
|
||||
assert!(
|
||||
std::fs::read_to_string(dir.join("whitelist.json"))
|
||||
.unwrap()
|
||||
.contains("Steve")
|
||||
);
|
||||
assert!(!config::Config::load(&dir).unwrap().server.whitelist);
|
||||
run(&dir, "deop", &s(&["Alex"])).unwrap();
|
||||
assert!(
|
||||
!std::fs::read_to_string(dir.join("ops.json"))
|
||||
.unwrap()
|
||||
.contains("Alex")
|
||||
);
|
||||
// A running server owns the lists: without its API, nothing changes.
|
||||
let lock = supervisor::lock(&dir).unwrap();
|
||||
assert!(run(&dir, "op", &s(&["Alex"])).is_err());
|
||||
drop(lock);
|
||||
assert!(
|
||||
!std::fs::read_to_string(dir.join("ops.json"))
|
||||
.unwrap()
|
||||
.contains("Alex")
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//! `horizon-server`: host a Horizon server (docs/server.md). It keeps the server's settings in `server.toml`,
|
||||
//! runs the game headless as the engine, and manages the vanilla files around it.
|
||||
|
||||
mod api;
|
||||
mod backup;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod engine;
|
||||
mod http;
|
||||
mod init;
|
||||
mod lists;
|
||||
mod panel;
|
||||
mod service;
|
||||
mod signals;
|
||||
mod supervisor;
|
||||
|
||||
use std::{path::PathBuf, process::ExitCode};
|
||||
|
||||
const HELP: &str = "\
|
||||
horizon-server: host a Horizon (Minecraft Java Edition 26.3) server
|
||||
|
||||
Usage: horizon-server [--dir DIR] <command>
|
||||
|
||||
init Set up a server here: the EULA, the world, the port, who may join (asks, or takes flags:
|
||||
--eula --world NAME --seed SEED --port N --whitelist/--no-whitelist --player NAME... --op NAME
|
||||
--yes)
|
||||
run Run the server in the foreground; type console commands, Ctrl-C stops it cleanly. It
|
||||
restarts the game if it crashes.
|
||||
start Run the server in the background (its output goes to logs/supervisor.log)
|
||||
stop, restart
|
||||
status [--json]
|
||||
Up or not, TPS, MSPT, players, RAM and CPU
|
||||
cmd COMMAND...
|
||||
Run a console command on the running server and print what it answers
|
||||
logs [-f] [-n N]
|
||||
The last N lines of the log (default 50); -f follows it
|
||||
backup [NAME]
|
||||
Zip the world and the settings into backups/ (a running server saves first and stays up)
|
||||
backups List the backups
|
||||
restore BACKUP [--yes]
|
||||
Put a backup's world in place (the current one is kept in backups/); a running
|
||||
server restarts with it
|
||||
service install|uninstall|print [--system]
|
||||
Start the server at boot or login: a systemd unit on Linux (--system: for every user,
|
||||
with sudo), a launchd agent on macOS, a task at logon on Windows
|
||||
panel A one-time login link for the web panel ([panel] in server.toml; 127.0.0.1:8130 by
|
||||
default)
|
||||
import FILE Write server.toml from a vanilla server.properties
|
||||
op NAME, deop NAME
|
||||
whitelist on|off|list, whitelist add|remove NAME
|
||||
Who may join (on the running server, or in the files when it is stopped)
|
||||
|
||||
--dir DIR The server folder (default: the current folder)
|
||||
|
||||
Settings live in server.toml; the server writes server.properties from it before every start.
|
||||
";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut dir = PathBuf::from(".");
|
||||
if let Some(i) = args.iter().position(|a| a == "--dir") {
|
||||
if i + 1 >= args.len() {
|
||||
eprintln!("horizon-server: --dir needs a folder");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
dir = PathBuf::from(args.remove(i + 1));
|
||||
args.remove(i);
|
||||
}
|
||||
let result = match args.first().map(String::as_str) {
|
||||
None | Some("help" | "-h" | "--help") => {
|
||||
print!("{HELP}");
|
||||
Ok(())
|
||||
}
|
||||
Some("version" | "-V" | "--version") => {
|
||||
println!("horizon-server {}", env!("CARGO_PKG_VERSION"));
|
||||
Ok(())
|
||||
}
|
||||
Some("init") => init_answers(&args[1..]).and_then(|a| init::run(&dir, a)),
|
||||
Some("run") => supervisor::run(&dir),
|
||||
Some("start") => cli::start(&dir),
|
||||
Some("stop") => cli::stop(&dir, false),
|
||||
Some("restart") => cli::stop(&dir, true),
|
||||
Some("status") => cli::status(&dir, args[1..].iter().any(|a| a == "--json")),
|
||||
Some("cmd") => cli::command(&dir, &args[1..]),
|
||||
Some("logs") => logs(&dir, &args[1..]),
|
||||
Some("panel") => cli::panel(&dir),
|
||||
Some("backup") => cli::backup(&dir, args.get(1).map(String::as_str)),
|
||||
Some("backups") => cli::backups(&dir),
|
||||
Some("service") => service::command(&dir, &args[1..]),
|
||||
Some("restore") => match args.get(1) {
|
||||
Some(name) => cli::restore(&dir, name, args[2..].iter().any(|a| a == "--yes")),
|
||||
None => Err("restore needs a backup (`horizon-server backups` lists them)".into()),
|
||||
},
|
||||
Some("import") => import(&dir, &args[1..]),
|
||||
Some(command @ ("op" | "deop" | "whitelist")) => lists::run(&dir, command, &args[1..]),
|
||||
Some(other) => Err(format!(
|
||||
"unknown command {other}; `horizon-server help` lists them"
|
||||
)),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("horizon-server: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn logs(dir: &std::path::Path, args: &[String]) -> Result<(), String> {
|
||||
let mut follow = false;
|
||||
let mut count = 50;
|
||||
let mut it = args.iter();
|
||||
while let Some(arg) = it.next() {
|
||||
match arg.as_str() {
|
||||
"-f" | "--follow" => follow = true,
|
||||
"-n" => {
|
||||
count = it
|
||||
.next()
|
||||
.and_then(|n| n.parse().ok())
|
||||
.ok_or("-n needs a number of lines")?;
|
||||
}
|
||||
other => return Err(format!("logs: unknown option {other}")),
|
||||
}
|
||||
}
|
||||
cli::logs(dir, follow, count)
|
||||
}
|
||||
|
||||
fn init_answers(args: &[String]) -> Result<init::Answers, String> {
|
||||
let mut answers = init::Answers::from_env()?;
|
||||
let mut it = args.iter();
|
||||
while let Some(arg) = it.next() {
|
||||
let mut value = |flag: &str| {
|
||||
it.next()
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("{flag} needs a value"))
|
||||
};
|
||||
match arg.as_str() {
|
||||
"--eula" => answers.eula = true,
|
||||
"--yes" | "-y" => answers.yes = true,
|
||||
"--world" => answers.world = Some(value(arg)?),
|
||||
"--seed" => answers.seed = Some(value(arg)?),
|
||||
"--port" => {
|
||||
answers.port = Some(
|
||||
value(arg)?
|
||||
.parse()
|
||||
.map_err(|_| "--port needs a number from 1 to 65535")?,
|
||||
);
|
||||
}
|
||||
"--whitelist" => answers.whitelist = Some(true),
|
||||
"--no-whitelist" => answers.whitelist = Some(false),
|
||||
"--player" => answers.players.push(value(arg)?),
|
||||
"--op" => answers.op = Some(value(arg)?),
|
||||
other => return Err(format!("init: unknown option {other}")),
|
||||
}
|
||||
}
|
||||
Ok(answers)
|
||||
}
|
||||
|
||||
fn import(dir: &std::path::Path, args: &[String]) -> Result<(), String> {
|
||||
let [source] = args else {
|
||||
return Err("import needs the server.properties to read".into());
|
||||
};
|
||||
let target = dir.join(config::FILE);
|
||||
if target.exists() {
|
||||
return Err(format!(
|
||||
"{} already exists; move it away first",
|
||||
target.display()
|
||||
));
|
||||
}
|
||||
let cfg = config::Config::import(&config::read_properties(std::path::Path::new(source))?)?;
|
||||
std::fs::write(&target, config::render(&cfg)).map_err(|e| e.to_string())?;
|
||||
println!("Wrote {}", target.display());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
//! The web panel (docs/server.md, section 6): one page embedded in the binary, served by the supervisor on
|
||||
//! `[panel] bind` (127.0.0.1:8130 by default; a tailnet address to reach it from the owner's devices). It
|
||||
//! uses the control API's routes with a browser session instead of the token.
|
||||
//!
|
||||
//! - **Login.** `horizon-server panel` asks the API for a link with a one-time code, good for 10 minutes;
|
||||
//! opening it swaps the code for an `HttpOnly; SameSite=Strict` session cookie. Anyone who can read the
|
||||
//! server folder's token can make a link, and no one else can. Sessions end when the supervisor does.
|
||||
//! - **Rebinding and CSRF.** The `Host` header must name the panel's own address (`localhost` too on
|
||||
//! loopback, a MagicDNS name on a tailnet). Every POST needs the `X-Horizon: 1` header, which a page from
|
||||
//! another site can't send without the browser asking first.
|
||||
//! - **The page** loads nothing from elsewhere (a strict Content-Security-Policy) and can't be framed.
|
||||
|
||||
use crate::{
|
||||
api::{self, Shared},
|
||||
http::{self, Request, Response},
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
net::{SocketAddr, TcpListener},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const COOKIE: &str = "horizon_panel";
|
||||
/// How long a login link works.
|
||||
const LINK_LIFE: Duration = Duration::from_secs(600);
|
||||
/// Failed logins allowed per minute before the panel refuses them for a while.
|
||||
const FAILURES_PER_MINUTE: usize = 10;
|
||||
const SESSIONS: usize = 32;
|
||||
|
||||
const PAGE: &str = include_str!("../panel/index.html");
|
||||
const SCRIPT: &str = include_str!("../panel/panel.js");
|
||||
const STYLE: &str = include_str!("../panel/panel.css");
|
||||
|
||||
/// The panel's address, its pending login codes and its sessions.
|
||||
#[derive(Default)]
|
||||
pub struct Auth {
|
||||
address: Option<SocketAddr>,
|
||||
codes: Vec<(String, Instant)>,
|
||||
sessions: VecDeque<String>,
|
||||
failures: VecDeque<Instant>,
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// A one-time login link; `None` when the panel is off.
|
||||
pub fn login_link(&mut self) -> Option<String> {
|
||||
let address = self.address?;
|
||||
self.codes.retain(|(_, at)| at.elapsed() < LINK_LIFE);
|
||||
let code = api::random_token();
|
||||
self.codes.push((code.clone(), Instant::now()));
|
||||
Some(format!("http://{address}/login?code={code}"))
|
||||
}
|
||||
|
||||
/// Swaps a login code for a new session.
|
||||
fn redeem(&mut self, code: &str) -> Result<String, Response> {
|
||||
self.failures
|
||||
.retain(|at| at.elapsed() < Duration::from_secs(60));
|
||||
if self.failures.len() >= FAILURES_PER_MINUTE {
|
||||
return Err(page_error(
|
||||
429,
|
||||
"Too many failed logins: wait a minute, then open a new link.",
|
||||
));
|
||||
}
|
||||
self.codes.retain(|(_, at)| at.elapsed() < LINK_LIFE);
|
||||
let Some(i) = self
|
||||
.codes
|
||||
.iter()
|
||||
.position(|(c, _)| api::same_token(c, code))
|
||||
else {
|
||||
self.failures.push_back(Instant::now());
|
||||
return Err(page_error(
|
||||
403,
|
||||
"This login link was used already or has expired. Run `horizon-server panel` for a new one.",
|
||||
));
|
||||
};
|
||||
self.codes.remove(i);
|
||||
let session = api::random_token();
|
||||
if self.sessions.len() == SESSIONS {
|
||||
self.sessions.pop_front();
|
||||
}
|
||||
self.sessions.push_back(session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn signed_in(&self, request: &Request) -> bool {
|
||||
request
|
||||
.cookie(COOKIE)
|
||||
.is_some_and(|s| self.sessions.iter().any(|t| api::same_token(t, s)))
|
||||
}
|
||||
|
||||
fn sign_out(&mut self, request: &Request) {
|
||||
if let Some(s) = request.cookie(COOKIE) {
|
||||
self.sessions.retain(|t| !api::same_token(t, s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn page_error(status: u16, message: &str) -> Response {
|
||||
let body = format!(
|
||||
"<!doctype html><meta charset=utf-8><title>Horizon server</title>\
|
||||
<link rel=stylesheet href=/panel.css><main class=message><p>{}</p></main>",
|
||||
message
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
);
|
||||
Response::text(status, "text/html; charset=utf-8", body)
|
||||
}
|
||||
|
||||
/// The `Host` header names the panel itself: its address, `localhost` on loopback, or a tailnet name
|
||||
/// (a MagicDNS short name or `*.ts.net`, with or without the port when `tailscale serve` passes it on).
|
||||
fn host_allowed(host: &str, address: SocketAddr) -> bool {
|
||||
if host == address.to_string() {
|
||||
return true;
|
||||
}
|
||||
let (name, port) = match host.rsplit_once(':') {
|
||||
Some((name, port)) if !name.ends_with(']') || name.starts_with('[') => (name, Some(port)),
|
||||
_ => (host, None),
|
||||
};
|
||||
let same_port = port == Some(&address.port().to_string());
|
||||
if address.ip().is_loopback() && name.eq_ignore_ascii_case("localhost") && same_port {
|
||||
return true;
|
||||
}
|
||||
let tailnet_name = name.to_ascii_lowercase().ends_with(".ts.net")
|
||||
|| (!name.is_empty()
|
||||
&& !name.contains('.')
|
||||
&& !name.contains('[')
|
||||
&& !name.eq_ignore_ascii_case("localhost"));
|
||||
tailnet_name
|
||||
&& (same_port || port.is_none())
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
|
||||
}
|
||||
|
||||
fn secure(response: Response) -> Response {
|
||||
response
|
||||
.with(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; \
|
||||
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||
)
|
||||
.with("X-Content-Type-Options", "nosniff")
|
||||
.with("X-Frame-Options", "DENY")
|
||||
.with("Referrer-Policy", "no-referrer")
|
||||
}
|
||||
|
||||
fn handle(shared: &Shared, address: SocketAddr, request: &Request) -> Response {
|
||||
if !request
|
||||
.header("host")
|
||||
.is_some_and(|h| host_allowed(h, address))
|
||||
{
|
||||
return Response::error(403, "wrong Host");
|
||||
}
|
||||
let method = request.method.as_str();
|
||||
let path = request.path.as_str();
|
||||
match (method, path) {
|
||||
("GET", "/") => return Response::text(200, "text/html; charset=utf-8", PAGE),
|
||||
("GET", "/panel.js") => {
|
||||
return Response::text(200, "text/javascript; charset=utf-8", SCRIPT);
|
||||
}
|
||||
("GET", "/panel.css") => return Response::text(200, "text/css; charset=utf-8", STYLE),
|
||||
("GET", "/login") => {
|
||||
let code = request.param("code").unwrap_or_default();
|
||||
return match shared.panel.lock().unwrap().redeem(code) {
|
||||
Ok(session) => Response::text(303, "text/plain", "")
|
||||
.with("Location", "/")
|
||||
.with(
|
||||
"Set-Cookie",
|
||||
format!("{COOKIE}={session}; HttpOnly; SameSite=Strict; Path=/"),
|
||||
),
|
||||
Err(response) => response,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if method == "POST" && request.header("x-horizon") != Some("1") {
|
||||
return Response::error(403, "missing the X-Horizon header");
|
||||
}
|
||||
if (method, path) == ("POST", "/logout") {
|
||||
shared.panel.lock().unwrap().sign_out(request);
|
||||
return Response::json(200, &serde_json::json!({ "ok": true })).with(
|
||||
"Set-Cookie",
|
||||
format!("{COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0"),
|
||||
);
|
||||
}
|
||||
if !path.starts_with("/api/v1/") {
|
||||
return Response::error(404, "no such page");
|
||||
}
|
||||
if !shared.panel.lock().unwrap().signed_in(request) {
|
||||
return Response::error(
|
||||
401,
|
||||
"sign in with a link from `horizon-server panel` on the server",
|
||||
);
|
||||
}
|
||||
if path == "/api/v1/panel/login" {
|
||||
return Response::error(403, "login links come from `horizon-server panel` only");
|
||||
}
|
||||
api::route(shared, request)
|
||||
}
|
||||
|
||||
/// Starts the panel on `address`.
|
||||
pub fn start(shared: Arc<Shared>, address: SocketAddr) -> Result<(), String> {
|
||||
let listener = TcpListener::bind(address).map_err(|e| e.to_string())?;
|
||||
shared.panel.lock().unwrap().address = Some(address);
|
||||
http::serve(listener, move |request| {
|
||||
secure(handle(&shared, address, request))
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
#[test]
|
||||
fn hosts() {
|
||||
let local: SocketAddr = "127.0.0.1:8130".parse().unwrap();
|
||||
assert!(host_allowed("127.0.0.1:8130", local));
|
||||
assert!(host_allowed("localhost:8130", local));
|
||||
assert!(!host_allowed("localhost:8131", local));
|
||||
assert!(!host_allowed("evil.example:8130", local));
|
||||
assert!(!host_allowed("127.0.0.1.nip.io:8130", local));
|
||||
let tailnet: SocketAddr = "100.100.1.2:8130".parse().unwrap();
|
||||
assert!(host_allowed("100.100.1.2:8130", tailnet));
|
||||
assert!(host_allowed("myserver:8130", tailnet));
|
||||
assert!(host_allowed("myserver.tail1234.ts.net", tailnet));
|
||||
assert!(!host_allowed("localhost:8130", tailnet));
|
||||
assert!(!host_allowed("evil.example", tailnet));
|
||||
let v6: SocketAddr = "[::1]:8130".parse().unwrap();
|
||||
assert!(host_allowed("[::1]:8130", v6));
|
||||
assert!(!host_allowed("[::2]:8130", v6));
|
||||
}
|
||||
|
||||
/// One raw request to the panel; the status line, the headers and the body.
|
||||
fn send(address: SocketAddr, text: &str) -> (String, String) {
|
||||
let mut stream = std::net::TcpStream::connect(address).unwrap();
|
||||
stream.write_all(text.as_bytes()).unwrap();
|
||||
let mut out = String::new();
|
||||
stream.read_to_string(&mut out).unwrap();
|
||||
let (head, body) = out.split_once("\r\n\r\n").unwrap();
|
||||
(head.to_owned(), body.to_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_in_with_a_link() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-server-panel-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let shared = Shared::new(&dir);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
start(shared.clone(), address).unwrap();
|
||||
let host = format!("Host: {address}\r\n");
|
||||
let get = |path: &str, extra: &str| {
|
||||
send(
|
||||
address,
|
||||
&format!("GET {path} HTTP/1.1\r\n{host}{extra}Connection: close\r\n\r\n"),
|
||||
)
|
||||
};
|
||||
// The page itself is public; the API is not.
|
||||
let (head, body) = get("/", "");
|
||||
assert!(head.starts_with("HTTP/1.1 200"), "{head}");
|
||||
assert!(head.contains("Content-Security-Policy"));
|
||||
assert!(body.contains("panel.js"));
|
||||
assert!(get("/api/v1/status", "").0.starts_with("HTTP/1.1 401"));
|
||||
let rebound = send(
|
||||
address,
|
||||
"GET / HTTP/1.1\r\nHost: evil.example\r\nConnection: close\r\n\r\n",
|
||||
);
|
||||
assert!(rebound.0.starts_with("HTTP/1.1 403"));
|
||||
// A link works once.
|
||||
let url = shared.panel.lock().unwrap().login_link().unwrap();
|
||||
let path = url.split_once(&address.to_string()).unwrap().1.to_owned();
|
||||
let (head, _) = get(&path, "");
|
||||
assert!(head.starts_with("HTTP/1.1 303"), "{head}");
|
||||
let cookie = head
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("Set-Cookie: "))
|
||||
.unwrap();
|
||||
assert!(cookie.contains("HttpOnly") && cookie.contains("SameSite=Strict"));
|
||||
let session = cookie.split(';').next().unwrap().to_owned();
|
||||
assert!(get(&path, "").0.starts_with("HTTP/1.1 403"));
|
||||
let with_cookie = format!("Cookie: other=1; {session}\r\n");
|
||||
let (head, body) = get("/api/v1/status", &with_cookie);
|
||||
assert!(head.starts_with("HTTP/1.1 200"), "{head}");
|
||||
assert!(body.contains("\"phase\":\"starting\""));
|
||||
// Changes need the header a foreign page can't send.
|
||||
let post = |extra: &str| {
|
||||
send(
|
||||
address,
|
||||
&format!(
|
||||
"POST /api/v1/restart HTTP/1.1\r\n{host}{with_cookie}{extra}Content-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
),
|
||||
)
|
||||
.0
|
||||
};
|
||||
assert!(post("").starts_with("HTTP/1.1 403"));
|
||||
assert!(!shared.restart.load(std::sync::atomic::Ordering::SeqCst));
|
||||
assert!(post("X-Horizon: 1\r\n").starts_with("HTTP/1.1 200"));
|
||||
assert!(shared.restart.load(std::sync::atomic::Ordering::SeqCst));
|
||||
// Login links come only from the token API.
|
||||
assert!(
|
||||
send(
|
||||
address,
|
||||
&format!(
|
||||
"POST /api/v1/panel/login HTTP/1.1\r\n{host}{with_cookie}X-Horizon: 1\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
),
|
||||
)
|
||||
.0
|
||||
.starts_with("HTTP/1.1 403")
|
||||
);
|
||||
// Wrong codes are counted (the used link above was one), then refused for a while.
|
||||
for _ in 1..FAILURES_PER_MINUTE {
|
||||
assert!(get("/login?code=nope", "").0.starts_with("HTTP/1.1 403"));
|
||||
}
|
||||
assert!(get("/login?code=nope", "").0.starts_with("HTTP/1.1 429"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
//! `horizon-server service install|uninstall|print`: run the server at boot or login under the system's own
|
||||
//! service manager (docs/server.md, section 3): a systemd unit on Linux, a launchd agent on macOS, a task at
|
||||
//! logon on Windows. The service runs `horizon-server run`, which restarts the game if it crashes; the
|
||||
//! service manager restarts the supervisor itself.
|
||||
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
/// The service's name for a server folder: `horizon-server-<folder>`, in letters, digits and dashes.
|
||||
pub fn name(dir: &Path) -> String {
|
||||
let folder = dir
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let mut clean: String = folder
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() {
|
||||
c.to_ascii_lowercase()
|
||||
} else {
|
||||
'-'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
clean = clean.trim_matches('-').to_owned();
|
||||
if clean.is_empty() {
|
||||
clean = "server".into();
|
||||
}
|
||||
format!("horizon-server-{clean}")
|
||||
}
|
||||
|
||||
/// The program the service runs: the `horizon-server` on the PATH (the installer's launcher, which keeps
|
||||
/// running the current version after an update), else this program.
|
||||
fn program() -> Result<PathBuf, String> {
|
||||
let on_path = std::env::var_os("PATH")
|
||||
.map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|d| d.join(format!("horizon-server{}", std::env::consts::EXE_SUFFIX)))
|
||||
.find(|p| p.is_file());
|
||||
match on_path {
|
||||
Some(path) => Ok(path),
|
||||
None => std::env::current_exe().map_err(|e| e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A systemd unit: a user unit, or with `user` a system unit running as that user.
|
||||
pub fn systemd_unit(program: &Path, dir: &Path, user: Option<&str>) -> String {
|
||||
let (run_as, wanted_by) = match user {
|
||||
Some(user) => (format!("User={user}\n"), "multi-user.target"),
|
||||
None => (String::new(), "default.target"),
|
||||
};
|
||||
format!(
|
||||
"[Unit]
|
||||
Description=Horizon server in {dir}
|
||||
Documentation=https://github.com/ludovic111/horizon/blob/main/docs/server.md
|
||||
Wants=network-online.target
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
{run_as}WorkingDirectory={dir}
|
||||
ExecStart=\"{program}\" --dir \"{dir}\" run
|
||||
# SIGTERM makes the supervisor stop the game cleanly; saving a big world takes a moment.
|
||||
TimeoutStopSec=180
|
||||
Restart=on-failure
|
||||
RestartSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy={wanted_by}
|
||||
",
|
||||
dir = dir.display(),
|
||||
program = program.display(),
|
||||
)
|
||||
}
|
||||
|
||||
fn xml(text: &str) -> String {
|
||||
text.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
/// A launchd agent: started at login, and again if the supervisor exits with an error.
|
||||
pub fn launchd_plist(label: &str, program: &Path, dir: &Path) -> String {
|
||||
let log = dir.join("logs/supervisor.log");
|
||||
format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>{label}</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>{program}</string>
|
||||
<string>--dir</string>
|
||||
<string>{dir}</string>
|
||||
<string>run</string>
|
||||
</array>
|
||||
<key>WorkingDirectory</key>
|
||||
<string>{dir}</string>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>KeepAlive</key>
|
||||
<dict>
|
||||
<key>SuccessfulExit</key>
|
||||
<false/>
|
||||
</dict>
|
||||
<key>ExitTimeOut</key>
|
||||
<integer>180</integer>
|
||||
<key>StandardOutPath</key>
|
||||
<string>{log}</string>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>{log}</string>
|
||||
</dict>
|
||||
</plist>
|
||||
"#,
|
||||
program = xml(&program.display().to_string()),
|
||||
dir = xml(&dir.display().to_string()),
|
||||
log = xml(&log.display().to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
fn home() -> Result<PathBuf, String> {
|
||||
std::env::var_os("HOME")
|
||||
.map(PathBuf::from)
|
||||
.ok_or_else(|| "HOME is not set".into())
|
||||
}
|
||||
|
||||
fn launchd_path(label: &str) -> Result<PathBuf, String> {
|
||||
Ok(home()?
|
||||
.join("Library/LaunchAgents")
|
||||
.join(format!("{label}.plist")))
|
||||
}
|
||||
|
||||
fn launchd_label(dir: &Path) -> String {
|
||||
format!(
|
||||
"dev.horizon.server.{}",
|
||||
name(dir).trim_start_matches("horizon-server-")
|
||||
)
|
||||
}
|
||||
|
||||
fn systemd_path(service: &str, system: bool) -> Result<PathBuf, String> {
|
||||
Ok(if system {
|
||||
PathBuf::from("/etc/systemd/system")
|
||||
} else {
|
||||
std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map_or_else(
|
||||
|| home().map(|h| h.join(".config")),
|
||||
|c| Ok(PathBuf::from(c)),
|
||||
)?
|
||||
.join("systemd/user")
|
||||
}
|
||||
.join(format!("{service}.service")))
|
||||
}
|
||||
|
||||
fn run(program: &str, args: &[&str]) -> Result<(), String> {
|
||||
let status = Command::new(program)
|
||||
.args(args)
|
||||
.status()
|
||||
.map_err(|e| format!("{program}: {e}"))?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("`{program} {}` failed ({status})", args.join(" ")))
|
||||
}
|
||||
}
|
||||
|
||||
/// A step that may fail harmlessly (stopping what isn't running): its output would only alarm.
|
||||
fn quiet(program: &str, args: &[&str]) {
|
||||
let _ = Command::new(program)
|
||||
.args(args)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status();
|
||||
}
|
||||
|
||||
/// What `service print` shows and `service install` writes, and where.
|
||||
fn definition(dir: &Path, system: bool) -> Result<(PathBuf, String), String> {
|
||||
let program = program()?;
|
||||
if cfg!(target_os = "macos") {
|
||||
if system {
|
||||
return Err("on macOS the server runs as a login agent: drop --system".into());
|
||||
}
|
||||
let label = launchd_label(dir);
|
||||
Ok((launchd_path(&label)?, launchd_plist(&label, &program, dir)))
|
||||
} else if cfg!(windows) {
|
||||
Err(
|
||||
"on Windows, `service install` creates a task at logon; there is no file to print"
|
||||
.into(),
|
||||
)
|
||||
} else {
|
||||
let user = system.then(|| std::env::var("USER").unwrap_or_else(|_| "root".into()));
|
||||
Ok((
|
||||
systemd_path(&name(dir), system)?,
|
||||
systemd_unit(&program, dir, user.as_deref()),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn command(dir: &Path, args: &[String]) -> Result<(), String> {
|
||||
let dir = dir
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
crate::config::Config::load(&dir)?;
|
||||
let system = args.iter().any(|a| a == "--system");
|
||||
let service = name(&dir);
|
||||
match args.first().map(String::as_str) {
|
||||
Some("print") => {
|
||||
let (path, text) = definition(&dir, system)?;
|
||||
println!("# {}\n{text}", path.display());
|
||||
Ok(())
|
||||
}
|
||||
Some("install") => install(&dir, &service, system),
|
||||
Some("uninstall") => uninstall(&dir, &service, system),
|
||||
_ => Err("use: service install|uninstall|print [--system]".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn install(dir: &Path, service: &str, system: bool) -> Result<(), String> {
|
||||
if cfg!(windows) {
|
||||
let program = program()?;
|
||||
let action = format!("\"{}\" --dir \"{}\" run", program.display(), dir.display());
|
||||
run(
|
||||
"schtasks",
|
||||
&[
|
||||
"/Create", "/TN", service, "/TR", &action, "/SC", "ONLOGON", "/RL", "LIMITED", "/F",
|
||||
],
|
||||
)?;
|
||||
run("schtasks", &["/Run", "/TN", service])?;
|
||||
println!("Installed the task {service}: the server starts when you log in, and now.");
|
||||
return Ok(());
|
||||
}
|
||||
let (path, text) = definition(dir, system)?;
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
||||
}
|
||||
std::fs::create_dir_all(dir.join("logs")).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&path, text).map_err(|e| {
|
||||
format!(
|
||||
"{}: {e}{}",
|
||||
path.display(),
|
||||
if system { " (--system needs sudo)" } else { "" }
|
||||
)
|
||||
})?;
|
||||
if cfg!(target_os = "macos") {
|
||||
let uid = String::from_utf8_lossy(
|
||||
&Command::new("id")
|
||||
.arg("-u")
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?
|
||||
.stdout,
|
||||
)
|
||||
.trim()
|
||||
.to_owned();
|
||||
quiet(
|
||||
"launchctl",
|
||||
&[
|
||||
"bootout",
|
||||
&format!("gui/{uid}"),
|
||||
&path.display().to_string(),
|
||||
],
|
||||
);
|
||||
run(
|
||||
"launchctl",
|
||||
&[
|
||||
"bootstrap",
|
||||
&format!("gui/{uid}"),
|
||||
&path.display().to_string(),
|
||||
],
|
||||
)?;
|
||||
println!(
|
||||
"Installed {}: the server starts at login, and now. Its output: logs/supervisor.log",
|
||||
path.display()
|
||||
);
|
||||
} else {
|
||||
let scope: &[&str] = if system { &[] } else { &["--user"] };
|
||||
run("systemctl", &[scope, &["daemon-reload"]].concat())?;
|
||||
run(
|
||||
"systemctl",
|
||||
&[scope, &["enable", "--now", service]].concat(),
|
||||
)?;
|
||||
println!(
|
||||
"Installed {}: the server starts at boot, and now.",
|
||||
path.display()
|
||||
);
|
||||
if !system {
|
||||
println!(
|
||||
"To keep it running while you are logged out: loginctl enable-linger $USER. \
|
||||
Its log: journalctl --user -u {service}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn uninstall(dir: &Path, service: &str, system: bool) -> Result<(), String> {
|
||||
if cfg!(windows) {
|
||||
quiet("schtasks", &["/End", "/TN", service]);
|
||||
run("schtasks", &["/Delete", "/TN", service, "/F"])?;
|
||||
println!("Removed the task {service}.");
|
||||
return Ok(());
|
||||
}
|
||||
let (path, _) = definition(dir, system)?;
|
||||
if cfg!(target_os = "macos") {
|
||||
let uid = String::from_utf8_lossy(
|
||||
&Command::new("id")
|
||||
.arg("-u")
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?
|
||||
.stdout,
|
||||
)
|
||||
.trim()
|
||||
.to_owned();
|
||||
quiet(
|
||||
"launchctl",
|
||||
&[
|
||||
"bootout",
|
||||
&format!("gui/{uid}"),
|
||||
&path.display().to_string(),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
let scope: &[&str] = if system { &[] } else { &["--user"] };
|
||||
quiet(
|
||||
"systemctl",
|
||||
&[scope, &["disable", "--now", service]].concat(),
|
||||
);
|
||||
}
|
||||
std::fs::remove_file(&path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
if !cfg!(target_os = "macos") {
|
||||
let scope: &[&str] = if system { &[] } else { &["--user"] };
|
||||
quiet("systemctl", &[scope, &["daemon-reload"]].concat());
|
||||
}
|
||||
println!(
|
||||
"Removed {}; the server's folder is untouched.",
|
||||
path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn names_follow_the_folder() {
|
||||
assert_eq!(
|
||||
name(Path::new("/srv/My Server!")),
|
||||
"horizon-server-my-server"
|
||||
);
|
||||
assert_eq!(name(Path::new("/")), "horizon-server-server");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units_run_the_supervisor() {
|
||||
let unit = systemd_unit(
|
||||
Path::new("/home/a/.local/bin/horizon-server"),
|
||||
Path::new("/srv/mc"),
|
||||
Some("mc"),
|
||||
);
|
||||
assert!(
|
||||
unit.contains("ExecStart=\"/home/a/.local/bin/horizon-server\" --dir \"/srv/mc\" run")
|
||||
);
|
||||
assert!(unit.contains("User=mc\n"));
|
||||
assert!(unit.contains("WantedBy=multi-user.target"));
|
||||
let plist = launchd_plist(
|
||||
"dev.horizon.server.mc",
|
||||
Path::new("/opt/h/horizon-server"),
|
||||
Path::new("/srv/R&D"),
|
||||
);
|
||||
assert!(plist.contains("<string>/srv/R&D</string>"));
|
||||
assert!(plist.contains("<string>/srv/R&D/logs/supervisor.log</string>"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Stop requests from outside: Ctrl-C in the terminal, SIGTERM from systemd or launchd, SIGHUP when the
|
||||
//! terminal closes, the console window closing on Windows. The handler only counts them; the supervisor
|
||||
//! sees the count and stops the game cleanly (a second request stops it at once).
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
static REQUESTS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// How many stop requests arrived.
|
||||
pub fn requests() -> u32 {
|
||||
REQUESTS.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn install() {
|
||||
extern "C" fn handle(_: libc::c_int) {
|
||||
REQUESTS.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
let handler = handle as extern "C" fn(libc::c_int);
|
||||
for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
|
||||
// SAFETY: the handler only increments an atomic, which is async-signal-safe.
|
||||
unsafe {
|
||||
libc::signal(signal, handler as libc::sighandler_t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn install() {
|
||||
unsafe extern "system" fn handle(_: u32) -> windows_sys::core::BOOL {
|
||||
REQUESTS.fetch_add(1, Ordering::SeqCst);
|
||||
1
|
||||
}
|
||||
// SAFETY: the handler only increments an atomic; it stays valid for the life of the process.
|
||||
unsafe {
|
||||
windows_sys::Win32::System::Console::SetConsoleCtrlHandler(Some(handle), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
pub fn install() {}
|
||||
@@ -0,0 +1,461 @@
|
||||
//! `horizon-server run`: writes `server.properties` from `server.toml`, runs the engine with the console on
|
||||
//! stdin, serves the control API, stops the game cleanly on Ctrl-C, SIGTERM or `stop`, and restarts it when
|
||||
//! it crashes (docs/server.md, sections 2 and 7).
|
||||
|
||||
use crate::{
|
||||
api::{self, Phase, Shared},
|
||||
backup, config,
|
||||
config::Config,
|
||||
engine, signals,
|
||||
};
|
||||
use horizon_server_files::java_properties::now_millis;
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
path::Path,
|
||||
process::{Child, ExitStatus},
|
||||
sync::{Arc, atomic::Ordering, mpsc},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
/// After this many crashes within [`CRASH_WINDOW`] the supervisor stops restarting the game.
|
||||
const MAX_CRASHES: usize = 5;
|
||||
const CRASH_WINDOW: Duration = Duration::from_secs(600);
|
||||
/// The first wait before a restart; it doubles after each crash, up to [`MAX_BACKOFF`].
|
||||
const FIRST_BACKOFF: Duration = Duration::from_secs(5);
|
||||
const MAX_BACKOFF: Duration = Duration::from_secs(300);
|
||||
/// How long `stop` may take before the game is killed.
|
||||
const STOP_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// A line from the supervisor, in the game's log format (`[HH:mm:ss] [thread/LEVEL]: message`, UTC), on
|
||||
/// stdout and in the log the API serves.
|
||||
fn note(shared: &Shared, level: &str, message: &str) {
|
||||
let secs = now_millis().div_euclid(1000).rem_euclid(86_400);
|
||||
let line = format!(
|
||||
"[{:02}:{:02}:{:02}] [Supervisor/{level}]: {message}",
|
||||
secs / 3600,
|
||||
secs / 60 % 60,
|
||||
secs % 60
|
||||
);
|
||||
println!("{line}");
|
||||
shared.log.lock().unwrap().push(line);
|
||||
}
|
||||
|
||||
/// The folder's lock: one supervisor per server folder. Released when the process ends, even by a crash.
|
||||
pub fn lock(dir: &Path) -> Result<File, String> {
|
||||
let state = dir.join(".horizon");
|
||||
std::fs::create_dir_all(&state).map_err(|e| format!("{}: {e}", state.display()))?;
|
||||
let file = File::options()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(state.join("lock"))
|
||||
.map_err(|e| e.to_string())?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {
|
||||
Err(format!("a server is already running in {}", dir.display()))
|
||||
}
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
enum Exit {
|
||||
/// Asked to stop, or the game ended by itself without an error (`stop` typed in its console, the EULA
|
||||
/// not agreed, the port taken): not restarted.
|
||||
Stopped,
|
||||
/// Asked to restart (`horizon-server restart`).
|
||||
Restart,
|
||||
Crashed(ExitStatus),
|
||||
}
|
||||
|
||||
pub fn run(dir: &Path) -> Result<(), String> {
|
||||
signals::install();
|
||||
let config = Config::load(dir)?;
|
||||
let program = engine::program(&config, dir)?;
|
||||
let resources = engine::resources(&config, dir, Some(&program))?;
|
||||
let _lock = lock(dir)?;
|
||||
let shared = Shared::new(dir);
|
||||
let _endpoint = api::start(shared.clone())?;
|
||||
match config.panel.address() {
|
||||
Ok(Some(address)) => match crate::panel::start(shared.clone(), address) {
|
||||
Ok(()) => note(
|
||||
&shared,
|
||||
"INFO",
|
||||
&format!(
|
||||
"Web panel on http://{address} (`horizon-server panel` prints a login link)"
|
||||
),
|
||||
),
|
||||
Err(e) => note(
|
||||
&shared,
|
||||
"WARN",
|
||||
&format!("The web panel can't listen on {address}: {e}"),
|
||||
),
|
||||
},
|
||||
Ok(None) => {}
|
||||
Err(e) => note(&shared, "WARN", &e),
|
||||
}
|
||||
sample(shared.clone());
|
||||
schedule_backups(shared.clone());
|
||||
let console = console_lines();
|
||||
let mut crashes: Vec<Instant> = Vec::new();
|
||||
loop {
|
||||
// Read again before every start: edits to server.toml apply on the next restart.
|
||||
let config = Config::load(dir)?;
|
||||
let written = config
|
||||
.write_properties(dir)
|
||||
.map_err(|e| format!("server.properties: {e}"))?;
|
||||
note(
|
||||
&shared,
|
||||
"INFO",
|
||||
&format!(
|
||||
"Starting {} with the game files in {}",
|
||||
program.display(),
|
||||
resources.display()
|
||||
),
|
||||
);
|
||||
shared.set_phase(Phase::Starting);
|
||||
let mut child = engine::spawn(&program, &resources, dir)
|
||||
.map_err(|e| format!("{}: {e}", program.display()))?;
|
||||
{
|
||||
let mut state = shared.state.lock().unwrap();
|
||||
state.engine_pid = Some(child.id());
|
||||
state.engine_started = Some(Instant::now());
|
||||
}
|
||||
let exit = supervise(&shared, &mut child, &console);
|
||||
{
|
||||
let mut state = shared.state.lock().unwrap();
|
||||
state.engine_pid = None;
|
||||
state.engine_started = None;
|
||||
}
|
||||
match config::sync_back(dir, &written) {
|
||||
Ok(keys) if !keys.is_empty() => note(
|
||||
&shared,
|
||||
"INFO",
|
||||
&format!(
|
||||
"Copied into server.toml what the game changed: {}",
|
||||
keys.join(", ")
|
||||
),
|
||||
),
|
||||
Ok(_) => {}
|
||||
Err(e) => note(
|
||||
&shared,
|
||||
"WARN",
|
||||
&format!("Could not update server.toml: {e}"),
|
||||
),
|
||||
}
|
||||
let status = match exit {
|
||||
Exit::Stopped => return Ok(()),
|
||||
Exit::Restart => {
|
||||
let restore = shared.restore.lock().unwrap().take();
|
||||
if let Some(name) = restore {
|
||||
match backup::restore(dir, &config, &name) {
|
||||
Ok(Some(old)) => note(
|
||||
&shared,
|
||||
"INFO",
|
||||
&format!(
|
||||
"Restored {name}; the world it replaced is in {}",
|
||||
old.display()
|
||||
),
|
||||
),
|
||||
Ok(None) => note(&shared, "INFO", &format!("Restored {name}")),
|
||||
Err(e) => note(&shared, "ERROR", &format!("Could not restore {name}: {e}")),
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Exit::Crashed(status) => status,
|
||||
};
|
||||
{
|
||||
let mut state = shared.state.lock().unwrap();
|
||||
state.crashes += 1;
|
||||
state.last_crash = Some(status.to_string());
|
||||
}
|
||||
if !config.engine.restart_on_crash {
|
||||
return Err(format!(
|
||||
"the game stopped unexpectedly ({status}); engine.restart_on_crash is off"
|
||||
));
|
||||
}
|
||||
let now = Instant::now();
|
||||
crashes.retain(|t| now.duration_since(*t) < CRASH_WINDOW);
|
||||
crashes.push(now);
|
||||
if crashes.len() >= MAX_CRASHES {
|
||||
return Err(format!(
|
||||
"the game stopped unexpectedly {MAX_CRASHES} times in {} minutes: not restarting it. \
|
||||
See logs/latest.log and crash-reports/",
|
||||
CRASH_WINDOW.as_secs() / 60
|
||||
));
|
||||
}
|
||||
let wait = backoff(crashes.len());
|
||||
note(
|
||||
&shared,
|
||||
"WARN",
|
||||
&format!(
|
||||
"The game stopped unexpectedly ({status}); restarting in {} s",
|
||||
wait.as_secs()
|
||||
),
|
||||
);
|
||||
shared.set_phase(Phase::Restarting);
|
||||
let until = Instant::now() + wait;
|
||||
while Instant::now() < until {
|
||||
if signals::requests() > 0 || shared.stop.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wait before the restart that follows the `crashes`th recent crash.
|
||||
fn backoff(crashes: usize) -> Duration {
|
||||
let doublings = u32::try_from(crashes.saturating_sub(1))
|
||||
.unwrap_or(u32::MAX)
|
||||
.min(16);
|
||||
(FIRST_BACKOFF * 2u32.pow(doublings)).min(MAX_BACKOFF)
|
||||
}
|
||||
|
||||
/// The supervisor's own stdin, line by line (nothing when it has none, as under a service manager).
|
||||
fn console_lines() -> mpsc::Receiver<String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let _ = thread::Builder::new()
|
||||
.name("console".into())
|
||||
.spawn(move || {
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
/// Copies the game's output to ours and to the API's log, line by line; the game's `Done` line means it
|
||||
/// is up.
|
||||
fn pump(shared: &Arc<Shared>, from: impl Read + Send + 'static, to_stderr: bool) {
|
||||
let shared = shared.clone();
|
||||
let _ = thread::Builder::new()
|
||||
.name("engine-log".into())
|
||||
.spawn(move || {
|
||||
for line in BufReader::new(from).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if to_stderr {
|
||||
eprintln!("{line}");
|
||||
} else {
|
||||
println!("{line}");
|
||||
if line.contains("/INFO]: Done (") {
|
||||
let mut state = shared.state.lock().unwrap();
|
||||
if state.phase == Phase::Starting {
|
||||
state.phase = Phase::Running;
|
||||
}
|
||||
}
|
||||
}
|
||||
shared.log.lock().unwrap().push(line);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Every second, the game's RAM, CPU and status, for `status` and the panel's graphs.
|
||||
fn sample(shared: Arc<Shared>) {
|
||||
let _ = thread::Builder::new()
|
||||
.name("sampler".into())
|
||||
.spawn(move || {
|
||||
let mut control: Option<engine::Control> = None;
|
||||
let mut previous: Option<(u32, Instant, f64)> = None;
|
||||
loop {
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
let (pid, running) = {
|
||||
let state = shared.state.lock().unwrap();
|
||||
(state.engine_pid, state.phase == Phase::Running)
|
||||
};
|
||||
let Some(pid) = pid else {
|
||||
control = None;
|
||||
previous = None;
|
||||
shared.state.lock().unwrap().sample = serde_json::Value::Null;
|
||||
continue;
|
||||
};
|
||||
let now = Instant::now();
|
||||
let cpu = horizon_bench::cpu_seconds(pid);
|
||||
let cpu_percent = match (previous, cpu) {
|
||||
(Some((p, at, before)), Some(cpu)) if p == pid => {
|
||||
Some((cpu - before) / now.duration_since(at).as_secs_f64() * 100.0)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
previous = cpu.map(|c| (pid, now, c));
|
||||
if !running {
|
||||
control = None;
|
||||
} else if control.is_none() {
|
||||
control = engine::Control::connect(&shared.dir).ok();
|
||||
}
|
||||
let game = control
|
||||
.as_mut()
|
||||
.map(|c| c.ask("server-status"))
|
||||
.transpose()
|
||||
.unwrap_or_else(|_| {
|
||||
control = None;
|
||||
None
|
||||
});
|
||||
let rss = horizon_bench::rss_bytes(pid);
|
||||
shared.record(json!({
|
||||
"t": std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs()),
|
||||
"tps": game.as_ref().and_then(|g| g["tps"].as_f64()),
|
||||
"mspt": game.as_ref().and_then(|g| g["mspt"]["average"].as_f64()),
|
||||
"mspt_p95": game.as_ref().and_then(|g| g["mspt"]["p95"].as_f64()),
|
||||
"rss_bytes": rss,
|
||||
"cpu_percent": cpu_percent,
|
||||
"players": game.as_ref().and_then(|g| g["players"].as_array().map(Vec::len)),
|
||||
}));
|
||||
shared.state.lock().unwrap().sample = json!({
|
||||
"rss_bytes": rss,
|
||||
"cpu_percent": cpu_percent,
|
||||
"game": game,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Automatic backups every `backups.every` while the game runs, keeping the last `backups.keep`.
|
||||
fn schedule_backups(shared: Arc<Shared>) {
|
||||
let _ = thread::Builder::new()
|
||||
.name("backups".into())
|
||||
.spawn(move || {
|
||||
let mut last = Instant::now();
|
||||
loop {
|
||||
thread::sleep(Duration::from_secs(30));
|
||||
let Ok(config) = Config::load(&shared.dir) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(Some(every)) = backup::interval(&config.backups.every) else {
|
||||
continue;
|
||||
};
|
||||
if last.elapsed() < every || shared.state.lock().unwrap().phase != Phase::Running {
|
||||
continue;
|
||||
}
|
||||
last = Instant::now();
|
||||
match shared.back_up(&backup::auto_name(std::time::SystemTime::now())) {
|
||||
Ok(path) => {
|
||||
note(&shared, "INFO", &format!("Backed up to {}", path.display()));
|
||||
let pruned = backup::prune(&shared.dir, config.backups.keep as usize);
|
||||
if !pruned.is_empty() {
|
||||
note(
|
||||
&shared,
|
||||
"INFO",
|
||||
&format!("Deleted older backups: {}", pruned.join(", ")),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => note(
|
||||
&shared,
|
||||
"WARN",
|
||||
&format!("The automatic backup failed: {e}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Runs one engine process to its end: console lines in, the log out, and a clean `stop` when asked.
|
||||
fn supervise(shared: &Arc<Shared>, child: &mut Child, console: &mpsc::Receiver<String>) -> Exit {
|
||||
if let Some(out) = child.stdout.take() {
|
||||
pump(shared, out, false);
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
pump(shared, err, true);
|
||||
}
|
||||
let mut stdin = child.stdin.take();
|
||||
let mut stopping: Option<Instant> = None;
|
||||
let mut restart = false;
|
||||
let mut handled = signals::requests();
|
||||
loop {
|
||||
while let Ok(line) = console.try_recv() {
|
||||
let command = line.trim().trim_start_matches('/');
|
||||
if command == "stop" && stopping.is_none() {
|
||||
stopping = Some(Instant::now());
|
||||
shared.set_phase(Phase::Stopping);
|
||||
}
|
||||
if let Some(input) = stdin.as_mut()
|
||||
&& writeln!(input, "{line}")
|
||||
.and_then(|()| input.flush())
|
||||
.is_err()
|
||||
{
|
||||
stdin = None;
|
||||
}
|
||||
}
|
||||
let requests = signals::requests();
|
||||
let asked = requests > handled || shared.stop.swap(false, Ordering::SeqCst);
|
||||
handled = requests;
|
||||
if shared.restart.swap(false, Ordering::SeqCst) && stopping.is_none() {
|
||||
restart = true;
|
||||
note(shared, "INFO", "Restarting the server");
|
||||
stopping = Some(Instant::now());
|
||||
shared.set_phase(Phase::Restarting);
|
||||
send_stop(&mut stdin);
|
||||
}
|
||||
if asked {
|
||||
restart = false;
|
||||
if stopping.is_none() {
|
||||
note(shared, "INFO", "Stopping the server");
|
||||
stopping = Some(Instant::now());
|
||||
shared.set_phase(Phase::Stopping);
|
||||
send_stop(&mut stdin);
|
||||
} else {
|
||||
note(shared, "WARN", "Stopping the game at once, without saving");
|
||||
let _ = child.kill();
|
||||
}
|
||||
}
|
||||
if stopping.is_some_and(|t| t.elapsed() > STOP_TIMEOUT) {
|
||||
note(
|
||||
shared,
|
||||
"WARN",
|
||||
&format!(
|
||||
"The game did not stop within {} s: killing it",
|
||||
STOP_TIMEOUT.as_secs()
|
||||
),
|
||||
);
|
||||
let _ = child.kill();
|
||||
stopping = Some(Instant::now());
|
||||
}
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) if restart => return Exit::Restart,
|
||||
Ok(Some(status)) if stopping.is_some() || status.success() => return Exit::Stopped,
|
||||
Ok(Some(status)) => return Exit::Crashed(status),
|
||||
Ok(None) => thread::sleep(Duration::from_millis(50)),
|
||||
Err(e) => {
|
||||
note(shared, "ERROR", &format!("Lost track of the game: {e}"));
|
||||
return Exit::Stopped;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send_stop(stdin: &mut Option<std::process::ChildStdin>) {
|
||||
if let Some(input) = stdin.as_mut() {
|
||||
let _ = writeln!(input, "stop").and_then(|()| input.flush());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn backoff_doubles_up_to_five_minutes() {
|
||||
let waits: Vec<u64> = (1..=8).map(|n| backoff(n).as_secs()).collect();
|
||||
assert_eq!(waits, [5, 10, 20, 40, 80, 160, 300, 300]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_supervisor_per_folder() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-server-lock-{}", std::process::id()));
|
||||
let first = lock(&dir).unwrap();
|
||||
assert!(lock(&dir).unwrap_err().contains("already running"));
|
||||
drop(first);
|
||||
lock(&dir).unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,15 @@ Scripts and AI agents
|
||||
horizon-ctl mcp is an MCP server for AI agents (stdio; add it to your MCP
|
||||
client as the command horizon-ctl with the argument mcp). It finds the game
|
||||
beside it or the version the launcher installed.
|
||||
|
||||
Running a server
|
||||
horizon-server, in this folder, hosts a server with this game as its engine,
|
||||
using the resources prepared above:
|
||||
./horizon-server --dir my-server init the EULA, world, seed, port, who may join
|
||||
./horizon-server --dir my-server start in the background; also stop, restart
|
||||
./horizon-server --dir my-server status TPS, MSPT, players, RAM and CPU
|
||||
./horizon-server --dir my-server cmd list
|
||||
./horizon-server --dir my-server backup also backups, restore
|
||||
./horizon-server --dir my-server service install start it at boot or login
|
||||
Its settings are in my-server/server.toml. ./horizon-server help lists every
|
||||
command; docs/server.md in the repository has the details.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# horizon-server in a container (docs/server.md, section 3). Build context: the repository root:
|
||||
# docker build -f packaging/server/Dockerfile -t horizon-server .
|
||||
#
|
||||
# The image holds none of Minecraft's files. Prepare them on the host from your own Minecraft 26.3
|
||||
# (horizon-prepare --prepare, see packaging/PLAY.txt) and mount the folder it writes, read-only:
|
||||
# docker run -d --name horizon -p 25565:25565 --stop-timeout 180 \
|
||||
# -v horizon-data:/data \
|
||||
# -v /path/to/.local/horizon-client/26.3:/opt/horizon/.local/horizon-client/26.3:ro \
|
||||
# -e HORIZON_EULA=true -e HORIZON_WHITELIST=true -e HORIZON_PLAYERS=Alex,Steve -e HORIZON_OP=Alex \
|
||||
# horizon-server
|
||||
#
|
||||
# HORIZON_EULA=true accepts the Minecraft EULA (https://aka.ms/MinecraftEULA) for this server. The first
|
||||
# start writes /data/server.toml from HORIZON_* (EULA, WORLD, SEED, PORT, WHITELIST, PLAYERS, OP); later
|
||||
# starts use the file. Manage it with `docker exec horizon horizon-server status|cmd|backup|logs ...`.
|
||||
FROM rust:1-slim-bookworm AS build
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends pkg-config libasound2-dev libudev-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN cargo build --release --locked -p horizon-client --bin horizon-client -p horizon-server --bin horizon-server \
|
||||
&& mkdir /out && cp target/release/horizon-client target/release/horizon-server /out/
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
# The game links ALSA and udev even when it runs headless with no sound.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libasound2 libudev1 \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& useradd --system --home-dir /data --shell /usr/sbin/nologin horizon \
|
||||
&& mkdir -p /data /opt/horizon/.local/horizon-client \
|
||||
&& chown horizon:horizon /data
|
||||
COPY --from=build /out/ /opt/horizon/
|
||||
ENV PATH=/opt/horizon:$PATH \
|
||||
HORIZON_NO_AUDIO=1
|
||||
WORKDIR /data
|
||||
VOLUME /data
|
||||
EXPOSE 25565
|
||||
USER horizon
|
||||
# SIGTERM makes horizon-server stop the game cleanly (it saves first): give it --stop-timeout 180.
|
||||
CMD ["sh", "-c", "test -f server.toml || horizon-server init --yes || exit 1; exec horizon-server run"]
|
||||
@@ -0,0 +1,79 @@
|
||||
# Installs horizon-server (docs/server.md) on Windows: the latest Horizon release, downloaded from GitHub
|
||||
# Releases and checked against the SHA-256 GitHub publishes for it.
|
||||
#
|
||||
# irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex
|
||||
# & ([scriptblock]::Create((irm .../install.ps1))) -Version v0.5.0 -Dir D:\Horizon
|
||||
#
|
||||
# Releases go to <Dir>\releases\<version>, <Dir>\current points at the one in use, and <Dir>\bin (added to
|
||||
# your PATH) holds horizon-server.cmd and horizon-prepare.cmd. The game files you prepare from your own
|
||||
# Minecraft stay in <Dir>\game-files across updates. Nothing of Mojang's is downloaded. No admin rights.
|
||||
param(
|
||||
[string]$Version = "latest",
|
||||
[string]$Dir = (Join-Path $env:LOCALAPPDATA "Horizon")
|
||||
)
|
||||
$ErrorActionPreference = "Stop"
|
||||
$ProgressPreference = "SilentlyContinue"
|
||||
|
||||
$Repo = "ludovic111/horizon"
|
||||
$Asset = "horizon-windows-x64.zip"
|
||||
if ($env:PROCESSOR_ARCHITECTURE -ne "AMD64") {
|
||||
throw "No Horizon release for Windows on $env:PROCESSOR_ARCHITECTURE yet: build it from source (docs/server.md)"
|
||||
}
|
||||
|
||||
$Api = if ($Version -eq "latest") { "https://api.github.com/repos/$Repo/releases/latest" }
|
||||
else { "https://api.github.com/repos/$Repo/releases/tags/$Version" }
|
||||
$Release = Invoke-RestMethod -Uri $Api -Headers @{ Accept = "application/vnd.github+json" }
|
||||
$Tag = $Release.tag_name
|
||||
$Item = $Release.assets | Where-Object { $_.name -eq $Asset } | Select-Object -First 1
|
||||
if (-not $Item) { throw "Release $Tag has no $Asset" }
|
||||
if (-not $Item.digest -or -not $Item.digest.StartsWith("sha256:")) { throw "Release $Tag publishes no SHA-256 for $Asset" }
|
||||
$Digest = $Item.digest.Substring(7)
|
||||
|
||||
$Tmp = Join-Path ([IO.Path]::GetTempPath()) ("horizon-install-" + [Guid]::NewGuid())
|
||||
New-Item -ItemType Directory -Path $Tmp | Out-Null
|
||||
try {
|
||||
Write-Host "Downloading Horizon $Tag ($Asset)..."
|
||||
$Zip = Join-Path $Tmp $Asset
|
||||
Invoke-WebRequest -Uri $Item.browser_download_url -OutFile $Zip
|
||||
$Got = (Get-FileHash -Algorithm SHA256 $Zip).Hash.ToLowerInvariant()
|
||||
if ($Got -ne $Digest.ToLowerInvariant()) {
|
||||
throw "$Asset doesn't match its SHA-256 (got $Got, expected $Digest): not installed"
|
||||
}
|
||||
$Unpacked = Join-Path $Tmp "x"
|
||||
Expand-Archive -Path $Zip -DestinationPath $Unpacked
|
||||
$Server = Get-ChildItem -Path $Unpacked -Recurse -Filter "horizon-server.exe" | Select-Object -First 1
|
||||
if (-not $Server) { throw "$Asset holds no horizon-server.exe (a release from before it existed?)" }
|
||||
|
||||
$Releases = Join-Path $Dir "releases"
|
||||
$GameFiles = Join-Path $Dir "game-files\horizon-client"
|
||||
$Bin = Join-Path $Dir "bin"
|
||||
New-Item -ItemType Directory -Force -Path $Releases, $GameFiles, $Bin | Out-Null
|
||||
$Target = Join-Path $Releases $Tag
|
||||
if (Test-Path $Target) { Remove-Item -Recurse -Force $Target }
|
||||
Move-Item -Path $Server.Directory.FullName -Destination $Target
|
||||
# Prepared game files live outside the release, so updates and rollbacks keep them. Junctions need no
|
||||
# admin rights, unlike symbolic links.
|
||||
$Local = Join-Path $Target ".local"
|
||||
New-Item -ItemType Directory -Force -Path $Local | Out-Null
|
||||
New-Item -ItemType Junction -Path (Join-Path $Local "horizon-client") -Target $GameFiles | Out-Null
|
||||
$Current = Join-Path $Dir "current"
|
||||
if (Test-Path $Current) { (Get-Item $Current).Delete() }
|
||||
New-Item -ItemType Junction -Path $Current -Target $Target | Out-Null
|
||||
foreach ($Tool in "horizon-server", "horizon-prepare") {
|
||||
Set-Content -Path (Join-Path $Bin "$Tool.cmd") -Encoding ASCII -Value "@`"$Current\$Tool.exe`" %*"
|
||||
}
|
||||
$UserPath = [Environment]::GetEnvironmentVariable("Path", "User")
|
||||
if (-not (($UserPath -split ";") -contains $Bin)) {
|
||||
[Environment]::SetEnvironmentVariable("Path", ($UserPath.TrimEnd(";") + ";" + $Bin).TrimStart(";"), "User")
|
||||
Write-Host "Added $Bin to your PATH: open a new terminal to use it."
|
||||
}
|
||||
Write-Host "Installed Horizon $Tag in $Target."
|
||||
if (-not (Get-ChildItem -Path $GameFiles -ErrorAction SilentlyContinue)) {
|
||||
Write-Host "Next, prepare the game files from your own Minecraft 26.3 (it needs Java 25 and the game installed"
|
||||
Write-Host "once by the official launcher; see docs/server.md):"
|
||||
Write-Host " horizon-prepare --prepare --server-jar C:\path\to\server.jar"
|
||||
}
|
||||
Write-Host "Then set up a server: mkdir my-server; cd my-server; horizon-server init"
|
||||
} finally {
|
||||
Remove-Item -Recurse -Force $Tmp -ErrorAction SilentlyContinue
|
||||
}
|
||||
Executable
+98
@@ -0,0 +1,98 @@
|
||||
#!/bin/sh
|
||||
# Installs horizon-server (docs/server.md) on Linux or macOS: the latest Horizon release for this computer,
|
||||
# downloaded from GitHub Releases and checked against the SHA-256 GitHub publishes for it.
|
||||
#
|
||||
# curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh
|
||||
# curl -fsSL .../install.sh | sh -s -- --version v0.5.0 --dir /opt/horizon --bin /usr/local/bin
|
||||
#
|
||||
# It needs curl, tar or unzip, and sha256sum or shasum; it never asks for sudo (pick folders you can write).
|
||||
# Releases go to <dir>/releases/<version>, <dir>/current points at the one in use, and <bin>/horizon-server
|
||||
# runs it. The game files you prepare from your own Minecraft stay in <dir>/game-files across updates.
|
||||
# Nothing of Mojang's is downloaded.
|
||||
set -eu
|
||||
|
||||
REPO=ludovic111/horizon
|
||||
VERSION=latest
|
||||
DIR="${XDG_DATA_HOME:-$HOME/.local/share}/horizon"
|
||||
BIN="$HOME/.local/bin"
|
||||
|
||||
die() { echo "horizon install: $*" >&2; exit 1; }
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--version) [ $# -ge 2 ] || die "--version needs a tag"; VERSION=$2; shift 2 ;;
|
||||
--dir) [ $# -ge 2 ] || die "--dir needs a folder"; DIR=$2; shift 2 ;;
|
||||
--bin) [ $# -ge 2 ] || die "--bin needs a folder"; BIN=$2; shift 2 ;;
|
||||
-h|--help) sed -n '2,12p' "$0" 2>/dev/null || true; exit 0 ;;
|
||||
*) die "unknown option $1" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
case "$(uname -s)-$(uname -m)" in
|
||||
Linux-x86_64) ASSET=horizon-linux-x86_64.tar.gz ;;
|
||||
Darwin-arm64) ASSET=horizon-macos-arm64.zip ;;
|
||||
*) die "no Horizon release for $(uname -s) $(uname -m) yet: build it from source (docs/server.md)" ;;
|
||||
esac
|
||||
|
||||
command -v curl >/dev/null || die "curl is needed"
|
||||
if command -v sha256sum >/dev/null; then SHA="sha256sum"
|
||||
elif command -v shasum >/dev/null; then SHA="shasum -a 256"
|
||||
else die "sha256sum or shasum is needed"; fi
|
||||
|
||||
if [ "$VERSION" = latest ]; then API="https://api.github.com/repos/$REPO/releases/latest"
|
||||
else API="https://api.github.com/repos/$REPO/releases/tags/$VERSION"; fi
|
||||
JSON=$(curl -fsSL -H "Accept: application/vnd.github+json" "$API") || die "no release $VERSION on GitHub"
|
||||
|
||||
TAG=$(printf '%s\n' "$JSON" | sed -n 's/^ "tag_name": "\([^"]*\)".*/\1/p' | head -n 1)
|
||||
[ -n "$TAG" ] || die "could not read the release's tag"
|
||||
# The asset's download address and digest, from its block in the release's JSON.
|
||||
FIELDS=$(printf '%s\n' "$JSON" | awk -v asset="$ASSET" '
|
||||
/"name": / { line = $0; sub(/.*"name": "/, "", line); sub(/".*/, "", line); current = line }
|
||||
current == asset && /"digest": / { line = $0; sub(/.*"digest": "sha256:/, "", line); sub(/".*/, "", line); digest = line }
|
||||
current == asset && /"browser_download_url": / { line = $0; sub(/.*"browser_download_url": "/, "", line); sub(/".*/, "", line); url = line }
|
||||
END { print url; print digest }')
|
||||
URL=$(printf '%s\n' "$FIELDS" | sed -n 1p)
|
||||
DIGEST=$(printf '%s\n' "$FIELDS" | sed -n 2p)
|
||||
[ -n "$URL" ] || die "release $TAG has no $ASSET"
|
||||
[ -n "$DIGEST" ] || die "release $TAG publishes no SHA-256 for $ASSET"
|
||||
|
||||
TMP=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
echo "Downloading Horizon $TAG ($ASSET)..."
|
||||
curl -fL --progress-bar -o "$TMP/$ASSET" "$URL"
|
||||
GOT=$($SHA "$TMP/$ASSET" | cut -d' ' -f1)
|
||||
[ "$GOT" = "$DIGEST" ] || die "$ASSET doesn't match its SHA-256 (got $GOT, expected $DIGEST): not installed"
|
||||
|
||||
mkdir -p "$TMP/x"
|
||||
case "$ASSET" in
|
||||
*.tar.gz) tar -xzf "$TMP/$ASSET" -C "$TMP/x" ;;
|
||||
*.zip) command -v unzip >/dev/null || die "unzip is needed"; unzip -q "$TMP/$ASSET" -d "$TMP/x" ;;
|
||||
esac
|
||||
SOURCE=$(dirname "$(find "$TMP/x" -name horizon-server -type f | head -n 1)")
|
||||
[ -x "$SOURCE/horizon-server" ] || die "$ASSET holds no horizon-server (a release from before it existed?)"
|
||||
|
||||
RELEASE="$DIR/releases/$TAG"
|
||||
mkdir -p "$DIR/releases" "$DIR/game-files/horizon-client" "$BIN"
|
||||
rm -rf "$RELEASE"
|
||||
mv "$SOURCE" "$RELEASE"
|
||||
# Prepared game files live outside the release, so updates and rollbacks keep them.
|
||||
mkdir -p "$RELEASE/.local"
|
||||
ln -sfn "$DIR/game-files/horizon-client" "$RELEASE/.local/horizon-client"
|
||||
ln -sfn "$RELEASE" "$DIR/current"
|
||||
# Small launchers rather than links: the programs find their release folder from where they run.
|
||||
for tool in horizon-server horizon-prepare; do
|
||||
printf '#!/bin/sh\nexec "%s/current/%s" "$@"\n' "$DIR" "$tool" > "$BIN/$tool"
|
||||
chmod +x "$BIN/$tool"
|
||||
done
|
||||
|
||||
echo "Installed Horizon $TAG in $RELEASE; horizon-server and horizon-prepare are in $BIN."
|
||||
case ":$PATH:" in
|
||||
*":$BIN:"*) ;;
|
||||
*) echo "Add $BIN to your PATH, for example: echo 'export PATH=\"$BIN:\$PATH\"' >> ~/.profile" ;;
|
||||
esac
|
||||
if [ -z "$(ls -A "$DIR/game-files/horizon-client" 2>/dev/null)" ]; then
|
||||
echo "Next, prepare the game files from your own Minecraft 26.3 (it needs Java 25 and the game installed once"
|
||||
echo "by the official launcher; see docs/server.md):"
|
||||
echo " horizon-prepare --prepare --server-jar /path/to/server.jar"
|
||||
fi
|
||||
echo "Then set up a server: mkdir my-server && cd my-server && horizon-server init"
|
||||
Executable
+301
@@ -0,0 +1,301 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Server benchmark: the same bots on Horizon's server and on vanilla 26.3's (docs/server.md, section 9).
|
||||
|
||||
Every run starts a fresh server from the same server.properties (seed, view and simulation distance 10,
|
||||
offline, creative so the bots can fly), waits for `Done`, lets `horizon-bots` join one a second, warms up,
|
||||
then measures for a while:
|
||||
|
||||
- MSPT (average, P50, P95, P99) from each server's own `/tick query`, asked every 5 seconds on the console:
|
||||
vanilla's ServerTickRateManager numbers, which Horizon reproduces, so both measure themselves the same way;
|
||||
- RSS and CPU of the server's whole process tree, once a second;
|
||||
- chunks the bots receive per second (new terrain while the `explore` bots fly outwards);
|
||||
- the start time to `Done`, and every bot that failed to join or was dropped.
|
||||
|
||||
python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --seconds 120
|
||||
|
||||
The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The
|
||||
Horizon side runs target/release/horizon-server with the engine beside it; build both first:
|
||||
cargo build --release -p horizon-client --bin horizon-client -p horizon-server -p horizon-bots
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
ROOT = lab.ROOT
|
||||
EXE = '.exe' if os.name == 'nt' else ''
|
||||
# Where horizon-server and horizon-bots are (the engine is found beside horizon-server or on the PATH).
|
||||
BIN = Path(os.environ.get('HORIZON_BENCH_BIN', ROOT / 'target/release'))
|
||||
|
||||
PROPERTIES = {
|
||||
'level-seed': '12345',
|
||||
'view-distance': '10',
|
||||
'simulation-distance': '10',
|
||||
'online-mode': 'false',
|
||||
'white-list': 'false',
|
||||
'gamemode': 'creative',
|
||||
'force-gamemode': 'true',
|
||||
'spawn-protection': '0',
|
||||
'max-players': '200',
|
||||
'difficulty': 'easy',
|
||||
'sync-chunk-writes': 'true',
|
||||
}
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as s:
|
||||
s.bind(('127.0.0.1', 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def cpu_seconds(text):
|
||||
"""ps's cumulative CPU time: [[DD-]HH:]MM:SS[.ss]."""
|
||||
days, _, rest = text.rpartition('-')
|
||||
parts = [float(p) for p in rest.split(':')]
|
||||
seconds = 0.0
|
||||
for p in parts:
|
||||
seconds = seconds * 60 + p
|
||||
return seconds + (float(days) * 86400 if days else 0)
|
||||
|
||||
|
||||
def tree_usage(root):
|
||||
"""RSS (bytes) and CPU seconds of a process and all its descendants."""
|
||||
out = subprocess.run(['ps', '-A', '-o', 'pid=,ppid=,rss=,time='], capture_output=True, text=True).stdout
|
||||
rows = {}
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 4:
|
||||
rows[int(parts[0])] = (int(parts[1]), int(parts[2]) * 1024, cpu_seconds(parts[3]))
|
||||
tree, frontier = {root}, [root]
|
||||
while frontier:
|
||||
parent = frontier.pop()
|
||||
for pid, (ppid, _, _) in rows.items():
|
||||
if ppid == parent and pid not in tree:
|
||||
tree.add(pid)
|
||||
frontier.append(pid)
|
||||
rss = sum(rows[p][1] for p in tree if p in rows)
|
||||
cpu = sum(rows[p][2] for p in tree if p in rows)
|
||||
return rss, cpu
|
||||
|
||||
|
||||
class Server:
|
||||
"""A server with its console on stdin and its output collected."""
|
||||
|
||||
def __init__(self, command, directory, log_path):
|
||||
self.lines = []
|
||||
self.lock = threading.Lock()
|
||||
self.log = log_path.open('w', encoding='utf-8')
|
||||
self.process = subprocess.Popen([str(c) for c in command], cwd=directory, stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
encoding='utf-8', errors='replace',
|
||||
env=dict(os.environ, HORIZON_NO_AUDIO='1'))
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
|
||||
def _read(self):
|
||||
for line in self.process.stdout:
|
||||
with self.lock:
|
||||
self.lines.append(line.rstrip('\n'))
|
||||
self.log.write(line)
|
||||
self.log.flush()
|
||||
|
||||
def count(self):
|
||||
with self.lock:
|
||||
return len(self.lines)
|
||||
|
||||
def since(self, n):
|
||||
with self.lock:
|
||||
return self.lines[n:]
|
||||
|
||||
def wait_for(self, pattern, timeout):
|
||||
regex = re.compile(pattern)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if any(regex.search(l) for l in self.since(0)):
|
||||
return
|
||||
if self.process.poll() is not None:
|
||||
raise RuntimeError('the server exited:\n' + '\n'.join(self.since(0)[-20:]))
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError(f'no {pattern!r} within {timeout} s')
|
||||
|
||||
def console(self, line):
|
||||
self.process.stdin.write(line + '\n')
|
||||
self.process.stdin.flush()
|
||||
|
||||
def stop(self):
|
||||
if self.process.poll() is None:
|
||||
try:
|
||||
self.console('stop')
|
||||
self.process.wait(timeout=180)
|
||||
except (BrokenPipeError, subprocess.TimeoutExpired):
|
||||
self.process.kill()
|
||||
self.process.wait()
|
||||
self.log.close()
|
||||
|
||||
|
||||
TICK_AVERAGE = re.compile(r'Average time per tick: ([0-9.]+) ?ms')
|
||||
TICK_PERCENTILES = re.compile(r'P50: ([0-9.]+) ?ms P95: ([0-9.]+) ?ms P99: ([0-9.]+) ?ms')
|
||||
|
||||
|
||||
def tick_query(server):
|
||||
"""Asks `tick query` and reads the average and percentiles it prints (both servers print the same)."""
|
||||
start = server.count()
|
||||
server.console('tick query')
|
||||
deadline = time.time() + 5
|
||||
average = percentiles = None
|
||||
while time.time() < deadline and (average is None or percentiles is None):
|
||||
for line in server.since(start):
|
||||
if (m := TICK_AVERAGE.search(line)) and average is None:
|
||||
average = float(m.group(1))
|
||||
if (m := TICK_PERCENTILES.search(line)) and percentiles is None:
|
||||
percentiles = tuple(float(g) for g in m.groups())
|
||||
time.sleep(0.05)
|
||||
if average is None or percentiles is None:
|
||||
return None
|
||||
return {'average': average, 'p50': percentiles[0], 'p95': percentiles[1], 'p99': percentiles[2]}
|
||||
|
||||
|
||||
def server_command(kind, directory, args):
|
||||
if kind == 'vanilla':
|
||||
_, jars, libraries = base.verify_artifacts()
|
||||
classpath = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
return ['java', f'-Xms{args.heap}', f'-Xmx{args.heap}', '-Duser.timezone=UTC', '-cp', classpath,
|
||||
'net.minecraft.server.Main', 'nogui']
|
||||
server = BIN / f'horizon-server{EXE}'
|
||||
subprocess.run([server, '--dir', directory, 'import', directory / 'server.properties'], check=True,
|
||||
capture_output=True)
|
||||
toml = directory / 'server.toml'
|
||||
# The same settings, without the web panel.
|
||||
toml.write_text(re.sub(r'(?m)^bind = "127\.0\.0\.1:8130"', 'bind = ""', toml.read_text()))
|
||||
return [server, '--dir', directory, 'run']
|
||||
|
||||
|
||||
def run_once(kind, bots, args, out):
|
||||
directory = out / f'{kind}-{bots}'
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir(parents=True)
|
||||
port = free_port()
|
||||
props = dict(PROPERTIES, **{'server-port': str(port), 'level-seed': str(args.seed)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
command = server_command(kind, directory, args)
|
||||
started = time.time()
|
||||
server = Server(command, directory, out / f'{kind}-{bots}.log')
|
||||
result = {'server': kind, 'bots': bots}
|
||||
try:
|
||||
server.wait_for(r'/INFO\]: Done \(', 600)
|
||||
result['start_seconds'] = round(time.time() - started, 2)
|
||||
time.sleep(5)
|
||||
report = out / f'{kind}-{bots}-bots.json'
|
||||
total = bots * args.join_every + args.warmup + args.seconds
|
||||
bot_process = subprocess.Popen(
|
||||
[BIN / f'horizon-bots{EXE}', '--server', f'127.0.0.1:{port}', '--bots', str(bots),
|
||||
'--behaviour', args.behaviour, '--join-every', str(args.join_every), '--seconds', str(int(total)),
|
||||
'--seed', str(args.seed), '--report', report],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
bot_lines = []
|
||||
threading.Thread(target=lambda: bot_lines.extend(bot_process.stdout), daemon=True).start()
|
||||
# All bots in, then the warm-up.
|
||||
time.sleep(bots * args.join_every + args.warmup)
|
||||
measure_start = time.time()
|
||||
rss, cpu, ticks = [], [], []
|
||||
_, last_cpu = tree_usage(server.process.pid)
|
||||
last_time = time.time()
|
||||
next_query = time.time()
|
||||
while time.time() - measure_start < args.seconds:
|
||||
time.sleep(1)
|
||||
now = time.time()
|
||||
r, c = tree_usage(server.process.pid)
|
||||
rss.append(r)
|
||||
cpu.append((c - last_cpu) / (now - last_time) * 100)
|
||||
last_cpu, last_time = c, now
|
||||
if now >= next_query:
|
||||
if (t := tick_query(server)) is not None:
|
||||
ticks.append(t)
|
||||
next_query = now + 5
|
||||
measured = [json.loads(l) for l in list(bot_lines) if l.startswith('{')]
|
||||
window = [l for l in measured if l['t'] >= measured[-1]['t'] - args.seconds] if measured else []
|
||||
bot_process.wait(timeout=total + 120)
|
||||
summary = json.loads(report.read_text()) if report.exists() else {}
|
||||
mean = lambda xs: round(statistics.fmean(xs), 2) if xs else None
|
||||
result.update({
|
||||
'mspt': {k: mean([t[k] for t in ticks]) for k in ('average', 'p50', 'p95', 'p99')},
|
||||
'mspt_worst_p99': max((t['p99'] for t in ticks), default=None),
|
||||
# /tick query reports times, not the rate: 20 while the average fits in 50 ms.
|
||||
'tps': round(min(20.0, 1000 / max(statistics.fmean([t['average'] for t in ticks]), 1e-9)), 2) if ticks else None,
|
||||
'rss_mb': {'mean': mean([r / 1e6 for r in rss]), 'max': round(max(rss) / 1e6, 1) if rss else None},
|
||||
'cpu_percent': mean(cpu),
|
||||
'chunks_per_second': mean([l['chunks_per_second'] for l in window]),
|
||||
'bots_joined': summary.get('joined'),
|
||||
'bots_failed': [b for b in summary.get('per_bot', []) if b.get('error')],
|
||||
'tick_queries': len(ticks),
|
||||
})
|
||||
except Exception as e: # a failed run is reported, and the next one still runs
|
||||
result['error'] = str(e)
|
||||
finally:
|
||||
server.stop()
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
|
||||
parser.add_argument('--servers', default='horizon,vanilla')
|
||||
parser.add_argument('--bots', default='1,10,25,50')
|
||||
parser.add_argument('--behaviour', default='mixed')
|
||||
parser.add_argument('--join-every', type=float, default=1.0)
|
||||
parser.add_argument('--warmup', type=int, default=60)
|
||||
parser.add_argument('--seconds', type=int, default=300)
|
||||
parser.add_argument('--seed', type=int, default=12345)
|
||||
parser.add_argument('--heap', default='4g', help='the Java heap, -Xms and -Xmx (vanilla)')
|
||||
parser.add_argument('--out', type=Path, default=None, help='the report (JSON)')
|
||||
args = parser.parse_args()
|
||||
out = lab.LOCAL / 'server-bench'
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
runs = []
|
||||
for bots in [int(b) for b in args.bots.split(',')]:
|
||||
for kind in args.servers.split(','):
|
||||
print(f'{kind}, {bots} bots...', flush=True)
|
||||
result = run_once(kind, bots, args, out)
|
||||
runs.append(result)
|
||||
print(json.dumps(result), flush=True)
|
||||
report = {
|
||||
'kind': 'horizon-server-benchmark',
|
||||
'date': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'),
|
||||
'machine': {'system': platform.system(), 'machine': platform.machine(), 'cpus': os.cpu_count()},
|
||||
'commit': subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=ROOT, capture_output=True, text=True).stdout.strip(),
|
||||
'java': subprocess.run(['java', '--version'], capture_output=True, text=True).stdout.splitlines()[:1],
|
||||
'settings': {**vars(args), 'out': str(args.out), 'properties': PROPERTIES},
|
||||
'runs': runs,
|
||||
}
|
||||
path = args.out or out / 'report.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(f'\n{"server":8} {"bots":>4} {"start s":>8} {"MSPT":>6} {"P95":>6} {"P99":>6} {"RSS MB":>7} {"CPU %":>6} {"chunks/s":>8} {"joined":>6}')
|
||||
for r in runs:
|
||||
if 'error' in r:
|
||||
print(f'{r["server"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}')
|
||||
continue
|
||||
print(f'{r["server"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} {r["mspt"]["p95"]!s:>6} '
|
||||
f'{r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} {r["chunks_per_second"]!s:>8} '
|
||||
f'{r["bots_joined"]!s:>6}')
|
||||
print(f'\nWrote {path}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
+8
-7
@@ -1,8 +1,8 @@
|
||||
//! Repository tasks, run with `cargo run -p xtask -- TASK`.
|
||||
//!
|
||||
//! `package BINARY OUTDIR`: a playable Horizon folder with the game binary, horizon-ctl and
|
||||
//! horizon-prepare (built beside it: cargo build --release -p horizon-client --bins -p
|
||||
//! horizon-prepare), the exporters horizon-prepare compiles, its sources (the launcher compares
|
||||
//! `package BINARY OUTDIR`: a playable Horizon folder with the game binary, horizon-ctl,
|
||||
//! horizon-prepare and horizon-server (built beside it: cargo build --release -p horizon-client
|
||||
//! --bins -p horizon-prepare -p horizon-server), the exporters horizon-prepare compiles, its sources (the launcher compares
|
||||
//! them to its own), and PLAY.txt. It holds none of Minecraft's files: players prepare those
|
||||
//! from their own copy. .github/workflows/release.yml makes the release folders with it.
|
||||
//!
|
||||
@@ -29,9 +29,10 @@ const ARCHIVED: [&str; 5] = [
|
||||
];
|
||||
|
||||
/// The programs that sit beside the client: horizon-ctl, the command line and MCP server that
|
||||
/// play the game, and horizon-prepare, which prepares the resources from the player's own
|
||||
/// Minecraft.
|
||||
const TOOLS: [&str; 2] = ["horizon-ctl", "horizon-prepare"];
|
||||
/// play the game, horizon-prepare, which prepares the resources from the player's own
|
||||
/// Minecraft, and horizon-server, which hosts a server with the client as its engine
|
||||
/// (docs/server.md).
|
||||
const TOOLS: [&str; 3] = ["horizon-ctl", "horizon-prepare", "horizon-server"];
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
@@ -234,7 +235,7 @@ fn package(binary: &Path, out: &Path) -> Result<(), String> {
|
||||
let path = binary.parent().unwrap_or(Path::new("")).join(name);
|
||||
if !path.is_file() {
|
||||
return Err(format!(
|
||||
"{} is missing; build it too: cargo build --release -p horizon-client --bins -p horizon-prepare",
|
||||
"{} is missing; build it too: cargo build --release -p horizon-client --bins -p horizon-prepare -p horizon-server",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user