Merge pull request #1575 from RobertTGreat/fix/launcher-startup-windows
🤖 Agent: merged after verify passed and the integration run on the desktop.
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
//! The machine a report was measured on. CPU, RAM and OS are detected here; the GPU and the display
|
||||
//! come from the program that rendered (the game knows its adapter, the launcher its window).
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
use horizon_telemetry::system::command_output as output;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -173,12 +172,6 @@ pub fn cpu_seconds(pid: u32) -> Option<f64> {
|
||||
Some(ticks / 100.0)
|
||||
}
|
||||
|
||||
fn output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let out = Command::new(program).args(args).output().ok()?;
|
||||
let text = String::from_utf8(out.stdout).ok()?.trim().to_owned();
|
||||
(out.status.success() && !text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn os_version() -> Option<String> {
|
||||
output("sw_vers", &["-productVersion"])
|
||||
|
||||
@@ -245,13 +245,19 @@ pub struct Report {
|
||||
impl Report {
|
||||
/// An empty report for this machine, created now.
|
||||
pub fn new(kind: Kind, app: App) -> Report {
|
||||
Self::with_hardware(kind, app, Hardware::detect())
|
||||
}
|
||||
|
||||
/// Starts a report using supplied hardware, without running system probes.
|
||||
/// Interactive apps can collect the remaining machine details after their first frame.
|
||||
pub fn with_hardware(kind: Kind, app: App, hardware: Hardware) -> Report {
|
||||
Report {
|
||||
format: FORMAT.to_owned(),
|
||||
version: VERSION,
|
||||
kind,
|
||||
created: utc_now(),
|
||||
app,
|
||||
hardware: Hardware::detect(),
|
||||
hardware,
|
||||
conditions: Conditions::default(),
|
||||
metrics: BTreeMap::new(),
|
||||
frames: Vec::new(),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The JDK that compiles and runs the vanilla exporters. They call Mojang's own code, so they
|
||||
//! stay Java; everything around them is here.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
@@ -13,6 +14,20 @@ pub struct Jdk {
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(3600);
|
||||
|
||||
/// Exporters and JDK probes write to pipes or log files: on Windows they open no terminal.
|
||||
fn command(program: impl AsRef<OsStr>) -> Command {
|
||||
let command = Command::new(program);
|
||||
#[cfg(windows)]
|
||||
let command = {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
let mut command = command;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
command
|
||||
};
|
||||
command
|
||||
}
|
||||
|
||||
fn executable(dir: &Path, name: &str) -> PathBuf {
|
||||
dir.join(if cfg!(windows) {
|
||||
format!("{name}.exe")
|
||||
@@ -29,7 +44,7 @@ fn on_path(name: &str) -> Option<PathBuf> {
|
||||
|
||||
/// The major version `javac -version` reports ("javac 25.0.1" → 25; "javac 1.8.0" → 8).
|
||||
fn javac_major(javac: &Path) -> Result<u32, String> {
|
||||
let output = Command::new(javac)
|
||||
let output = command(javac)
|
||||
.arg("-version")
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
@@ -183,7 +198,7 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result<Jdk, String> {
|
||||
candidates.push((javac, java, "PATH"));
|
||||
}
|
||||
if cfg!(target_os = "macos") {
|
||||
if let Ok(out) = Command::new("/usr/libexec/java_home")
|
||||
if let Ok(out) = command("/usr/libexec/java_home")
|
||||
.args(["-v", &major.to_string()])
|
||||
.stderr(Stdio::null())
|
||||
.output()
|
||||
@@ -260,7 +275,7 @@ impl Jdk {
|
||||
/// `javac --release <major> -proc:none` with Python's `subprocess.run(..., check=True,
|
||||
/// stdout=log, stderr=STDOUT, timeout=3600)`.
|
||||
pub fn javac(&self, major: i64, args: &[String], log: &fs::File) -> Result<(), String> {
|
||||
let mut command = Command::new(&self.javac);
|
||||
let mut command = command(&self.javac);
|
||||
command
|
||||
.args(["--release", &major.to_string(), "-proc:none"])
|
||||
.args(args);
|
||||
@@ -268,7 +283,7 @@ impl Jdk {
|
||||
}
|
||||
|
||||
pub fn java(&self, args: &[String], cwd: Option<&Path>, log: &fs::File) -> Result<(), String> {
|
||||
let mut command = Command::new(&self.java);
|
||||
let mut command = command(&self.java);
|
||||
command.args(args);
|
||||
if let Some(dir) = cwd {
|
||||
command.current_dir(dir);
|
||||
|
||||
@@ -68,7 +68,8 @@ pub fn program_in(
|
||||
/// system can't load the program, as on a Linux without the ALSA and udev libraries the full game links
|
||||
/// (the server build doesn't). The reason, with what to install.
|
||||
pub fn check_starts(program: &Path) -> Result<(), String> {
|
||||
let output = Command::new(program)
|
||||
let mut command = crate::process::command(program);
|
||||
let output = command
|
||||
.arg("--help")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
@@ -176,7 +177,8 @@ pub fn spawn(program: &Path, resources: &Path, dir: &Path) -> std::io::Result<Ch
|
||||
#[cfg(windows)]
|
||||
std::os::windows::process::CommandExt::creation_flags(
|
||||
&mut command,
|
||||
windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP,
|
||||
windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP
|
||||
| windows_sys::Win32::System::Threading::CREATE_NO_WINDOW,
|
||||
);
|
||||
command.spawn()
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ mod http;
|
||||
mod init;
|
||||
mod lists;
|
||||
mod panel;
|
||||
mod process;
|
||||
mod service;
|
||||
mod settings;
|
||||
mod signals;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! The programs the server runs. Started by the launcher, the server has no console, and each
|
||||
//! console program it started would open a terminal window on Windows: those open none. Run from
|
||||
//! a terminal, they share it, so what they print still reaches it.
|
||||
use std::{ffi::OsStr, process::Command};
|
||||
|
||||
pub fn command(program: impl AsRef<OsStr>) -> Command {
|
||||
let command = Command::new(program);
|
||||
#[cfg(windows)]
|
||||
let command = {
|
||||
use std::os::windows::process::CommandExt;
|
||||
use windows_sys::Win32::System::{Console::GetConsoleWindow, Threading::CREATE_NO_WINDOW};
|
||||
let mut command = command;
|
||||
// SAFETY: no arguments; it returns this process's console window or null.
|
||||
if unsafe { GetConsoleWindow() }.is_null() {
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
command
|
||||
};
|
||||
command
|
||||
}
|
||||
@@ -178,7 +178,7 @@ fn systemd_path(service: &str, system: bool) -> Result<PathBuf, String> {
|
||||
}
|
||||
|
||||
fn run(program: &str, args: &[&str]) -> Result<(), String> {
|
||||
let status = Command::new(program)
|
||||
let status = crate::process::command(program)
|
||||
.args(args)
|
||||
.status()
|
||||
.map_err(|e| format!("{program}: {e}"))?;
|
||||
@@ -191,7 +191,7 @@ fn run(program: &str, args: &[&str]) -> Result<(), String> {
|
||||
|
||||
/// 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)
|
||||
let _ = crate::process::command(program)
|
||||
.args(args)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
|
||||
@@ -10,7 +10,6 @@ use serde_json::{Value, json};
|
||||
use std::{
|
||||
io::Read,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
@@ -206,7 +205,7 @@ fn point(link: &Path, target: &Path) -> std::io::Result<()> {
|
||||
if link.exists() || link.symlink_metadata().is_ok() {
|
||||
std::fs::remove_dir(link)?;
|
||||
}
|
||||
let status = Command::new("cmd")
|
||||
let status = crate::process::command("cmd")
|
||||
.arg("/C")
|
||||
.arg("mklink")
|
||||
.arg("/J")
|
||||
@@ -474,7 +473,7 @@ pub fn unpack(install: &Install, archive: &Path, tag: &str) -> Result<PathBuf, S
|
||||
// tar is on every Linux and macOS, and on Windows 10 and later. The files are the
|
||||
// user's, not the archive's owners: as root in a user namespace (an unprivileged LXC
|
||||
// or rootless container) taking those fails, and as plain root they'd be strangers'.
|
||||
let status = Command::new("tar")
|
||||
let status = crate::process::command("tar")
|
||||
.arg("--no-same-owner")
|
||||
.arg("-xzf")
|
||||
.arg(archive)
|
||||
@@ -1058,7 +1057,7 @@ mod tests {
|
||||
std::fs::write(inner.join("horizon-server"), "v2").unwrap();
|
||||
std::fs::write(inner.join("horizon-engine"), "engine").unwrap();
|
||||
let archive = source.join("horizon-server-linux-x86_64.tar.gz");
|
||||
let status = Command::new("tar")
|
||||
let status = std::process::Command::new("tar")
|
||||
.arg("-czf")
|
||||
.arg(&archive)
|
||||
.arg("-C")
|
||||
|
||||
@@ -9,11 +9,19 @@ use std::sync::OnceLock;
|
||||
|
||||
use crate::payload::System;
|
||||
|
||||
fn command_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let out = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
/// What `program args` prints, trimmed, when it succeeds and prints something. On Windows the
|
||||
/// program opens no console window: a GUI launcher or a game started without one would flash a
|
||||
/// terminal for every probe.
|
||||
pub fn command_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let mut command = std::process::Command::new(program);
|
||||
command.args(args);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
let out = command.output().ok()?;
|
||||
let text = String::from_utf8_lossy(&out.stdout).trim().to_owned();
|
||||
(out.status.success() && !text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
+8
-3
@@ -131,7 +131,12 @@ and `horizon-launcher-windows-x64.zip`, never marked latest. The version is buil
|
||||
|
||||
## Command line
|
||||
|
||||
The same binary is a command-line tool; without a subcommand it opens the window.
|
||||
The same binary is a command-line tool; without a subcommand it opens the window. On Windows it
|
||||
is a windowed program, so a desktop start opens no terminal; a subcommand writes to the terminal
|
||||
it was typed in, or to the pipes and files it was given (MCP keeps its stdio). Interactive `cmd`
|
||||
and PowerShell don't wait for a windowed program: they show the prompt again before its output
|
||||
and don't set `%ERRORLEVEL%` / `$LASTEXITCODE`. Scripts that need the exit code use
|
||||
`start /wait horizon-launcher …` or `Start-Process -Wait`, or read its output through a pipe.
|
||||
|
||||
horizon-launcher versions [--installed] releases on GitHub, or what is installed (* = selected)
|
||||
horizon-launcher install <tag|latest>
|
||||
@@ -254,8 +259,8 @@ Each session writes its own measurements to `benchmarks/launcher-<time>-session.
|
||||
launcher's data folder, in the [benchmark report format](../docs/benchmark-report.md): start to the
|
||||
first frame, the release list fetch, installs and updates (download and unpack), preparing, Play to
|
||||
the game's first frame, memory, UI frame times and the binary's size, with the machine's CPU, RAM
|
||||
and OS. Attach it to an issue about the launcher being slow. `horizon-launcher benchmark` measures
|
||||
on purpose: it starts the launcher `--repeats` times (5; the first start is the cold one, as far
|
||||
and OS (read on a thread after the first frame: on Windows those queries take seconds). Attach it
|
||||
to an issue about the launcher being slow. `horizon-launcher benchmark` measures on purpose: it starts the launcher `--repeats` times (5; the first start is the cold one, as far
|
||||
as the OS's file cache allows), switches pages for a few seconds in each, rests 3 seconds to
|
||||
measure idle CPU, fetches the release list 3 times, and writes one report there with means and
|
||||
95% confidence intervals. Its window has to be on a screen that is awake. Session logs stay on
|
||||
|
||||
@@ -122,8 +122,8 @@ pub fn locate(program: &str) -> std::path::PathBuf {
|
||||
/// Settings page's "Test the connection".
|
||||
pub fn self_test(exe: &Path) -> Result<usize, String> {
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
let mut child = Command::new(exe)
|
||||
use std::process::Stdio;
|
||||
let mut child = crate::process::command(exe)
|
||||
.arg("mcp")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
|
||||
@@ -207,7 +207,7 @@ impl Launcher {
|
||||
|
||||
/// Runs a client's add command; (went well, what it said).
|
||||
fn run_add(program: &str, args: &[String]) -> (bool, String) {
|
||||
match std::process::Command::new(agents::locate(program))
|
||||
match horizon_launcher::process::command(agents::locate(program))
|
||||
.args(args)
|
||||
.output()
|
||||
{
|
||||
|
||||
+5
-10
@@ -943,7 +943,7 @@ pub fn default_minecraft_dir() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
fn found(program: &str, arg: &str) -> bool {
|
||||
Command::new(program)
|
||||
crate::process::command(program)
|
||||
.arg(arg)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
@@ -1239,14 +1239,14 @@ pub fn sounds(tag: &str, minecraft: &Path, log: &dyn Fn(String)) {
|
||||
let own = horizon_prepare::sources_sha256(&dir.join(PREPARER_CRATE)).as_deref()
|
||||
== Some(horizon_prepare::SOURCES_SHA256);
|
||||
let binary = preparer_binary(&dir).filter(|binary| {
|
||||
!own && Command::new(binary)
|
||||
!own && crate::process::command(binary)
|
||||
.arg("--help")
|
||||
.output()
|
||||
.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("horizon-prepare sounds"))
|
||||
});
|
||||
log("Copying the sounds from your Minecraft install".into());
|
||||
let result = match binary {
|
||||
Some(binary) => Command::new(binary)
|
||||
Some(binary) => crate::process::command(binary)
|
||||
.current_dir(&dir)
|
||||
.arg("sounds")
|
||||
.arg("--root")
|
||||
@@ -1877,16 +1877,10 @@ fn parse_version_output(out: &str) -> Option<&str> {
|
||||
/// The version of the launcher binary now at `path`, which is not this process's once another
|
||||
/// update (the command line, another window) has replaced the file.
|
||||
fn installed_launcher_version(path: &Path) -> Option<String> {
|
||||
let mut cmd = Command::new(path);
|
||||
let mut cmd = crate::process::command(path);
|
||||
cmd.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
let out = cmd.output().ok()?;
|
||||
parse_version_output(&String::from_utf8_lossy(&out.stdout)).map(String::from)
|
||||
}
|
||||
@@ -2220,6 +2214,7 @@ impl Running {
|
||||
}
|
||||
|
||||
pub fn spawn(job: Job, mut cmd: Command, tx: Sender<Msg>) -> Result<Running, String> {
|
||||
crate::process::hide_console(&mut cmd);
|
||||
let mut child = cmd
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
|
||||
@@ -210,7 +210,7 @@ impl Tool {
|
||||
pub fn call(&self, args: &Value) -> Result<String, String> {
|
||||
let words = self.argv(args)?;
|
||||
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||
let out = std::process::Command::new(exe)
|
||||
let out = horizon_launcher::process::command(exe)
|
||||
.arg("--json")
|
||||
.args(&words)
|
||||
.stdin(std::process::Stdio::null())
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
//! A desktop launch has no console; CLI commands can use the invoking terminal or pipes.
|
||||
#[cfg(windows)]
|
||||
pub fn attach_for_cli() -> std::io::Result<()> {
|
||||
use std::ffi::c_void;
|
||||
|
||||
const ATTACH_PARENT_PROCESS: u32 = u32::MAX;
|
||||
const STD_INPUT_HANDLE: u32 = -10_i32 as u32;
|
||||
const STD_OUTPUT_HANDLE: u32 = -11_i32 as u32;
|
||||
const STD_ERROR_HANDLE: u32 = -12_i32 as u32;
|
||||
const INVALID_HANDLE_VALUE: isize = -1;
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
extern "system" {
|
||||
fn AttachConsole(process_id: u32) -> i32;
|
||||
fn GetStdHandle(kind: u32) -> *mut c_void;
|
||||
fn SetStdHandle(kind: u32, handle: *mut c_void) -> i32;
|
||||
}
|
||||
|
||||
if std::env::args_os().nth(1).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Attaching can replace the standard handles. Keep inherited pipes/files intact for
|
||||
// JSON output, MCP and redirected logs, while filling missing handles from the terminal.
|
||||
// SAFETY: These APIs take numeric constants and opaque handles returned by Windows.
|
||||
// No handles are closed or dereferenced, and this runs before any worker starts.
|
||||
unsafe {
|
||||
let handles = [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE]
|
||||
.map(|kind| (kind, GetStdHandle(kind)));
|
||||
if AttachConsole(ATTACH_PARENT_PROCESS) == 0 {
|
||||
// No parent console (for example, an MCP client), or already attached.
|
||||
return Ok(());
|
||||
}
|
||||
for (kind, handle) in handles {
|
||||
if handle.is_null() || handle as isize == INVALID_HANDLE_VALUE {
|
||||
continue;
|
||||
}
|
||||
if SetStdHandle(kind, handle) == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn attach_for_cli() -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use horizon_launcher::backend;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Stdio};
|
||||
|
||||
pub const PREFIX: &str = "game_";
|
||||
|
||||
@@ -61,7 +61,7 @@ impl GameTools {
|
||||
if !ctl.exists() {
|
||||
return Err(format!("{tag} has no {CTL}"));
|
||||
}
|
||||
let mut child = Command::new(&ctl)
|
||||
let mut child = horizon_launcher::process::command(&ctl)
|
||||
.arg("--socket")
|
||||
.arg(socket_path())
|
||||
.arg("mcp")
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod game_app;
|
||||
pub mod heads;
|
||||
pub mod modpacks;
|
||||
pub mod mojang;
|
||||
pub mod process;
|
||||
pub mod servers;
|
||||
pub mod signed;
|
||||
pub mod sources;
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
//! Horizon launcher: installs Horizon builds, prepares them from the player's own Minecraft,
|
||||
//! and starts the client or a dedicated server.
|
||||
|
||||
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
|
||||
|
||||
mod agents_page;
|
||||
mod art;
|
||||
mod blocks;
|
||||
mod cli;
|
||||
mod cli_tools;
|
||||
mod collection;
|
||||
mod console;
|
||||
mod cull;
|
||||
mod game_tools;
|
||||
mod internet;
|
||||
@@ -3517,6 +3520,10 @@ fn menus() -> Vec<Menu> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = console::attach_for_cli() {
|
||||
eprintln!("Could not restore the launcher's terminal streams: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
perf::process_started();
|
||||
backend::exe_path();
|
||||
if let Some(code) = cli::run() {
|
||||
|
||||
+89
-4
@@ -9,10 +9,11 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{self, Receiver, TryRecvError};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use horizon_bench::{App, Frames, Kind, Report};
|
||||
use horizon_bench::{App, Frames, Hardware, Kind, Report};
|
||||
|
||||
/// The first thing `main` does; every start time counts from here.
|
||||
pub fn process_started() -> Instant {
|
||||
@@ -35,14 +36,36 @@ pub struct Perf {
|
||||
dirty: bool,
|
||||
/// Off for the windows `horizon-launcher benchmark` starts: they report to it instead.
|
||||
log: bool,
|
||||
/// Machine probes run after the first frame, never while opening the window.
|
||||
hardware: Option<Receiver<Machine>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Machine {
|
||||
hardware: Hardware,
|
||||
power: Option<String>,
|
||||
load_average: Option<f64>,
|
||||
}
|
||||
|
||||
impl Machine {
|
||||
fn detect() -> Self {
|
||||
Self {
|
||||
hardware: Hardware::detect(),
|
||||
power: horizon_bench::power_source().map(str::to_owned),
|
||||
load_average: horizon_bench::load_average(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Perf {
|
||||
pub fn new(scenario: &str) -> Perf {
|
||||
let mut report = Report::new(Kind::Launcher, app());
|
||||
let hardware = Hardware {
|
||||
os: std::env::consts::OS.to_owned(),
|
||||
arch: std::env::consts::ARCH.to_owned(),
|
||||
..Hardware::default()
|
||||
};
|
||||
let mut report = Report::with_hardware(Kind::Launcher, app(), hardware);
|
||||
report.conditions.scenario = Some(scenario.to_owned());
|
||||
report.conditions.power = horizon_bench::power_source().map(str::to_owned);
|
||||
report.conditions.load_avg_1m = horizon_bench::load_average();
|
||||
let path = crate::backend::data_dir().join("benchmarks").join(format!(
|
||||
"launcher-{}-{scenario}.json",
|
||||
report
|
||||
@@ -61,6 +84,7 @@ impl Perf {
|
||||
saved: Instant::now(),
|
||||
dirty: false,
|
||||
log: true,
|
||||
hardware: None,
|
||||
};
|
||||
if let Some(bytes) = binary_bytes() {
|
||||
perf.record("launcher.binary_bytes", bytes);
|
||||
@@ -89,6 +113,12 @@ impl Perf {
|
||||
if first {
|
||||
self.first_frame = Some(now);
|
||||
self.record_since("launcher.start_ms", process_started());
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
self.hardware = Some(receiver);
|
||||
std::thread::spawn(move || {
|
||||
// The window may close before the optional report details finish.
|
||||
let _ = sender.send(Machine::detect());
|
||||
});
|
||||
} else if let Some(gap) = self.last_frame.map(|t| now - t).filter(|g| *g < IDLE_GAP) {
|
||||
self.ui_frames.push(gap.as_secs_f32() * 1000.0);
|
||||
}
|
||||
@@ -102,6 +132,7 @@ impl Perf {
|
||||
|
||||
/// Samples memory and writes the report when something changed, at most every few seconds.
|
||||
pub fn tick(&mut self) {
|
||||
self.poll_hardware();
|
||||
if self.saved.elapsed() < Duration::from_secs(5) {
|
||||
return;
|
||||
}
|
||||
@@ -118,6 +149,7 @@ impl Perf {
|
||||
}
|
||||
|
||||
pub fn report(&mut self) -> &Report {
|
||||
self.poll_hardware();
|
||||
for (name, values) in &self.values {
|
||||
self.report.metric(name, values);
|
||||
}
|
||||
@@ -128,6 +160,24 @@ impl Perf {
|
||||
&self.report
|
||||
}
|
||||
|
||||
/// Takes the machine's details into the report once their thread has them.
|
||||
fn poll_hardware(&mut self) {
|
||||
let Some(receiver) = &self.hardware else {
|
||||
return;
|
||||
};
|
||||
match receiver.try_recv() {
|
||||
Ok(machine) => {
|
||||
self.report.hardware = machine.hardware;
|
||||
self.report.conditions.power = machine.power;
|
||||
self.report.conditions.load_avg_1m = machine.load_average;
|
||||
self.hardware = None;
|
||||
self.dirty = true;
|
||||
}
|
||||
Err(TryRecvError::Empty) => {}
|
||||
Err(TryRecvError::Disconnected) => self.hardware = None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&mut self) {
|
||||
self.dirty = false;
|
||||
if !self.log {
|
||||
@@ -381,6 +431,41 @@ fn binary_bytes() -> Option<f64> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn performance_tracking_starts_without_hardware_probes() {
|
||||
let mut perf = Perf::new("test");
|
||||
perf.keep_local_log(false);
|
||||
assert!(perf.hardware.is_none());
|
||||
assert_eq!(perf.report.hardware.os, std::env::consts::OS);
|
||||
assert!(perf.report.hardware.cpu.is_none());
|
||||
assert!(perf.report.conditions.power.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_hardware_details_preserve_recorded_metrics() {
|
||||
let mut perf = Perf::new("test");
|
||||
perf.keep_local_log(false);
|
||||
perf.record("launcher.start_ms", 125.);
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
perf.hardware = Some(receiver);
|
||||
assert_eq!(perf.report().metrics["launcher.start_ms"].mean, 125.);
|
||||
sender
|
||||
.send(Machine {
|
||||
hardware: Hardware {
|
||||
cpu: Some("Detected CPU".into()),
|
||||
..Hardware::default()
|
||||
},
|
||||
power: Some("ac".into()),
|
||||
load_average: Some(0.5),
|
||||
})
|
||||
.unwrap();
|
||||
let report = perf.report();
|
||||
assert_eq!(report.hardware.cpu.as_deref(), Some("Detected CPU"));
|
||||
assert_eq!(report.conditions.power.as_deref(), Some("ac"));
|
||||
assert_eq!(report.metrics["launcher.start_ms"].mean, 125.);
|
||||
assert!(perf.hardware.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_frame_is_the_start_and_close_frames_are_ui_frames() {
|
||||
let mut perf = Perf::new("test");
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! The programs the launcher runs in the background: on Windows they open no console window
|
||||
//! (the launcher has none to share), and keep the streams their caller gives them.
|
||||
use std::ffi::OsStr;
|
||||
use std::process::Command;
|
||||
|
||||
pub fn command(program: impl AsRef<OsStr>) -> Command {
|
||||
let mut command = Command::new(program);
|
||||
hide_console(&mut command);
|
||||
command
|
||||
}
|
||||
|
||||
/// [`command`] for a `Command` made elsewhere.
|
||||
pub fn hide_console(command: &mut Command) -> &mut Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
command
|
||||
}
|
||||
@@ -245,7 +245,7 @@ fn point(link: &Path, target: &Path) -> std::io::Result<()> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = fs::remove_dir(link);
|
||||
let status = Command::new("cmd")
|
||||
let status = crate::process::command("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.arg(link)
|
||||
.arg(target)
|
||||
@@ -266,10 +266,8 @@ pub fn command(dir: &Path, args: &[&str]) -> Result<Command, String> {
|
||||
let program = program().ok_or(
|
||||
"The server programs aren't set up yet: create a server, or press Prepare on its page.",
|
||||
)?;
|
||||
let mut cmd = Command::new(program);
|
||||
let mut cmd = crate::process::command(program);
|
||||
cmd.arg("--dir").arg(dir).args(args);
|
||||
#[cfg(windows)]
|
||||
std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // CREATE_NO_WINDOW
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
@@ -752,7 +750,7 @@ pub fn lan_address() -> Option<std::net::IpAddr> {
|
||||
pub fn service_installed(dir: &Path) -> bool {
|
||||
if cfg!(windows) {
|
||||
let name = format!("horizon-server-{}", service_suffix(dir));
|
||||
return Command::new("schtasks")
|
||||
return crate::process::command("schtasks")
|
||||
.args(["/Query", "/TN", &name])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
|
||||
@@ -488,7 +488,7 @@ fn make_link(target: &Path, link: &Path) -> std::io::Result<()> {
|
||||
arg.push("\"");
|
||||
arg
|
||||
};
|
||||
let status = std::process::Command::new("cmd")
|
||||
let status = crate::process::command("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.raw_arg(quoted(link))
|
||||
.raw_arg(quoted(target))
|
||||
|
||||
@@ -126,13 +126,8 @@ pub fn status_of(cli: Option<PathBuf>) -> State {
|
||||
let Some(cli) = cli else {
|
||||
return State::Missing;
|
||||
};
|
||||
let mut command = Command::new(&cli);
|
||||
let mut command = crate::process::command(&cli);
|
||||
command.args(["status", "--json"]);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
let out = match command.output() {
|
||||
Ok(out) => out,
|
||||
Err(e) => return State::Off(e.to_string()),
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Windows background processes must keep logs, input and exit status without a console.
|
||||
#![cfg(windows)]
|
||||
|
||||
mod support;
|
||||
use horizon_launcher::{
|
||||
backend::{self, Job, Msg},
|
||||
process,
|
||||
};
|
||||
use std::{fs, path::Path, sync::mpsc, time::Duration};
|
||||
use support::console_probe as probe;
|
||||
|
||||
fn logged_child(fail: bool) -> (Vec<String>, Result<(), String>) {
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let mut command = std::process::Command::new(probe());
|
||||
if fail {
|
||||
command.arg("--fail");
|
||||
}
|
||||
let mut child = backend::spawn(Job::Prepare, command, sender).unwrap();
|
||||
child.send("input reaches the child");
|
||||
let mut lines = Vec::new();
|
||||
loop {
|
||||
match receiver.recv_timeout(Duration::from_secs(10)).unwrap() {
|
||||
Msg::Line(Job::Prepare, line) => lines.push(line),
|
||||
Msg::Exit(Job::Prepare, result) => return (lines, result),
|
||||
_ => panic!("unexpected job message"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_children_keep_stdout_stderr_stdin_and_success() {
|
||||
let (lines, result) = logged_child(false);
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
for expected in [
|
||||
"console_window_visible=false",
|
||||
"stdout is captured",
|
||||
"stderr is captured",
|
||||
"stdin=input reaches the child",
|
||||
] {
|
||||
assert!(
|
||||
lines.iter().any(|line| line == expected),
|
||||
"missing {expected}: {lines:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_children_report_failure_and_keep_their_logs() {
|
||||
let (lines, result) = logged_child(true);
|
||||
assert!(result.unwrap_err().contains('7'));
|
||||
assert!(lines.iter().any(|line| line == "stderr is captured"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exporters_write_to_their_log_file_without_a_console() {
|
||||
let root = probe().parent().unwrap();
|
||||
let path = root.join("exporter.log");
|
||||
let log = fs::File::create(&path).unwrap();
|
||||
let jdk = horizon_prepare::java::Jdk {
|
||||
java: probe().into(),
|
||||
javac: probe().into(),
|
||||
};
|
||||
jdk.java(&[], Some(root), &log).unwrap();
|
||||
let output = fs::read_to_string(path).unwrap();
|
||||
for expected in [
|
||||
"console_window_visible=false",
|
||||
"stdout is captured",
|
||||
"stderr is captured",
|
||||
] {
|
||||
assert!(output.contains(expected), "missing {expected}: {output}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_keeps_redirected_stdout_and_stderr() {
|
||||
let executable = env!("CARGO_BIN_EXE_horizon-launcher");
|
||||
let version = process::command(executable)
|
||||
.arg("--version")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(version.status.success());
|
||||
assert!(String::from_utf8_lossy(&version.stdout).starts_with("horizon-launcher "));
|
||||
let invalid = process::command(executable)
|
||||
.arg("--unknown-option")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!invalid.status.success());
|
||||
assert!(String::from_utf8_lossy(&invalid.stderr).contains("--unknown-option"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_keeps_its_stdio_transport() {
|
||||
let executable = Path::new(env!("CARGO_BIN_EXE_horizon-launcher"));
|
||||
assert!(horizon_launcher::agents::self_test(executable).unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_executable_uses_the_windows_gui_subsystem() {
|
||||
const PE_HEADER_POINTER: usize = 0x3c;
|
||||
const PE_OPTIONAL_HEADER_OFFSET: usize = 24;
|
||||
const SUBSYSTEM_OFFSET: usize = 68;
|
||||
const WINDOWS_GUI_SUBSYSTEM: u16 = 2;
|
||||
|
||||
let executable = fs::read(env!("CARGO_BIN_EXE_horizon-launcher")).unwrap();
|
||||
let header = u32::from_le_bytes(
|
||||
executable[PE_HEADER_POINTER..PE_HEADER_POINTER + 4]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
assert_eq!(&executable[header..header + 4], b"PE\0\0");
|
||||
let subsystem = header + PE_OPTIONAL_HEADER_OFFSET + SUBSYSTEM_OFFSET;
|
||||
assert_eq!(
|
||||
u16::from_le_bytes(executable[subsystem..subsystem + 2].try_into().unwrap()),
|
||||
WINDOWS_GUI_SUBSYSTEM
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Full launcher startup against instrumented Windows hardware probes.
|
||||
#![cfg(windows)]
|
||||
|
||||
mod support;
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::{Child, Output, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
fn fixture() -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("horizon-startup-{}", std::process::id()));
|
||||
for folder in ["game/telemetry", "launcher", "data", "config", "probes"] {
|
||||
fs::create_dir_all(root.join(folder)).unwrap();
|
||||
}
|
||||
fs::write(root.join("launcher/settings.json"), r#"{"skip_opening":true,"install_new_versions":false,"desktop_entry":false,"ping_notice_seen":true}"#).unwrap();
|
||||
let consent = serde_json::json!({"version":horizon_telemetry::CONSENT_VERSION,"choices":{}});
|
||||
fs::write(
|
||||
root.join("game/telemetry/consent.json"),
|
||||
consent.to_string(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::copy(support::console_probe(), root.join("probes/powershell.exe")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn launch(root: &Path) -> Child {
|
||||
let inherited_path = std::env::var_os("PATH").unwrap();
|
||||
let paths = std::iter::once(root.join("probes")).chain(std::env::split_paths(&inherited_path));
|
||||
horizon_launcher::process::command(env!("CARGO_BIN_EXE_horizon-launcher"))
|
||||
.current_dir(root)
|
||||
.env("PATH", std::env::join_paths(paths).unwrap())
|
||||
.env("HORIZON_HOME", root.join("game"))
|
||||
.env("HORIZON_LAUNCHER_HOME", root.join("launcher"))
|
||||
.env("XDG_DATA_HOME", root.join("data"))
|
||||
.env("XDG_CONFIG_HOME", root.join("config"))
|
||||
.env("HORIZON_LAUNCHER_NO_SELF_UPDATE", "1")
|
||||
.env("HORIZON_NO_AUDIO", "1")
|
||||
.env("HORIZON_TELEMETRY_URL", "off")
|
||||
.env("HORIZON_STARTUP_PROBE_LOG", root.join("probes.log"))
|
||||
.env("HORIZON_LAUNCHER_BENCH", root.join("timing.json"))
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn wait_for_exit(mut child: Child, root: &Path) -> Output {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
panic!("launcher startup timed out: {}", root.display());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an interactive Windows desktop and graphics adapter"]
|
||||
fn hardware_probes_run_hidden_after_the_first_frame() {
|
||||
let root = fixture();
|
||||
let output = wait_for_exit(launch(&root), &root);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let timing: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(root.join("timing.json")).unwrap()).unwrap();
|
||||
let first_frame = timing["first_frame_epoch_ms"].as_f64().unwrap().floor();
|
||||
let probes = fs::read_to_string(root.join("probes.log")).unwrap();
|
||||
// Rust resolves cmd.exe to the system directory, so instrument the seven PowerShell
|
||||
// probes, which exercise both shared helpers (the cmd probes use those same helpers).
|
||||
const POWERSHELL_PROBES: usize = 7;
|
||||
assert_eq!(probes.lines().count(), POWERSHELL_PROBES, "{probes}");
|
||||
for probe in probes.lines() {
|
||||
let fields: Vec<_> = probe.split('|').collect();
|
||||
assert!(
|
||||
fields[0].parse::<f64>().unwrap() >= first_frame,
|
||||
"probe blocked startup: {probe}"
|
||||
);
|
||||
assert_eq!(fields[1], "false", "probe opened a terminal: {probe}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! A real Windows console program used to check hidden children and their streams.
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
|
||||
fn hardware_probe(visible: bool) -> bool {
|
||||
let Some(path) = std::env::var_os("HORIZON_STARTUP_PROBE_LOG") else {
|
||||
return false;
|
||||
};
|
||||
use std::io::Write;
|
||||
let arguments = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
|
||||
let program = std::env::current_exe().unwrap();
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
let mut log = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)
|
||||
.unwrap();
|
||||
writeln!(
|
||||
log,
|
||||
"{timestamp}|{visible}|{}",
|
||||
program.file_name().unwrap().to_string_lossy()
|
||||
)
|
||||
.unwrap();
|
||||
// Slow probes make a synchronous startup regression visible without relying on WMI speed.
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
let responses = [
|
||||
("TotalPhysicalMemory", "17179869184"),
|
||||
("NumberOfCores", "8"),
|
||||
("MaxClockSpeed", "3600"),
|
||||
("BatteryStatus", "2"),
|
||||
("Win32_Battery", "0"),
|
||||
];
|
||||
let response = responses
|
||||
.iter()
|
||||
.find_map(|&(query, response)| arguments.contains(query).then_some(response))
|
||||
.unwrap_or("Microsoft Windows [Version 10.0.26100]");
|
||||
println!("{response}");
|
||||
true
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
extern "system" {
|
||||
fn GetConsoleWindow() -> *mut c_void;
|
||||
}
|
||||
|
||||
#[link(name = "user32")]
|
||||
extern "system" {
|
||||
fn IsWindowVisible(window: *mut c_void) -> i32;
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// A console connection can exist without a terminal window, including in ConPTY.
|
||||
// SAFETY: The opaque window handle comes from Windows and is only queried, never changed.
|
||||
let visible = unsafe {
|
||||
let window = GetConsoleWindow();
|
||||
!window.is_null() && IsWindowVisible(window) != 0
|
||||
};
|
||||
if hardware_probe(visible) {
|
||||
return;
|
||||
}
|
||||
println!("console_window_visible={visible}");
|
||||
println!("stdout is captured");
|
||||
eprintln!("stderr is captured");
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
println!("stdin={}", input.trim());
|
||||
if std::env::args().any(|argument| argument == "--fail") {
|
||||
std::process::exit(7);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use horizon_launcher::process;
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::OnceLock,
|
||||
};
|
||||
|
||||
pub fn console_probe() -> &'static Path {
|
||||
static PROBE: OnceLock<PathBuf> = OnceLock::new();
|
||||
PROBE.get_or_init(|| {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("horizon-console-probe-{}", std::process::id()));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let executable = root.join("console-probe.exe");
|
||||
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/console_probe.rs");
|
||||
let output = process::command("rustc")
|
||||
.arg(source)
|
||||
.arg("-o")
|
||||
.arg(&executable)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
executable
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user