added container broadcasting
All checks were successful
Rust Cross-Platform Build / Detect Rust Project (push) Successful in 5s
Rust Cross-Platform Build / Run Tests (push) Successful in 1m14s
Rust Cross-Platform Build / Build (x86_64-unknown-linux-gnu) (push) Successful in 3m18s
Rust Cross-Platform Build / Build (x86_64-pc-windows-gnu) (push) Successful in 4m4s
Rust Cross-Platform Build / Set Tag Name (push) Successful in 5s
Rust Cross-Platform Build / Build and Push Docker Image (push) Successful in 2m19s
Rust Cross-Platform Build / Workflow Summary (push) Successful in 2s
Rust Cross-Platform Build / Create Tag (push) Successful in 5s

This commit is contained in:
2025-10-09 10:59:21 +02:00
parent c7bce926e9
commit 1c7a169956
4 changed files with 59 additions and 9 deletions

View File

@@ -12,10 +12,12 @@
/// These functions are called from the main agent loop and background tasks. All network operations are asynchronous and robust to transient failures. /// These functions are called from the main agent loop and background tasks. All network operations are asynchronous and robust to transient failures.
use std::time::Duration; use std::time::Duration;
use crate::docker::container;
use crate::docker::serverclientcomm::handle_server_message; use crate::docker::serverclientcomm::handle_server_message;
use crate::hardware::HardwareInfo; use crate::hardware::HardwareInfo;
use crate::models::{ use crate::models::{
Acknowledgment, HeartbeatDto, IdResponse, MetricDto, RegistrationDto, ServerMessage, DockerMetricDto Acknowledgment, DockerMetricDto, DockerRegistrationDto, HeartbeatDto, IdResponse, MetricDto,
RegistrationDto, ServerMessage,
}; };
use anyhow::Result; use anyhow::Result;
@@ -151,6 +153,46 @@ async fn get_server_id_by_ip(
} }
} }
pub async fn broadcast_docker_containers(
base_url: &str,
server_id: u16,
container_dto: &mut DockerRegistrationDto,
) -> Result<(u16, String), Box<dyn Error + Send + Sync>> {
// First get local IP
println!("Preparing to broadcast docker containers...");
// Create HTTP client for registration
let client = Client::builder()
.danger_accept_invalid_certs(true)
.build()?;
// Prepare registration data
let container_dto = container_dto;
container_dto.server_id = server_id;
// Try to register (will retry on failure)
loop {
println!("Attempting to broadcast containers...");
let url = format!("{}/monitoring/service-discovery", base_url);
match client.post(&url).json(&container_dto).send().await {
Ok(resp) if resp.status().is_success() => {
println!("✅ Successfully broadcasted docker container.");
}
Ok(resp) => {
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
println!(
"⚠️ Broadcasting failed ({}): {} (will retry in 10 seconds)",
status, text
);
}
Err(err) => {
println!("⚠️ Broadcasting failed: {} (will retry in 10 seconds)", err);
}
}
sleep(Duration::from_secs(10)).await;
}
}
/// Periodically sends heartbeat signals to the backend server to indicate agent liveness. /// Periodically sends heartbeat signals to the backend server to indicate agent liveness.
/// ///
/// This function runs in a background task and will retry on network errors. /// This function runs in a background task and will retry on network errors.
@@ -359,7 +401,3 @@ pub async fn send_docker_metrics(
Ok(()) Ok(())
} }
pub async fn broadcast_docker_containers() {
// Placeholder for future implementation
}

View File

@@ -206,10 +206,9 @@ impl DockerManager {
&self, &self,
) -> Result<DockerRegistrationDto, Box<dyn Error + Send + Sync>> { ) -> Result<DockerRegistrationDto, Box<dyn Error + Send + Sync>> {
let containers = self.get_containers().await?; let containers = self.get_containers().await?;
let container_count = containers.len();
let dto = DockerRegistrationDto { let dto = DockerRegistrationDto {
server_id: 0, server_id: 0,
container_count, //container_count,
containers: serde_json::to_string(&containers)?, containers: serde_json::to_string(&containers)?,
}; };

View File

@@ -94,7 +94,7 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
Ok((id, ip)) => { Ok((id, ip)) => {
println!("Registered with server. ID: {}, IP: {}", id, ip); println!("Registered with server. ID: {}, IP: {}", id, ip);
(id, ip) (id, ip)
}, }
Err(e) => { Err(e) => {
eprintln!("Fehler bei der Registrierung am Server: {e}"); eprintln!("Fehler bei der Registrierung am Server: {e}");
return Err(e); return Err(e);
@@ -112,6 +112,19 @@ async fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
}; };
println!("Client Version: {}", client_version); println!("Client Version: {}", client_version);
// Prepare Docker registration DTO
let container_dto = if let Some(ref docker_manager) = docker_manager {
docker_manager.create_registration_dto().await?
} else {
models::DockerRegistrationDto {
server_id: 0,
//container_count: 0, --- IGNORE ---
containers: "[]".to_string(),
}
};
let _ =
api::broadcast_docker_containers(server_url, server_id, &mut container_dto.clone()).await?;
// Start background tasks // Start background tasks
// Start server listening for commands (only if Docker is available) // Start server listening for commands (only if Docker is available)
let listening_handle = if let Some(ref docker_manager) = docker_manager { let listening_handle = if let Some(ref docker_manager) = docker_manager {

View File

@@ -190,7 +190,7 @@ pub struct DockerRegistrationDto {
/// Unique server identifier (integer) /// Unique server identifier (integer)
pub server_id: u16, pub server_id: u16,
/// Number of currently running containers /// Number of currently running containers
pub container_count: usize, // pub container_count: usize, --- IGNORE ---
/// json stringified array of DockerContainer /// json stringified array of DockerContainer
/// ///
/// ## Json Example /// ## Json Example