daemon_base/
binary.rs

1//! Binary management for the daemon library.
2//!
3//! This module provides functionality to load and unload binaries or resources
4//! in a specified order.
5
6use log::{info};
7use std::path::Path;
8use std::process::Command;
9use crate::error::DaemonError;
10
11/// Represents a binary or resource to be loaded.
12pub struct Binary {
13    path: String,
14}
15
16impl Binary {
17    /// Creates a new `Binary` instance.
18    pub fn new(path: String) -> Self {
19        Binary { path }
20    }
21
22    /// Loads the binary or resource.
23    pub fn load(&self) -> Result<(), DaemonError> {
24        info!("Loading binary: {}", self.path);
25
26        if !Path::new(&self.path).exists() {
27            return Err(DaemonError::CustomError(format!("Binary not found: {}", self.path)));
28        }
29
30        // Example: Execute the binary (replace with actual logic)
31        let output = Command::new(&self.path)
32            .output()
33            .map_err(|e| DaemonError::CustomError(format!("Failed to execute binary: {}", e)))?;
34
35        if !output.status.success() {
36            return Err(DaemonError::CustomError(format!(
37                "Binary failed with output: {}",
38                String::from_utf8_lossy(&output.stderr)
39            )));
40        }
41
42        info!("Successfully loaded binary: {}", self.path);
43        Ok(())
44    }
45
46    /// Unloads the binary or resource.
47    pub fn unload(&self) -> Result<(), DaemonError> {
48        info!("Unloading binary: {}", self.path);
49
50        // Example: Kill the process (replace with actual logic)
51        let output = Command::new("pkill")
52            .arg(&self.path)
53            .output()
54            .map_err(|e| DaemonError::CustomError(format!("Failed to unload binary: {}", e)))?;
55
56        if !output.status.success() {
57            return Err(DaemonError::CustomError(format!(
58                "Failed to unload binary: {}",
59                String::from_utf8_lossy(&output.stderr)
60            )));
61        }
62
63        info!("Successfully unloaded binary: {}", self.path);
64        Ok(())
65    }
66}
67
68/// Manages a list of binaries or resources.
69pub struct BinaryManager {
70    binaries: Vec<Binary>,
71}
72
73impl BinaryManager {
74    /// Creates a new `BinaryManager` instance.
75    pub fn new(binaries: Vec<String>) -> Self {
76        BinaryManager {
77            binaries: binaries.into_iter().map(Binary::new).collect(),
78        }
79    }
80
81    /// Loads all binaries or resources.
82    pub fn load_all(&self) -> Result<(), DaemonError> {
83        for binary in &self.binaries {
84            binary.load()?;
85        }
86        Ok(())
87    }
88
89    /// Unloads all binaries or resources.
90    pub fn unload_all(&self) -> Result<(), DaemonError> {
91        for binary in &self.binaries {
92            binary.unload()?;
93        }
94        Ok(())
95    }
96}