diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 38b3af3d0..27636b0eb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/crates/horizon-server/src/init.rs b/crates/horizon-server/src/init.rs index 51d8abaf7..37e43df80 100644 --- a/crates/horizon-server/src/init.rs +++ b/crates/horizon-server/src/init.rs @@ -27,6 +27,38 @@ pub struct Answers { 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 { + 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, } diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index e38a16730..b19e14973 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -9,6 +9,7 @@ mod engine; mod http; mod init; mod lists; +mod service; mod signals; mod supervisor; @@ -38,6 +39,9 @@ Usage: horizon-server [--dir DIR] 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 import FILE Write server.toml from a vanilla server.properties op NAME, deop NAME whitelist on|off|list, whitelist add|remove NAME @@ -78,6 +82,7 @@ fn main() -> ExitCode { Some("logs") => logs(&dir, &args[1..]), 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()), @@ -117,7 +122,7 @@ fn logs(dir: &std::path::Path, args: &[String]) -> Result<(), String> { } fn init_answers(args: &[String]) -> Result { - let mut answers = init::Answers::default(); + let mut answers = init::Answers::from_env()?; let mut it = args.iter(); while let Some(arg) = it.next() { let mut value = |flag: &str| { diff --git a/crates/horizon-server/src/service.rs b/crates/horizon-server/src/service.rs new file mode 100644 index 000000000..2cafa0e3d --- /dev/null +++ b/crates/horizon-server/src/service.rs @@ -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-`, 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 { + let on_path = std::env::var_os("PATH") + .map(|p| std::env::split_paths(&p).collect::>()) + .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#" + + + + Label + {label} + ProgramArguments + + {program} + --dir + {dir} + run + + WorkingDirectory + {dir} + RunAtLoad + + KeepAlive + + SuccessfulExit + + + ExitTimeOut + 180 + StandardOutPath + {log} + StandardErrorPath + {log} + + +"#, + program = xml(&program.display().to_string()), + dir = xml(&dir.display().to_string()), + log = xml(&log.display().to_string()), + ) +} + +fn home() -> Result { + std::env::var_os("HOME") + .map(PathBuf::from) + .ok_or_else(|| "HOME is not set".into()) +} + +fn launchd_path(label: &str) -> Result { + 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 { + 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("/srv/R&D")); + assert!(plist.contains("/srv/R&D/logs/supervisor.log")); + } +} diff --git a/packaging/PLAY.txt b/packaging/PLAY.txt index 5ad53d062..20ea402fb 100644 --- a/packaging/PLAY.txt +++ b/packaging/PLAY.txt @@ -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. diff --git a/packaging/server/Dockerfile b/packaging/server/Dockerfile new file mode 100644 index 000000000..bbb74ba26 --- /dev/null +++ b/packaging/server/Dockerfile @@ -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"] diff --git a/packaging/server/install.ps1 b/packaging/server/install.ps1 new file mode 100644 index 000000000..6ed2adf34 --- /dev/null +++ b/packaging/server/install.ps1 @@ -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 \releases\, \current points at the one in use, and \bin (added to +# your PATH) holds horizon-server.cmd and horizon-prepare.cmd. The game files you prepare from your own +# Minecraft stay in \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 +} diff --git a/packaging/server/install.sh b/packaging/server/install.sh new file mode 100755 index 000000000..221fcf0a8 --- /dev/null +++ b/packaging/server/install.sh @@ -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 /releases/, /current points at the one in use, and /horizon-server +# runs it. The game files you prepare from your own Minecraft stay in /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" diff --git a/xtask/src/main.rs b/xtask/src/main.rs index b436b45a7..05b84553b 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -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 = 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() )); }