cargo fmt

pull/9/head
prplV 2024-11-01 16:55:23 +03:00
parent 32e182682f
commit 27c21e5cd9
11 changed files with 56 additions and 72 deletions

View File

@ -1,13 +1,13 @@
use crate::options::structs::*; use crate::options::structs::*;
use log::{error, info, warn}; use log::{error, info, warn};
use redis::{Client, Commands, Connection, RedisResult}; use redis::{Client, Commands, Connection, RedisResult};
use std::fs::OpenOptions;
use std::io::Write;
use std::os::unix::process::CommandExt; use std::os::unix::process::CommandExt;
use std::process::Command; use std::process::Command;
use std::sync::Arc; use std::sync::Arc;
use std::{env, fs}; use std::{env, fs};
use tokio::time::Duration; use tokio::time::Duration;
use std::fs::OpenOptions;
use std::io::Write;
const CONFIG_PATH: &str = "settings.json"; const CONFIG_PATH: &str = "settings.json";
@ -258,21 +258,21 @@ fn save_new_config(config: &Processes, config_file: &str) -> Result<(), CustomEr
Ok(st) => { Ok(st) => {
let file = OpenOptions::new() let file = OpenOptions::new()
.read(true) .read(true)
.write(true) .write(true)
.create(true) .create(true)
.truncate(false) .truncate(false)
.open(config_file); .open(config_file);
match file { match file {
Ok(fs) => { Ok(fs) => {
let mut writer = fs; let mut writer = fs;
match writeln!(writer, "{}", st) { match writeln!(writer, "{}", st) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(_) => Err(CustomError::Fatal), Err(_) => Err(CustomError::Fatal),
} }
}, }
Err(_) => return Err(CustomError::Fatal) Err(_) => return Err(CustomError::Fatal),
} }
}, }
Err(_) => Err(CustomError::Fatal), Err(_) => Err(CustomError::Fatal),
} }
} }
@ -284,12 +284,9 @@ fn parse_extern_config(json_string: &str) -> Option<Processes> {
None None
} }
// unit tests // unit tests
#[cfg(test)] #[cfg(test)]
mod config_unittests { mod config_unittests {
use super::*; use super::*;
#[test] #[test]
fn parsing_valid_conf() { fn parsing_valid_conf() {
@ -316,7 +313,7 @@ fn parse_extern_config(json_string: &str) -> Option<Processes> {
assert_eq!(config_comparing(&a, &b), ConfigActuality::Remote); assert_eq!(config_comparing(&a, &b), ConfigActuality::Remote);
} }
// TODO : strange output // TODO : strange output
// #[test] // #[test]
// fn get_actual_config_mechanism() { // fn get_actual_config_mechanism() {
// assert!(get_actual_config().is_some()) // assert!(get_actual_config().is_some())
@ -340,4 +337,4 @@ fn parse_extern_config(json_string: &str) -> Option<Processes> {
}; };
assert!(save_new_config(&a, "tests/examples/none.json").is_ok()); assert!(save_new_config(&a, "tests/examples/none.json").is_ok());
} }
} }

View File

