Compare commits

...

4 Commits

Author SHA1 Message Date
prplV 991bae50f6 unixsocket fix + disable lint warnings 2025-01-16 15:12:35 +03:00
prplV 4c88b27d82 pull_local_config + init_config_grub_mechanism (50%) + init_unix_listener 2025-01-16 14:38:22 +03:00
prplV e777571d12 true logging + cleaning main 2025-01-16 14:37:25 +03:00
prplV 186674da22 config api replace + struct of config changed 2025-01-16 14:37:03 +03:00
8 changed files with 132 additions and 22 deletions

13
config_api.json Normal file
View File

@ -0,0 +1,13 @@
{
"endpoints" : [
{
"url" : "http://127.0.0.1:8081/ping",
"method" : "GET"
},
{
"url" : "http://127.0.0.1:8081/",
"method" : "GET"
}
],
"delay" : 5
}

View File

@ -1,6 +1,6 @@
[package] [package]
name = "api-grub" name = "api-grub"
version = "0.1.0" version = "0.3.8"
edition = "2021" edition = "2021"
[dependencies] [dependencies]

View File

@ -1,5 +0,0 @@
{
"api-endpoint" : "http://127.0.0.1:8081/ping",
"method" : "GET",
"delay" : "5"
}

View File

@ -2,13 +2,80 @@
// 1) check changes in unix-socket // 1) check changes in unix-socket
// 2) save changes in local config file // 2) save changes in local config file
use integr_structs::api::ApiConfig; use integr_structs::api::ApiConfig;
use tokio::net::UnixListener; use anyhow::{Error, Ok, Result};
use anyhow::Result; use log::{info, warn, error};
use std::{fs, path::Path};
use serde_json::from_str;
use tokio::{io::AsyncReadExt, net::UnixListener};
use tokio::time::{sleep, Duration};
use std::result::Result::Ok as stdOk;
const CONFIG_PATH: &str = "config_api.json";
const SOCKET_PATH: &str = "api-grub.sock";
// todo! rewrite to use current_exe
pub async fn pull_local_config() -> Result<ApiConfig> {
// let conf_path = std::env::current_exe()?;
let path = Path::new(CONFIG_PATH);
// return match conf_path.parent() {
// Some(dir) => {
// let config: ApiConfig = from_str(
// &fs::read_to_string(dir.join(CONFIG_PATH))?
// )?;
// Ok(config)
// },
// None => Err(Error::msg("No local conf was found"))
// }
if path.exists() && path.is_file() {
let config: ApiConfig = from_str(
&fs::read_to_string(CONFIG_PATH)?
)?;
Ok(config)
} else {
Err(Error::msg("No local conf was found"))
}
}
// for config pulling // for config pulling
async fn init_api_grub_mechanism(config: ApiConfig) { // ++++ reader to channel
pub async fn init_config_grub_mechanism() -> Result<()> {
info!("Initializing Unix-Socket listening for pulling new configs...");
let server = init_unix_listener().await?;
//
info!("Listening Unix-Socket...");
let mut buffer = String::new();
//
loop {
if let stdOk((mut stream, _)) = server.accept().await {
if let Err(er) = stream.read_to_string(&mut buffer).await {
warn!("Cannot read config from stream due to {}", er);
} else {
let config: Result<ApiConfig, serde_json::Error> = from_str(&buffer);
if let stdOk(_conf) = config {
info!("New config was pulled from Unix-Stream. Saving it locally...");
if let Err(er) = save_new_config(&buffer).await {
error!("Cannot save new config locally due to: {}", er);
}
// TODO!
// reading new config to channel
// saving new config locally
} else if let Err(er) = config {
warn!("Invalid config was pulled. Error: {}", er);
}
}
}
sleep(Duration::from_millis(500)).await;
}
}
// saving new config locally
async fn save_new_config(config: &String) -> Result<()> {
fs::write(CONFIG_PATH, config)?;
Ok(())
} }
async fn init_unix_listener() {} async fn init_unix_listener() -> Result<UnixListener> {
let _ = fs::remove_file(SOCKET_PATH);
Ok(UnixListener::bind(SOCKET_PATH)?)
}

View File

@ -3,8 +3,9 @@ use env_logger::Builder;
use log::LevelFilter; use log::LevelFilter;
use std::io::Write; use std::io::Write;
use anyhow::Result; use anyhow::Result;
use log::info;
pub fn setup_logger() -> Result<()> { pub async fn setup_logger() -> Result<()> {
Builder::new() Builder::new()
.format(move |buf, record| { .format(move |buf, record| {
writeln!( writeln!(
@ -20,5 +21,6 @@ pub fn setup_logger() -> Result<()> {
.target(env_logger::Target::Stdout) .target(env_logger::Target::Stdout)
.init(); .init();
info!("Logger configured");
Ok(()) Ok(())
} }

View File

@ -3,8 +3,11 @@ mod net;
mod logger; mod logger;
use anyhow::Result; use anyhow::Result;
use integr_structs::api::ApiConfig;
use logger::setup_logger; use logger::setup_logger;
use log::info; use log::{info, warn};
use config::{pull_local_config, init_config_grub_mechanism};
use net::init_api_grub_mechanism;
#[tokio::main(flavor = "multi_thread")] #[tokio::main(flavor = "multi_thread")]
async fn main() -> Result<()>{ async fn main() -> Result<()>{
@ -12,7 +15,27 @@ async fn main() -> Result<()>{
// 1) unix-socket coroutine (for config updating) // 1) unix-socket coroutine (for config updating)
// 2) api coroutine // 2) api coroutine
// 3) ? // 3) ?
setup_logger()?; setup_logger().await?;
info!("Logger configured"); let config = get_config().await;
// futures
let config_fut = init_config_grub_mechanism();
let grub_fut = init_api_grub_mechanism(&config);
let _ = tokio::join!(config_fut, grub_fut);
Ok(()) Ok(())
} }
async fn get_config() -> ApiConfig {
return match pull_local_config().await {
Ok(conf) => {
info!("Local config was loaded");
conf
},
Err(er) => {
warn!("Cannot get local config due to {}", er);
ApiConfig::default()
}
}
}

View File

@ -1,9 +1,15 @@
// module to handle unix-socket connection + pulling info from api // module to handle unix-socket connection + pulling info from api
use anyhow; use anyhow::Result;
use integr_structs::api::ApiConfig;
use log::info;
// for api info pulling // for api info pulling
async fn init_api_grub_mechanism() { pub async fn init_api_grub_mechanism(_config: &ApiConfig) -> Result<()> {
info!("Initializing API-info grubbing mechanism...");
Ok(())
} }
// one-time exec func to send request, deserialize it and return object
#[allow(dead_code)]
async fn send_api_request() -> Result<()> {Ok(())}

View File

@ -1,19 +1,23 @@
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize, Debug)]
pub struct ApiConfig { pub struct ApiConfig {
url : String, #[serde(default)]
method : String, endpoints : Vec<ApiEndpoint>,
delay : u32, delay : u32,
} }
#[derive(Serialize, Deserialize, Debug)]
pub struct ApiEndpoint {
url : String,
method : String,
}
impl Default for ApiConfig { impl Default for ApiConfig {
fn default() -> Self { fn default() -> Self {
ApiConfig { ApiConfig {
url : String::new(), endpoints : vec![],
method : String::new(),
delay : 0, delay : 0,
} }
} }