herolib-virt 0.3.13

Virtualization and container management for herolib (buildah, nerdctl, kubernetes)
Documentation
// File: /root/code/git.threefold.info/herocode/sal/src/virt/nerdctl/container.rs

use super::container_types::Container;
use super::{execute_nerdctl_command, NerdctlError};
use crate::os as os;
use std::collections::HashMap;

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,
            runtime: None,
            disk_limit: None,
            annotations: HashMap::new(),
            privileged: false,
            devices: Vec::new(),
        })
    }

    /// 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)
    }
}