@ -45,7 +45,6 @@ pub fn setup_logger() -> Result<(), crate::options::structs::CustomError> {
Ok(()) Ok(())
} }
#[cfg(test)] #[cfg(test)]
mod logger_tests { mod logger_tests {
use super::*; use super::*;
@ -53,4 +52,4 @@ mod logger_tests {
fn setting_up_logger() { fn setting_up_logger() {
assert!(setup_logger().is_ok()); assert!(setup_logger().is_ok());
} }
} }

View File

@ -76,7 +76,6 @@ impl SigPostProcessing for Sig {
} }
} }
#[cfg(test)] #[cfg(test)]
mod signals_unittest { mod signals_unittest {
use super::*; use super::*;
@ -84,4 +83,4 @@ mod signals_unittest {
async fn get_signal_check() { async fn get_signal_check() {
assert!(Signals::Sigint.get_signal().is_ok()) assert!(Signals::Sigint.get_signal().is_ok())
} }
} }

View File

@ -3,7 +3,6 @@ use serde::{Deserialize, Serialize};
/// # an Error enum (next will be deleted and replaced) /// # an Error enum (next will be deleted and replaced)
pub enum CustomError { pub enum CustomError {
Fatal, Fatal,
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum ConfigActuality { pub enum ConfigActuality {

View File

@ -1,8 +1,8 @@
pub mod files; pub mod files;
pub mod prcs;
pub mod services;
pub mod hagent; pub mod hagent;
pub mod metrics; pub mod metrics;
pub mod prcs;
pub mod services;
use crate::options::structs::TrackingProcess; use crate::options::structs::TrackingProcess;
use files::create_watcher; use files::create_watcher;
@ -34,9 +34,8 @@ pub async fn run_daemons(
let mut watchers: Vec<Inotify> = vec![]; let mut watchers: Vec<Inotify> = vec![];
for file in proc.dependencies.files.clone().into_iter() { for file in proc.dependencies.files.clone().into_iter() {
if let Ok(watcher) = create_watcher(&file.filename, &file.src).await { if let Ok(watcher) = create_watcher(&file.filename, &file.src).await {
watchers.push(watcher); watchers.push(watcher);
} } else {
else {
let _ = tx.send(121).await; let _ = tx.send(121).await;
} }
// watchers.push(create_watcher(&file.filename, &file.src).await.unwrap()); // watchers.push(create_watcher(&file.filename, &file.src).await.unwrap());
@ -141,7 +140,7 @@ pub async fn run_daemons(
// //
// 121 - Cannot create valid watcher for file dependency // 121 - Cannot create valid watcher for file dependency
121 => { 121 => {
error!("Cannot create valid watcher for {}'s file dependency. Terminating...", proc.name); error!("Cannot create valid watcher for {}'s file dependency. Terminating thread...", proc.name);
let _ = terminate_process("runner-rs").await; let _ = terminate_process("runner-rs").await;
break; break;
}, },
@ -212,13 +211,10 @@ pub fn get_container_id() -> Option<String> {
} }
Some(String::from_utf8_lossy(&output.stdout).to_string()) Some(String::from_utf8_lossy(&output.stdout).to_string())
} }
Err(_) => { Err(_) => None,
None
}
} }
} }
#[cfg(test)] #[cfg(test)]
mod utils_unittests { mod utils_unittests {
use super::get_container_id; use super::get_container_id;

View File

@ -115,8 +115,6 @@ pub async fn check_file(filename: &str, path: &str) -> Result<(), CustomError> {
}) })
} }
#[cfg(test)] #[cfg(test)]
mod files_unittests { mod files_unittests {
use super::*; use super::*;
@ -140,4 +138,4 @@ mod files_unittests {
let res = check_file("invalid-file", "/path/to/the/hell").await; let res = check_file("invalid-file", "/path/to/the/hell").await;
assert!(res.is_err()); assert!(res.is_err());
} }
} }

View File

