2 Commits

Author SHA1 Message Date
1f23c303c1 removed overloading metrics print statements
All checks were successful
Rust Cross-Platform Build / Detect Rust Project (push) Successful in 5s
Rust Cross-Platform Build / Set Tag Name (push) Successful in 5s
Rust Cross-Platform Build / Run Tests (push) Successful in 1m10s
Rust Cross-Platform Build / Build (x86_64-unknown-linux-gnu) (push) Successful in 3m6s
Rust Cross-Platform Build / Build (x86_64-pc-windows-gnu) (push) Successful in 3m43s
Rust Cross-Platform Build / Build and Push Docker Image (push) Successful in 2m14s
Rust Cross-Platform Build / Workflow Summary (push) Successful in 2s
Rust Cross-Platform Build / Create Tag (push) Successful in 5s
2025-09-28 17:46:42 +02:00
1cc85bfa14 added debugging for docker image
All checks were successful
Rust Cross-Platform Build / Detect Rust Project (push) Successful in 5s
Rust Cross-Platform Build / Set Tag Name (push) Successful in 4s
Rust Cross-Platform Build / Run Tests (push) Successful in 1m10s
Rust Cross-Platform Build / Build (x86_64-unknown-linux-gnu) (push) Successful in 3m6s
Rust Cross-Platform Build / Build (x86_64-pc-windows-gnu) (push) Successful in 3m54s
Rust Cross-Platform Build / Build and Push Docker Image (push) Successful in 2m12s
Rust Cross-Platform Build / Workflow Summary (push) Successful in 2s
Rust Cross-Platform Build / Create Tag (push) Successful in 5s
2025-09-28 01:00:26 +02:00
2 changed files with 96 additions and 114 deletions

View File

