Skip to main content

herolib_virt/nerdctl/
container.rs

1// File: /root/code/git.threefold.info/herocode/sal/src/virt/nerdctl/container.rs
2
3use super::container_types::Container;
4use super::{execute_nerdctl_command, NerdctlError};
5use crate::os as os;
6use std::collections::HashMap;
7
8impl Container {
9    /// Create a new container reference with the given name
10    ///
11    /// # Arguments
12    ///
13    /// * `name` - Name for the container
14    ///
15    /// # Returns
16    ///
17    /// * `Result<Self, NerdctlError>` - Container instance or error
18    pub fn new(name: &str) -> Result<Self, NerdctlError> {
19        // Check if required commands exist
20        match os::cmd_ensure_exists("nerdctl,runc,buildah") {
21            Err(e) => {
22                return Err(NerdctlError::CommandExecutionFailed(std::io::Error::new(
23                    std::io::ErrorKind::NotFound,
24                    format!("Required commands not found: {}", e),
25                )))
26            }
27            _ => {}
28        }
29
30        // Check if container exists
31        let result = execute_nerdctl_command(&["ps", "-a", "--format", "{{.Names}} {{.ID}}"])?;
32
33        // Look for the container name in the output
34        let container_id = result
35            .stdout
36            .lines()
37            .filter_map(|line| {
38                if line.starts_with(&format!("{} ", name)) {
39                    Some(line.split_whitespace().nth(1)?.to_string())
40                } else {
41                    None
42                }
43            })
44            .next();
45
46        Ok(Self {
47            name: name.to_string(),
48            container_id,
49            image: None,
50            config: HashMap::new(),
51            ports: Vec::new(),
52            volumes: Vec::new(),
53            env_vars: HashMap::new(),
54            network: None,
55            network_aliases: Vec::new(),
56            cpu_limit: None,
57            memory_limit: None,
58            memory_swap_limit: None,
59            cpu_shares: None,
60            restart_policy: None,
61            health_check: None,
62            detach: false,
63            snapshotter: None,
64            runtime: None,
65            disk_limit: None,
66            annotations: HashMap::new(),
67            privileged: false,
68            devices: Vec::new(),
69        })
70    }
71
72    /// Create a container from an image
73    ///
74    /// # Arguments
75    ///
76    /// * `name` - Name for the container
77    /// * `image` - Image to create the container from
78    ///
79    /// # Returns
80    ///
81    /// * `Result<Self, NerdctlError>` - Container instance or error
82    pub fn from_image(name: &str, image: &str) -> Result<Self, NerdctlError> {
83        let mut container = Self::new(name)?;
84        container.image = Some(image.to_string());
85        Ok(container)
86    }
87}