This commit is contained in:
2025-04-05 05:46:30 +02:00
parent e48063a79c
commit 7cdd9f5559
52 changed files with 2062 additions and 1256 deletions

View File

@@ -1,122 +0,0 @@
//! Example usage of the buildah module
//!
//! This file demonstrates how to use the buildah module to perform
//! common container operations like creating containers, running commands,
//! and managing images.
use sal::virt::buildah::{BuildahError, Builder};
use std::collections::HashMap;
/// Run a complete buildah workflow example
pub fn run_buildah_example() -> Result<(), BuildahError> {
println!("Starting buildah example workflow...");
// Step 1: Create a container from an image using the Builder
println!("\n=== Creating container from fedora:latest ===");
let mut builder = Builder::new("my-fedora-container", "fedora:latest")?;
// Reset the builder to remove any existing container
println!("\n=== Resetting the builder to start fresh ===");
builder.reset()?;
// Create a new container (or continue with existing one)
println!("\n=== Creating container from fedora:latest ===");
builder = Builder::new("my-fedora-container", "fedora:latest")?;
println!("Created container: {}", builder.container_id().unwrap_or(&"unknown".to_string()));
// Step 2: Run a command in the container
println!("\n=== Installing nginx in container ===");
// Use chroot isolation to avoid BPF issues
let install_result = builder.run_with_isolation("dnf install -y nginx", "chroot")?;
println!("{:#?}", install_result);
println!("Installation output: {}", install_result.stdout);
// Step 3: Copy a file into the container
println!("\n=== Copying configuration file to container ===");
builder.copy("./example.conf", "/etc/example.conf")?;
// Step 4: Configure container metadata
println!("\n=== Configuring container metadata ===");
let mut config_options = HashMap::new();
config_options.insert("port".to_string(), "80".to_string());
config_options.insert("label".to_string(), "maintainer=example@example.com".to_string());
config_options.insert("entrypoint".to_string(), "/usr/sbin/nginx".to_string());
builder.config(config_options)?;
println!("Container configured");
// Step 5: Commit the container to create a new image
println!("\n=== Committing container to create image ===");
let image_name = "my-nginx:latest";
builder.commit(image_name)?;
println!("Created image: {}", image_name);
// Step 6: List images to verify our new image exists
println!("\n=== Listing images ===");
let images = Builder::images()?;
println!("Found {} images:", images.len());
for image in images {
println!(" ID: {}", image.id);
println!(" Names: {}", image.names.join(", "));
println!(" Size: {}", image.size);
println!(" Created: {}", image.created);
println!();
}
// Step 7: Clean up (optional in a real workflow)
println!("\n=== Cleaning up ===");
Builder::image_remove(image_name)?;
builder.remove()?;
println!("\nBuildah example workflow completed successfully!");
Ok(())
}
/// Demonstrate how to build an image from a Containerfile/Dockerfile
pub fn build_image_example() -> Result<(), BuildahError> {
println!("Building an image from a Containerfile...");
// Use the build function with tag, context directory, and isolation to avoid BPF issues
let result = Builder::build(Some("my-app:latest"), ".", "example_Dockerfile", Some("chroot"))?;
println!("Build output: {}", result.stdout);
println!("Image built successfully!");
Ok(())
}
/// Example of pulling and pushing images
pub fn registry_operations_example() -> Result<(), BuildahError> {
println!("Demonstrating registry operations...");
// Pull an image
println!("\n=== Pulling an image ===");
Builder::image_pull("docker.io/library/alpine:latest", true)?;
println!("Image pulled successfully");
// Tag the image
println!("\n=== Tagging the image ===");
Builder::image_tag("alpine:latest", "my-alpine:v1.0")?;
println!("Image tagged successfully");
// Push an image (this would typically go to a real registry)
// println!("\n=== Pushing an image (example only) ===");
// println!("In a real scenario, you would push to a registry with:");
// println!("Builder::image_push(\"my-alpine:v1.0\", \"docker://registry.example.com/my-alpine:v1.0\", true)");
Ok(())
}
/// Main function to run all examples
pub fn run_all_examples() -> Result<(), BuildahError> {
println!("=== BUILDAH MODULE EXAMPLES ===\n");
run_buildah_example()?;
build_image_example()?;
registry_operations_example()?;
Ok(())
}
fn main() {
let _ = run_all_examples().unwrap();
}

