forked from navos/sheepd
60 lines
1.6 KiB
Rust
60 lines
1.6 KiB
Rust
use std::{path::PathBuf, time::Duration};
|
|
|
|
use rumqttc::{AsyncClient, QoS};
|
|
use sage::Identity;
|
|
use serde_json::json;
|
|
|
|
use crate::{api, sheepd_core::config::AgentConfig};
|
|
|
|
use super::mqtt::send_back;
|
|
|
|
pub async fn report_online(client: AsyncClient) {
|
|
loop {
|
|
send_back(&client, "online", json!(crate::api::Result::Ok())).await;
|
|
tokio::time::sleep(Duration::from_secs(60)).await;
|
|
}
|
|
}
|
|
|
|
pub async fn start_daemon() {
|
|
log::info!("Starting sheepd");
|
|
|
|
let conf = AgentConfig::try_load();
|
|
if conf.is_none() {
|
|
log::error!("No config file at /etc/sheepd/config.toml");
|
|
std::process::exit(1);
|
|
}
|
|
|
|
let i = if let Some(i) = Identity::try_load(&PathBuf::from("/etc/sheepd")) {
|
|
i
|
|
} else {
|
|
let i = Identity::new();
|
|
i.save(&PathBuf::from("/etc/sheepd"));
|
|
i
|
|
};
|
|
let _ = crate::IDENTITY.set(i);
|
|
|
|
let conf = conf.unwrap();
|
|
crate::AGENT.set(conf).unwrap();
|
|
let machine_id = std::fs::read_to_string("/etc/machine-id").unwrap();
|
|
let machine_id = machine_id.trim();
|
|
|
|
log::info!("Connecting to MQTT as {machine_id}");
|
|
|
|
let (client, eventloop) = api::mqtt_connect(machine_id, &crate::AGENT.get().unwrap().mqtt);
|
|
|
|
crate::MQTT.set(client.clone()).unwrap();
|
|
|
|
log::info!("Connection done");
|
|
|
|
tokio::task::spawn(report_online(client.clone()));
|
|
|
|
log::info!("Listen on {}", format!("{machine_id}/cmd"));
|
|
crate::MQTT
|
|
.get()
|
|
.unwrap()
|
|
.subscribe(format!("{machine_id}/cmd"), QoS::AtMostOnce)
|
|
.await
|
|
.unwrap();
|
|
|
|
api::run_event_loop(eventloop, crate::sheepd_core::mqtt::handle_mqtt).await;
|
|
}
|