@ -1,26 +1,25 @@
// module needed to check host-agent health condition and to communicate with it // module needed to check host-agent health condition and to communicate with it
use tokio::net::UnixStream;
use crate::options::structs::CustomError; use crate::options::structs::CustomError;
// use tokio::net::UnixStream;
//
// code will be here // code will be here
// //
async fn open_unix_socket() -> Result<UnixStream, std::io::Error> { async fn open_unix_socket() -> Result<UnixStream, std::io::Error> {
let socket = UnixStream::connect("/var/run/runner-rs.sock").await?; let socket = UnixStream::connect("/var/run/runner-rs.sock").await?;
Ok(socket) Ok(socket)
} }
#[cfg(test)] #[cfg(test)]
mod hagent_unittets { mod hagent_unittets {
use super::*; use super::*;
#[tokio::test] #[tokio::test]
// maybe bool : true -> alive, false -> dead // maybe bool : true -> alive, false -> dead
// simple request on api // simple request on api
async fn hagent_healthcheck() { async fn hagent_healthcheck() {
assert!(true); assert!(true);
} }
#[tokio::test] #[tokio::test]
// Result<maybe Response> // Result<maybe Response>
// one-shot func // one-shot func
async fn send_metrics_to_hagent() { async fn send_metrics_to_hagent() {
assert!(true); assert!(true);
@ -29,4 +28,4 @@ mod hagent_unittets {
async fn open_unixsocket_test() { async fn open_unixsocket_test() {
assert!(open_unix_socket().await.is_ok()); assert!(open_unix_socket().await.is_ok());
} }
} }

View File

@ -1,10 +1,9 @@
// module needed to get metrics such as // module needed to get metrics such as
// cpu load, memmory load and net activity // cpu load, memmory load and net activity
// //
// code will be here // code will be here
// //
#[cfg(test)] #[cfg(test)]
mod metrics_unittets { mod metrics_unittets {
@ -13,23 +12,23 @@ mod metrics_unittets {
// echo func // echo func
async fn get_cpu_load() { async fn get_cpu_load() {
assert!(true); assert!(true);
} }
#[tokio::test] #[tokio::test]
// Option<String> output // Option<String> output
// echo func // echo func
async fn get_ram_load() { async fn get_ram_load() {
assert!(true); assert!(true);
} }
#[tokio::test] #[tokio::test]
// Option<String> output // Option<String> output
// echo func // echo func
async fn get_mem_load() { async fn get_mem_load() {
assert!(true); assert!(true);
} }
#[tokio::test] #[tokio::test]
// can't be tested this way because of 0-0 loop of checking buffer // can't be tested this way because of 0-0 loop of checking buffer
// async func with loop inside // async func with loop inside
async fn get_net_stat(){ async fn get_net_stat() {
assert!(true); assert!(true);
} }
#[tokio::test] #[tokio::test]
@ -42,4 +41,4 @@ mod metrics_unittets {
async fn get_info_about_subsystems() { async fn get_info_about_subsystems() {
assert!(true); assert!(true);
} }
} }

View File

@ -7,15 +7,11 @@ use tokio::time::Duration;
pub async fn get_pid(name: &str) -> Result<Output, std::io::Error> { pub async fn get_pid(name: &str) -> Result<Output, std::io::Error> {
let name = Arc::new(name.to_string()); let name = Arc::new(name.to_string());
let res= tokio::task::spawn_blocking(move || { let res =
Command::new("pidof") tokio::task::spawn_blocking(move || Command::new("pidof").arg(&*name).output()).await?;
.arg(&*name)
.output()
})
.await?;
if let Ok(output) = res { if let Ok(output) = res {
if output.stderr.is_empty() && output.stdout.is_empty() { if output.stderr.is_empty() && output.stdout.is_empty() {
return Err(io::ErrorKind::NotFound.into()); return Err(io::ErrorKind::NotFound.into());
} else { } else {
Ok(output) Ok(output)
} }
@ -43,7 +39,7 @@ pub async fn is_active(name: &str) -> bool {
// T is for stopped processes // T is for stopped processes
pub async fn is_frozen(name: &str) -> bool { pub async fn is_frozen(name: &str) -> bool {
let temp: Output ; let temp: Output;
if let Ok(output) = get_pid(name).await { if let Ok(output) = get_pid(name).await {
temp = output; temp = output;
} else { } else {
@ -107,39 +103,42 @@ pub async fn start_process(name: &str, path: &str) -> Result<(), CustomError> {
// let runsh = format!("{} {}", "exec", path); // let runsh = format!("{} {}", "exec", path);
let mut command = Command::new(path); let mut command = Command::new(path);
// command.arg(path); // command.arg(path);
match command.spawn() { match command.spawn() {
Ok(_) => { Ok(_) => {
warn!("Process {} is running now!", name); warn!("Process {} is running now!", name);
Ok(()) Ok(())
} }
Err(er) => {println!("{:?}", er); Err(CustomError::Fatal)}, Err(er) => {
println!("{:?}", er);
Err(CustomError::Fatal)
}
} }
} }
#[cfg(test)] #[cfg(test)]
mod process_unittests { mod process_unittests {
use super::*; use super::*;
// 1 full cycle - start -> restart -> stop // 1 full cycle - start -> restart -> stop
// 2 full cycle - start -> freeze -> unfreze -> stop // 2 full cycle - start -> freeze -> unfreze -> stop
// 2x is active // 2x is active
// 2x is frozen // 2x is frozen
// 2x pidof // 2x pidof
// rewrite, its a pipe // rewrite, its a pipe
#[tokio::test] #[tokio::test]
async fn full_cycle_with_restart() { async fn full_cycle_with_restart() {
assert!(true); assert!(true);
let res1 = start_process("temp-process", "/home/user/monitor/runner-rs/temp-process").await; let res1 = start_process("temp-process", "/home/user/monitor/runner-rs/temp-process").await;
assert!(res1.is_ok()); assert!(res1.is_ok());
let res2 = restart_process("temp-process", "/home/user/monitor/runner-rs/temp-process").await; let res2 =
restart_process("temp-process", "/home/user/monitor/runner-rs/temp-process").await;
assert!(res2.is_ok()); assert!(res2.is_ok());
let _ = terminate_process("temp-process").await; let _ = terminate_process("temp-process").await;
let res3 = is_active("temp-process").await; let res3 = is_active("temp-process").await;
assert!(res3); assert!(res3);
} }
// rewrite, its a pipe // rewrite, its a pipe
#[tokio::test] #[tokio::test]
async fn full_cycle_with_freeze() { async fn full_cycle_with_freeze() {
assert!(true); assert!(true);
@ -166,4 +165,4 @@ mod process_unittests {
async fn pidof_disabled_process() { async fn pidof_disabled_process() {
assert!(get_pid("invalid-process-name").await.is_err()); assert!(get_pid("invalid-process-name").await.is_err());
} }
} }

View File

@ -120,7 +120,6 @@ async fn check_service(hostname: &str, port: &u32) -> Result<(), CustomError> {
} }
} }
#[cfg(test)] #[cfg(test)]
mod service_unittests { mod service_unittests {
use super::check_service; use super::check_service;
@ -132,4 +131,4 @@ mod service_unittests {
async fn check_unavailable_service() { async fn check_unavailable_service() {
assert!(check_service("unavailable.service", &1111).await.is_err()); assert!(check_service("unavailable.service", &1111).await.is_err());
} }
} }

View File

@ -3,4 +3,4 @@
#[test] #[test]
fn test() { fn test() {
assert_eq!(2, 2); assert_eq!(2, 2);
} }