From 3428a637ce420baef9aa9f9803e71bd587867005 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Wed, 10 Apr 2024 00:16:55 +0200 Subject: Closes #24. Changed postgres to json directory storage --- src/main.rs | 33 ++++++++------------------------- 1 file changed, 8 insertions(+), 25 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 70c67cf..cf0d39b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,5 @@ use crate::{ - config::Config, - db::init_db_pool, - routes::{device, start, status}, - services::ping::{BroadcastCommand, StatusMap}, + config::Config, routes::{device, start, status}, services::ping::{BroadcastCommand, StatusMap}, storage::Device }; use axum::{ middleware::from_fn_with_state, @@ -10,7 +7,6 @@ use axum::{ Router, }; use dashmap::DashMap; -use sqlx::PgPool; use std::{env, sync::Arc}; use time::UtcOffset; use tokio::sync::broadcast::{channel, Sender}; @@ -26,10 +22,10 @@ use utoipa::{ }; use utoipa_swagger_ui::SwaggerUi; +mod auth; mod config; -mod db; +mod storage; mod error; -mod auth; mod routes; mod services; mod wol; @@ -39,20 +35,16 @@ mod wol; paths( start::post, start::get, - start::start_payload, device::get, - device::get_payload, device::post, device::put, ), components( schemas( - start::PayloadOld, start::Payload, start::Response, - device::DevicePayload, - device::GetDevicePayload, - db::DeviceSchema, + device::Payload, + storage::DeviceSchema, ) ), modifiers(&SecurityAddon), @@ -99,34 +91,26 @@ async fn main() -> color_eyre::eyre::Result<()> { ) .init(); - let version = env!("CARGO_PKG_VERSION"); + Device::setup()?; + let version = env!("CARGO_PKG_VERSION"); info!("start webol v{}", version); - let db = init_db_pool(&config.database_url).await; - sqlx::migrate!().run(&db).await.unwrap(); - let (tx, _) = channel(32); let ping_map: StatusMap = DashMap::new(); let shared_state = AppState { - db, config: config.clone(), ping_send: tx, ping_map, }; let app = Router::new() - .route("/start", post(start::start_payload)) .route("/start/:id", post(start::post).get(start::get)) - .route( - "/device", - post(device::post).get(device::get_payload).put(device::put), - ) + .route("/device", post(device::post).put(device::put)) .route("/device/:id", get(device::get)) .route("/status", get(status::status)) - // TODO: Don't load on `None` Auth .route_layer(from_fn_with_state(shared_state.clone(), auth::auth)) .merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", ApiDoc::openapi())) .with_state(Arc::new(shared_state)); @@ -141,7 +125,6 @@ async fn main() -> color_eyre::eyre::Result<()> { #[derive(Clone)] pub struct AppState { - db: PgPool, config: Config, ping_send: Sender, ping_map: StatusMap, -- cgit v1.2.3 From bd5ed2f47fe870776783a5b2a56c899126a51860 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Wed, 10 Apr 2024 12:20:17 +0200 Subject: Closes #29. Usable Readme and hopefully versioned container --- .github/workflows/push.yml | 1 + README.md | 27 +++++++++++++++++++++++---- src/config.rs | 1 + src/main.rs | 1 - 4 files changed, 25 insertions(+), 5 deletions(-) (limited to 'src/main.rs') diff --git a/.github/workflows/push.yml b/.github/workflows/push.yml index c04a19a..bdedfee 100644 --- a/.github/workflows/push.yml +++ b/.github/workflows/push.yml @@ -47,3 +47,4 @@ jobs: tags: | ghcr.io/fxqnlr/webol:dev-latest ghcr.io/fxqnlr/webol:dev-${{ github.run_number }} + ghcr.io/fxqnlr/webol:${{ env.CARGO_PKG_VERSION }} diff --git a/README.md b/README.md index eabc051..88f786a 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,28 @@ # webol -DATABASE_URL: `String` +## Config +Default `config.toml`: +```toml +serveraddr = "0.0.0.0:7229" # String +pingtimeout = 10 # i64 +pingthreshold = 1 # i64 +timeoffset = 0 # i8 -WEBOL_APIKEY: `String` +[auth] +method = "none" # "none"|"key" +secret = "" # String +``` -WEBOL_SERVERADDR: `Option` (0.0.0.0:7229) +## Docker -WEBOL_PINGTIMEOUT: `Option` (10) +minimal `docker-compose.yaml`: +```yaml +services: + webol: + image: ghcr.io/fxqnlr/webol:0.4.0 + container_name: webol + restart: unless-stopped + volumes: + - ./devices:/devices + network_mode: host +``` diff --git a/src/config.rs b/src/config.rs index 124893b..bfb28be 100644 --- a/src/config.rs +++ b/src/config.rs @@ -25,6 +25,7 @@ impl Config { .set_default("pingtimeout", 10)? .set_default("pingthreshold", 1)? .set_default("timeoffset", 0)? + .set_default("auth.method", "none")? .set_default("auth.secret", "")? .add_source(File::with_name("config.toml").required(false)) .add_source(File::with_name("config.dev.toml").required(false)) diff --git a/src/main.rs b/src/main.rs index cf0d39b..779385f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -68,7 +68,6 @@ impl Modify for SecurityAddon { } #[tokio::main] -#[allow(deprecated)] async fn main() -> color_eyre::eyre::Result<()> { color_eyre::install()?; -- cgit v1.2.3 From 07740f3d985b4cc921b69cd45ec9191a2daecd67 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Wed, 10 Apr 2024 13:29:01 +0200 Subject: Closes #31. Renamed Payloads --- src/main.rs | 4 ++-- src/routes/device.rs | 10 +++++----- src/routes/start.rs | 8 ++++---- 3 files changed, 11 insertions(+), 11 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index 779385f..8af8c63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -41,9 +41,9 @@ mod wol; ), components( schemas( - start::Payload, + start::SPayload, start::Response, - device::Payload, + device::DPayload, storage::DeviceSchema, ) ), diff --git a/src/routes/device.rs b/src/routes/device.rs index b6bd9d0..49361f2 100644 --- a/src/routes/device.rs +++ b/src/routes/device.rs @@ -32,7 +32,7 @@ pub async fn get(Path(id): Path) -> Result, Error> { } #[derive(Deserialize, ToSchema)] -pub struct Payload { +pub struct DPayload { id: String, mac: String, broadcast_addr: String, @@ -42,14 +42,14 @@ pub struct Payload { #[utoipa::path( put, path = "/device", - request_body = Payload, + request_body = DPayload, responses( (status = 200, description = "add device to storage", body = [DeviceSchema]) ), security((), ("api_key" = [])) )] pub async fn put( - Json(payload): Json, + Json(payload): Json, ) -> Result, Error> { info!( "add device {} ({}, {}, {})", @@ -73,14 +73,14 @@ pub async fn put( #[utoipa::path( post, path = "/device", - request_body = Payload, + request_body = DPayload, responses( (status = 200, description = "update device in storage", body = [DeviceSchema]) ), security((), ("api_key" = [])) )] pub async fn post( - Json(payload): Json, + Json(payload): Json, ) -> Result, Error> { info!( "edit device {} ({}, {}, {})", diff --git a/src/routes/start.rs b/src/routes/start.rs index 6907193..ae2b384 100644 --- a/src/routes/start.rs +++ b/src/routes/start.rs @@ -14,7 +14,7 @@ use uuid::Uuid; #[utoipa::path( post, path = "/start/{id}", - request_body = Option, + request_body = Option, responses( (status = 200, description = "start the device with the given id", body = [Response]) ), @@ -26,7 +26,7 @@ use uuid::Uuid; pub async fn post( State(state): State>, Path(id): Path, - payload: Option>, + payload: Option>, ) -> Result, Error> { send_wol(state, &id, payload) } @@ -52,7 +52,7 @@ pub async fn get( fn send_wol( state: Arc, id: &str, - payload: Option>, + payload: Option>, ) -> Result, Error> { info!("start request for {id}"); let device = Device::read(id)?; @@ -134,7 +134,7 @@ fn get_eta(times: Option>) -> i64 { } #[derive(Deserialize, ToSchema)] -pub struct Payload { +pub struct SPayload { ping: Option, } -- cgit v1.2.3 From 69d3e0e6564b416637978a69f0a035066aea4759 Mon Sep 17 00:00:00 2001 From: FxQnLr Date: Wed, 10 Apr 2024 20:15:39 +0200 Subject: Closes #30 and #27. At least a little --- src/auth.rs | 5 +++++ src/error.rs | 13 +++++++++---- src/main.rs | 5 +++-- src/storage.rs | 7 ++++++- 4 files changed, 23 insertions(+), 7 deletions(-) (limited to 'src/main.rs') diff --git a/src/auth.rs b/src/auth.rs index 74008b5..c662e36 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -6,6 +6,7 @@ use axum::{ response::Response, }; use serde::Deserialize; +use tracing::trace; #[derive(Debug, Clone, Deserialize)] pub enum Methods { @@ -20,15 +21,19 @@ pub async fn auth( next: Next, ) -> Result { let auth = state.config.auth; + trace!(?auth.method, "auth request"); match auth.method { Methods::Key => { if let Some(secret) = headers.get("authorization") { if auth.secret.as_str() != secret { + trace!("auth failed, unknown secret"); return Err(StatusCode::UNAUTHORIZED); }; + trace!("auth successfull"); let response = next.run(request).await; Ok(response) } else { + trace!("auth failed, no secret"); Err(StatusCode::UNAUTHORIZED) } } diff --git a/src/error.rs b/src/error.rs index 8a011bf..2d70592 100644 --- a/src/error.rs +++ b/src/error.rs @@ -7,7 +7,7 @@ use mac_address::MacParseError; use serde_json::json; use utoipa::ToSchema; use std::io; -use tracing::error; +use tracing::{error, warn}; #[derive(Debug, thiserror::Error, ToSchema)] pub enum Error { @@ -50,15 +50,20 @@ pub enum Error { impl IntoResponse for Error { fn into_response(self) -> Response { - error!("{}", self.to_string()); + // error!("{}", self.to_string()); let (status, error_message) = match self { Self::Json { source } => { error!("{source}"); (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") } Self::Io { source } => { - error!("{source}"); - (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") + if source.kind() == io::ErrorKind::NotFound { + warn!("unknown device requested"); + (StatusCode::NOT_FOUND, "Requested device not found") + } else { + error!("{source}"); + (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") + } } Self::ParseHeader { source } => { error!("{source}"); diff --git a/src/main.rs b/src/main.rs index 8af8c63..204c318 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ use dashmap::DashMap; use std::{env, sync::Arc}; use time::UtcOffset; use tokio::sync::broadcast::{channel, Sender}; -use tracing::{info, level_filters::LevelFilter}; +use tracing::{info, level_filters::LevelFilter, trace}; use tracing_subscriber::{ fmt::{self, time::OffsetTime}, prelude::*, @@ -89,11 +89,12 @@ async fn main() -> color_eyre::eyre::Result<()> { .from_env_lossy(), ) .init(); + trace!("logging initialized"); Device::setup()?; let version = env!("CARGO_PKG_VERSION"); - info!("start webol v{}", version); + info!(?version, "start webol"); let (tx, _) = channel(32); diff --git a/src/storage.rs b/src/storage.rs index 6ba5ee1..0da245b 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -8,7 +8,7 @@ use ipnetwork::IpNetwork; use mac_address::MacAddress; use serde::{Deserialize, Serialize}; use serde_json::json; -use tracing::{debug, warn}; +use tracing::{debug, trace, warn}; use utoipa::ToSchema; use crate::error::Error; @@ -26,6 +26,7 @@ impl Device { const STORAGE_PATH: &'static str = "devices"; pub fn setup() -> Result { + trace!("check for storage at {}", Self::STORAGE_PATH); let sp = Path::new(Self::STORAGE_PATH); if !sp.exists() { warn!("device storage path doesn't exist, creating it"); @@ -38,17 +39,21 @@ impl Device { } pub fn read(id: &str) -> Result { + trace!(?id, "attempt to read file"); let mut file = File::open(format!("{}/{id}.json", Self::STORAGE_PATH))?; let mut buf = String::new(); file.read_to_string(&mut buf)?; + trace!(?id, ?buf, "read successfully from file"); let dev = serde_json::from_str(&buf)?; Ok(dev) } pub fn write(&self) -> Result<(), Error> { + trace!(?self.id, ?self, "attempt to write to file"); let mut file = File::create(format!("{}/{}.json", Self::STORAGE_PATH, self.id))?; file.write_all(json!(self).to_string().as_bytes())?; + trace!(?self.id, "wrote successfully to file"); Ok(()) } -- cgit v1.2.3