dotfiles/agent/src/main.rs

57 lines
1.7 KiB
Rust
Raw Normal View History

2024-01-25 15:16:27 +00:00
use std::time::Duration;
2024-01-24 23:18:30 +00:00
use tracing::Level;
2024-01-25 15:16:27 +00:00
mod health;
2024-01-26 16:22:09 +00:00
mod messaging;
2024-01-25 15:16:27 +00:00
2024-01-24 23:18:30 +00:00
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let subscriber = tracing_subscriber::fmt()
.with_max_level(Level::TRACE)
.finish();
tracing::subscriber::set_global_default(subscriber)
.expect("to set a tracing global subscriber");
2024-01-26 16:22:09 +00:00
run().await.map_err(|err| {
tracing::error!(cause = %err, "could not start agent");
err
})
}
2024-01-25 15:16:27 +00:00
2024-01-26 16:22:09 +00:00
async fn run() -> anyhow::Result<()> {
let agent = messaging::Agent::connect("demo_agent").await?;
tracing::info!("initialized messaging system");
init_health_subsystem(agent.clone());
tracing::info!("initialized health system");
tracing::info!("agent is ready");
2024-01-25 15:16:27 +00:00
tokio::signal::ctrl_c().await?;
2024-01-24 23:18:30 +00:00
Ok(())
}
2024-01-26 16:22:09 +00:00
fn init_health_subsystem(agent: messaging::Agent) {
let mut system = health::System::new();
2024-01-25 15:16:27 +00:00
let health_monitor = health::HealthMonitor::new();
let health_monitor_clone = health_monitor.clone();
2024-01-26 16:22:09 +00:00
// Forever refresh system resources and monitor changes
2024-01-25 15:16:27 +00:00
std::thread::spawn(move || loop {
const REFRESH_INTERVAL: Duration = Duration::from_secs(1);
2024-01-26 16:22:09 +00:00
system.refresh_resources();
2024-01-25 15:16:27 +00:00
health_monitor.check_system(&system);
std::thread::sleep(REFRESH_INTERVAL);
});
tokio::spawn(async move {
let mut recv = health_monitor_clone.monitor();
while let Ok(()) = recv.changed().await {
2024-01-26 16:22:09 +00:00
tracing::info!(health = ?&*recv.borrow(), "health watermark");
let payload = serde_json::to_string(&*recv.borrow()).expect("serializable health");
let message = messaging::OutgoingMessage::Health(payload);
agent.publish(message).await;
2024-01-25 15:16:27 +00:00
}
});
2024-01-24 23:18:30 +00:00
}