View File

@@ -0,0 +1,62 @@
// File: /root/code/git.ourworld.tf/herocode/sal/examples/container_example.rs
use std::error::Error;
use sal::virt::nerdctl::Container;
fn main() -> Result<(), Box<dyn Error>> {
// Create a container from an image
println!("Creating container from image...");
let container = Container::from_image("my-nginx", "nginx:latest")?
.with_port("8080:80")
.with_env("NGINX_HOST", "example.com")
.with_volume("/tmp/nginx:/usr/share/nginx/html")
.with_health_check("curl -f http://localhost/ || exit 1")
.with_detach(true)
.build()?;
println!("Container created successfully");
// Execute a command in the container
println!("Executing command in container...");
let result = container.exec("echo 'Hello from container'")?;
println!("Command output: {}", result.stdout);
// Get container status
println!("Getting container status...");
let status = container.status()?;
println!("Container status: {}", status.status);
// Get resource usage
println!("Getting resource usage...");
let resources = container.resources()?;
println!("CPU usage: {}", resources.cpu_usage);
println!("Memory usage: {}", resources.memory_usage);
// Stop and remove the container
println!("Stopping and removing container...");
container.stop()?;
container.remove()?;
println!("Container stopped and removed");
// Get a container by name (if it exists)
println!("\nGetting a container by name...");
match Container::new("existing-container") {
Ok(container) => {
if container.container_id.is_some() {
println!("Found container with ID: {}", container.container_id.unwrap());
// Perform operations on the existing container
let status = container.status()?;
println!("Container status: {}", status.status);
} else {
println!("Container exists but has no ID");
}
},
Err(e) => {
println!("Error getting container: {}", e);
}
}
Ok(())
}

View File

@@ -1,84 +0,0 @@
//! Example usage of the nerdctl module
//!
//! This file demonstrates how to use the nerdctl module to perform
//! common container operations like creating containers, running commands,
//! and managing images.
use sal::virt::nerdctl::{self, NerdctlError};
/// Run a complete nerdctl workflow example
pub fn run_nerdctl_example() -> Result<(), NerdctlError> {
println!("Starting nerdctl example workflow...");
// Step 1: Pull an image
println!("\n=== Pulling nginx:latest image ===");
let pull_result = nerdctl::image_pull("nginx:latest")?;
println!("Pull output: {}", pull_result.stdout);
// Step 2: Create a container from the image
println!("\n=== Creating container from nginx:latest ===");
// Use "native" snapshotter to avoid overlay mount issues
let run_result = nerdctl::run("nginx:latest", Some("my-nginx"), true, Some(&["8080:80"]), Some("native"))?;
println!("Container created: {}", run_result.stdout.trim());
let container_id = "my-nginx"; // Using the name we specified
// Step 3: Execute a command in the container
println!("\n=== Installing curl in container ===");
let update_result = nerdctl::exec(container_id, "apt-get update")?;
println!("Update output: {}", update_result.stdout);
let install_result = nerdctl::exec(container_id, "apt-get install -y curl")?;
println!("Installation output: {}", install_result.stdout);
// Step 4: Copy a file into the container (assuming nginx.conf exists)
println!("\n=== Copying configuration file to container ===");
nerdctl::copy("./nginx.conf", format!("{}:/etc/nginx/nginx.conf", container_id).as_str())?;
// Step 5: Commit the container to create a new image
println!("\n=== Committing container to create image ===");
let image_name = "my-custom-nginx:latest";
nerdctl::image_commit(container_id, image_name)?;
println!("Created image: {}", image_name);
// Step 6: Stop and remove the container
println!("\n=== Stopping and removing container ===");
nerdctl::stop(container_id)?;
nerdctl::remove(container_id)?;
println!("Container stopped and removed");
// Step 7: Create a new container from our custom image
println!("\n=== Creating container from custom image ===");
// Use "native" snapshotter to avoid overlay mount issues
nerdctl::run(image_name, Some("nginx-custom"), true, Some(&["8081:80"]), Some("native"))?;
println!("Custom container created");
// Step 8: List images
println!("\n=== Listing images ===");
let images_result = nerdctl::images()?;
println!("Images: \n{}", images_result.stdout);
// Step 9: Clean up (optional in a real workflow)
println!("\n=== Cleaning up ===");
nerdctl::stop("nginx-custom")?;
nerdctl::remove("nginx-custom")?;
nerdctl::image_remove(image_name)?;
println!("\nNerdctl example workflow completed successfully!");
Ok(())
}
/// Main function to run all examples
pub fn run_all_examples() -> Result<(), NerdctlError> {
println!("=== NERDCTL MODULE EXAMPLES ===\n");
run_nerdctl_example()?;
println!("\nNote that these examples require nerdctl to be installed on your system");
println!("and may require root/sudo privileges depending on your setup.");
Ok(())
}
fn main() {
let _ = run_all_examples().unwrap();
}

