The UI follows the Warden/FLARE console shape rather than inventing one: a fixed sidebar of groups and items, hash-routed pages, and dashboards that are a JSON document an operator edits in place, with a default template per deck and server-side caps on what a save may contain. Sections: Dashboard and Mining/Overview are editable dashboards (drag to reorder, add a block, save, reset). Mining also serves Hashboards, Power Supply and Fans from the hardware document. Settings serves System, Drivers, Security, Services, Monitor, Logs, Files and Terminal. Files and Terminal are gated on a token at /var/lib/alkane/ui-token so a shared network cannot use them. Served on port 80 of the miner's own address (8080 if 80 cannot be bound), and started from the runlevel so the page is up without an operator. The JSON API remains the interface of record: every value shown is also at /api/, and nothing is reachable only through the page. Verified: 165 tests, clippy clean, all 13 pages answering, and on the bench S21 Pro the UI answers on port 80 after an unattended reboot.
450 lines
16 KiB
Rust
450 lines
16 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
use alkane_os::app;
|
|
use alkane_os::detect::{
|
|
ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome,
|
|
PsuCapability, SensorTopology,
|
|
};
|
|
use alkane_os::hal_wire::HalClient;
|
|
use alkane_os::management::MiningStatus;
|
|
use alkane_os::miner::{Bm1366Miner, ChipModel};
|
|
use alkane_os::runtime::{Tick, TickOutcome};
|
|
use alkane_os::stratum_client::{PoolConnection, PoolEvent};
|
|
use alkane_os::target_matrix;
|
|
use alkane_os::tuning::{PidConfig, TuningTarget};
|
|
use alkane_os::HardwareBackend;
|
|
use std::error::Error;
|
|
use std::io;
|
|
use std::net::SocketAddr;
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
fn sim_mine(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
|
let socket = args.next().ok_or("missing HAL socket")?;
|
|
let address: SocketAddr = args.next().ok_or("missing pool address")?.parse()?;
|
|
let worker = args.next().ok_or("missing pool worker")?;
|
|
let chip = match args.next().as_deref() {
|
|
Some("BM1362") => ChipModel::Bm1362,
|
|
Some("BM1366") => ChipModel::Bm1366,
|
|
_ => return Err("select BM1362 or BM1366".into()),
|
|
};
|
|
let max_accepts: Option<u64> = args.next().map(|value| value.parse()).transpose()?;
|
|
if args.next().is_some() || worker.is_empty() || max_accepts == Some(0) {
|
|
return Err("invalid simulator mining arguments".into());
|
|
}
|
|
let password = std::env::var("ALKANE_POOL_PASSWORD")
|
|
.map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?;
|
|
let status = Arc::new(MiningStatus::new());
|
|
let api = std::env::var("ALKANE_API_LISTEN")
|
|
.ok()
|
|
.map(|bind| bind.parse())
|
|
.transpose()?;
|
|
let web = web_listen()?;
|
|
let servers = app::start(Arc::clone(&status), api, web)?;
|
|
let (api_address, web_address) = servers.addresses();
|
|
if let Some(address) = api_address {
|
|
println!("management API on {address}");
|
|
}
|
|
if let Some(address) = web_address {
|
|
println!("web UI on http://{address}/");
|
|
}
|
|
|
|
// Connect to the pool before enabling power. The SDK HAL server owns the
|
|
// power lease and cuts power if this process stalls or disconnects.
|
|
let mut pool = PoolConnection::connect(
|
|
address,
|
|
concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
|
|
&worker,
|
|
&password,
|
|
Duration::from_secs(2),
|
|
Duration::from_secs(5),
|
|
)
|
|
.map_err(|error| io::Error::other(format!("pool handshake: {error:?}")))?;
|
|
let mut backend = HalClient::connect(socket)?;
|
|
let mut miner = Bm1366Miner::new_for_chip(&mut backend, chip, 0, 0, 0, 100, 80_000)
|
|
.ok_or("invalid simulator safety configuration")?;
|
|
miner.start()?;
|
|
status.set_running(true);
|
|
let mut accepted = 0_u64;
|
|
loop {
|
|
let (event, reports) = pool
|
|
.cycle(&mut miner)
|
|
.map_err(|error| io::Error::other(format!("mining cycle: {error:?}")))?;
|
|
match event {
|
|
PoolEvent::ShareAccepted(_) => {
|
|
accepted += 1;
|
|
status.share_accepted();
|
|
if max_accepts == Some(accepted) {
|
|
miner.stop()?;
|
|
status.set_running(false);
|
|
println!("simulator shares accepted: {accepted}");
|
|
return Ok(());
|
|
}
|
|
}
|
|
PoolEvent::ShareRejected(id) => {
|
|
status.share_rejected();
|
|
eprintln!("pool rejected share request {id}");
|
|
}
|
|
_ => {}
|
|
}
|
|
if matches!(event, PoolEvent::Idle) && reports.is_empty() {
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A backend that answers without hardware, so the boot path can be exercised on any machine.
|
|
struct SelfCheckBackend;
|
|
|
|
impl DetectionBackend for SelfCheckBackend {
|
|
type Error = ();
|
|
|
|
fn probe(&mut self, _chain: u8, _attempt: u8) -> Result<ProbeOutcome, ()> {
|
|
Ok(ProbeOutcome::Identified {
|
|
chip: DetectedChip::Bm1362,
|
|
chips: 126,
|
|
})
|
|
}
|
|
|
|
fn eeprom(&mut self, _chain: u8) -> Result<EepromState, ()> {
|
|
Ok(EepromState::Absent)
|
|
}
|
|
|
|
fn identify_psu(&mut self) -> Result<Option<PsuCapability>, ()> {
|
|
Ok(Some(PsuCapability {
|
|
name: "APW12".into(),
|
|
envelope: Envelope {
|
|
v_min_mv: 1200,
|
|
v_max_mv: 1600,
|
|
f_min_mhz: 0,
|
|
f_max_mhz: 1000,
|
|
},
|
|
max_dc_watts: 3600,
|
|
}))
|
|
}
|
|
}
|
|
|
|
/// Run detection, the runtime loop and the API document against the self-check backend.
|
|
///
|
|
/// This is the smoke test an image can run on a bench machine before any hashboard is attached:
|
|
/// it proves the profile database parses, detection produces a plan, the tuner moves within the
|
|
/// envelope and the published document is well formed.
|
|
fn self_check() -> Result<(), Box<dyn Error>> {
|
|
let status = MiningStatus::new();
|
|
let config = app::BootConfig {
|
|
profile_db_json: include_str!("../profiles.example.json").to_owned(),
|
|
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: Default::default(),
|
|
};
|
|
let mut backend = SelfCheckBackend;
|
|
let mut runtime = app::boot(&mut backend, &config, &status)?;
|
|
let start = runtime.operating_point().frequency_mhz;
|
|
for _ in 0..20 {
|
|
let power = 4.0 * f32::from(runtime.operating_point().frequency_mhz);
|
|
runtime.tick(&Tick {
|
|
power_w: Some(power),
|
|
hashrate_ths: None,
|
|
hottest_mc: Some(70_000),
|
|
ambient_mc: None,
|
|
dt_s: 1.0,
|
|
});
|
|
}
|
|
let end = runtime.operating_point().frequency_mhz;
|
|
if end <= start {
|
|
return Err("self-check: frequency did not move toward the target".into());
|
|
}
|
|
if runtime.active_chains().len() != 3 {
|
|
return Err("self-check: detection did not expose three chains".into());
|
|
}
|
|
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
|
|
let document = status.hardware_document();
|
|
if document["available"] != true {
|
|
return Err("self-check: hardware document is not available".into());
|
|
}
|
|
println!("{}", serde_json::to_string_pretty(&document)?);
|
|
Ok(())
|
|
}
|
|
|
|
fn parse_target(text: &str) -> Result<TuningTarget, Box<dyn Error>> {
|
|
let (kind, value) = text
|
|
.split_once(':')
|
|
.ok_or("target must look like power:2400")?;
|
|
let value: f32 = value.parse()?;
|
|
Ok(match kind {
|
|
"power" => TuningTarget::PowerW(value),
|
|
"hashrate" => TuningTarget::HashrateThs(value),
|
|
"ambient" => TuningTarget::AmbientC {
|
|
margin_mc: value as i32,
|
|
},
|
|
"fan" => TuningTarget::MaxFan {
|
|
max_pwm: value as u8,
|
|
},
|
|
_ => return Err("target must be power, hashrate, ambient or fan".into()),
|
|
})
|
|
}
|
|
|
|
/// Boot a real board through the HAL socket, then run a bounded tuning loop.
|
|
fn boot_hal(mut args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
|
|
let socket = args.next().ok_or("missing HAL socket")?;
|
|
let profiles = args.next().ok_or("missing profile database path")?;
|
|
let target = parse_target(&args.next().ok_or("missing target")?)?;
|
|
let sensor = match args.next().as_deref() {
|
|
Some("nopic") => SensorTopology::NoPic,
|
|
Some("pic") | None => SensorTopology::Pic,
|
|
Some(_) => return Err("sensor must be pic or nopic".into()),
|
|
};
|
|
let ticks: usize = args
|
|
.next()
|
|
.map(|value| value.parse())
|
|
.transpose()?
|
|
.unwrap_or(30);
|
|
let profile_db_json = std::fs::read_to_string(&profiles)?;
|
|
let status = Arc::new(MiningStatus::new());
|
|
let api = std::env::var("ALKANE_API_LISTEN")
|
|
.ok()
|
|
.map(|bind| bind.parse())
|
|
.transpose()?;
|
|
let web = web_listen()?;
|
|
let servers = app::start(Arc::clone(&status), api, web)?;
|
|
|
|
let config = app::BootConfig {
|
|
profile_db_json,
|
|
chain_ports: vec![0, 1, 2],
|
|
sensor,
|
|
budget: ProbeBudget::default(),
|
|
fan_zones: Vec::new(),
|
|
target,
|
|
pid: PidConfig::default(),
|
|
ceiling_mc: 95_000,
|
|
fault_policy: Default::default(),
|
|
};
|
|
let map_path = std::path::PathBuf::from(
|
|
std::env::var("ALKANE_FANMAP").unwrap_or_else(|_| "/var/lib/alkane/fanmap.json".into()),
|
|
);
|
|
// Fan mapping is opt-in: it perturbs the machine and takes minutes, so a plain boot skips it.
|
|
let fans: u8 = std::env::var("ALKANE_FAN_FANS")
|
|
.ok()
|
|
.and_then(|v| v.parse().ok())
|
|
.unwrap_or(0);
|
|
let zones: u8 = std::env::var("ALKANE_FAN_ZONES")
|
|
.ok()
|
|
.and_then(|v| v.parse().ok())
|
|
.unwrap_or(0);
|
|
let settings = app::HalBoot {
|
|
config: &config,
|
|
sweep: alkane_os::fanmap::SweepConfig {
|
|
fans,
|
|
zones,
|
|
low_pwm: 40,
|
|
high_pwm: 100,
|
|
repeats: 1,
|
|
settle_ms: std::env::var("ALKANE_FAN_SETTLE_MS")
|
|
.ok()
|
|
.and_then(|v| v.parse().ok())
|
|
.unwrap_or(20_000),
|
|
},
|
|
thresholds: Default::default(),
|
|
map_path: &map_path,
|
|
};
|
|
let (mut runtime, _map) =
|
|
app::boot_from_hal(std::path::Path::new(&socket), &settings, &status)?;
|
|
println!(
|
|
"detected {} with {} active chains",
|
|
runtime.plan().profile,
|
|
runtime.active_chains().len()
|
|
);
|
|
|
|
let mut client = HalClient::connect(std::path::Path::new(&socket))?;
|
|
let label = app::target_label(&config.target);
|
|
for _ in 0..ticks {
|
|
let hottest = client.read_temperature_mc(0).ok();
|
|
let power_w = client.read_power_w().ok().map(f32::from);
|
|
let outcome = runtime.tick(&Tick {
|
|
power_w,
|
|
hashrate_ths: None,
|
|
hottest_mc: hottest,
|
|
ambient_mc: None,
|
|
dt_s: 1.0,
|
|
});
|
|
if let TickOutcome::Run(command) = outcome {
|
|
for chain in runtime.active_chains() {
|
|
client.set_chain_frequency(chain, command.frequency_mhz)?;
|
|
}
|
|
if let Some(pwm) = command.fan_pwm {
|
|
client.set_fan_target(0, pwm)?;
|
|
}
|
|
}
|
|
// Publish every period: a client watching the API must see the live operating point,
|
|
// not the boot-time snapshot.
|
|
status.set_hardware(app::snapshot(&runtime, &label));
|
|
if let Some(reason) = runtime.stop_reason() {
|
|
println!("stopped: {reason:?}");
|
|
break;
|
|
}
|
|
std::thread::sleep(Duration::from_millis(50));
|
|
}
|
|
status.set_hardware(app::snapshot(&runtime, &app::target_label(&config.target)));
|
|
println!(
|
|
"{}",
|
|
serde_json::to_string_pretty(&status.hardware_document())?
|
|
);
|
|
let _ = servers;
|
|
Ok(())
|
|
}
|
|
|
|
/// Where the UI listens. The miner serves it on port 80 of its own address;
|
|
/// if that is not permitted (a non-root development run), fall back to 8080
|
|
/// rather than refusing to start.
|
|
fn web_listen() -> Result<Option<std::net::SocketAddr>, Box<dyn std::error::Error>> {
|
|
if let Ok(bind) = std::env::var("ALKANE_WEB_LISTEN") {
|
|
return Ok(Some(bind.parse()?));
|
|
}
|
|
let port = if std::net::TcpListener::bind("0.0.0.0:80").is_ok() {
|
|
80
|
|
} else {
|
|
8080
|
|
};
|
|
Ok(Some(std::net::SocketAddr::from(([0, 0, 0, 0], port))))
|
|
}
|
|
|
|
/// Serve the UI and the API without a mining backend. A board whose HAL
|
|
/// backend is not written yet still has to be reachable and observable; every
|
|
/// page says "not identified" rather than claiming hardware it cannot see.
|
|
fn serve_only() -> Result<(), Box<dyn std::error::Error>> {
|
|
let status = Arc::new(MiningStatus::new());
|
|
let api = std::env::var("ALKANE_API_LISTEN")
|
|
.ok()
|
|
.map(|bind| bind.parse())
|
|
.transpose()?;
|
|
let api = api.or(Some("0.0.0.0:4028".parse()?));
|
|
let servers = app::start(Arc::clone(&status), api, web_listen()?)?;
|
|
let (api_address, web_address) = servers.addresses();
|
|
if let Some(address) = api_address {
|
|
println!("management API on {address}");
|
|
}
|
|
if let Some(address) = web_address {
|
|
println!("web UI on http://{address}");
|
|
}
|
|
loop {
|
|
std::thread::sleep(Duration::from_secs(3600));
|
|
}
|
|
}
|
|
|
|
fn main() {
|
|
let mut args = std::env::args().skip(1);
|
|
match args.next().as_deref() {
|
|
Some("--list-targets") => {
|
|
println!("control_board,hash_chip,algorithm");
|
|
for target in target_matrix() {
|
|
println!(
|
|
"{},{},{:?}",
|
|
target.control.id, target.chip.id, target.chip.algorithm
|
|
);
|
|
}
|
|
}
|
|
Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")),
|
|
Some("--serve") => {
|
|
if let Err(error) = serve_only() {
|
|
eprintln!("serve failed: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--boot") => {
|
|
if let Err(error) = boot_hal(args) {
|
|
eprintln!("boot failed: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--sim-hal") => {
|
|
let socket = match args.next() {
|
|
Some(path) => path,
|
|
None => {
|
|
eprintln!("usage: alkane-os --sim-hal SOCKET");
|
|
std::process::exit(2);
|
|
}
|
|
};
|
|
if let Err(error) = alkane_os::hal_sim::serve(
|
|
std::path::Path::new(&socket),
|
|
alkane_os::hal_sim::SimConfig::default(),
|
|
) {
|
|
eprintln!("reference HAL stopped: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--check-profiles") => {
|
|
let path = match args.next() {
|
|
Some(path) => path,
|
|
None => {
|
|
eprintln!("usage: alkane-os --check-profiles PATH");
|
|
std::process::exit(2);
|
|
}
|
|
};
|
|
let text = match std::fs::read_to_string(&path) {
|
|
Ok(text) => text,
|
|
Err(error) => {
|
|
eprintln!("cannot read {path}: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
};
|
|
match alkane_os::profiles::ProfileDb::from_json(&text) {
|
|
Ok(db) => {
|
|
println!("{} profiles, schema 1, validated", db.len());
|
|
}
|
|
Err(error) => {
|
|
eprintln!("profile database rejected: {error:?}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
Some("--check-hal") => {
|
|
let socket = match args.next() {
|
|
Some(path) => path,
|
|
None => {
|
|
eprintln!("usage: alkane-os --check-hal SOCKET");
|
|
std::process::exit(2);
|
|
}
|
|
};
|
|
let checks = alkane_os::hal_conformance::run(std::path::Path::new(&socket));
|
|
let mut failed = 0;
|
|
for check in &checks {
|
|
println!(
|
|
"{:<28} {:<4} {}",
|
|
check.name,
|
|
if check.passed { "PASS" } else { "FAIL" },
|
|
check.detail
|
|
);
|
|
if !check.passed {
|
|
failed += 1;
|
|
}
|
|
}
|
|
if failed > 0 {
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--self-check") => {
|
|
if let Err(error) = self_check() {
|
|
eprintln!("self-check failed: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
Some("--mine-simulator") => {
|
|
if let Err(error) = sim_mine(args) {
|
|
eprintln!("simulator mining failed: {error}");
|
|
std::process::exit(1);
|
|
}
|
|
}
|
|
_ => {
|
|
eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]");
|
|
eprintln!(
|
|
"env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..."
|
|
);
|
|
std::process::exit(2);
|
|
}
|
|
}
|
|
}
|