@@ -37,28 +37,12 @@ pub async fn get_disk_info() -> Result<DiskInfo, Box<dyn std::error::Error + Sen
component_disk_label: String::new(), component_disk_label: String::new(),
component_disk_temperature: 0.0, component_disk_temperature: 0.0,
}); });
println!(
"Disk_Name: {:?}:\n---- Disk_Kind: {},\n---- Total: {},\n---- Available: {},\n---- Used: {}, \n---- Mount_Point: {:?}",
disk.name(),
disk.kind(),
disk.total_space(),
disk.available_space(),
disk_used,
disk.mount_point()
);
} }
// Get component temperatures // Get component temperatures
let components = Components::new_with_refreshed_list(); let components = Components::new_with_refreshed_list();
for component in &components { for component in &components {
if let Some(temperature) = component.temperature() { if let Some(temperature) = component.temperature() {
println!(
"Component_Label: {}, Temperature: {}°C",
component.label(),
temperature
);
// Update detailed info with temperature data if it matches a disk component // Update detailed info with temperature data if it matches a disk component
for disk_info in &mut detailed_info { for disk_info in &mut detailed_info {
if component.label().contains(&disk_info.disk_name) { if component.label().contains(&disk_info.disk_name) {

View File

@@ -1,9 +1,8 @@
use crate::models::{ServerMessage}; use crate::models::{ServerMessage};
use std::error::Error; use std::error::Error;
use bollard::Docker; use bollard::Docker;
use bollard::query_parameters::{CreateImageOptions, RestartContainerOptions, InspectContainerOptions}; use bollard::query_parameters::{CreateImageOptions, RestartContainerOptions, InspectContainerOptions, ListContainersOptions};
use futures_util::StreamExt; use futures_util::StreamExt;
pub async fn handle_server_message(docker: &Docker, msg: ServerMessage) -> Result<(), Box<dyn Error + Send + Sync>> { pub async fn handle_server_message(docker: &Docker, msg: ServerMessage) -> Result<(), Box<dyn Error + Send + Sync>> {
@@ -75,20 +74,28 @@ pub async fn update_docker_image(docker: &Docker, image: &str) -> Result<(), Box
} }
pub async fn get_current_image(docker: &Docker) -> Result<Option<String>, Box<dyn Error + Send + Sync>> { pub async fn get_current_image(docker: &Docker) -> Result<Option<String>, Box<dyn Error + Send + Sync>> {
// First, let's debug the environment
debug_docker_environment(docker).await;
// Get the current container ID from /proc/self/cgroup // Get the current container ID from /proc/self/cgroup
let container_id = match std::fs::read_to_string("/proc/self/cgroup") { let container_id = match std::fs::read_to_string("/proc/self/cgroup") {
Ok(content) => { Ok(content) => {
content let mut found_id = None;
.lines() println!("Searching cgroup for container ID...");
.find_map(|line| {
// Look for any line that might contain container information for line in content.lines() {
if line.contains("docker") || line.contains("crio") || line.contains("containerd") || line.contains("kubepods") { println!("Checking line: {}", line);
// Extract the container ID from the line
extract_container_id(line) // Look for container runtime indicators
} else { if line.contains("docker") || line.contains("crio") || line.contains("containerd") {
None if let Some(id) = extract_container_id(line) {
println!("Found potential container ID: {}", id);
found_id = Some(id);
break;
} }
}) }
}
found_id
} }
Err(e) => { Err(e) => {
eprintln!("Error reading cgroup file: {}", e); eprintln!("Error reading cgroup file: {}", e);
@@ -96,121 +103,112 @@ pub async fn get_current_image(docker: &Docker) -> Result<Option<String>, Box<dy
} }
}; };
// Debug: Print what we found
println!("Container ID search result: {:?}", container_id);
let container_id = match container_id { let container_id = match container_id {
Some(id) if !id.is_empty() => { Some(id) if !id.is_empty() => {
println!("Found container ID: '{}'", id); println!("Using container ID: '{}'", id);
id id
} }
_ => { _ => {
// Debug the cgroup file content
if let Ok(content) = std::fs::read_to_string("/proc/self/cgroup") {
eprintln!("Cgroup file content for debugging:");
for (i, line) in content.lines().enumerate() {
eprintln!("Line {}: {}", i, line);
}
}
eprintln!("Could not find valid container ID in cgroup"); eprintln!("Could not find valid container ID in cgroup");
return Ok(None); return Ok(None);
} }
}; };
// Clean up the container ID - remove any non-hex characters // Try to inspect the container
let clean_container_id: String = container_id println!("Attempting to inspect container with ID: '{}'", container_id);
.chars()
.filter(|c| c.is_ascii_hexdigit())
.collect();
// Validate the container ID (should be 64 characters for full ID, but short ID might work too)
if clean_container_id.is_empty() {
eprintln!("Container ID contains no hex characters: '{}'", container_id);
return Ok(None);
}
println!("Using container ID: '{}' (cleaned: '{}')", container_id, clean_container_id);
// Try with both the original and cleaned ID
let ids_to_try = vec![&clean_container_id, &container_id];
for id in ids_to_try { match docker.inspect_container(&container_id, None::<InspectContainerOptions>).await {
println!("Attempting to inspect container with ID: '{}'", id); Ok(container_info) => {
if let Some(config) = container_info.config {
match docker.inspect_container(id, None::<InspectContainerOptions>).await { if let Some(image) = config.image {
Ok(container_info) => { println!("Successfully found image: {}", image);
if let Some(config) = container_info.config { return Ok(Some(image));
if let Some(image) = config.image {
println!("Successfully found image: {}", image);
return Ok(Some(image));
}
} }
eprintln!("Container inspected but no image found in config");
return Ok(Some("unknown".to_string()));
}
Err(e) => {
eprintln!("Error inspecting container with ID '{}': {}", id, e);
// Continue to try the next ID
} }
eprintln!("Container inspected but no image found in config");
Ok(Some("unknown".to_string()))
}
Err(e) => {
eprintln!("Error inspecting container: {}", e);
Ok(None)
} }
} }
eprintln!("All attempts to inspect container failed");
Ok(None)
} }
fn extract_container_id(line: &str) -> Option<String> { fn extract_container_id(line: &str) -> Option<String> {
let parts: Vec<&str> = line.split('/').collect(); // Split by slashes and take the last part
if let Some(last_part) = line.split('/').last() {
if let Some(last_part) = parts.last() {
let last_part = last_part.trim(); let last_part = last_part.trim();
println!("Processing cgroup line part: '{}'", last_part); // Remove common suffixes
let clean_id = last_part
.trim_end_matches(".scope")
.trim_start_matches("docker-")
.trim_start_matches("crio-")
.trim_start_matches("containerd-");
// Common patterns for container IDs in cgroups: // Check if it looks like a container ID (hex characters)
if clean_id.chars().all(|c| c.is_ascii_hexdigit()) && clean_id.len() >= 12 {
// Pattern 1: Full container ID (64-character hex) return Some(clean_id.to_string());
if last_part.len() == 64 && last_part.chars().all(|c| c.is_ascii_hexdigit()) {
println!("Found full container ID: {}", last_part);
return Some(last_part.to_string());
} }
// Pattern 2: docker-<short_id>.scope // If it's not pure hex, try to extract hex sequence
if last_part.starts_with("docker-") && last_part.ends_with(".scope") { let hex_part: String = clean_id.chars()
let id = last_part .take_while(|c| c.is_ascii_hexdigit())
.trim_start_matches("docker-") .collect();
.trim_end_matches(".scope")
.to_string(); if hex_part.len() >= 12 {
println!("Found docker scope ID: {}", id); return Some(hex_part);
return Some(id);
}
// Pattern 3: <short_id> (12-character hex or similar)
if last_part.chars().all(|c| c.is_ascii_hexdigit()) && last_part.len() >= 12 {
println!("Found hex ID: {}", last_part);
return Some(last_part.to_string());
}
// Pattern 4: Try to extract ID from any string that looks like it contains a hex ID
if let Some(caps) = regex::Regex::new(r"[a-fA-F0-9]{12,64}")
.ok()
.and_then(|re| re.find(last_part))
{
let id = caps.as_str().to_string();
println!("Extracted ID via regex: {}", id);
return Some(id);
}
// Pattern 5: If nothing else matches, try the last part as-is
if !last_part.is_empty() {
println!("Using last part as ID: {}", last_part);
return Some(last_part.to_string());
} }
} }
None None
} }
// Add this function to debug the Docker connection and environment
async fn debug_docker_environment(docker: &Docker) {
println!("=== DOCKER ENVIRONMENT DEBUG ===");
// List containers to see what's available - CORRECTED
let options = Some(ListContainersOptions {
all: true, // include stopped containers
..Default::default()
});
match docker.list_containers(options).await {
Ok(containers) => {
println!("Available containers ({}):", containers.len());
for container in containers {
if let Some(id) = container.id {
let short_id = if id.len() > 12 { &id[..12] } else { &id };
println!(" - ID: {}, Image: {:?}", short_id, container.image);
// Also print the names for easier identification
if let Some(names) = container.names {
println!(" Names: {:?}", names);
}
}
}
}
Err(e) => {
eprintln!("Failed to list containers: {}", e);
}
}
// Check if we're actually running in a container
if let Ok(content) = std::fs::read_to_string("/proc/self/cgroup") {
println!("Cgroup contents:");
println!("{}", content);
}
// Check other container indicators
if std::path::Path::new("/.dockerenv").exists() {
println!("/.dockerenv exists - running in Docker container");
} else {
println!("/.dockerenv does not exist");
}
}
pub async fn restart_container(docker: &Docker) -> Result<(), Box<dyn Error + Send + Sync>> { pub async fn restart_container(docker: &Docker) -> Result<(), Box<dyn Error + Send + Sync>> {
if let Ok(container_id) = std::env::var("HOSTNAME") { if let Ok(container_id) = std::env::var("HOSTNAME") {
println!("Restarting container {}", container_id); println!("Restarting container {}", container_id);