View File

@@ -1,74 +0,0 @@
//! Example of using the Rhai integration with SAL Buildah module
//!
//! This example demonstrates how to use the Rhai scripting language
//! with the System Abstraction Layer (SAL) Buildah module.
use rhai::Engine;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
// Create a new Rhai engine
let mut engine = Engine::new();
// Register println function
engine.register_fn("println", |s: &str| println!("{}", s));
// Register SAL functions with the engine
sal::rhai::register(&mut engine)?;
// Run a Rhai script that uses SAL Buildah functions
let script = r#"
// List available images
println("Listing available images:");
let images = buildah_images();
println("Found " + images.len() + " images");
// Create a container from an image (uncomment if you have a valid image)
// let container = buildah_from("alpine:latest");
// println("Created container: " + container.stdout.trim());
// Build an image using options
let build_options = buildah_new_build_options();
build_options.tag = "example-image:latest";
build_options.context_dir = ".";
build_options.file = "example_Dockerfile";
println("Building image with options:");
println(" Tag: " + build_options.tag);
println(" Context: " + build_options.context_dir);
println(" Dockerfile: " + build_options.file);
// Uncomment to actually build the image
// let build_result = buildah_build(build_options);
// println("Build result: " + build_result.success);
// Create a container configuration
let config_options = buildah_new_config_options();
config_options.author = "Rhai Example";
config_options.cmd = "/bin/sh -c 'echo Hello from Buildah'";
println("Container config options:");
println(" Author: " + config_options.author);
println(" Command: " + config_options.cmd);
// Commit options
let commit_options = buildah_new_commit_options();
commit_options.format = "docker";
commit_options.squash = true;
commit_options.rm = true;
println("Commit options:");
println(" Format: " + commit_options.format);
println(" Squash: " + commit_options.squash);
println(" Remove container: " + commit_options.rm);
// Return success
true
"#;
// Evaluate the script
let result = engine.eval::<bool>(script)?;
println!("Script execution successful: {}", result);
Ok(())
}

View File

@@ -1,79 +0,0 @@
//! Example of using the Rhai integration with SAL
//!
//! This example demonstrates how to use the Rhai scripting language
//! with the System Abstraction Layer (SAL) library.
use sal::rhai::{self, Engine};
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a new Rhai engine
let mut engine = Engine::new();
// Register SAL functions with the engine
rhai::register(&mut engine)?;
// Create a test file
let test_file = "rhai_test_file.txt";
fs::write(test_file, "Hello, Rhai!")?;
// Create a test directory
let test_dir = "rhai_test_dir";
if !fs::metadata(test_dir).is_ok() {
fs::create_dir(test_dir)?;
}
// Run a Rhai script that uses SAL functions
let script = r#"
// Check if files exist
let file_exists = exist("rhai_test_file.txt");
let dir_exists = exist("rhai_test_dir");
// Get file size
let size = file_size("rhai_test_file.txt");
// Create a new directory
let new_dir = "rhai_new_dir";
let mkdir_result = mkdir(new_dir);
// Copy a file
let copy_result = copy("rhai_test_file.txt", "rhai_test_dir/copied_file.txt");
// Find files
let files = find_files(".", "*.txt");
// Return a map with all the results
#{
file_exists: file_exists,
dir_exists: dir_exists,
file_size: size,
mkdir_result: mkdir_result,
copy_result: copy_result,
files: files
}
"#;
// Evaluate the script and get the results
let result = engine.eval::<rhai::Map>(script)?;
// Print the results
println!("Script results:");
println!(" File exists: {}", result.get("file_exists").unwrap().clone().cast::<bool>());
println!(" Directory exists: {}", result.get("dir_exists").unwrap().clone().cast::<bool>());
println!(" File size: {} bytes", result.get("file_size").unwrap().clone().cast::<i64>());
println!(" Mkdir result: {}", result.get("mkdir_result").unwrap().clone().cast::<String>());
println!(" Copy result: {}", result.get("copy_result").unwrap().clone().cast::<String>());
// Print the found files
let files = result.get("files").unwrap().clone().cast::<rhai::Array>();
println!(" Found files:");
for file in files {
println!(" - {}", file.cast::<String>());
}
// Clean up
fs::remove_file(test_file)?;
fs::remove_dir_all(test_dir)?;
fs::remove_dir_all("rhai_new_dir")?;
Ok(())
}

