Skip to main content

sal_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 crate::nerdctl::{execute_nerdctl_command, NerdctlError};
5use sal_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        })
65    }
66
67    /// Create a container from an image
68    ///
69    /// # Arguments
70    ///
71    /// * `name` - Name for the container
72    /// * `image` - Image to create the container from
73    ///
74    /// # Returns
75    ///
76    /// * `Result<Self, NerdctlError>` - Container instance or error
77    pub fn from_image(name: &str, image: &str) -> Result<Self, NerdctlError> {
78        let mut container = Self::new(name)?;
79        container.image = Some(image.to_string());
80        Ok(container)
81    }
82}