From 3bc7cf8ed36016ca3da9438a98f4fe8b8e6f9e61 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Thu, 15 Feb 2024 17:17:30 +0100 Subject: Closes #10 & #12. Added `thiserror` crate and changed to `IntoSocketAddr` for easier usage and error handling --- Cargo.lock | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'Cargo.lock') diff --git a/Cargo.lock b/Cargo.lock index f95052b..835335b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2353,7 +2353,7 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "webol" -version = "0.3.1" +version = "0.3.2" dependencies = [ "axum", "axum-macros", @@ -2364,6 +2364,7 @@ dependencies = [ "serde_json", "sqlx", "surge-ping", + "thiserror", "time", "tokio", "tracing", -- cgit v1.2.3 From 2f9f18b80a9e2134f674f345e48a5f21de5efadd Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Sun, 18 Feb 2024 21:16:46 +0100 Subject: Refactor stuff. Use Postgres Types --- ...f32262fd643b452aacca373ee527c978e816115de6.json | 8 +- ...f6b4f7ee6dae2130c2109fb6f1e47e0990ec395744.json | 4 +- ...b8cf06394a302d288e91f5eedde65db6630021f737.json | 4 +- Cargo.lock | 50 ++++++- Cargo.toml | 4 +- migrations/20231009123228_devices.sql | 4 +- src/db.rs | 6 +- src/error.rs | 22 +++ src/main.rs | 54 ++++---- src/routes.rs | 3 + src/routes/device.rs | 19 ++- src/routes/mod.rs | 3 - src/routes/start.rs | 78 ++++++----- src/routes/status.rs | 79 ++++++++++- src/services.rs | 1 + src/services/mod.rs | 1 - src/services/ping.rs | 154 +++++++++------------ 17 files changed, 317 insertions(+), 177 deletions(-) create mode 100644 src/routes.rs delete mode 100644 src/routes/mod.rs create mode 100644 src/services.rs delete mode 100644 src/services/mod.rs (limited to 'Cargo.lock') diff --git a/.sqlx/query-1dc5f44967ffdee882f4cef32262fd643b452aacca373ee527c978e816115de6.json b/.sqlx/query-1dc5f44967ffdee882f4cef32262fd643b452aacca373ee527c978e816115de6.json index 33d524d..dd85eaa 100644 --- a/.sqlx/query-1dc5f44967ffdee882f4cef32262fd643b452aacca373ee527c978e816115de6.json +++ b/.sqlx/query-1dc5f44967ffdee882f4cef32262fd643b452aacca373ee527c978e816115de6.json @@ -11,7 +11,7 @@ { "ordinal": 1, "name": "mac", - "type_info": "Varchar" + "type_info": "Macaddr" }, { "ordinal": 2, @@ -21,7 +21,7 @@ { "ordinal": 3, "name": "ip", - "type_info": "Varchar" + "type_info": "Inet" }, { "ordinal": 4, @@ -31,9 +31,9 @@ ], "parameters": { "Left": [ + "Macaddr", "Varchar", - "Varchar", - "Varchar", + "Inet", "Text" ] }, diff --git a/.sqlx/query-62c84231c7e9c85dc91d71f6b4f7ee6dae2130c2109fb6f1e47e0990ec395744.json b/.sqlx/query-62c84231c7e9c85dc91d71f6b4f7ee6dae2130c2109fb6f1e47e0990ec395744.json index 5ec47e3..905bb51 100644 --- a/.sqlx/query-62c84231c7e9c85dc91d71f6b4f7ee6dae2130c2109fb6f1e47e0990ec395744.json +++ b/.sqlx/query-62c84231c7e9c85dc91d71f6b4f7ee6dae2130c2109fb6f1e47e0990ec395744.json @@ -11,7 +11,7 @@ { "ordinal": 1, "name": "mac", - "type_info": "Varchar" + "type_info": "Macaddr" }, { "ordinal": 2, @@ -21,7 +21,7 @@ { "ordinal": 3, "name": "ip", - "type_info": "Varchar" + "type_info": "Inet" }, { "ordinal": 4, diff --git a/.sqlx/query-adead45e1a6b02d5eabd68b8cf06394a302d288e91f5eedde65db6630021f737.json b/.sqlx/query-adead45e1a6b02d5eabd68b8cf06394a302d288e91f5eedde65db6630021f737.json index bc4bdd3..d25b12e 100644 --- a/.sqlx/query-adead45e1a6b02d5eabd68b8cf06394a302d288e91f5eedde65db6630021f737.json +++ b/.sqlx/query-adead45e1a6b02d5eabd68b8cf06394a302d288e91f5eedde65db6630021f737.json @@ -6,9 +6,9 @@ "parameters": { "Left": [ "Varchar", + "Macaddr", "Varchar", - "Varchar", - "Varchar" + "Inet" ] }, "nullable": [] diff --git a/Cargo.lock b/Cargo.lock index 835335b..5d10375 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -71,7 +71,7 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edcdbedc2236483ab103a53415653d6b4442ea6141baf1ffa85df29635e88436" dependencies = [ - "nix", + "nix 0.27.1", "rand", ] @@ -826,6 +826,15 @@ dependencies = [ "hashbrown 0.14.3", ] +[[package]] +name = "ipnetwork" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf466541e9d546596ee94f9f69590f89473455f88372423e0008fc1a7daf100e" +dependencies = [ + "serde", +] + [[package]] name = "itertools" version = "0.12.1" @@ -912,6 +921,17 @@ version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +[[package]] +name = "mac_address" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4863ee94f19ed315bf3bc00299338d857d4b5bc856af375cc97d237382ad3856" +dependencies = [ + "nix 0.23.2", + "serde", + "winapi", +] + [[package]] name = "matchers" version = "0.1.0" @@ -943,6 +963,15 @@ version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + [[package]] name = "mime" version = "0.3.17" @@ -975,6 +1004,19 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "nix" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f3790c00a0150112de0f4cd161e3d7fc4b2d8a5542ffc35f099a2562aecb35c" +dependencies = [ + "bitflags 1.3.2", + "cc", + "cfg-if", + "libc", + "memoffset", +] + [[package]] name = "nix" version = "0.27.1" @@ -1709,7 +1751,9 @@ dependencies = [ "hashlink", "hex", "indexmap", + "ipnetwork", "log", + "mac_address", "memchr", "once_cell", "paste", @@ -1829,8 +1873,10 @@ dependencies = [ "hkdf", "hmac", "home", + "ipnetwork", "itoa", "log", + "mac_address", "md-5", "memchr", "once_cell", @@ -2360,6 +2406,8 @@ dependencies = [ "color-eyre", "config", "dashmap", + "ipnetwork", + "mac_address", "serde", "serde_json", "sqlx", diff --git a/Cargo.toml b/Cargo.toml index f4633c9..c320da1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,10 +14,12 @@ time = { version = "0.3", features = ["macros"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" config = "0.14" -sqlx = { version = "0.7", features = ["postgres", "runtime-tokio"]} +sqlx = { version = "0.7", features = ["postgres", "runtime-tokio", "ipnetwork", "mac_address"]} surge-ping = "0.8" axum-macros = "0.4" uuid = { version = "1.6", features = ["v4", "fast-rng"] } dashmap = "5.5" color-eyre = "0.6" thiserror = "1.0" +ipnetwork = "0.20.0" +mac_address = { version = "1.1.5", features = ["serde"] } diff --git a/migrations/20231009123228_devices.sql b/migrations/20231009123228_devices.sql index d36946c..6983ada 100644 --- a/migrations/20231009123228_devices.sql +++ b/migrations/20231009123228_devices.sql @@ -2,8 +2,8 @@ CREATE TABLE IF NOT EXISTS "devices" ( "id" VARCHAR(255) PRIMARY KEY NOT NULL, - "mac" VARCHAR(17) NOT NULL, + "mac" MACADDR NOT NULL, "broadcast_addr" VARCHAR(39) NOT NULL, - "ip" VARCHAR(39) NOT NULL, + "ip" INET NOT NULL, "times" BIGINT[] ) diff --git a/src/db.rs b/src/db.rs index 489a000..47e907d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -1,13 +1,13 @@ use serde::Serialize; -use sqlx::{PgPool, postgres::PgPoolOptions}; +use sqlx::{PgPool, postgres::PgPoolOptions, types::{ipnetwork::IpNetwork, mac_address::MacAddress}}; use tracing::{debug, info}; #[derive(Serialize, Debug)] pub struct Device { pub id: String, - pub mac: String, + pub mac: MacAddress, pub broadcast_addr: String, - pub ip: String, + pub ip: IpNetwork, pub times: Option> } diff --git a/src/error.rs b/src/error.rs index 63b214e..66a61f4 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,6 +2,8 @@ use axum::http::header::ToStrError; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::Json; +use ::ipnetwork::IpNetworkError; +use mac_address::MacParseError; use serde_json::json; use std::io; use tracing::error; @@ -29,6 +31,18 @@ pub enum Error { source: ToStrError, }, + #[error("string parse: {source}")] + IpParse { + #[from] + source: IpNetworkError, + }, + + #[error("mac parse: {source}")] + MacParse { + #[from] + source: MacParseError, + }, + #[error("io: {source}")] Io { #[from] @@ -57,6 +71,14 @@ impl IntoResponse for Error { error!("{source}"); (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") } + Self::MacParse { source } => { + error!("{source}"); + (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") + } + Self::IpParse { source } => { + error!("{source}"); + (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") + } }; let body = Json(json!({ "error": error_message, diff --git a/src/main.rs b/src/main.rs index 4ef129b..7d8c1da 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,42 +1,44 @@ -use std::env; -use std::sync::Arc; -use axum::{Router, routing::post}; -use axum::routing::{get, put}; -use dashmap::DashMap; -use sqlx::PgPool; -use time::util::local_offset; -use tokio::sync::broadcast::{channel, Sender}; -use tracing::{info, level_filters::LevelFilter}; -use tracing_subscriber::{EnvFilter, fmt::{self, time::LocalTime}, prelude::*}; use crate::config::Config; use crate::db::init_db_pool; use crate::routes::device; use crate::routes::start::start; use crate::routes::status::status; -use crate::services::ping::{BroadcastCommands, StatusMap}; +use crate::services::ping::StatusMap; +use axum::routing::{get, put}; +use axum::{routing::post, Router}; +use dashmap::DashMap; +use services::ping::BroadcastCommand; +use sqlx::PgPool; +use tracing_subscriber::fmt::time::UtcTime; +use std::env; +use std::sync::Arc; +use tokio::sync::broadcast::{channel, Sender}; +use tracing::{info, level_filters::LevelFilter}; +use tracing_subscriber::{ + fmt, + prelude::*, + EnvFilter, +}; mod auth; mod config; -mod routes; -mod wol; mod db; mod error; +mod routes; mod services; +mod wol; #[tokio::main] async fn main() -> color_eyre::eyre::Result<()> { - color_eyre::install()?; + - unsafe { local_offset::set_soundness(local_offset::Soundness::Unsound); } let time_format = time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"); - let loc = LocalTime::new(time_format); + let loc = UtcTime::new(time_format); tracing_subscriber::registry() - .with(fmt::layer() - .with_timer(loc) - ) + .with(fmt::layer().with_timer(loc)) .with( EnvFilter::builder() .with_default_directive(LevelFilter::INFO.into()) @@ -56,8 +58,13 @@ async fn main() -> color_eyre::eyre::Result<()> { let (tx, _) = channel(32); let ping_map: StatusMap = DashMap::new(); - - let shared_state = Arc::new(AppState { db, config: config.clone(), ping_send: tx, ping_map }); + + let shared_state = Arc::new(AppState { + db, + config: config.clone(), + ping_send: tx, + ping_map, + }); let app = Router::new() .route("/start", post(start)) @@ -69,8 +76,7 @@ async fn main() -> color_eyre::eyre::Result<()> { let addr = config.serveraddr; info!("start server on {}", addr); - let listener = tokio::net::TcpListener::bind(addr) - .await?; + let listener = tokio::net::TcpListener::bind(addr).await?; axum::serve(listener, app).await?; Ok(()) @@ -79,6 +85,6 @@ async fn main() -> color_eyre::eyre::Result<()> { pub struct AppState { db: PgPool, config: Config, - ping_send: Sender, + ping_send: Sender, ping_map: StatusMap, } diff --git a/src/routes.rs b/src/routes.rs new file mode 100644 index 0000000..d5ab0d6 --- /dev/null +++ b/src/routes.rs @@ -0,0 +1,3 @@ +pub mod start; +pub mod device; +pub mod status; \ No newline at end of file diff --git a/src/routes/device.rs b/src/routes/device.rs index 5ca574a..2f0093d 100644 --- a/src/routes/device.rs +++ b/src/routes/device.rs @@ -4,9 +4,11 @@ use crate::error::Error; use axum::extract::State; use axum::http::HeaderMap; use axum::Json; +use mac_address::MacAddress; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -use std::sync::Arc; +use sqlx::types::ipnetwork::IpNetwork; +use std::{sync::Arc, str::FromStr}; use tracing::{debug, info}; pub async fn get( @@ -14,7 +16,7 @@ pub async fn get( headers: HeaderMap, Json(payload): Json, ) -> Result, Error> { - info!("add device {}", payload.id); + info!("get device {}", payload.id); let secret = headers.get("authorization"); let authorized = matches!(auth(&state.config, secret)?, crate::auth::Response::Success); if authorized { @@ -52,18 +54,21 @@ pub async fn put( "add device {} ({}, {}, {})", payload.id, payload.mac, payload.broadcast_addr, payload.ip ); + let secret = headers.get("authorization"); let authorized = matches!(auth(&state.config, secret)?, crate::auth::Response::Success); if authorized { + let ip = IpNetwork::from_str(&payload.ip)?; + let mac = MacAddress::from_str(&payload.mac)?; sqlx::query!( r#" INSERT INTO devices (id, mac, broadcast_addr, ip) VALUES ($1, $2, $3, $4); "#, payload.id, - payload.mac, + mac, payload.broadcast_addr, - payload.ip + ip ) .execute(&state.db) .await?; @@ -99,6 +104,8 @@ pub async fn post( let secret = headers.get("authorization"); let authorized = matches!(auth(&state.config, secret)?, crate::auth::Response::Success); if authorized { + let ip = IpNetwork::from_str(&payload.ip)?; + let mac = MacAddress::from_str(&payload.mac)?; let device = sqlx::query_as!( Device, r#" @@ -106,9 +113,9 @@ pub async fn post( SET mac = $1, broadcast_addr = $2, ip = $3 WHERE id = $4 RETURNING id, mac, broadcast_addr, ip, times; "#, - payload.mac, + mac, payload.broadcast_addr, - payload.ip, + ip, payload.id ) .fetch_one(&state.db) diff --git a/src/routes/mod.rs b/src/routes/mod.rs deleted file mode 100644 index d5ab0d6..0000000 --- a/src/routes/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod start; -pub mod device; -pub mod status; \ No newline at end of file diff --git a/src/routes/start.rs b/src/routes/start.rs index ec4f98f..4888325 100644 --- a/src/routes/start.rs +++ b/src/routes/start.rs @@ -12,7 +12,6 @@ use std::sync::Arc; use tracing::{debug, info}; use uuid::Uuid; -#[axum_macros::debug_handler] pub async fn start( State(state): State>, headers: HeaderMap, @@ -41,45 +40,11 @@ pub async fn start( let _ = send_packet( bind_addr, &device.broadcast_addr, - &create_buffer(&device.mac)?, + &create_buffer(&device.mac.to_string())?, )?; let dev_id = device.id.clone(); let uuid = if payload.ping.is_some_and(|ping| ping) { - let mut uuid: Option = None; - for (key, value) in state.ping_map.clone() { - if value.ip == device.ip { - debug!("service already exists"); - uuid = Some(key); - break; - } - } - let uuid_gen = match uuid { - Some(u) => u, - None => Uuid::new_v4().to_string(), - }; - let uuid_genc = uuid_gen.clone(); - - tokio::spawn(async move { - debug!("init ping service"); - state.ping_map.insert( - uuid_gen.clone(), - PingValue { - ip: device.ip.clone(), - online: false, - }, - ); - - crate::services::ping::spawn( - state.ping_send.clone(), - &state.config, - device, - uuid_gen.clone(), - &state.ping_map, - &state.db, - ) - .await; - }); - Some(uuid_genc) + Some(setup_ping(state, device)) } else { None }; @@ -93,6 +58,45 @@ pub async fn start( } } +fn setup_ping(state: Arc, device: Device) -> String { + let mut uuid: Option = None; + for (key, value) in state.ping_map.clone() { + if value.ip == device.ip { + debug!("service already exists"); + uuid = Some(key); + break; + } + } + let uuid_gen = match uuid { + Some(u) => u, + None => Uuid::new_v4().to_string(), + }; + let uuid_ret = uuid_gen.clone(); + + debug!("init ping service"); + state.ping_map.insert( + uuid_gen.clone(), + PingValue { + ip: device.ip, + online: false, + }, + ); + + tokio::spawn(async move { + crate::services::ping::spawn( + state.ping_send.clone(), + &state.config, + device, + uuid_gen, + &state.ping_map, + &state.db, + ) + .await; + }); + + uuid_ret +} + #[derive(Deserialize)] pub struct Payload { id: String, diff --git a/src/routes/status.rs b/src/routes/status.rs index 31ef996..0e25f7d 100644 --- a/src/routes/status.rs +++ b/src/routes/status.rs @@ -1,10 +1,79 @@ -use std::sync::Arc; +use crate::services::ping::BroadcastCommand; +use crate::AppState; +use axum::extract::ws::{Message, WebSocket}; use axum::extract::{State, WebSocketUpgrade}; use axum::response::Response; -use crate::AppState; -use crate::services::ping::status_websocket; +use sqlx::PgPool; +use std::sync::Arc; +use tracing::{debug, trace}; -#[axum_macros::debug_handler] pub async fn status(State(state): State>, ws: WebSocketUpgrade) -> Response { - ws.on_upgrade(move |socket| status_websocket(socket, state)) + ws.on_upgrade(move |socket| websocket(socket, state)) +} + +pub async fn websocket(mut socket: WebSocket, state: Arc) { + trace!("wait for ws message (uuid)"); + let msg = socket.recv().await; + let uuid = msg.unwrap().unwrap().into_text().unwrap(); + + trace!("Search for uuid: {}", uuid); + + let eta = get_eta(&state.db).await; + let _ = socket + .send(Message::Text(format!("eta_{eta}_{uuid}"))) + .await; + + let device_exists = state.ping_map.contains_key(&uuid); + if device_exists { + let _ = socket + .send(receive_ping_broadcast(state.clone(), uuid).await) + .await; + } else { + debug!("didn't find any device"); + let _ = socket.send(Message::Text(format!("notfound_{uuid}"))).await; + }; + + let _ = socket.close().await; +} + +async fn receive_ping_broadcast(state: Arc, uuid: String) -> Message { + let pm = state.ping_map.clone().into_read_only(); + let device = pm.get(&uuid).expect("fatal error"); + debug!("got device: {} (online: {})", device.ip, device.online); + if device.online { + debug!("already started"); + Message::Text(BroadcastCommand::success(uuid).to_string()) + } else { + loop { + trace!("wait for tx message"); + let message = state + .ping_send + .subscribe() + .recv() + .await + .expect("fatal error"); + trace!("got message {:?}", message); + + if message.uuid != uuid { + continue; + } + trace!("message == uuid success"); + return Message::Text(message.to_string()); + } + } +} + +async fn get_eta(db: &PgPool) -> i64 { + let query = sqlx::query!(r#"SELECT times FROM devices;"#) + .fetch_one(db) + .await + .unwrap(); + + let times = if let Some(times) = query.times { + times + } else { + vec![0] + }; + + times.iter().sum::() / i64::try_from(times.len()).unwrap() } diff --git a/src/services.rs b/src/services.rs new file mode 100644 index 0000000..a766209 --- /dev/null +++ b/src/services.rs @@ -0,0 +1 @@ +pub mod ping; diff --git a/src/services/mod.rs b/src/services/mod.rs deleted file mode 100644 index a766209..0000000 --- a/src/services/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod ping; diff --git a/src/services/ping.rs b/src/services/ping.rs index 9b164c8..9191f86 100644 --- a/src/services/ping.rs +++ b/src/services/ping.rs @@ -1,59 +1,58 @@ -use std::str::FromStr; -use std::net::IpAddr; -use std::sync::Arc; - -use axum::extract::ws::WebSocket; -use axum::extract::ws::Message; +use crate::config::Config; +use crate::db::Device; use dashmap::DashMap; +use ipnetwork::IpNetwork; use sqlx::PgPool; +use std::fmt::Display; use time::{Duration, Instant}; use tokio::sync::broadcast::Sender; use tracing::{debug, error, trace}; -use crate::AppState; -use crate::config::Config; -use crate::db::Device; pub type StatusMap = DashMap; #[derive(Debug, Clone)] pub struct Value { - pub ip: String, - pub online: bool + pub ip: IpNetwork, + pub online: bool, } -pub async fn spawn(tx: Sender, config: &Config, device: Device, uuid: String, ping_map: &StatusMap, db: &PgPool) { +pub async fn spawn( + tx: Sender, + config: &Config, + device: Device, + uuid: String, + ping_map: &StatusMap, + db: &PgPool, +) { let timer = Instant::now(); let payload = [0; 8]; - let ping_ip = IpAddr::from_str(&device.ip).expect("bad ip"); - - let mut msg: Option = None; + let mut msg: Option = None; while msg.is_none() { - let ping = surge_ping::ping( - ping_ip, - &payload - ).await; + let ping = surge_ping::ping(device.ip.ip(), &payload).await; if let Err(ping) = ping { let ping_timeout = matches!(ping, surge_ping::SurgeError::Timeout { .. }); if !ping_timeout { error!("{}", ping.to_string()); - msg = Some(BroadcastCommands::Error(uuid.clone())); + msg = Some(BroadcastCommand::error(uuid.clone())); } if timer.elapsed() >= Duration::minutes(config.pingtimeout) { - msg = Some(BroadcastCommands::Timeout(uuid.clone())); + msg = Some(BroadcastCommand::timeout(uuid.clone())); } } else { - let (_, duration) = ping.map_err(|err| error!("{}", err.to_string())).expect("fatal error"); + let (_, duration) = ping + .map_err(|err| error!("{}", err.to_string())) + .expect("fatal error"); debug!("ping took {:?}", duration); - msg = Some(BroadcastCommands::Success(uuid.clone())); + msg = Some(BroadcastCommand::success(uuid.clone())); }; } let msg = msg.expect("fatal error"); let _ = tx.send(msg.clone()); - if let BroadcastCommands::Success(..) = msg { + if let BroadcastCommands::Success = msg.command { sqlx::query!( r#" UPDATE devices @@ -62,8 +61,17 @@ pub async fn spawn(tx: Sender, config: &Config, device: Devic "#, timer.elapsed().whole_seconds(), device.id - ).execute(db).await.unwrap(); - ping_map.insert(uuid.clone(), Value { ip: device.ip.clone(), online: true }); + ) + .execute(db) + .await + .unwrap(); + ping_map.insert( + uuid.clone(), + Value { + ip: device.ip, + online: true, + }, + ); tokio::time::sleep(tokio::time::Duration::from_secs(60)).await; } trace!("remove {} from ping_map", uuid); @@ -72,74 +80,48 @@ pub async fn spawn(tx: Sender, config: &Config, device: Devic #[derive(Clone, Debug, PartialEq)] pub enum BroadcastCommands { - Success(String), - Timeout(String), - Error(String), + Success, + Timeout, + Error, } -pub async fn status_websocket(mut socket: WebSocket, state: Arc) { - trace!("wait for ws message (uuid)"); - let msg = socket.recv().await; - let uuid = msg.unwrap().unwrap().into_text().unwrap(); - - trace!("Search for uuid: {}", uuid); - - let eta = get_eta(&state.db).await; - let _ = socket.send(Message::Text(format!("eta_{eta}_{uuid}"))).await; +#[derive(Clone, Debug, PartialEq)] +pub struct BroadcastCommand { + pub uuid: String, + pub command: BroadcastCommands, +} - let device_exists = state.ping_map.contains_key(&uuid); - if device_exists { - let _ = socket.send(process_device(state.clone(), uuid).await).await; - } else { - debug!("didn't find any device"); - let _ = socket.send(Message::Text(format!("notfound_{uuid}"))).await; - }; +impl Display for BroadcastCommand { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let prefix = match self.command { + BroadcastCommands::Success => "start", + BroadcastCommands::Timeout => "timeout", + BroadcastCommands::Error => "error", + }; - let _ = socket.close().await; + f.write_str(format!("{prefix}_{}", self.uuid).as_str()) + } } -async fn get_eta(db: &PgPool) -> i64 { - let query = sqlx::query!( - r#"SELECT times FROM devices;"# - ).fetch_one(db).await.unwrap(); - - let times = match query.times { - None => { vec![0] }, - Some(t) => t, - }; - times.iter().sum::() / i64::try_from(times.len()).unwrap() +impl BroadcastCommand { + pub fn success(uuid: String) -> Self { + Self { + uuid, + command: BroadcastCommands::Success, + } + } -} + pub fn timeout(uuid: String) -> Self { + Self { + uuid, + command: BroadcastCommands::Timeout, + } + } -async fn process_device(state: Arc, uuid: String) -> Message { - let pm = state.ping_map.clone().into_read_only(); - let device = pm.get(&uuid).expect("fatal error"); - debug!("got device: {} (online: {})", device.ip, device.online); - if device.online { - debug!("already started"); - Message::Text(format!("start_{uuid}")) - } else { - loop { - trace!("wait for tx message"); - let message = state.ping_send.subscribe().recv().await.expect("fatal error"); - trace!("got message {:?}", message); - return match message { - BroadcastCommands::Success(msg_uuid) => { - if msg_uuid != uuid { continue; } - trace!("message == uuid success"); - Message::Text(format!("start_{uuid}")) - }, - BroadcastCommands::Timeout(msg_uuid) => { - if msg_uuid != uuid { continue; } - trace!("message == uuid timeout"); - Message::Text(format!("timeout_{uuid}")) - }, - BroadcastCommands::Error(msg_uuid) => { - if msg_uuid != uuid { continue; } - trace!("message == uuid error"); - Message::Text(format!("error_{uuid}")) - } - } + pub fn error(uuid: String) -> Self { + Self { + uuid, + command: BroadcastCommands::Error, } } } -- cgit v1.2.3 From 91cd665671d564620bce13e693cd7ecaad697db9 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Sun, 25 Feb 2024 15:27:54 +0100 Subject: Closes #11. Write log to file. Update deps --- .gitignore | 3 ++ Cargo.lock | 158 ++++++++++++++++++++++++++++++++++-------------------------- Cargo.toml | 1 + src/main.rs | 4 ++ 4 files changed, 97 insertions(+), 69 deletions(-) (limited to 'Cargo.lock') diff --git a/.gitignore b/.gitignore index 0fd9734..d8ed708 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ target/ config.* .idea + +logs/ +*.log diff --git a/Cargo.lock b/Cargo.lock index 5d10375..fcbf58a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,9 +19,9 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "ahash" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42cd52102d3df161c77a887b608d7a4897d7cc112886a9537b738a887a03aaff" +checksum = "d713b3834d76b85304d4d525563c1276e2e30dc97cc67bfb4585a4a29fc2c89f" dependencies = [ "cfg-if", "getrandom", @@ -53,7 +53,7 @@ checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -148,7 +148,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -216,12 +216,9 @@ checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" [[package]] name = "cc" -version = "1.0.83" +version = "1.0.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] +checksum = "02f341c093d19155a6e41631ce5971aac4e9a868262212153124c15fa22d1cdc" [[package]] name = "cfg-if" @@ -335,6 +332,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" +[[package]] +name = "crossbeam-channel" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "176dc175b78f56c0f321911d9c8eb2b77a78a4860b9c19db83835fea1a46649b" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-queue" version = "0.3.11" @@ -682,9 +688,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.3.5" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0c62115964e08cb8039170eb33c1d0e2388a256930279edca206fff675f82c3" +checksum = "379dada1584ad501b383485dd706b8afb7a70fcbc7f4da7d780638a5a6124a60" [[package]] name = "hex" @@ -767,9 +773,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5aa53871fc917b1a9ed87b683a5d86db645e23acb32c2e0785a353e522fb75" +checksum = "186548d73ac615b32a73aafe38fb4f56c0d340e110e5a200bcadbaf2e199263a" dependencies = [ "bytes", "futures-channel", @@ -781,6 +787,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", + "smallvec", "tokio", ] @@ -1119,9 +1126,9 @@ dependencies = [ [[package]] name = "num_threads" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" dependencies = [ "libc", ] @@ -1244,7 +1251,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -1275,7 +1282,7 @@ checksum = "266c042b60c9c76b8d53061e52b2e0d1116abc57cefc8c5cd671619a56ac3690" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -1313,9 +1320,9 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.29" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2900ede94e305130c13ddd391e0ab7cbaeb783945ae07a279c268cb05109c6cb" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "pnet_base" @@ -1541,9 +1548,9 @@ checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.16" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" +checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" [[package]] name = "scopeguard" @@ -1553,29 +1560,29 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "serde" -version = "1.0.196" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "870026e60fa08c69f064aa766c10f10b1d62db9ccd4d0abb206472bee0ce3b32" +checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.196" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33c85360c95e7d137454dc81d9a4ed2b8efd8fbe19cee57357b32b9771fccb67" +checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] name = "serde_json" -version = "1.0.113" +version = "1.0.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79" +checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" dependencies = [ "itoa", "ryu", @@ -1671,12 +1678,12 @@ checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" [[package]] name = "socket2" -version = "0.5.5" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" +checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871" dependencies = [ "libc", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] @@ -1962,9 +1969,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.48" +version = "2.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" +checksum = "74f1bdc9872430ce9b75da68329d1c1746faf50ffac5f19e02b71e37ff881ffb" dependencies = [ "proc-macro2", "quote", @@ -2006,14 +2013,14 @@ checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] name = "thread_local" -version = "1.1.7" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" dependencies = [ "cfg-if", "once_cell", @@ -2101,7 +2108,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -2164,9 +2171,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.4" +version = "0.22.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ffdf896f8daaabf9b66ba8e77ea1ed5ed0f72821b398aba62352e95062951" +checksum = "2c1b5fd4128cc8d3e0cb74d4ed9a9cc7c7284becd4df68f5f940e1ad123606f6" dependencies = [ "indexmap", "serde", @@ -2215,6 +2222,18 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-appender" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3566e8ce28cc0a3fe42519fc80e6b4c943cc4c8cef275620eb8dac2d3d4e06cf" +dependencies = [ + "crossbeam-channel", + "thiserror", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.27" @@ -2223,7 +2242,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] @@ -2321,9 +2340,9 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-normalization" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" dependencies = [ "tinyvec", ] @@ -2416,6 +2435,7 @@ dependencies = [ "time", "tokio", "tracing", + "tracing-appender", "tracing-subscriber", "uuid", ] @@ -2463,7 +2483,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.3", ] [[package]] @@ -2483,17 +2503,17 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +checksum = "d380ba1dc7187569a8a9e91ed34b8ccfc33123bbacb8c0aed2d1ad7f3ef2dc5f" dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", + "windows_aarch64_gnullvm 0.52.3", + "windows_aarch64_msvc 0.52.3", + "windows_i686_gnu 0.52.3", + "windows_i686_msvc 0.52.3", + "windows_x86_64_gnu 0.52.3", + "windows_x86_64_gnullvm 0.52.3", + "windows_x86_64_msvc 0.52.3", ] [[package]] @@ -2504,9 +2524,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" +checksum = "68e5dcfb9413f53afd9c8f86e56a7b4d86d9a2fa26090ea2dc9e40fba56c6ec6" [[package]] name = "windows_aarch64_msvc" @@ -2516,9 +2536,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" +checksum = "8dab469ebbc45798319e69eebf92308e541ce46760b49b18c6b3fe5e8965b30f" [[package]] name = "windows_i686_gnu" @@ -2528,9 +2548,9 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +checksum = "2a4e9b6a7cac734a8b4138a4e1044eac3404d8326b6c0f939276560687a033fb" [[package]] name = "windows_i686_msvc" @@ -2540,9 +2560,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" +checksum = "28b0ec9c422ca95ff34a78755cfa6ad4a51371da2a5ace67500cf7ca5f232c58" [[package]] name = "windows_x86_64_gnu" @@ -2552,9 +2572,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" +checksum = "704131571ba93e89d7cd43482277d6632589b18ecf4468f591fbae0a8b101614" [[package]] name = "windows_x86_64_gnullvm" @@ -2564,9 +2584,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" +checksum = "42079295511643151e98d61c38c0acc444e52dd42ab456f7ccfd5152e8ecf21c" [[package]] name = "windows_x86_64_msvc" @@ -2576,15 +2596,15 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "0770833d60a970638e989b3fa9fd2bb1aaadcf88963d1659fd7d9990196ed2d6" [[package]] name = "winnow" -version = "0.5.39" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5389a154b01683d28c77f8f68f49dea75f0a4da32557a58f68ee51ebba472d29" +checksum = "7a4191c47f15cc3ec71fcb4913cb83d58def65dd3787610213c649283b5ce178" dependencies = [ "memchr", ] @@ -2615,7 +2635,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.48", + "syn 2.0.50", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index c320da1..8a86115 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,3 +23,4 @@ color-eyre = "0.6" thiserror = "1.0" ipnetwork = "0.20.0" mac_address = { version = "1.1.5", features = ["serde"] } +tracing-appender = "0.2.3" diff --git a/src/main.rs b/src/main.rs index eae89f6..d17984f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -33,7 +33,11 @@ async fn main() -> color_eyre::eyre::Result<()> { time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"); let loc = UtcTime::new(time_format); + let file_appender = tracing_appender::rolling::daily("logs", "webol.log"); + let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender); + tracing_subscriber::registry() + .with(fmt::layer().with_writer(non_blocking).with_ansi(false)) .with(fmt::layer().with_timer(loc)) .with( EnvFilter::builder() -- cgit v1.2.3