diff --git a/WatcherAgent/Cargo.toml b/WatcherAgent/Cargo.toml index 708a8c3..741f6e1 100644 --- a/WatcherAgent/Cargo.toml +++ b/WatcherAgent/Cargo.toml @@ -11,7 +11,7 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tokio = { version = "1.37", features = ["full"] } local-ip-address = "0.5" -reqwest = { version = "0.11", default-features = false, features = ["json", "blocking", "cookies", "rustls-tls"] } +reqwest = { version = "0.11", default-features = false, features = ["json", "blocking", "cookies", "rustls-tls", "statuscode"] } sysinfo = "0.29" metrics = "0.24.2" chrono = "0.4" diff --git a/WatcherAgent/src/main.rs b/WatcherAgent/src/main.rs index f4b77a2..9261545 100644 --- a/WatcherAgent/src/main.rs +++ b/WatcherAgent/src/main.rs @@ -147,15 +147,15 @@ impl HardwareInfo { } } -async fn register_with_server(base_url: &str) -> Result<(i32, String), Box> { +async fn get_server_id_by_ip(base_url: &str, ip: &str) -> Result<(i32, String), Box> { let client = Client::builder() .danger_accept_invalid_certs(true) .build()?; - // First get server ID - let url = format!("{}/server-id", base_url); - let (id, ip_address) = loop { - println!("Attempting to fetch server ID..."); + let url = format!("{}/monitoring/server-id-by-ip?ipAddress={}", base_url, ip); + + loop { + println!("Attempting to fetch server ID for IP {}...", ip); match client.get(&url).send().await { Ok(resp) if resp.status().is_success() => { let id_resp: IdResponse = resp.json().await?; @@ -163,19 +163,38 @@ async fn register_with_server(base_url: &str) -> Result<(i32, String), Box { + eprintln!("❌ Server with IP {} not found in database", ip); + return Err("Server not registered in database".into()); + } + Ok(resp) => { + println!("⚠️ Server responded with status: {}", resp.status()); + sleep(Duration::from_secs(3)).await; + } + Err(err) => { + println!("❌ Request failed: {}", err); + sleep(Duration::from_secs(3)).await; } - Ok(resp) => println!("⚠️ Server responded with status: {}", resp.status()), - Err(err) => println!("❌ Request failed: {}", err), } - sleep(Duration::from_secs(3)).await; - }; + } +} - // Then register hardware info +async fn register_with_server(base_url: &str) -> Result<(i32, String), Box> { + // First get local IP + let ip = local_ip_address::local_ip()?.to_string(); + + // Get server ID from backend + let (server_id, registered_ip) = get_server_id_by_ip(base_url, &ip).await?; + + // Collect hardware info let hardware = HardwareInfo::collect().await?; + + // Send registration data let registration = RegistrationDto { - id, - ip_address: ip_address.clone(), + id: server_id, + ip_address: registered_ip, cpu_type: hardware.cpu_type, cpu_cores: hardware.cpu_cores, gpu_type: hardware.gpu_type, @@ -187,12 +206,12 @@ async fn register_with_server(base_url: &str) -> Result<(i32, String), Box Result<(), Box> {