// SPDX-License-Identifier: MIT //! Process wiring: start the API and UI servers and publish the hardware snapshot. //! //! The binary and the tests use the same function, so the wiring that CI exercises is the wiring //! that runs on a board. Servers are bound before they are spawned, which lets a caller discover //! ephemeral ports instead of guessing them. use crate::bus::Bus; use crate::detect::{ run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget, SensorTopology, }; use crate::fanmap::{FanMap, MapThresholds, SweepConfig}; use crate::fanmap_store::ensure_map; use crate::fault::FaultPolicy; use crate::hal_wire::{HalClient, HalError}; use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus}; use crate::profiles::{ProfileDb, ProfileError}; use crate::runtime::MinerRuntime; use crate::tuning::{PidConfig, TuningTarget}; use crate::web; use std::fmt; use std::io; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::path::Path; use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; /// Bound servers and their worker threads. pub struct Servers { pub api: Option, pub web: Option, handles: Vec>, } impl Servers { /// Addresses actually bound, which matters when port 0 was requested. pub fn addresses(&self) -> (Option, Option) { (self.api, self.web) } /// Wait for the workers. Only useful in tests; the binary runs until it is killed. pub fn join(self) { for handle in self.handles { let _ = handle.join(); } } } /// Bind and start the cgminer-style API and the web UI, each when an address is given. pub fn start( status: Arc, api: Option, web_bind: Option, bus: Arc, ) -> io::Result { let api_listener = match api { Some(address) => Some(bind_local(address)?), None => None, }; let api_address = api_listener .as_ref() .map(|listener| listener.local_addr()) .transpose()?; let web_listener = match web_bind { Some(address) => Some(TcpListener::bind(address)?), None => None, }; let web_address = web_listener .as_ref() .map(|listener| listener.local_addr()) .transpose()?; let mut handles = Vec::new(); if let Some(listener) = api_listener { let snapshot = Arc::clone(&status); handles.push(std::thread::spawn(move || { if let Err(error) = serve(listener, snapshot) { eprintln!("management API stopped: {error}"); } })); } if let Some(listener) = web_listener { let ctx = web::WebContext::new(Arc::clone(&bus)); handles.push(std::thread::spawn(move || { if let Err(error) = web::serve_listener(listener, ctx) { eprintln!("web UI stopped: {error}"); } })); } Ok(Servers { api: api_address, web: web_address, handles, }) } /// Build the API snapshot from the live runtime. pub fn snapshot(runtime: &MinerRuntime, target: &str) -> HardwareSnapshot { let plan = runtime.plan(); HardwareSnapshot { plan: plan.clone(), active_chains: runtime.active_chains(), stopped: runtime.stop_reason().map(|reason| match reason { crate::fault::StopReason::Temperature => "temperature", crate::fault::StopReason::NoChainsLeft => "no chains left", }), frequency_mhz: runtime.operating_point().frequency_mhz, target: target.to_owned(), } } /// Everything a boot needs besides the backend. #[derive(Clone, Debug, PartialEq)] pub struct BootConfig { pub profile_db_json: String, pub chain_ports: Vec, pub sensor: SensorTopology, pub budget: ProbeBudget, pub fan_zones: Vec, pub target: TuningTarget, pub pid: PidConfig, pub ceiling_mc: i32, pub fault_policy: FaultPolicy, } /// Why boot did not reach a running runtime. #[derive(Clone, Debug, Eq, PartialEq)] pub enum BootError { Profile(ProfileError), Detection(DetectionFailure), /// The board backend could not be reached or refused an operation. Backend(E), } impl fmt::Display for BootError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Profile(error) => write!(f, "profile database rejected: {error:?}"), Self::Detection(error) => write!(f, "hardware detection refused: {error:?}"), Self::Backend(error) => write!(f, "hardware backend failed: {error:?}"), } } } impl std::error::Error for BootError {} /// Operator target in the form the API and UI report. pub fn target_label(target: &TuningTarget) -> String { match *target { TuningTarget::PowerW(watts) => format!("power:{watts:.0}"), TuningTarget::HashrateThs(rate) => format!("hashrate:{rate:.0}"), TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"), TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"), } } /// Detect, decide, and publish: the sequence a family image runs at start-up. pub fn boot( backend: &mut B, config: &BootConfig, status: &MiningStatus, ) -> Result> { let db = ProfileDb::from_json(&config.profile_db_json).map_err(BootError::Profile)?; let request = DetectionRequest { chain_ports: &config.chain_ports, budget: config.budget, sensor: config.sensor, fan_zones: config.fan_zones.clone(), }; let plan = run_detection(backend, &db, &request).map_err(BootError::Detection)?; let runtime = MinerRuntime::new( plan, config.fault_policy, config.target, config.pid, config.ceiling_mc, ); status.set_hardware(snapshot(&runtime, &target_label(&config.target))); Ok(runtime) } /// A boot over the real local HAL contract, including the one-time fan sweep. pub struct HalBoot<'a> { pub config: &'a BootConfig, pub sweep: SweepConfig, pub thresholds: MapThresholds, pub map_path: &'a Path, } /// Connect the board backend, detect, map the fans once, and publish. /// /// This is the path an image takes on real hardware; the fakes in the tests speak the same HAL /// protocol, so the wiring is exercised rather than assumed. pub fn boot_from_hal( socket: &Path, settings: &HalBoot<'_>, status: &MiningStatus, ) -> Result<(MinerRuntime, FanMap), BootError> { let mut client = HalClient::connect(socket).map_err(BootError::Backend)?; let zone_count = settings.sweep.zones; let map = if zone_count == 0 { FanMap::default() } else { ensure_map( &mut client, &settings.sweep, settings.thresholds, settings.map_path, |millis| std::thread::sleep(std::time::Duration::from_millis(u64::from(millis))), ) .map_err(|error| match error { crate::fanmap_store::StoreError::Sweep(crate::fanmap::SweepError::Backend(error)) => { BootError::Backend(error) } crate::fanmap_store::StoreError::Sweep(_) => { BootError::Backend(HalError::Protocol("fan sweep configuration rejected")) } crate::fanmap_store::StoreError::Io(message) => { BootError::Backend(HalError::Protocol(message)) } })? }; let config = BootConfig { fan_zones: map.assignments.clone(), ..settings.config.clone() }; let runtime = boot(&mut client, &config, status)?; Ok((runtime, map)) } /// Read one HTTP response body from a bound server, for health checks and tests. pub fn http_get(address: SocketAddr, path: &str) -> io::Result { use std::io::{Read, Write}; let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(2))?; stream.set_read_timeout(Some(Duration::from_secs(2)))?; stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())?; let mut reply = String::new(); stream.read_to_string(&mut reply)?; Ok(reply) } #[cfg(test)] mod tests { use super::*; use crate::detect::{ ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint, }; use crate::detect::{ProbeOutcome, PsuCapability}; use crate::fanmap::{MapThresholds, SweepConfig}; use crate::fault::FaultPolicy; use crate::tuning::{PidConfig, TuningTarget}; use std::io::{Read, Write}; fn runtime() -> MinerRuntime { MinerRuntime::new( HardwarePlan { profile: "s19jpro-bm1362-pic".into(), chip: ChipModel::Bm1362, chains: vec![ChainReport { index: 0, chip: ChipModel::Bm1362, chips_found: 126, eeprom: EepromState::Absent, response_per_mille: Some(950), }], envelope: Envelope { v_min_mv: 1100, v_max_mv: 1500, f_min_mhz: 300, f_max_mhz: 700, }, operating_point: OperatingPoint { voltage_mv: 1200, frequency_mhz: 300, confirmed: false, }, psu: "APW12".into(), fan_zones: vec![FanZone { fan: 0, zones: vec![0], }], }, FaultPolicy::default(), TuningTarget::PowerW(2_400.0), PidConfig::default(), 95_000, ) } #[test] fn both_servers_serve_the_published_snapshot() { let status = Arc::new(MiningStatus::new()); status.set_hardware(snapshot(&runtime(), "power:2400")); let bus = crate::bus::Bus::new(); let control = Arc::new(crate::control::Control::default()); crate::service::register(&bus, Arc::clone(&status), Arc::clone(&control)); crate::service::publish(&bus, &status, &control); let servers = start( Arc::clone(&status), Some("127.0.0.1:0".parse().unwrap()), Some("127.0.0.1:0".parse().unwrap()), bus, ) .expect("start"); let (api, web) = servers.addresses(); let api = api.expect("api address"); let web = web.expect("web address"); let page = http_get(web, "/api/hardware").expect("web"); assert!(page.contains("s19jpro-bm1362-pic")); assert!(page.contains("power:2400")); let mut client = TcpStream::connect_timeout(&api, Duration::from_secs(2)).expect("api connect"); client .set_read_timeout(Some(Duration::from_secs(3))) .expect("timeout"); client.write_all(b"summary").expect("api write"); let mut summary = String::new(); client.read_to_string(&mut summary).expect("api read"); assert!(summary.contains("SUMMARY")); } #[test] fn servers_are_optional() { let status = Arc::new(MiningStatus::new()); let servers = start(status, None, None, crate::bus::Bus::new()).expect("start"); assert_eq!(servers.addresses(), (None, None)); } #[test] fn the_snapshot_reports_runtime_state_not_boot_defaults() { let mut runtime = runtime(); runtime.tick(&crate::runtime::Tick { power_w: Some(1_000.0), hashrate_ths: None, hottest_mc: Some(60_000), ambient_mc: None, dt_s: 1.0, }); let snapshot = snapshot(&runtime, "power:2400"); assert_eq!(snapshot.target, "power:2400"); assert_eq!(snapshot.active_chains, vec![0]); assert!(snapshot.frequency_mhz > 300); assert!(snapshot.stopped.is_none()); } struct BootBackend { outcome: ProbeOutcome, psu: Option, } impl DetectionBackend for BootBackend { type Error = (); fn probe(&mut self, _chain: u8, _attempt: u8) -> Result { Ok(self.outcome) } fn eeprom(&mut self, _chain: u8) -> Result { Ok(EepromState::Absent) } fn identify_psu(&mut self) -> Result, ()> { Ok(self.psu.clone()) } } const DB: &str = r#"{"schema":1,"profiles":[{"name":"s19jpro-bm1362-pic", "chip":"bm1362","sensor":"pic","chains":3, "envelope":{"v_min_mv":1100,"v_max_mv":1500,"f_min_mhz":300,"f_max_mhz":700}}]}"#; fn boot_config() -> BootConfig { BootConfig { profile_db_json: DB.into(), chain_ports: vec![0, 1, 2], sensor: SensorTopology::Pic, budget: ProbeBudget::default(), fan_zones: Vec::new(), target: TuningTarget::PowerW(2_400.0), pid: PidConfig::default(), ceiling_mc: 95_000, fault_policy: FaultPolicy::default(), } } fn psu() -> PsuCapability { PsuCapability { name: "APW12".into(), envelope: Envelope { v_min_mv: 1200, v_max_mv: 1600, f_min_mhz: 0, f_max_mhz: 1_000, }, max_dc_watts: 3_600, } } #[test] fn boot_detects_and_publishes() { let mut backend = BootBackend { outcome: ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, psu: Some(psu()), }; let status = MiningStatus::new(); let runtime = boot(&mut backend, &boot_config(), &status).expect("boot"); assert_eq!(runtime.active_chains(), vec![0, 1, 2]); let document = status.hardware_document(); assert_eq!(document["available"], true); assert_eq!(document["target"], "power:2400"); assert_eq!(document["psu"], "APW12"); } #[test] fn boot_refuses_an_unknown_chip() { let mut backend = BootBackend { outcome: ProbeOutcome::Silent, psu: Some(psu()), }; let status = MiningStatus::new(); assert!(matches!( boot(&mut backend, &boot_config(), &status), Err(BootError::Detection(DetectionFailure::Refused(_))) )); assert_eq!(status.hardware_document()["available"], false); } #[test] fn boot_refuses_a_bad_profile_database() { let mut backend = BootBackend { outcome: ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, psu: Some(psu()), }; let mut config = boot_config(); config.profile_db_json = "{\"schema\": 9}".into(); assert!(matches!( boot(&mut backend, &config, &MiningStatus::new()), Err(BootError::Profile(_)) )); } #[test] fn boot_refuses_a_missing_psu() { let mut backend = BootBackend { outcome: ProbeOutcome::Identified { chip: ChipModel::Bm1362, chips: 126, }, psu: None, }; assert!(matches!( boot(&mut backend, &boot_config(), &MiningStatus::new()), Err(BootError::Detection(DetectionFailure::Refused(_))) )); } #[test] fn target_labels_are_stable() { assert_eq!(target_label(&TuningTarget::PowerW(3_000.0)), "power:3000"); assert_eq!( target_label(&TuningTarget::HashrateThs(200.0)), "hashrate:200" ); assert_eq!( target_label(&TuningTarget::AmbientC { margin_mc: 20_000 }), "ambient:20000" ); assert_eq!( target_label(&TuningTarget::MaxFan { max_pwm: 100 }), "fan:100" ); } fn hal_server(socket: std::path::PathBuf) -> std::thread::JoinHandle<()> { use std::io::{Read, Write}; use std::os::unix::net::UnixListener; let listener = UnixListener::bind(&socket).expect("bind hal"); std::thread::spawn(move || { let (mut stream, _) = listener.accept().expect("accept"); loop { let mut header = [0_u8; 16]; if stream.read_exact(&mut header).is_err() { return; } let opcode = header[5]; let sequence = header[8..12].to_vec(); let length = u32::from_le_bytes([header[12], header[13], header[14], header[15]]) as usize; let mut payload = vec![0_u8; length]; if length > 0 && stream.read_exact(&mut payload).is_err() { return; } let body: Vec = match opcode { // CAPABILITIES: chain probe, EEPROM, PSU identity. 7 => { let mut body = vec![0_u8]; body.extend_from_slice(&7_u32.to_le_bytes()); body } // PROBE_CHAIN: identified, bm1362, 126 chips. 8 => vec![0, 0, 1, 126, 0], // READ_EEPROM: absent. 9 => vec![0, 1], // IDENTIFY_PSU: APW12 with its envelope. 10 => { let name = b"APW12"; let mut body = vec![0_u8, name.len() as u8]; body.extend_from_slice(name); for word in [1200_u16, 1600, 0, 1000, 3600] { body.extend_from_slice(&word.to_le_bytes()); } body } _ => vec![1], }; let mut out = [0_u8; 16]; out[..4].copy_from_slice(b"ALKH"); out[4] = 1; out[5] = opcode; out[6..8].copy_from_slice(&1_u16.to_le_bytes()); out[8..12].copy_from_slice(&sequence); out[12..16].copy_from_slice(&(body.len() as u32).to_le_bytes()); if stream.write_all(&out).is_err() || stream.write_all(&body).is_err() { return; } } }) } #[test] fn boot_over_the_hal_socket_detects_and_publishes() { let base = std::env::temp_dir().join(format!("alkane-hal-{}", std::process::id())); let socket = base.with_extension("sock"); let map_path = base.with_extension("map.json"); let _ = std::fs::remove_file(&socket); let server = hal_server(socket.clone()); let status = MiningStatus::new(); let config = boot_config(); let settings = HalBoot { config: &config, sweep: SweepConfig { fans: 0, zones: 0, low_pwm: 40, high_pwm: 100, repeats: 1, settle_ms: 0, }, thresholds: MapThresholds::default(), map_path: &map_path, }; let (runtime, map) = boot_from_hal(&socket, &settings, &status).expect("boot over hal"); assert_eq!(runtime.active_chains(), vec![0, 1, 2]); assert!(map.assignments.is_empty()); let document = status.hardware_document(); assert_eq!(document["available"], true); assert_eq!(document["psu"], "APW12"); assert_eq!(document["chip"], "bm1362"); let _ = std::fs::remove_file(&socket); let _ = server.join(); } #[test] fn boot_over_a_missing_socket_is_a_backend_error() { let socket = std::env::temp_dir().join(format!("alkane-missing-{}.sock", std::process::id())); let status = MiningStatus::new(); let config = boot_config(); let settings = HalBoot { config: &config, sweep: SweepConfig { fans: 0, zones: 0, low_pwm: 40, high_pwm: 100, repeats: 1, settle_ms: 0, }, thresholds: MapThresholds::default(), map_path: &socket, }; assert!(matches!( boot_from_hal(&socket, &settings, &status), Err(BootError::Backend(_)) )); } }