feat: automatically discover inventory (#127)
All checks were successful
Run Check Script / check (pull_request) Successful in 1m15s

## Fully automated inventory gathering now works!

Boot up harmony_inventory_agent with `cargo run -p harmony_inventory_agent`
Launch the DiscoverInventoryAgentScore , currently available this way :

`RUST_LOG=info cargo run -p example-cli -- -f Discover -y`

And you will have automatically all hosts saved to the database. Run `cargo sqlx setup` if you have not done it yet.

Co-authored-by: Ian Letourneau <ian@noma.to>
Reviewed-on: #127
Co-authored-by: Jean-Gabriel Gill-Couture <jg@nationtech.io>
Co-committed-by: Jean-Gabriel Gill-Couture <jg@nationtech.io>
This commit is contained in:
2025-08-31 22:45:07 +00:00
committed by Ian Letourneau
parent f9906cb419
commit 701d8cfab9
19 changed files with 442 additions and 304 deletions

View File

@@ -12,6 +12,9 @@ log.workspace = true
env_logger.workspace = true
tokio.workspace = true
thiserror.workspace = true
reqwest.workspace = true
# mdns-sd = "0.14.1"
mdns-sd = { git = "https://github.com/jggc/mdns-sd.git", branch = "patch-1" }
local-ip-address = "0.6.5"
harmony_types = { path = "../harmony_types" }
harmony_macros = { path = "../harmony_macros" }

View File

@@ -0,0 +1,15 @@
use crate::hwinfo::PhysicalHost;
pub async fn get_host_inventory(host: &str, port: u16) -> Result<PhysicalHost, String> {
let url = format!("http://{host}:{port}/inventory");
let client = reqwest::Client::new();
let response = client
.get(url)
.send()
.await
.map_err(|e| format!("Failed to download file: {e}"))?;
let host = response.json().await.map_err(|e| e.to_string())?;
Ok(host)
}

View File

@@ -1,3 +1,4 @@
use harmony_types::net::MacAddress;
use log::{debug, warn};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -18,7 +19,7 @@ pub struct PhysicalHost {
pub host_uuid: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct StorageDrive {
pub name: String,
pub model: String,
@@ -32,13 +33,30 @@ pub struct StorageDrive {
pub smart_status: Option<String>,
}
impl StorageDrive {
pub fn dummy() -> Self {
Self {
name: String::new(),
model: String::new(),
serial: String::new(),
size_bytes: 0,
logical_block_size: 0,
physical_block_size: 0,
rotational: false,
wwn: None,
interface_type: String::new(),
smart_status: None,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct StorageController {
pub name: String,
pub driver: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct MemoryModule {
pub size_bytes: u64,
pub speed_mhz: Option<u32>,
@@ -48,7 +66,7 @@ pub struct MemoryModule {
pub rank: Option<u8>,
}
#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CPU {
pub model: String,
pub vendor: String,
@@ -63,10 +81,10 @@ pub struct Chipset {
pub vendor: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NetworkInterface {
pub name: String,
pub mac_address: String,
pub mac_address: MacAddress,
pub speed_mbps: Option<u32>,
pub is_up: bool,
pub mtu: u32,
@@ -76,6 +94,24 @@ pub struct NetworkInterface {
pub firmware_version: Option<String>,
}
impl NetworkInterface {
pub fn dummy() -> Self {
use harmony_macros::mac_address;
Self {
name: String::new(),
mac_address: mac_address!("00:00:00:00:00:00"),
speed_mbps: Some(0),
is_up: false,
mtu: 0,
ipv4_addresses: vec![],
ipv6_addresses: vec![],
driver: String::new(),
firmware_version: None,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ManagementInterface {
pub kind: String,
@@ -509,6 +545,7 @@ impl PhysicalHost {
let mac_address = Self::read_sysfs_string(&iface_path.join("address"))
.map_err(|e| format!("Failed to read MAC address for {}: {}", iface_name, e))?;
let mac_address = MacAddress::try_from(mac_address).map_err(|e| e.to_string())?;
let speed_mbps = if iface_path.join("speed").exists() {
match Self::read_sysfs_u32(&iface_path.join("speed")) {

View File

@@ -1,2 +1,3 @@
mod hwinfo;
pub mod client;
pub mod hwinfo;
pub mod local_presence;

View File

@@ -1,10 +1,14 @@
use log::{debug, error};
use mdns_sd::{ServiceDaemon, ServiceEvent};
use crate::local_presence::SERVICE_NAME;
pub type DiscoveryEvent = ServiceEvent;
pub fn discover_agents(timeout: Option<u64>, on_event: impl Fn(DiscoveryEvent) + Send + 'static) {
pub async fn discover_agents<F>(timeout: Option<u64>, on_event: F)
where
F: FnOnce(DiscoveryEvent) -> Result<(), String> + Send + 'static + Copy,
{
// Create a new mDNS daemon.
let mdns = ServiceDaemon::new().expect("Failed to create mDNS daemon");
@@ -12,23 +16,24 @@ pub fn discover_agents(timeout: Option<u64>, on_event: impl Fn(DiscoveryEvent) +
// The receiver will be a stream of events.
let receiver = mdns.browse(SERVICE_NAME).expect("Failed to browse");
std::thread::spawn(move || {
tokio::task::spawn_blocking(move || {
while let Ok(event) = receiver.recv() {
on_event(event.clone());
if let Err(e) = on_event(event.clone()) {
error!("Event callback failed : {e}");
}
match event {
ServiceEvent::ServiceResolved(resolved) => {
println!("Resolved a new service: {}", resolved.fullname);
debug!("Resolved a new service: {}", resolved.fullname);
}
other_event => {
println!("Received other event: {:?}", &other_event);
debug!("Received other event: {:?}", &other_event);
}
}
}
});
if let Some(timeout) = timeout {
// Gracefully shutdown the daemon.
std::thread::sleep(std::time::Duration::from_secs(timeout));
tokio::time::sleep(std::time::Duration::from_secs(timeout)).await;
mdns.shutdown().unwrap();
}
}