250 lines
8.3 KiB
Rust
250 lines
8.3 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! Bounded, read-only cgminer-style status for a local management client.
|
|
|
|
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::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);
|
|
|
|
#[derive(Debug)]
|
|
pub struct MiningStatus {
|
|
started: Instant,
|
|
running: AtomicBool,
|
|
accepted: AtomicU64,
|
|
rejected: AtomicU64,
|
|
}
|
|
|
|
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),
|
|
}
|
|
}
|
|
|
|
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"
|
|
}]}),
|
|
),
|
|
_ => ("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 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"),
|
|
_ => Some("unknown"),
|
|
}
|
|
} else {
|
|
match request {
|
|
"summary" => Some("summary"),
|
|
"version" => Some("version"),
|
|
_ => 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();
|
|
}
|
|
}
|