source-pr / source (pull_request) Successful in 13s
The live frequency and the boot-time operating point were both in the hardware document, so a client could read 563 MHz in one field and 300 MHz in another. The document and the cgminer stats now both derive the operating point from the live frequency and the envelope, which is also what makes the reported voltage correct.
446 lines
15 KiB
Rust
446 lines
15 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! Bounded, read-only cgminer-style status for a local management client.
|
|
|
|
use crate::detect::{EepromState, HardwarePlan};
|
|
use serde_json::{json, Value};
|
|
use std::io::{self, Read, Write};
|
|
use std::net::{SocketAddr, TcpListener, TcpStream};
|
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
|
use std::sync::Arc;
|
|
use std::sync::Mutex;
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|
|
|
const MAX_REQUEST_BYTES: usize = 2048;
|
|
const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
|
|
const REQUEST_DEADLINE: Duration = Duration::from_secs(2);
|
|
|
|
/// Everything the extended API exposes beyond share counters.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub struct HardwareSnapshot {
|
|
pub plan: HardwarePlan,
|
|
/// Chains the supervisor still allows work on.
|
|
pub active_chains: Vec<u8>,
|
|
/// `None` while hashing; otherwise why the machine stopped.
|
|
pub stopped: Option<&'static str>,
|
|
pub frequency_mhz: u16,
|
|
/// Operator target in the form `power:3000`, `hashrate:200`, `ambient:20000`, `fan:100`.
|
|
pub target: String,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct MiningStatus {
|
|
started: Instant,
|
|
running: AtomicBool,
|
|
accepted: AtomicU64,
|
|
rejected: AtomicU64,
|
|
hardware: Mutex<Option<HardwareSnapshot>>,
|
|
}
|
|
|
|
impl Default for MiningStatus {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
impl MiningStatus {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
started: Instant::now(),
|
|
running: AtomicBool::new(false),
|
|
accepted: AtomicU64::new(0),
|
|
rejected: AtomicU64::new(0),
|
|
hardware: Mutex::new(None),
|
|
}
|
|
}
|
|
|
|
/// Publish the current hardware view for the API.
|
|
pub fn set_hardware(&self, snapshot: HardwareSnapshot) {
|
|
if let Ok(mut slot) = self.hardware.lock() {
|
|
*slot = Some(snapshot);
|
|
}
|
|
}
|
|
|
|
/// The `hardware` document, for the on-box UI and local clients.
|
|
pub fn hardware_document(&self) -> Value {
|
|
hardware_json(self.hardware())
|
|
}
|
|
|
|
/// The `summary` document, for the on-box UI and local clients.
|
|
pub fn summary_document(&self) -> Value {
|
|
self.response("summary")
|
|
}
|
|
|
|
fn hardware(&self) -> Option<HardwareSnapshot> {
|
|
self.hardware.lock().ok().and_then(|slot| slot.clone())
|
|
}
|
|
|
|
pub fn set_running(&self, running: bool) {
|
|
self.running.store(running, Ordering::Relaxed);
|
|
}
|
|
|
|
pub fn share_accepted(&self) {
|
|
self.accepted.fetch_add(1, Ordering::Relaxed);
|
|
}
|
|
|
|
pub fn share_rejected(&self) {
|
|
self.rejected.fetch_add(1, Ordering::Relaxed);
|
|
}
|
|
|
|
fn response(&self, command: &str) -> Value {
|
|
let now = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap_or_default()
|
|
.as_secs();
|
|
let (code, description, payload) = match command {
|
|
"summary" => (
|
|
"S",
|
|
"Summary",
|
|
json!({"SUMMARY": [{
|
|
"Elapsed": self.started.elapsed().as_secs(),
|
|
"Accepted": self.accepted.load(Ordering::Relaxed),
|
|
"Rejected": self.rejected.load(Ordering::Relaxed),
|
|
"Status": if self.running.load(Ordering::Relaxed) { "Mining" } else { "Stopped" }
|
|
}]}),
|
|
),
|
|
"version" => (
|
|
"S",
|
|
"Version",
|
|
json!({"VERSION": [{
|
|
"Miner": concat!("alkane-os/", env!("CARGO_PKG_VERSION")),
|
|
"API": "1.0"
|
|
}]}),
|
|
),
|
|
"hardware" => (
|
|
"S",
|
|
"Hardware",
|
|
json!({"HARDWARE": [hardware_json(self.hardware())]}),
|
|
),
|
|
"stats" => (
|
|
"S",
|
|
"Stats",
|
|
json!({"STATS": [stats_json(self.hardware())]}),
|
|
),
|
|
_ => ("E", "Unknown command", json!({})),
|
|
};
|
|
let mut response = json!({"STATUS": [{
|
|
"STATUS": code,
|
|
"When": now,
|
|
"Code": if code == "S" { 0 } else { 14 },
|
|
"Msg": description,
|
|
"Description": "alkane-os"
|
|
}]});
|
|
response
|
|
.as_object_mut()
|
|
.unwrap()
|
|
.extend(payload.as_object().unwrap().clone());
|
|
response
|
|
}
|
|
}
|
|
|
|
fn eeprom_json(state: &EepromState) -> Value {
|
|
match state {
|
|
EepromState::Present { model } => json!({"state": "present", "model": model}),
|
|
EepromState::Absent => json!({"state": "absent"}),
|
|
EepromState::Invalid => json!({"state": "invalid"}),
|
|
}
|
|
}
|
|
|
|
fn hardware_json(snapshot: Option<HardwareSnapshot>) -> Value {
|
|
let Some(snapshot) = snapshot else {
|
|
return json!({"available": false});
|
|
};
|
|
let plan = &snapshot.plan;
|
|
json!({
|
|
"available": true,
|
|
"profile": plan.profile,
|
|
"chip": plan.chip.name(),
|
|
"psu": plan.psu,
|
|
"envelope": {
|
|
"v_min_mv": plan.envelope.v_min_mv,
|
|
"v_max_mv": plan.envelope.v_max_mv,
|
|
"f_min_mhz": plan.envelope.f_min_mhz,
|
|
"f_max_mhz": plan.envelope.f_max_mhz,
|
|
},
|
|
"operating_point": {
|
|
"voltage_mv": plan.envelope.voltage_for(snapshot.frequency_mhz),
|
|
"frequency_mhz": snapshot.frequency_mhz,
|
|
"confirmed": plan.operating_point.confirmed,
|
|
},
|
|
"chains": plan.chains.iter().map(|chain| json!({
|
|
"index": chain.index,
|
|
"chip": chain.chip.name(),
|
|
"chips_found": chain.chips_found,
|
|
"eeprom": eeprom_json(&chain.eeprom),
|
|
"response_per_mille": chain.response_per_mille,
|
|
})).collect::<Vec<_>>(),
|
|
"fan_zones": plan.fan_zones.iter().map(|zone| json!({
|
|
"fan": zone.fan,
|
|
"zones": zone.zones,
|
|
})).collect::<Vec<_>>(),
|
|
"active_chains": snapshot.active_chains,
|
|
"stopped": snapshot.stopped,
|
|
"target": snapshot.target,
|
|
"frequency_mhz": snapshot.frequency_mhz,
|
|
})
|
|
}
|
|
|
|
fn stats_json(snapshot: Option<HardwareSnapshot>) -> Value {
|
|
let Some(snapshot) = snapshot else {
|
|
return json!({"available": false});
|
|
};
|
|
json!({
|
|
"Profile": snapshot.plan.profile,
|
|
"Chip": snapshot.plan.chip.name(),
|
|
"PSU": snapshot.plan.psu,
|
|
"FrequencyMHz": snapshot.frequency_mhz,
|
|
"VoltageMV": snapshot.plan.envelope.voltage_for(snapshot.frequency_mhz),
|
|
"Target": snapshot.target,
|
|
"ActiveChains": snapshot.active_chains.len(),
|
|
"Stopped": snapshot.stopped,
|
|
})
|
|
}
|
|
|
|
fn request_command(bytes: &[u8]) -> Option<&str> {
|
|
let request = std::str::from_utf8(bytes).ok()?.trim();
|
|
if request.starts_with('{') {
|
|
let value: Value = serde_json::from_str(request).ok()?;
|
|
let command = value.get("command")?.as_str()?;
|
|
match command {
|
|
"summary" => Some("summary"),
|
|
"version" => Some("version"),
|
|
"hardware" => Some("hardware"),
|
|
"stats" => Some("stats"),
|
|
_ => Some("unknown"),
|
|
}
|
|
} else {
|
|
match request {
|
|
"summary" => Some("summary"),
|
|
"version" => Some("version"),
|
|
"hardware" => Some("hardware"),
|
|
"stats" => Some("stats"),
|
|
_ => Some("unknown"),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> {
|
|
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
|
|
let mut request = Vec::new();
|
|
let mut chunk = [0_u8; 256];
|
|
let deadline = Instant::now() + REQUEST_DEADLINE;
|
|
loop {
|
|
let remaining = deadline.saturating_duration_since(Instant::now());
|
|
if remaining.is_zero() {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::TimedOut,
|
|
"management request deadline",
|
|
));
|
|
}
|
|
stream.set_read_timeout(Some(CLIENT_TIMEOUT.min(remaining)))?;
|
|
let count = match stream.read(&mut chunk) {
|
|
Ok(count) => count,
|
|
Err(error) if error.kind() == io::ErrorKind::TimedOut && !request.is_empty() => break,
|
|
Err(error) if error.kind() == io::ErrorKind::WouldBlock && !request.is_empty() => break,
|
|
Err(error) => return Err(error),
|
|
};
|
|
if count == 0 {
|
|
break;
|
|
}
|
|
if request.len() + count > MAX_REQUEST_BYTES {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::InvalidData,
|
|
"management request too large",
|
|
));
|
|
}
|
|
request.extend_from_slice(&chunk[..count]);
|
|
if request.contains(&b'\n') || request.contains(&0) {
|
|
break;
|
|
}
|
|
if matches!(request_command(&request), Some("summary" | "version"))
|
|
|| serde_json::from_slice::<Value>(&request).is_ok()
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
let end = request
|
|
.iter()
|
|
.position(|byte| *byte == 0 || *byte == b'\n')
|
|
.unwrap_or(request.len());
|
|
let command = request_command(&request[..end]).unwrap_or("unknown");
|
|
let mut reply = serde_json::to_vec(&status.response(command)).map_err(io::Error::other)?;
|
|
reply.push(0);
|
|
stream.write_all(&reply)
|
|
}
|
|
|
|
/// Bind only to loopback. The board management plane can be reached through SSH.
|
|
pub fn bind_local(address: SocketAddr) -> io::Result<TcpListener> {
|
|
if !address.ip().is_loopback() {
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::InvalidInput,
|
|
"management API requires loopback address",
|
|
));
|
|
}
|
|
TcpListener::bind(address)
|
|
}
|
|
|
|
pub fn serve(listener: TcpListener, status: Arc<MiningStatus>) -> io::Result<()> {
|
|
for stream in listener.incoming() {
|
|
let stream = stream?;
|
|
if let Err(error) = handle(stream, &status) {
|
|
eprintln!("management request failed: {error}");
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::net::TcpStream;
|
|
|
|
#[test]
|
|
fn refuses_nonlocal_bind() {
|
|
let address = "0.0.0.0:0".parse().unwrap();
|
|
assert_eq!(
|
|
bind_local(address).unwrap_err().kind(),
|
|
io::ErrorKind::InvalidInput
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn reports_only_observed_share_counts() {
|
|
let status = MiningStatus::new();
|
|
status.set_running(true);
|
|
status.share_accepted();
|
|
status.share_rejected();
|
|
let reply = status.response("summary");
|
|
assert_eq!(reply["SUMMARY"][0]["Accepted"], 1);
|
|
assert_eq!(reply["SUMMARY"][0]["Rejected"], 1);
|
|
assert_eq!(reply["SUMMARY"][0]["Status"], "Mining");
|
|
assert!(reply["SUMMARY"][0].get("MHS av").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn local_socket_uses_nul_terminated_cgminer_envelope() {
|
|
let listener = bind_local("127.0.0.1:0".parse().unwrap()).unwrap();
|
|
let address = listener.local_addr().unwrap();
|
|
let status = Arc::new(MiningStatus::new());
|
|
let worker = std::thread::spawn(move || {
|
|
let (stream, _) = listener.accept().unwrap();
|
|
handle(stream, &status).unwrap();
|
|
});
|
|
let mut client = TcpStream::connect(address).unwrap();
|
|
client.write_all(b"{\"command\":\"summary\"}\n").unwrap();
|
|
let mut reply = Vec::new();
|
|
client.read_to_end(&mut reply).unwrap();
|
|
assert_eq!(reply.pop(), Some(0));
|
|
let parsed: Value = serde_json::from_slice(&reply).unwrap();
|
|
assert_eq!(parsed["STATUS"][0]["STATUS"], "S");
|
|
assert_eq!(parsed["SUMMARY"][0]["Status"], "Stopped");
|
|
worker.join().unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn fragmented_plain_command_is_not_answered_early() {
|
|
let listener = bind_local("127.0.0.1:0".parse().unwrap()).unwrap();
|
|
let address = listener.local_addr().unwrap();
|
|
let status = Arc::new(MiningStatus::new());
|
|
let worker = std::thread::spawn(move || {
|
|
let (stream, _) = listener.accept().unwrap();
|
|
handle(stream, &status).unwrap();
|
|
});
|
|
let mut client = TcpStream::connect(address).unwrap();
|
|
client.write_all(b"sum").unwrap();
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
client.write_all(b"mary").unwrap();
|
|
let mut reply = Vec::new();
|
|
client.read_to_end(&mut reply).unwrap();
|
|
assert_eq!(reply.pop(), Some(0));
|
|
let parsed: Value = serde_json::from_slice(&reply).unwrap();
|
|
assert_eq!(parsed["STATUS"][0]["STATUS"], "S");
|
|
assert!(parsed.get("SUMMARY").is_some());
|
|
worker.join().unwrap();
|
|
}
|
|
|
|
fn snapshot() -> HardwareSnapshot {
|
|
HardwareSnapshot {
|
|
plan: HardwarePlan {
|
|
profile: "s19jpro-bm1362-pic".into(),
|
|
chip: crate::detect::ChipModel::Bm1362,
|
|
chains: vec![crate::detect::ChainReport {
|
|
index: 0,
|
|
chip: crate::detect::ChipModel::Bm1362,
|
|
chips_found: 126,
|
|
eeprom: EepromState::Absent,
|
|
response_per_mille: Some(950),
|
|
}],
|
|
envelope: crate::detect::Envelope {
|
|
v_min_mv: 1100,
|
|
v_max_mv: 1500,
|
|
f_min_mhz: 300,
|
|
f_max_mhz: 700,
|
|
},
|
|
operating_point: crate::detect::OperatingPoint {
|
|
voltage_mv: 1200,
|
|
frequency_mhz: 500,
|
|
confirmed: false,
|
|
},
|
|
psu: "APW12".into(),
|
|
fan_zones: vec![crate::detect::FanZone {
|
|
fan: 0,
|
|
zones: vec![0, 1],
|
|
}],
|
|
},
|
|
active_chains: vec![0],
|
|
stopped: None,
|
|
frequency_mhz: 512,
|
|
target: "power:3000".into(),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn hardware_is_unavailable_until_published() {
|
|
let status = MiningStatus::new();
|
|
let reply = status.response("hardware");
|
|
assert_eq!(reply["HARDWARE"][0]["available"], false);
|
|
}
|
|
|
|
#[test]
|
|
fn hardware_command_exposes_detection_and_fault_state() {
|
|
let status = MiningStatus::new();
|
|
status.set_hardware(snapshot());
|
|
let reply = status.response("hardware");
|
|
let hardware = &reply["HARDWARE"][0];
|
|
assert_eq!(hardware["available"], true);
|
|
assert_eq!(hardware["profile"], "s19jpro-bm1362-pic");
|
|
assert_eq!(hardware["chip"], "bm1362");
|
|
assert_eq!(hardware["psu"], "APW12");
|
|
assert_eq!(hardware["chains"][0]["chips_found"], 126);
|
|
assert_eq!(hardware["chains"][0]["eeprom"]["state"], "absent");
|
|
assert_eq!(hardware["operating_point"]["confirmed"], false);
|
|
assert_eq!(hardware["active_chains"][0], 0);
|
|
assert_eq!(hardware["target"], "power:3000");
|
|
assert_eq!(hardware["fan_zones"][0]["zones"][1], 1);
|
|
}
|
|
|
|
#[test]
|
|
fn stats_command_keeps_cgminer_shape() {
|
|
let status = MiningStatus::new();
|
|
status.set_hardware(snapshot());
|
|
let reply = status.response("stats");
|
|
let stats = &reply["STATS"][0];
|
|
assert_eq!(stats["Profile"], "s19jpro-bm1362-pic");
|
|
assert_eq!(stats["FrequencyMHz"], 512);
|
|
assert_eq!(stats["VoltageMV"], 1312);
|
|
assert_eq!(stats["ActiveChains"], 1);
|
|
assert!(stats["Stopped"].is_null());
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_commands_still_refuse() {
|
|
let status = MiningStatus::new();
|
|
let reply = status.response("reboot");
|
|
assert_eq!(reply["STATUS"][0]["STATUS"], "E");
|
|
}
|
|
}
|