Docker start/stop

This commit is contained in:
2024-01-20 18:21:25 +01:00
parent 93be1c8352
commit 4ef959f673
3 changed files with 62 additions and 24 deletions
+45 -18
View File
@@ -1,13 +1,15 @@
use std::{path::Path, process::Command};
use std::{
path::Path,
process::{Command, ExitStatus},
};
use directories::BaseDirs;
pub fn is_container_running(container_name: &str) -> bool {
fn is_container_running(container_name: &str) -> Result<bool, Box<dyn std::error::Error>> {
// Run the `docker ps` command and capture the output
let output = Command::new("docker")
.args(["ps", "--format", "{{.Names}}"])
.output()
.expect("Failed to execute command");
.output()?;
// Convert the output to a string
let output_str = String::from_utf8_lossy(&output.stdout);
@@ -15,35 +17,60 @@ pub fn is_container_running(container_name: &str) -> bool {
// Check if the container name is in the list of running containers
let running: bool = output_str.lines().any(|line| line.trim() == container_name);
if running {
println!("Container '{}' is running already.", container_name);
}
running
Ok(running)
}
pub fn start_docker_compose(service_name: &str, container_path: &str) {
// Run the `docker-compose up` command
pub fn start_docker_compose(
service_name: &str,
container_path: &str,
start: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let base_dir: BaseDirs = BaseDirs::new().unwrap();
let absolute = base_dir.home_dir().join(container_path);
let compose_path = Path::new(&absolute);
// Check if the file exists before attempting to use it
if compose_path.exists() {
let status = Command::new("docker-compose")
let running: bool = is_container_running(service_name)?;
if running && start {
println!("Container running already.");
return Ok(());
}
if start && compose_path.exists() {
let status: ExitStatus = Command::new("docker-compose")
.current_dir(compose_path)
.args(["up", "-d"])
.status()
.expect("Failed to execute command");
.status()?;
// Check if the command was successful
if status.success() {
println!(
"Docker Compose service '{}' started successfully.",
service_name
);
} else {
eprintln!("Failed to start Docker Compose service '{}'.", service_name);
return Err(
format!("Failed to start Docker Compose service '{}'.", service_name).into(),
);
}
}
if !start && compose_path.exists() {
let status: ExitStatus = Command::new("docker-compose")
.current_dir(compose_path)
.args(["down"])
.status()?;
if status.success() {
println!(
"Docker Compose service '{}' stopped successfully.",
service_name
);
} else {
return Err(
format!("Failed to stop Docker Compose service '{}'.", service_name).into(),
);
}
}
Ok(())
}