110 lines
3.0 KiB
Rust
110 lines
3.0 KiB
Rust
use std::sync::Arc;
|
|
use std::process::{ Command, Output };
|
|
use log::{error, warn};
|
|
use tokio::time::Duration;
|
|
use crate::structs::CustomError;
|
|
|
|
pub async fn get_pid(name: &str) -> Output {
|
|
let name = Arc::new(name.to_string());
|
|
tokio::task::spawn_blocking(move || {
|
|
Command::new("pidof")
|
|
.arg(&*name)
|
|
.output()
|
|
.unwrap_or_else(|_| {
|
|
error!("Failed to execute command 'pidof'");
|
|
std::process::exit(101);
|
|
})
|
|
})
|
|
.await
|
|
.unwrap()
|
|
}
|
|
// ! can be with bug !!!
|
|
// * APPROVED
|
|
pub async fn is_active(name: &str)-> bool {
|
|
let arc_name = Arc::new(name.to_string());
|
|
tokio::task::spawn_blocking(move || {
|
|
let output = Command::new("pidof")
|
|
.arg(&*arc_name)
|
|
.output()
|
|
.unwrap_or_else(|_| {
|
|
error!("Failed to execute command 'pidof'");
|
|
std::process::exit(101);
|
|
});
|
|
!String::from_utf8_lossy(&output.stdout).trim().is_empty()
|
|
})
|
|
.await
|
|
.unwrap()
|
|
}
|
|
|
|
// T is for stopped processes
|
|
pub async fn is_frozen(name: &str) -> bool {
|
|
let temp = get_pid(name).await;
|
|
let pid = String::from_utf8_lossy(&temp.stdout);
|
|
let pid = pid.trim();
|
|
let arc_pid = Arc::new(pid.to_string());
|
|
if pid.is_empty(){
|
|
return false;
|
|
} else {
|
|
tokio::task::spawn_blocking(move || {
|
|
let cmd = Command::new("ps")
|
|
.args(["-o", "stat=", "-p", &arc_pid])
|
|
.output()
|
|
.unwrap_or_else(|_| {
|
|
error!("Failed to execute ps command");
|
|
std::process::exit(101);
|
|
});
|
|
String::from_utf8_lossy(&cmd.stdout).contains("T")
|
|
})
|
|
.await
|
|
.unwrap()
|
|
}
|
|
}
|
|
pub async fn terminate_process (name: &str) {
|
|
let _ = Command::new("pkill")
|
|
.arg(name)
|
|
.output()
|
|
.unwrap_or_else(|_| {
|
|
error!("Failed to execute command 'pkill'");
|
|
std::process::exit(101);
|
|
});
|
|
}
|
|
// another test
|
|
pub async fn freeze_process(name: &str) {
|
|
let _ = Command::new("pkill")
|
|
.args(["-STOP", name])
|
|
.output()
|
|
.unwrap_or_else(|_| {
|
|
error!("Failed to freeze process");
|
|
std::process::exit(101);
|
|
});
|
|
}
|
|
pub async fn unfreeze_process(name: &str) {
|
|
let _ = Command::new("pkill")
|
|
.args(["-CONT", name])
|
|
.output()
|
|
.unwrap_or_else(|_| {
|
|
error!("Failed to unfreeze process");
|
|
std::process::exit(101);
|
|
});
|
|
}
|
|
pub async fn restart_process(name: &str, path: &str) -> Result<(), CustomError> {
|
|
terminate_process(name).await;
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
return start_process(name, path).await;
|
|
}
|
|
|
|
pub async fn start_process(name: &str, path: &str) -> Result<(), CustomError> {
|
|
let runsh = format!("{}{}", path, "/run.sh");
|
|
let mut command = Command::new("bash");
|
|
command.arg(runsh);
|
|
|
|
match command.spawn() {
|
|
Ok(_) => {
|
|
warn!("Process {} is running now!", name);
|
|
Ok(())
|
|
},
|
|
Err(_) => {
|
|
return Err(CustomError::Fatal)
|
|
},
|
|
}
|
|
} |