static to const

pull/9/head
prplV 2024-09-30 14:47:55 +03:00
parent 03dd2c36c6
commit 881b5aa1a2
4 changed files with 29 additions and 21 deletions

View File

@ -1,13 +1,13 @@
use crate::structs::*; use crate::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::{env, fs};
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 tokio::time::Duration; use tokio::time::Duration;
static CONFIG_PATH: &str = "settings.json"; const CONFIG_PATH: &str = "settings.json";
type Res = RedisResult<Vec<Vec<(String, Vec<(String, String)>)>>>; type Res = RedisResult<Vec<Vec<(String, Vec<(String, String)>)>>>;
// 4ever sync // 4ever sync
@ -25,7 +25,10 @@ pub fn get_actual_config() -> Option<Processes> {
// let mut local = load_processes(&CONFIG_PATH); // let mut local = load_processes(&CONFIG_PATH);
match load_processes(CONFIG_PATH) { match load_processes(CONFIG_PATH) {
Some(local_conf) => { Some(local_conf) => {
info!("Found local configuration, version - {}", &local_conf.date_of_creation); info!(
"Found local configuration, version - {}",
&local_conf.date_of_creation
);
if let Some(remote_conf) = once_get_remote_configuration("redis://localhost") { if let Some(remote_conf) = once_get_remote_configuration("redis://localhost") {
return match config_comparing(&local_conf, &remote_conf) { return match config_comparing(&local_conf, &remote_conf) {
ConfigActuality::Local => { ConfigActuality::Local => {
@ -80,9 +83,12 @@ fn once_get_remote_configuration(serv_info: &str) -> Option<Processes> {
} }
match parse_extern_config(&config[0].1[0].1) { match parse_extern_config(&config[0].1[0].1) {
Some(prcs) => { Some(prcs) => {
info!("Config {} was pulled from Redis-Server", &prcs.date_of_creation); info!(
"Config {} was pulled from Redis-Server",
&prcs.date_of_creation
);
Some(prcs) Some(prcs)
}, }
None => { None => {
error!("Invalid configuration was pulled (PARSING_ERROR). Check configs state!"); error!("Invalid configuration was pulled (PARSING_ERROR). Check configs state!");
None None
@ -159,7 +165,10 @@ fn get_stream_info_watcher(conn: &mut Connection) {
fn invalid_config_watcher(conn: &mut Connection) -> Processes { fn invalid_config_watcher(conn: &mut Connection) -> Processes {
loop { loop {
if let Some(prcs) = get_remote_config(conn) { if let Some(prcs) = get_remote_config(conn) {
info!("Got new config from Redis-Server, version - {}", &prcs.date_of_creation); info!(
"Got new config from Redis-Server, version - {}",
&prcs.date_of_creation
);
return prcs; return prcs;
} }
error!("Got INVALID configuration. Update config! Retrying..."); error!("Got INVALID configuration. Update config! Retrying...");
@ -180,10 +189,9 @@ fn get_remote_config(conn: &mut Connection) -> Option<Processes> {
None None
} }
fn restart_main_thread() -> std::io::Result<()>{ fn restart_main_thread() -> std::io::Result<()> {
let current_exe = env::current_exe()?; let current_exe = env::current_exe()?;
Command::new(current_exe) Command::new(current_exe).exec();
.exec();
Ok(()) Ok(())
} }
pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>) -> Result<(), CustomError> { pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>) -> Result<(), CustomError> {
@ -198,13 +206,13 @@ pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>) -> Result<(),
info!("New config was pulled. Saving and restarting..."); info!("New config was pulled. Saving and restarting...");
if save_new_config(&prcs, CONFIG_PATH).is_err() { if save_new_config(&prcs, CONFIG_PATH).is_err() {
error!("Error with saving new config to {}", &CONFIG_PATH); error!("Error with saving new config to {}", &CONFIG_PATH);
return Err(CustomError::Fatal) return Err(CustomError::Fatal);
} }
if restart_main_thread().is_err() { if restart_main_thread().is_err() {
error!("Error with restarting Runner. Stopping sub mechanism..."); error!("Error with restarting Runner. Stopping sub mechanism...");
return Err(CustomError::Fatal) return Err(CustomError::Fatal);
} }
}, }
_ => continue, _ => continue,
} }
return Ok(()); return Ok(());
@ -245,7 +253,7 @@ fn save_new_config(config: &Processes, config_file: &str) -> Result<(), CustomEr
} }
fn parse_extern_config(json_string: &str) -> Option<Processes> { fn parse_extern_config(json_string: &str) -> Option<Processes> {
if let Ok(des) = serde_json::from_str::<Processes>(json_string){ if let Ok(des) = serde_json::from_str::<Processes>(json_string) {
return Some(des); return Some(des);
} }
None None

View File

@ -69,9 +69,9 @@ async fn main() {
// destructor addition // destructor addition
handler.push(tokio::spawn(async move { handler.push(tokio::spawn(async move {
if let Err(_) = set_valid_destructor(Arc::new(senders)).await { if set_valid_destructor(Arc::new(senders)).await.is_err() {
error!("Linux signals handler creation failed. Terminating main thread..."); error!("Linux signals handler creation failed. Terminating main thread...");
return; return
} }
// todo: rework this temp construction, use async/await in signals mod // todo: rework this temp construction, use async/await in signals mod
tokio::time::sleep(Duration::from_millis(200)).await; tokio::time::sleep(Duration::from_millis(200)).await;
@ -81,8 +81,8 @@ async fn main() {
// remote config update subscription // remote config update subscription
handler.push(tokio::spawn(async move { handler.push(tokio::spawn(async move {
if let Err(_) = subscribe_config_stream(Arc::new(processes)).await { if subscribe_config_stream(Arc::new(processes)).await.is_err() {
return; return
} }
})); }));

View File

@ -66,7 +66,7 @@ trait SigPostProcessing {
impl SigPostProcessing for Sig { impl SigPostProcessing for Sig {
async fn post_processing(&mut self) -> io::Result<()> { async fn post_processing(&mut self) -> io::Result<()> {
// manipulations ... // manipulations ...
if let Some(_) = self.signal.recv().await { if self.signal.recv().await.is_some() {
log::info!("Got {} signal", self.sig_type); log::info!("Got {} signal", self.sig_type);
for prc in self.senders.clone().iter() { for prc in self.senders.clone().iter() {
let _ = prc.send(111).await; let _ = prc.send(111).await;

View File

@ -14,12 +14,12 @@ use tokio::join;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tokio::time::Duration; use tokio::time::Duration;
static GET_ID_CMD: &str = const GET_ID_CMD: &str =
r"cat /proc/self/mountinfo | grep '/docker/containers/' | head -1 | awk -F '/' '{print \$6}'"; r"cat /proc/self/mountinfo | grep '/docker/containers/' | head -1 | awk -F '/' '{print \$6}'";
/// # async func to run 3 main daemons (now it's more like tree-form than classical 0.1.0 form ) /// # async func to run 3 main daemons (now it's more like tree-form than classical 0.1.0 form )
/// > hint : give mpsc with capacity 1 to jump over potential errors during running process /// > hint : give mpsc with capacity 1 to jump over potential errors during running process
/// ** in [developing](https://github.com/prplV/runner-rs "REPOSITORY") ** /// > ** in [developing](https://github.com/prplV/runner-rs "REPOSITORY") **
pub async fn run_daemons( pub async fn run_daemons(
proc: Arc<TrackingProcess>, proc: Arc<TrackingProcess>,
tx: Arc<mpsc::Sender<u8>>, tx: Arc<mpsc::Sender<u8>>,