Skip to main content

sal_virt/nerdctl/
container_builder.rs

1// File: /root/code/git.threefold.info/herocode/sal/src/virt/nerdctl/container_builder.rs
2
3use super::container_types::{Container, HealthCheck};
4use super::health_check_script::prepare_health_check_command;
5use crate::nerdctl::{execute_nerdctl_command, NerdctlError};
6use std::collections::HashMap;
7
8impl Container {
9    /// Reset the container configuration to defaults while keeping the name and image
10    /// If the container exists, it will be stopped and removed.
11    ///
12    /// # Returns
13    ///
14    /// * `Self` - The container instance for method chaining
15    pub fn reset(self) -> Self {
16        let name = self.name;
17        let image = self.image.clone();
18
19        // If container exists, stop and remove it
20        if let Some(container_id) = &self.container_id {
21            println!(
22                "Container exists. Stopping and removing container '{}'...",
23                name
24            );
25
26            // Try to stop the container
27            let _ = execute_nerdctl_command(&["stop", container_id]);
28
29            // Try to remove the container
30            let _ = execute_nerdctl_command(&["rm", container_id]);
31        }
32
33        // Create a new container with just the name and image, but no container_id
34        Self {
35            name,
36            container_id: None, // Reset container_id to None since we removed the container
37            image,
38            config: std::collections::HashMap::new(),
39            ports: Vec::new(),
40            volumes: Vec::new(),
41            env_vars: std::collections::HashMap::new(),
42            network: None,
43            network_aliases: Vec::new(),
44            cpu_limit: None,
45            memory_limit: None,
46            memory_swap_limit: None,
47            cpu_shares: None,
48            restart_policy: None,
49            health_check: None,
50            detach: false,
51            snapshotter: None,
52        }
53    }
54
55    /// Add a port mapping
56    ///
57    /// # Arguments
58    ///
59    /// * `port` - Port mapping (e.g., "8080:80")
60    ///
61    /// # Returns
62    ///
63    /// * `Self` - The container instance for method chaining
64    pub fn with_port(mut self, port: &str) -> Self {
65        self.ports.push(port.to_string());
66        self
67    }
68
69    /// Add multiple port mappings
70    ///
71    /// # Arguments
72    ///
73    /// * `ports` - Array of port mappings (e.g., ["8080:80", "8443:443"])
74    ///
75    /// # Returns
76    ///
77    /// * `Self` - The container instance for method chaining
78    pub fn with_ports(mut self, ports: &[&str]) -> Self {
79        for port in ports {
80            self.ports.push(port.to_string());
81        }
82        self
83    }
84
85    /// Add a volume mount
86    ///
87    /// # Arguments
88    ///
89    /// * `volume` - Volume mount (e.g., "/host/path:/container/path")
90    ///
91    /// # Returns
92    ///
93    /// * `Self` - The container instance for method chaining
94    pub fn with_volume(mut self, volume: &str) -> Self {
95        self.volumes.push(volume.to_string());
96        self
97    }
98
99    /// Add multiple volume mounts
100    ///
101    /// # Arguments
102    ///
103    /// * `volumes` - Array of volume mounts (e.g., ["/host/path1:/container/path1", "/host/path2:/container/path2"])
104    ///
105    /// # Returns
106    ///
107    /// * `Self` - The container instance for method chaining
108    pub fn with_volumes(mut self, volumes: &[&str]) -> Self {
109        for volume in volumes {
110            self.volumes.push(volume.to_string());
111        }
112        self
113    }
114
115    /// Add an environment variable
116    ///
117    /// # Arguments
118    ///
119    /// * `key` - Environment variable name
120    /// * `value` - Environment variable value
121    ///
122    /// # Returns
123    ///
124    /// * `Self` - The container instance for method chaining
125    pub fn with_env(mut self, key: &str, value: &str) -> Self {
126        self.env_vars.insert(key.to_string(), value.to_string());
127        self
128    }
129
130    /// Add multiple environment variables
131    ///
132    /// # Arguments
133    ///
134    /// * `env_map` - Map of environment variable names to values
135    ///
136    /// # Returns
137    ///
138    /// * `Self` - The container instance for method chaining
139    pub fn with_envs(mut self, env_map: &HashMap<&str, &str>) -> Self {
140        for (key, value) in env_map {
141            self.env_vars.insert(key.to_string(), value.to_string());
142        }
143        self
144    }
145
146    /// Set the network for the container
147    ///
148    /// # Arguments
149    ///
150    /// * `network` - Network name
151    ///
152    /// # Returns
153    ///
154    /// * `Self` - The container instance for method chaining
155    pub fn with_network(mut self, network: &str) -> Self {
156        self.network = Some(network.to_string());
157        self
158    }
159
160    /// Add a network alias for the container
161    ///
162    /// # Arguments
163    ///
164    /// * `alias` - Network alias
165    ///
166    /// # Returns
167    ///
168    /// * `Self` - The container instance for method chaining
169    pub fn with_network_alias(mut self, alias: &str) -> Self {
170        self.network_aliases.push(alias.to_string());
171        self
172    }
173
174    /// Add multiple network aliases for the container
175    ///
176    /// # Arguments
177    ///
178    /// * `aliases` - Array of network aliases
179    ///
180    /// # Returns
181    ///
182    /// * `Self` - The container instance for method chaining
183    pub fn with_network_aliases(mut self, aliases: &[&str]) -> Self {
184        for alias in aliases {
185            self.network_aliases.push(alias.to_string());
186        }
187        self
188    }
189
190    /// Set CPU limit for the container
191    ///
192    /// # Arguments
193    ///
194    /// * `cpus` - CPU limit (e.g., "0.5" for half a CPU, "2" for 2 CPUs)
195    ///
196    /// # Returns
197    ///
198    /// * `Self` - The container instance for method chaining
199    pub fn with_cpu_limit(mut self, cpus: &str) -> Self {
200        self.cpu_limit = Some(cpus.to_string());
201        self
202    }
203
204    /// Set memory limit for the container
205    ///
206    /// # Arguments
207    ///
208    /// * `memory` - Memory limit (e.g., "512m" for 512MB, "1g" for 1GB)
209    ///
210    /// # Returns
211    ///
212    /// * `Self` - The container instance for method chaining
213    pub fn with_memory_limit(mut self, memory: &str) -> Self {
214        self.memory_limit = Some(memory.to_string());
215        self
216    }
217
218    /// Set memory swap limit for the container
219    ///
220    /// # Arguments
221    ///
222    /// * `memory_swap` - Memory swap limit (e.g., "1g" for 1GB)
223    ///
224    /// # Returns
225    ///
226    /// * `Self` - The container instance for method chaining
227    pub fn with_memory_swap_limit(mut self, memory_swap: &str) -> Self {
228        self.memory_swap_limit = Some(memory_swap.to_string());
229        self
230    }
231
232    /// Set CPU shares for the container (relative weight)
233    ///
234    /// # Arguments
235    ///
236    /// * `shares` - CPU shares (e.g., "1024" for default, "512" for half)
237    ///
238    /// # Returns
239    ///
240    /// * `Self` - The container instance for method chaining
241    pub fn with_cpu_shares(mut self, shares: &str) -> Self {
242        self.cpu_shares = Some(shares.to_string());
243        self
244    }
245
246    /// Set restart policy for the container
247    ///
248    /// # Arguments
249    ///
250    /// * `policy` - Restart policy (e.g., "no", "always", "on-failure", "unless-stopped")
251    ///
252    /// # Returns
253    ///
254    /// * `Self` - The container instance for method chaining
255    pub fn with_restart_policy(mut self, policy: &str) -> Self {
256        self.restart_policy = Some(policy.to_string());
257        self
258    }
259
260    /// Set a simple health check for the container
261    ///
262    /// # Arguments
263    ///
264    /// * `cmd` - Command to run for health check (e.g., "curl -f http://localhost/ || exit 1")
265    ///
266    /// # Returns
267    ///
268    /// * `Self` - The container instance for method chaining
269    pub fn with_health_check(mut self, cmd: &str) -> Self {
270        // Use the health check script module to prepare the command
271        let prepared_cmd = prepare_health_check_command(cmd, &self.name);
272
273        self.health_check = Some(HealthCheck {
274            cmd: prepared_cmd,
275            interval: None,
276            timeout: None,
277            retries: None,
278            start_period: None,
279        });
280        self
281    }
282
283    /// Set a health check with custom options for the container
284    ///
285    /// # Arguments
286    ///
287    /// * `cmd` - Command to run for health check
288    /// * `interval` - Optional time between running the check (e.g., "30s", "1m")
289    /// * `timeout` - Optional maximum time to wait for a check to complete (e.g., "30s", "1m")
290    /// * `retries` - Optional number of consecutive failures needed to consider unhealthy
291    /// * `start_period` - Optional start period for the container to initialize before counting retries (e.g., "30s", "1m")
292    ///
293    /// # Returns
294    ///
295    /// * `Self` - The container instance for method chaining
296    pub fn with_health_check_options(
297        mut self,
298        cmd: &str,
299        interval: Option<&str>,
300        timeout: Option<&str>,
301        retries: Option<u32>,
302        start_period: Option<&str>,
303    ) -> Self {
304        // Use the health check script module to prepare the command
305        let prepared_cmd = prepare_health_check_command(cmd, &self.name);
306
307        let mut health_check = HealthCheck {
308            cmd: prepared_cmd,
309            interval: None,
310            timeout: None,
311            retries: None,
312            start_period: None,
313        };
314
315        if let Some(interval_value) = interval {
316            health_check.interval = Some(interval_value.to_string());
317        }
318
319        if let Some(timeout_value) = timeout {
320            health_check.timeout = Some(timeout_value.to_string());
321        }
322
323        if let Some(retries_value) = retries {
324            health_check.retries = Some(retries_value);
325        }
326
327        if let Some(start_period_value) = start_period {
328            health_check.start_period = Some(start_period_value.to_string());
329        }
330
331        self.health_check = Some(health_check);
332        self
333    }
334
335    /// Set the snapshotter
336    ///
337    /// # Arguments
338    ///
339    /// * `snapshotter` - Snapshotter to use
340    ///
341    /// # Returns
342    ///
343    /// * `Self` - The container instance for method chaining
344    pub fn with_snapshotter(mut self, snapshotter: &str) -> Self {
345        self.snapshotter = Some(snapshotter.to_string());
346        self
347    }
348
349    /// Set whether to run in detached mode
350    ///
351    /// # Arguments
352    ///
353    /// * `detach` - Whether to run in detached mode
354    ///
355    /// # Returns
356    ///
357    /// * `Self` - The container instance for method chaining
358    pub fn with_detach(mut self, detach: bool) -> Self {
359        self.detach = detach;
360        self
361    }
362
363    /// Build the container
364    ///
365    /// # Returns
366    ///
367    /// * `Result<Self, NerdctlError>` - Container instance or error
368    pub fn build(self) -> Result<Self, NerdctlError> {
369        // If container already exists, return it
370        if self.container_id.is_some() {
371            return Ok(self);
372        }
373
374        // If no image is specified, return an error
375        let image = match &self.image {
376            Some(img) => img,
377            None => {
378                return Err(NerdctlError::Other(
379                    "No image specified for container creation".to_string(),
380                ))
381            }
382        };
383
384        // Build the command arguments as strings
385        let mut args_strings = Vec::new();
386        args_strings.push("run".to_string());
387
388        if self.detach {
389            args_strings.push("-d".to_string());
390        }
391
392        args_strings.push("--name".to_string());
393        args_strings.push(self.name.clone());
394
395        // Add port mappings
396        for port in &self.ports {
397            args_strings.push("-p".to_string());
398            args_strings.push(port.clone());
399        }
400
401        // Add volume mounts
402        for volume in &self.volumes {
403            args_strings.push("-v".to_string());
404            args_strings.push(volume.clone());
405        }
406
407        // Add environment variables
408        for (key, value) in &self.env_vars {
409            args_strings.push("-e".to_string());
410            args_strings.push(format!("{}={}", key, value));
411        }
412
413        // Add network configuration
414        if let Some(network) = &self.network {
415            args_strings.push("--network".to_string());
416            args_strings.push(network.clone());
417        }
418
419        // Add network aliases
420        for alias in &self.network_aliases {
421            args_strings.push("--network-alias".to_string());
422            args_strings.push(alias.clone());
423        }
424
425        // Add resource limits
426        if let Some(cpu_limit) = &self.cpu_limit {
427            args_strings.push("--cpus".to_string());
428            args_strings.push(cpu_limit.clone());
429        }
430
431        if let Some(memory_limit) = &self.memory_limit {
432            args_strings.push("--memory".to_string());
433            args_strings.push(memory_limit.clone());
434        }
435
436        if let Some(memory_swap_limit) = &self.memory_swap_limit {
437            args_strings.push("--memory-swap".to_string());
438            args_strings.push(memory_swap_limit.clone());
439        }
440
441        if let Some(cpu_shares) = &self.cpu_shares {
442            args_strings.push("--cpu-shares".to_string());
443            args_strings.push(cpu_shares.clone());
444        }
445
446        // Add restart policy
447        if let Some(restart_policy) = &self.restart_policy {
448            args_strings.push("--restart".to_string());
449            args_strings.push(restart_policy.clone());
450        }
451
452        // Add health check
453        if let Some(health_check) = &self.health_check {
454            args_strings.push("--health-cmd".to_string());
455            args_strings.push(health_check.cmd.clone());
456
457            if let Some(interval) = &health_check.interval {
458                args_strings.push("--health-interval".to_string());
459                args_strings.push(interval.clone());
460            }
461
462            if let Some(timeout) = &health_check.timeout {
463                args_strings.push("--health-timeout".to_string());
464                args_strings.push(timeout.clone());
465            }
466
467            if let Some(retries) = &health_check.retries {
468                args_strings.push("--health-retries".to_string());
469                args_strings.push(retries.to_string());
470            }
471
472            if let Some(start_period) = &health_check.start_period {
473                args_strings.push("--health-start-period".to_string());
474                args_strings.push(start_period.clone());
475            }
476        }
477
478        if let Some(snapshotter_value) = &self.snapshotter {
479            args_strings.push("--snapshotter".to_string());
480            args_strings.push(snapshotter_value.clone());
481        }
482
483        // Add flags to avoid BPF issues
484        args_strings.push("--cgroup-manager=cgroupfs".to_string());
485
486        args_strings.push(image.clone());
487
488        // Convert to string slices for the command
489        let args: Vec<&str> = args_strings.iter().map(|s| s.as_str()).collect();
490
491        // Execute the command
492        let result = execute_nerdctl_command(&args)?;
493
494        // Get the container ID from the output
495        let container_id = result.stdout.trim().to_string();
496
497        Ok(Self {
498            name: self.name,
499            container_id: Some(container_id),
500            image: self.image,
501            config: self.config,
502            ports: self.ports,
503            volumes: self.volumes,
504            env_vars: self.env_vars,
505            network: self.network,
506            network_aliases: self.network_aliases,
507            cpu_limit: self.cpu_limit,
508            memory_limit: self.memory_limit,
509            memory_swap_limit: self.memory_swap_limit,
510            cpu_shares: self.cpu_shares,
511            restart_policy: self.restart_policy,
512            health_check: self.health_check,
513            detach: self.detach,
514            snapshotter: self.snapshotter,
515        })
516    }
517}