device page, fmt;

This commit is contained in:
lda
2026-04-12 21:47:23 +07:00 Unverified
parent bb813170d1
commit b576ba9a01
19 changed files with 356 additions and 162 deletions
+18 -4
View File
@@ -40,26 +40,40 @@ async fn dispatch_leases(req: LeasesRequest) -> Result<CommandResult> {
include_state: req.include_state,
})
.await?;
debug!(rows = leases.len(), include_state = req.include_state, "dispatched leases command");
debug!(
rows = leases.len(),
include_state = req.include_state,
"dispatched leases command"
);
Ok(CommandResult::Leases { rows: leases })
}
async fn dispatch_devs(req: DevsRequest) -> Result<CommandResult> {
let mut devs = if let Some(name) = &req.dev {
wakey::get_interface_summary(name).await?.into_iter().collect()
wakey::get_interface_summary(name)
.await?
.into_iter()
.collect()
} else {
wakey::get_interface_summaries().await?
};
if req.up_only {
devs.retain(|dev| dev.operstate == "up");
}
debug!(rows = devs.len(), up_only = req.up_only, "dispatched devs command");
debug!(
rows = devs.len(),
up_only = req.up_only,
"dispatched devs command"
);
Ok(CommandResult::Devs { rows: devs })
}
async fn dispatch_inventory(req: InventoryRequest) -> Result<CommandResult> {
let inventory = wakey::inventory(req.into_device_query()).await?;
debug!(rows = inventory.devices.len(), "dispatched inventory command");
debug!(
rows = inventory.devices.len(),
"dispatched inventory command"
);
Ok(CommandResult::Inventory(inventory))
}
+13 -3
View File
@@ -18,7 +18,11 @@ struct EnrollResponse {
server_url: Option<String>,
}
pub async fn enroll(server_url: &str, enroll_token: &str, config_path: &Path) -> Result<AgentConfig> {
pub async fn enroll(
server_url: &str,
enroll_token: &str,
config_path: &Path,
) -> Result<AgentConfig> {
let server_url = normalize_server_url(server_url);
let endpoint = format!("{server_url}/api/v1/agents/enroll");
info!(endpoint = %endpoint, config_path = %config_path.display(), "starting agent enrollment");
@@ -68,7 +72,10 @@ mod tests {
use std::net::{SocketAddr, TcpListener};
use std::thread;
fn spawn_enroll_server(response_body: &'static str, status: &'static str) -> (String, thread::JoinHandle<()>) {
fn spawn_enroll_server(
response_body: &'static str,
status: &'static str,
) -> (String, thread::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener");
let addr: SocketAddr = listener.local_addr().expect("local addr");
let handle = thread::spawn(move || {
@@ -103,7 +110,10 @@ mod tests {
#[test]
fn normalize_server_url_trims_slash() {
assert_eq!(normalize_server_url("https://example.com/"), "https://example.com");
assert_eq!(
normalize_server_url("https://example.com/"),
"https://example.com"
);
}
#[tokio::test]
+7 -3
View File
@@ -3,8 +3,8 @@ mod config;
mod dispatch;
mod enroll;
mod protocol;
mod session;
mod serve;
mod session;
mod tracing;
use anyhow::Result;
@@ -29,7 +29,9 @@ async fn main() -> Result<()> {
if args.reload_running {
match serve::reload_daemon(&args.pid_file) {
Ok(()) => println!("reload=signaled pid_file={}", args.pid_file.display()),
Err(err) => ::tracing::warn!(error = %err, pid_file = %args.pid_file.display(), "enroll completed but daemon reload failed"),
Err(err) => {
::tracing::warn!(error = %err, pid_file = %args.pid_file.display(), "enroll completed but daemon reload failed")
}
}
}
}
@@ -58,7 +60,9 @@ fn init_config(args: InitConfigArgs) -> Result<()> {
server_url: args
.server_url
.unwrap_or_else(|| "https://control-plane.example.com".to_string()),
agent_id: args.agent_id.unwrap_or_else(|| "REPLACE_ME_AGENT_ID".to_string()),
agent_id: args
.agent_id
.unwrap_or_else(|| "REPLACE_ME_AGENT_ID".to_string()),
agent_token: args
.agent_token
.unwrap_or_else(|| "REPLACE_ME_AGENT_TOKEN".to_string()),
+4 -4
View File
@@ -2,11 +2,11 @@ use macaddr::MacAddr;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::net::IpAddr;
use wakey_core::{
DeviceFilters, DeviceInventory, DeviceQuery, DhcpLeaseWithState, InterfaceSummary, NeighborEntry,
Status, WakeResult,
};
use wakey_core::parse::mac;
use wakey_core::{
DeviceFilters, DeviceInventory, DeviceQuery, DhcpLeaseWithState, InterfaceSummary,
NeighborEntry, Status, WakeResult,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RequestId(String);
+24 -11
View File
@@ -67,9 +67,12 @@ async fn run_once(config: &AgentConfig) -> Result<()> {
}
let (mut sink, mut source) = stream.split();
send_json(&mut sink, &ClientMessage::Hello {
agent_id: config.agent_id.clone(),
})
send_json(
&mut sink,
&ClientMessage::Hello {
agent_id: config.agent_id.clone(),
},
)
.await?;
send_json(
&mut sink,
@@ -223,7 +226,8 @@ where
S: SinkExt<Message> + Unpin,
<S as futures_util::Sink<Message>>::Error: std::error::Error + Send + Sync + 'static,
{
let payload = serde_json::to_string(message).context("failed to serialize websocket message")?;
let payload =
serde_json::to_string(message).context("failed to serialize websocket message")?;
debug!(message_type = %client_message_kind(message), "sending websocket message");
sink.send(Message::Text(payload))
.await
@@ -318,7 +322,10 @@ mod tests {
impl Sink<Message> for RecordingSink {
type Error = io::Error;
fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
fn poll_ready(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
@@ -331,11 +338,17 @@ mod tests {
Ok(())
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
fn poll_flush(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
fn poll_close(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
}
@@ -369,8 +382,8 @@ mod tests {
"wake",
CommandResult::Wake(wakey_core::WakeResult { result: vec![] }),
)
.await
.expect("send should succeed");
.await
.expect("send should succeed");
assert_eq!(sink.sent.len(), 1);
let Some(Message::Text(payload)) = sink.sent.pop_front() else {
@@ -391,8 +404,8 @@ mod tests {
"devs",
CommandResult::Devs { rows: vec![] },
)
.await
.expect("fallback error frame should be sent");
.await
.expect("fallback error frame should be sent");
assert_eq!(sink.sent.len(), 1);
let Some(Message::Text(payload)) = sink.sent.pop_front() else {