herolib_rust/src/virt/nerdctl/containers.rs

105 lines
3.0 KiB
Rust

// File: /root/code/git.ourworld.tf/herocode/sal/src/virt/nerdctl/containers.rs
use crate::virt::nerdctl::execute_nerdctl_command;
use crate::process::CommandResult;
use super::NerdctlError;
/// Run a container from an image
///
/// # Arguments
///
/// * `image` - The image to run
/// * `name` - Optional container name
/// * `detach` - Whether to run in detached mode
/// * `ports` - Optional port mappings (e.g., ["8080:80"])
/// * `snapshotter` - Optional snapshotter to use (e.g., "native", "fuse-overlayfs")
pub fn run(image: &str, name: Option<&str>, detach: bool, ports: Option<&[&str]>, snapshotter: Option<&str>) -> Result<CommandResult, NerdctlError> {
// First, try to remove any existing container with the same name to avoid conflicts
if let Some(name_str) = name {
// Ignore errors since the container might not exist
let _ = execute_nerdctl_command(&["rm", "-f", name_str]);
}
let mut args = vec!["run"];
if detach {
args.push("-d");
}
if let Some(name_str) = name {
args.push("--name");
args.push(name_str);
}
if let Some(port_mappings) = ports {
for port in port_mappings {
args.push("-p");
args.push(port);
}
}
if let Some(snapshotter_value) = snapshotter {
args.push("--snapshotter");
args.push(snapshotter_value);
}
// Add flags to avoid BPF issues
args.push("--cgroup-manager=cgroupfs");
args.push(image);
execute_nerdctl_command(&args)
}
/// Execute a command in a container
///
/// # Arguments
///
/// * `container` - The container ID or name
/// * [command](cci:1://file:///root/code/git.ourworld.tf/herocode/sal/src/process/run.rs:303:0-324:1) - The command to run
pub fn exec(container: &str, command: &str) -> Result<CommandResult, NerdctlError> {
execute_nerdctl_command(&["exec", container, "sh", "-c", command])
}
/// Copy files between container and local filesystem
///
/// # Arguments
///
/// * [source](cci:1://file:///root/code/git.ourworld.tf/herocode/sal/src/process/run.rs:55:4-64:5) - Source path (can be container:path or local path)
/// * `dest` - Destination path (can be container:path or local path)
pub fn copy(source: &str, dest: &str) -> Result<CommandResult, NerdctlError> {
execute_nerdctl_command(&["cp", source, dest])
}
/// Stop a container
///
/// # Arguments
///
/// * `container` - The container ID or name
pub fn stop(container: &str) -> Result<CommandResult, NerdctlError> {
execute_nerdctl_command(&["stop", container])
}
/// Remove a container
///
/// # Arguments
///
/// * `container` - The container ID or name
pub fn remove(container: &str) -> Result<CommandResult, NerdctlError> {
execute_nerdctl_command(&["rm", container])
}
/// List containers
///
/// # Arguments
///
/// * `all` - Whether to show all containers (including stopped ones)
pub fn list(all: bool) -> Result<CommandResult, NerdctlError> {
let mut args = vec!["ps"];
if all {
args.push("-a");
}
execute_nerdctl_command(&args)
}