summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock22
-rw-r--r--Cargo.toml2
-rw-r--r--README.md2
-rw-r--r--src/db.rs2
-rw-r--r--src/error.rs27
-rw-r--r--src/routes/device.rs10
-rw-r--r--src/routes/start.rs2
-rw-r--r--src/services/ping.rs92
8 files changed, 73 insertions, 86 deletions
diff --git a/Cargo.lock b/Cargo.lock
index df6537a..350c8e9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -276,9 +276,9 @@ dependencies = [
276 276
277[[package]] 277[[package]]
278name = "crc-catalog" 278name = "crc-catalog"
279version = "2.2.0" 279version = "2.3.0"
280source = "registry+https://github.com/rust-lang/crates.io-index" 280source = "registry+https://github.com/rust-lang/crates.io-index"
281checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484" 281checksum = "4939f9ed1444bd8c896d37f3090012fa6e7834fe84ef8c9daa166109515732f9"
282 282
283[[package]] 283[[package]]
284name = "crossbeam-queue" 284name = "crossbeam-queue"
@@ -726,9 +726,9 @@ dependencies = [
726 726
727[[package]] 727[[package]]
728name = "indexmap" 728name = "indexmap"
729version = "2.0.2" 729version = "2.1.0"
730source = "registry+https://github.com/rust-lang/crates.io-index" 730source = "registry+https://github.com/rust-lang/crates.io-index"
731checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897" 731checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f"
732dependencies = [ 732dependencies = [
733 "equivalent", 733 "equivalent",
734 "hashbrown 0.14.2", 734 "hashbrown 0.14.2",
@@ -1416,9 +1416,9 @@ dependencies = [
1416 1416
1417[[package]] 1417[[package]]
1418name = "serde_json" 1418name = "serde_json"
1419version = "1.0.107" 1419version = "1.0.108"
1420source = "registry+https://github.com/rust-lang/crates.io-index" 1420source = "registry+https://github.com/rust-lang/crates.io-index"
1421checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" 1421checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b"
1422dependencies = [ 1422dependencies = [
1423 "itoa", 1423 "itoa",
1424 "ryu", 1424 "ryu",
@@ -2187,7 +2187,7 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
2187 2187
2188[[package]] 2188[[package]]
2189name = "webol" 2189name = "webol"
2190version = "0.1.0" 2190version = "0.2.0"
2191dependencies = [ 2191dependencies = [
2192 "axum", 2192 "axum",
2193 "axum-macros", 2193 "axum-macros",
@@ -2310,18 +2310,18 @@ dependencies = [
2310 2310
2311[[package]] 2311[[package]]
2312name = "zerocopy" 2312name = "zerocopy"
2313version = "0.7.20" 2313version = "0.7.23"
2314source = "registry+https://github.com/rust-lang/crates.io-index" 2314source = "registry+https://github.com/rust-lang/crates.io-index"
2315checksum = "dd66a62464e3ffd4e37bd09950c2b9dd6c4f8767380fabba0d523f9a775bc85a" 2315checksum = "e50cbb27c30666a6108abd6bc7577556265b44f243e2be89a8bc4e07a528c107"
2316dependencies = [ 2316dependencies = [
2317 "zerocopy-derive", 2317 "zerocopy-derive",
2318] 2318]
2319 2319
2320[[package]] 2320[[package]]
2321name = "zerocopy-derive" 2321name = "zerocopy-derive"
2322version = "0.7.20" 2322version = "0.7.23"
2323source = "registry+https://github.com/rust-lang/crates.io-index" 2323source = "registry+https://github.com/rust-lang/crates.io-index"
2324checksum = "255c4596d41e6916ced49cfafea18727b24d67878fa180ddfd69b9df34fd1726" 2324checksum = "a25f293fe55f0a48e7010d65552bb63704f6ceb55a1a385da10d41d8f78e4a3d"
2325dependencies = [ 2325dependencies = [
2326 "proc-macro2", 2326 "proc-macro2",
2327 "quote", 2327 "quote",
diff --git a/Cargo.toml b/Cargo.toml
index 7b2c22b..1bf823f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
1[package] 1[package]
2name = "webol" 2name = "webol"
3version = "0.1.0" 3version = "0.2.0"
4edition = "2021" 4edition = "2021"
5 5
6# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 6# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/README.md b/README.md
index d177df2..e4a6c44 100644
--- a/README.md
+++ b/README.md
@@ -7,3 +7,5 @@ WEBOL_APIKEY: `String`
7WEBOL_SERVERADDR: `Option<String>` (0.0.0.0:7229) 7WEBOL_SERVERADDR: `Option<String>` (0.0.0.0:7229)
8 8
9WEBOL_BINDADDR: `Option<String>` (0.0.0.0:1111) 9WEBOL_BINDADDR: `Option<String>` (0.0.0.0:1111)
10
11WEBOL_PINGTIMEOUT: `Option<i64>` (10) \ No newline at end of file
diff --git a/src/db.rs b/src/db.rs
index 51ea469..c012b47 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -8,7 +8,7 @@ use tracing::{debug, info};
8#[cfg(not(debug_assertions))] 8#[cfg(not(debug_assertions))]
9use crate::config::SETTINGS; 9use crate::config::SETTINGS;
10 10
11#[derive(Serialize)] 11#[derive(Serialize, Debug)]
12pub struct Device { 12pub struct Device {
13 pub id: String, 13 pub id: String,
14 pub mac: String, 14 pub mac: String,
diff --git a/src/error.rs b/src/error.rs
index 1592a78..5b82534 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,4 +1,3 @@
1use std::error::Error;
2use std::io; 1use std::io;
3use axum::http::StatusCode; 2use axum::http::StatusCode;
4use axum::Json; 3use axum::Json;
@@ -10,9 +9,7 @@ use crate::auth::AuthError;
10#[derive(Debug)] 9#[derive(Debug)]
11pub enum WebolError { 10pub enum WebolError {
12 Generic, 11 Generic,
13 // User(UserError),
14 Auth(AuthError), 12 Auth(AuthError),
15 Ping(surge_ping::SurgeError),
16 DB(sqlx::Error), 13 DB(sqlx::Error),
17 IpParse(<std::net::IpAddr as std::str::FromStr>::Err), 14 IpParse(<std::net::IpAddr as std::str::FromStr>::Err),
18 BufferParse(std::num::ParseIntError), 15 BufferParse(std::num::ParseIntError),
@@ -22,13 +19,10 @@ pub enum WebolError {
22impl IntoResponse for WebolError { 19impl IntoResponse for WebolError {
23 fn into_response(self) -> Response { 20 fn into_response(self) -> Response {
24 let (status, error_message) = match self { 21 let (status, error_message) = match self {
25 Self::Auth(err) => err.get(), 22 Self::Auth(err) => {
26 // Self::User(err) => err.get(), 23 err.get()
27 Self::Generic => (StatusCode::INTERNAL_SERVER_ERROR, ""),
28 Self::Ping(err) => {
29 error!("Ping: {}", err.source().unwrap());
30 (StatusCode::INTERNAL_SERVER_ERROR, "Server Error")
31 }, 24 },
25 Self::Generic => (StatusCode::INTERNAL_SERVER_ERROR, ""),
32 Self::IpParse(err) => { 26 Self::IpParse(err) => {
33 error!("server error: {}", err.to_string()); 27 error!("server error: {}", err.to_string());
34 (StatusCode::INTERNAL_SERVER_ERROR, "Server Error") 28 (StatusCode::INTERNAL_SERVER_ERROR, "Server Error")
@@ -51,17 +45,4 @@ impl IntoResponse for WebolError {
51 })); 45 }));
52 (status, body).into_response() 46 (status, body).into_response()
53 } 47 }
54} 48} \ No newline at end of file
55
56// #[derive(Debug)]
57// pub enum UserError {
58// UnknownUUID,
59// }
60//
61// impl UserError {
62// pub fn get(self) -> (StatusCode, &'static str) {
63// match self {
64// Self::UnknownUUID => (StatusCode::UNPROCESSABLE_ENTITY, "Unknown UUID"),
65// }
66// }
67// }
diff --git a/src/routes/device.rs b/src/routes/device.rs
index 7353733..1eeff0b 100644
--- a/src/routes/device.rs
+++ b/src/routes/device.rs
@@ -4,13 +4,13 @@ use axum::headers::HeaderMap;
4use axum::Json; 4use axum::Json;
5use serde::{Deserialize, Serialize}; 5use serde::{Deserialize, Serialize};
6use serde_json::{json, Value}; 6use serde_json::{json, Value};
7use tracing::info; 7use tracing::{debug, info};
8use crate::auth::auth; 8use crate::auth::auth;
9use crate::db::Device; 9use crate::db::Device;
10use crate::error::WebolError; 10use crate::error::WebolError;
11 11
12pub async fn get_device(State(state): State<Arc<crate::AppState>>, headers: HeaderMap, Json(payload): Json<GetDevicePayload>) -> Result<Json<Value>, WebolError> { 12pub async fn get_device(State(state): State<Arc<crate::AppState>>, headers: HeaderMap, Json(payload): Json<GetDevicePayload>) -> Result<Json<Value>, WebolError> {
13 info!("GET request"); 13 info!("add device {}", payload.id);
14 let secret = headers.get("authorization"); 14 let secret = headers.get("authorization");
15 if auth(secret).map_err(WebolError::Auth)? { 15 if auth(secret).map_err(WebolError::Auth)? {
16 let device = sqlx::query_as!( 16 let device = sqlx::query_as!(
@@ -23,6 +23,8 @@ pub async fn get_device(State(state): State<Arc<crate::AppState>>, headers: Head
23 payload.id 23 payload.id
24 ).fetch_one(&state.db).await.map_err(WebolError::DB)?; 24 ).fetch_one(&state.db).await.map_err(WebolError::DB)?;
25 25
26 debug!("got device {:?}", device);
27
26 Ok(Json(json!(device))) 28 Ok(Json(json!(device)))
27 } else { 29 } else {
28 Err(WebolError::Generic) 30 Err(WebolError::Generic)
@@ -35,7 +37,7 @@ pub struct GetDevicePayload {
35} 37}
36 38
37pub async fn put_device(State(state): State<Arc<crate::AppState>>, headers: HeaderMap, Json(payload): Json<PutDevicePayload>) -> Result<Json<Value>, WebolError> { 39pub async fn put_device(State(state): State<Arc<crate::AppState>>, headers: HeaderMap, Json(payload): Json<PutDevicePayload>) -> Result<Json<Value>, WebolError> {
38 info!("PUT request"); 40 info!("add device {} ({}, {}, {})", payload.id, payload.mac, payload.broadcast_addr, payload.ip);
39 let secret = headers.get("authorization"); 41 let secret = headers.get("authorization");
40 if auth(secret).map_err(WebolError::Auth)? { 42 if auth(secret).map_err(WebolError::Auth)? {
41 sqlx::query!( 43 sqlx::query!(
@@ -69,7 +71,7 @@ pub struct PutDeviceResponse {
69} 71}
70 72
71pub async fn post_device(State(state): State<Arc<crate::AppState>>, headers: HeaderMap, Json(payload): Json<PostDevicePayload>) -> Result<Json<Value>, WebolError> { 73pub async fn post_device(State(state): State<Arc<crate::AppState>>, headers: HeaderMap, Json(payload): Json<PostDevicePayload>) -> Result<Json<Value>, WebolError> {
72 info!("POST request"); 74 info!("edit device {} ({}, {}, {})", payload.id, payload.mac, payload.broadcast_addr, payload.ip);
73 let secret = headers.get("authorization"); 75 let secret = headers.get("authorization");
74 if auth(secret).map_err(WebolError::Auth)? { 76 if auth(secret).map_err(WebolError::Auth)? {
75 let device = sqlx::query_as!( 77 let device = sqlx::query_as!(
diff --git a/src/routes/start.rs b/src/routes/start.rs
index c2c9378..9cd358b 100644
--- a/src/routes/start.rs
+++ b/src/routes/start.rs
@@ -49,8 +49,6 @@ pub async fn start(State(state): State<Arc<crate::AppState>>, headers: HeaderMap
49 debug!("Init ping service"); 49 debug!("Init ping service");
50 state.ping_map.insert(uuid_gen.clone(), PingValue { ip: device.ip.clone(), online: false }); 50 state.ping_map.insert(uuid_gen.clone(), PingValue { ip: device.ip.clone(), online: false });
51 51
52 warn!("{:?}", state.ping_map);
53
54 crate::services::ping::spawn(state.ping_send.clone(), device.ip, uuid_gen.clone(), &state.ping_map).await 52 crate::services::ping::spawn(state.ping_send.clone(), device.ip, uuid_gen.clone(), &state.ping_map).await
55 }); 53 });
56 Some(uuid_genc) 54 Some(uuid_genc)
diff --git a/src/services/ping.rs b/src/services/ping.rs
index f0cc4a3..a26dacc 100644
--- a/src/services/ping.rs
+++ b/src/services/ping.rs
@@ -1,14 +1,13 @@
1use std::borrow::Cow;
2use std::sync::Arc; 1use std::sync::Arc;
3 2
4use axum::extract::{ws::WebSocket}; 3use axum::extract::{ws::WebSocket};
5use axum::extract::ws::{CloseFrame, Message}; 4use axum::extract::ws::Message;
6use dashmap::DashMap; 5use dashmap::DashMap;
6use time::{Duration, Instant};
7use tokio::sync::broadcast::{Sender}; 7use tokio::sync::broadcast::{Sender};
8use tracing::{debug, trace, warn}; 8use tracing::{debug, error, trace};
9use crate::AppState; 9use crate::AppState;
10 10use crate::config::SETTINGS;
11use crate::error::WebolError;
12 11
13pub type PingMap = DashMap<String, PingValue>; 12pub type PingMap = DashMap<String, PingValue>;
14 13
@@ -18,92 +17,97 @@ pub struct PingValue {
18 pub online: bool 17 pub online: bool
19} 18}
20 19
21pub async fn spawn(tx: Sender<BroadcastCommands>, ip: String, uuid: String, ping_map: &PingMap) -> Result<(), WebolError> { 20pub async fn spawn(tx: Sender<BroadcastCommands>, ip: String, uuid: String, ping_map: &PingMap) {
21 let timer = Instant::now();
22 let payload = [0; 8]; 22 let payload = [0; 8];
23 23
24 // TODO: Better while
25 let mut cont = true; 24 let mut cont = true;
26 while cont { 25 while cont {
27 let ping = surge_ping::ping( 26 let ping = surge_ping::ping(
28 ip.parse().map_err(WebolError::IpParse)?, 27 ip.parse().expect("bad ip"),
29 &payload 28 &payload
30 ).await; 29 ).await;
31 30
32 if let Err(ping) = ping { 31 if let Err(ping) = ping {
33 cont = matches!(ping, surge_ping::SurgeError::Timeout { .. }); 32 cont = matches!(ping, surge_ping::SurgeError::Timeout { .. });
34 if !cont { 33 if !cont {
35 return Err(ping).map_err(WebolError::Ping) 34 error!("{}", ping.to_string());
35 }
36 if timer.elapsed() >= Duration::minutes(SETTINGS.get_int("pingtimeout").unwrap_or(10)) {
37 let _ = tx.send(BroadcastCommands::PingTimeout(uuid.clone()));
38 trace!("remove {} from ping_map after timeout", uuid);
39 ping_map.remove(&uuid);
40 cont = false;
36 } 41 }
37 } else { 42 } else {
38 let (_, duration) = ping.unwrap(); 43 let (_, duration) = ping.map_err(|err| error!("{}", err.to_string())).expect("fatal error");
39 debug!("Ping took {:?}", duration); 44 debug!("Ping took {:?}", duration);
40 cont = false; 45 cont = false;
41 handle_broadcast_send(&tx, ip.clone(), ping_map, uuid.clone()).await; 46 handle_broadcast_send(&tx, ip.clone(), ping_map, uuid.clone()).await;
42 }; 47 };
43 } 48 }
44
45 Ok(())
46} 49}
47 50
48async fn handle_broadcast_send(tx: &Sender<BroadcastCommands>, ip: String, ping_map: &PingMap, uuid: String) { 51async fn handle_broadcast_send(tx: &Sender<BroadcastCommands>, ip: String, ping_map: &PingMap, uuid: String) {
49 debug!("sending pingsuccess message"); 52 debug!("send pingsuccess message");
50 ping_map.insert(uuid.clone(), PingValue { ip: ip.clone(), online: true }); 53 ping_map.insert(uuid.clone(), PingValue { ip: ip.clone(), online: true });
51 let _ = tx.send(BroadcastCommands::PingSuccess(ip)); 54 let _ = tx.send(BroadcastCommands::PingSuccess(uuid.clone()));
52 tokio::time::sleep(tokio::time::Duration::from_secs(60)).await; 55 tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
53 trace!("remove {} from ping_map", uuid); 56 trace!("remove {} from ping_map after success", uuid);
54 ping_map.remove(&uuid); 57 ping_map.remove(&uuid);
55} 58}
56 59
57#[derive(Clone, Debug)] 60#[derive(Clone, Debug)]
58pub enum BroadcastCommands { 61pub enum BroadcastCommands {
59 PingSuccess(String) 62 PingSuccess(String),
63 PingTimeout(String)
60} 64}
61 65
62pub async fn status_websocket(mut socket: WebSocket, state: Arc<AppState>) { 66pub async fn status_websocket(mut socket: WebSocket, state: Arc<AppState>) {
63 warn!("{:?}", state.ping_map);
64
65 trace!("wait for ws message (uuid)"); 67 trace!("wait for ws message (uuid)");
66 let msg = socket.recv().await; 68 let msg = socket.recv().await;
67 let uuid = msg.unwrap().unwrap().into_text().unwrap(); 69 let uuid = msg.unwrap().unwrap().into_text().unwrap();
68 70
69 trace!("Search for uuid: {:?}", uuid); 71 trace!("Search for uuid: {:?}", uuid);
70 72
71 // TODO: Handle Error 73 match state.ping_map.get(&uuid) {
72 let device = state.ping_map.get(&uuid).unwrap().to_owned(); 74 Some(device) => {
75 debug!("got device: {} (online: {})", device.ip, device.online);
76 let _ = socket.send(process_device(state.clone(), uuid, device.to_owned()).await).await;
77 },
78 None => {
79 debug!("didn't find any device");
80 let _ = socket.send(Message::Text(format!("notfound_{}", uuid))).await;
81 },
82 };
73 83
74 trace!("got device: {:?}", device); 84 let _ = socket.close().await;
85}
75 86
87async fn process_device(state: Arc<AppState>, uuid: String, device: PingValue) -> Message {
76 match device.online { 88 match device.online {
77 true => { 89 true => {
78 debug!("already started"); 90 debug!("already started");
79 // TODO: What's better? 91 Message::Text(format!("start_{}", uuid))
80 // socket.send(Message::Text(format!("start_{}", uuid))).await.unwrap();
81 // socket.close().await.unwrap();
82 socket.send(Message::Close(Some(CloseFrame { code: 4001, reason: Cow::from(format!("start_{}", uuid)) }))).await.unwrap();
83 }, 92 },
84 false => { 93 false => {
85 let ip = device.ip.to_owned();
86 loop{ 94 loop{
87 trace!("wait for tx message"); 95 trace!("wait for tx message");
88 let message = state.ping_send.subscribe().recv().await.unwrap(); 96 let message = state.ping_send.subscribe().recv().await.expect("fatal error");
89 trace!("GOT = {:?}", message); 97 trace!("got message {:?}", message);
90 // if let BroadcastCommands::PingSuccess(msg_ip) = message { 98 return match message {
91 // if msg_ip == ip { 99 BroadcastCommands::PingSuccess(msg_uuid) => {
92 // trace!("message == ip"); 100 if msg_uuid != uuid { continue; }
93 // break; 101 trace!("message == uuid success");
94 // } 102 Message::Text(format!("start_{}", uuid))
95 // } 103 },
96 let BroadcastCommands::PingSuccess(msg_ip) = message; 104 BroadcastCommands::PingTimeout(msg_uuid) => {
97 if msg_ip == ip { 105 if msg_uuid != uuid { continue; }
98 trace!("message == ip"); 106 trace!("message == uuid timeout");
99 break; 107 Message::Text(format!("timeout_{}", uuid))
108 }
100 } 109 }
101 }; 110 }
102
103 socket.send(Message::Close(Some(CloseFrame { code: 4000, reason: Cow::from(format!("start_{}", uuid)) }))).await.unwrap();
104 // socket.send(Message::Text(format!("start_{}", uuid))).await.unwrap();
105 // socket.close().await.unwrap();
106 warn!("{:?}", state.ping_map);
107 } 111 }
108 } 112 }
109} \ No newline at end of file 113} \ No newline at end of file