View File

@@ -1,66 +0,0 @@
//! Example of using the Git module with Rhai
//!
//! This example demonstrates how to use the Git module functions
//! through the Rhai scripting language.
use sal::rhai::{self, Engine};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a new Rhai engine
let mut engine = Engine::new();
// Register SAL functions with the engine
rhai::register(&mut engine)?;
// Run a Rhai script that uses Git functions
let script = r#"
// Print a header
print("=== Testing Git Module Functions ===\n");
// Test git_list function
print("Listing git repositories...");
let repos = git_list();
print(`Found ${repos.len()} repositories`);
// Print the first few repositories
if repos.len() > 0 {
print("First few repositories:");
let count = if repos.len() > 3 { 3 } else { repos.len() };
for i in range(0, count) {
print(` - ${repos[i]}`);
}
}
// Test find_matching_repos function
if repos.len() > 0 {
print("\nTesting repository search...");
// Extract a part of the first repo name to search for
let repo_path = repos[0];
let parts = repo_path.split("/");
let repo_name = parts[parts.len() - 1];
print(`Searching for repositories containing "${repo_name}"`);
let matching = find_matching_repos(repo_name);
print(`Found ${matching.len()} matching repositories`);
for repo in matching {
print(` - ${repo}`);
}
// Check if a repository has changes
print("\nChecking for changes in repository...");
let has_changes = git_has_changes(repo_path);
print(`Repository ${repo_path} has changes: ${has_changes}`);
}
print("\n=== Git Module Test Complete ===");
"#;
// Evaluate the script
match engine.eval::<()>(script) {
Ok(_) => println!("Script executed successfully"),
Err(e) => eprintln!("Script execution error: {}", e),
}
Ok(())
}

View File

@@ -1,54 +0,0 @@
//! Example of using the Rhai integration with SAL Process module
//!
//! This example demonstrates how to use the Rhai scripting language
//! with the System Abstraction Layer (SAL) Process module.
use rhai::Engine;
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
// Create a new Rhai engine
let mut engine = Engine::new();
// Register SAL functions with the engine
sal::rhai::register(&mut engine)?;
// Run a Rhai script that uses SAL Process functions
let script = r#"
// Check if a command exists
let ls_exists = which("ls");
println("ls command exists: " + ls_exists);
// Run a simple command
let echo_result = run_command("echo 'Hello from Rhai!'");
println("Echo command output: " + echo_result.stdout);
println("Echo command success: " + echo_result.success);
// Run a command silently
let silent_result = run_silent("ls -la");
println("Silent command success: " + silent_result.success);
// Run a command with custom options using a Map
let options = new_run_options();
options["die"] = false; // Don't return error if command fails
options["silent"] = true; // Suppress output to stdout/stderr
options["async_exec"] = false; // Run synchronously
options["log"] = true; // Log command execution
let custom_result = run("echo 'Custom options'", options);
println("Custom command success: " + custom_result.success);
// List processes
let processes = process_list("");
println("Number of processes: " + processes.len());
// Return success
true
"#;
// Evaluate the script
let result = engine.eval::<bool>(script)?;
println!("Script execution successful: {}", result);
Ok(())
}