herolib_rust/src/virt/nerdctl/container.rs
2025-04-05 11:05:24 +02:00

79 lines
2.4 KiB
Rust

// File: /root/code/git.ourworld.tf/herocode/sal/src/virt/nerdctl/container.rs
use std::collections::HashMap;
use crate::virt::nerdctl::{execute_nerdctl_command, NerdctlError};
use crate::os;
use super::container_types::Container;
impl Container {
/// Create a new container reference with the given name
///
/// # Arguments
///
/// * `name` - Name for the container
///
/// # Returns
///
/// * `Result<Self, NerdctlError>` - Container instance or error
pub fn new(name: &str) -> Result<Self, NerdctlError> {
// Check if required commands exist
match os::cmd_ensure_exists("nerdctl,runc,buildah") {
Err(e) => return Err(NerdctlError::CommandExecutionFailed(
std::io::Error::new(std::io::ErrorKind::NotFound,
format!("Required commands not found: {}", e))
)),
_ => {}
}
// Check if container exists
let result = execute_nerdctl_command(&["ps", "-a", "--format", "{{.Names}} {{.ID}}"])?;
// Look for the container name in the output
let container_id = result.stdout.lines()
.filter_map(|line| {
if line.starts_with(&format!("{} ", name)) {
Some(line.split_whitespace().nth(1)?.to_string())
} else {
None
}
})
.next();
Ok(Self {
name: name.to_string(),
container_id,
image: None,
config: HashMap::new(),
ports: Vec::new(),
volumes: Vec::new(),
env_vars: HashMap::new(),
network: None,
network_aliases: Vec::new(),
cpu_limit: None,
memory_limit: None,
memory_swap_limit: None,
cpu_shares: None,
restart_policy: None,
health_check: None,
detach: false,
snapshotter: None,
})
}
/// Create a container from an image
///
/// # Arguments
///
/// * `name` - Name for the container
/// * `image` - Image to create the container from
///
/// # Returns
///
/// * `Result<Self, NerdctlError>` - Container instance or error
pub fn from_image(name: &str, image: &str) -> Result<Self, NerdctlError> {
let mut container = Self::new(name)?;
container.image = Some(image.to_string());
Ok(container)
}
}