From 0b699949a7a68a9db359a085f7dbc92807eff7fb Mon Sep 17 00:00:00 2001 From: Federico Ponzi Date: Sun, 20 Aug 2023 22:38:57 +0100 Subject: [PATCH] horust compiling and tests passing --- Cargo.lock | 275 ++++++-------------------- commands/src/lib.rs | 47 ++++- commands/tests/simple.rs | 7 +- horust/src/horust/commands_handler.rs | 53 ++++- horust/src/horust/healthcheck/mod.rs | 18 +- horust/src/horust/mod.rs | 22 +-- horust/src/horust/uds_messages.rs | 6 - horust/src/main.rs | 10 +- horustctl/Cargo.toml | 2 + horustctl/src/main.rs | 21 +- 10 files changed, 191 insertions(+), 270 deletions(-) delete mode 100644 horust/src/horust/uds_messages.rs diff --git a/Cargo.lock b/Cargo.lock index caaac27..5e2b6d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -137,7 +137,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40723b8fb387abc38f4f4a37c09073622e41dd12327033091ef8950659e6dc0c" dependencies = [ "memchr", - "regex-automata 0.4.8", + "regex-automata", "serde", ] @@ -331,6 +331,19 @@ dependencies = [ "regex", ] +[[package]] +name = "env_logger" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" +dependencies = [ + "humantime", + "is-terminal", + "log", + "regex", + "termcolor", +] + [[package]] name = "env_logger" version = "0.11.5" @@ -487,6 +500,12 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + [[package]] name = "horust" version = "0.1.8" @@ -496,7 +515,8 @@ dependencies = [ "bytefmt", "clap", "crossbeam", - "env_logger", + "env_logger 0.11.5", + "horust-commands-lib", "humantime-serde", "libc", "log", @@ -518,13 +538,12 @@ name = "horust-commands-lib" version = "0.1.0" dependencies = [ "anyhow", + "env_logger 0.10.2", + "log", "prost", "prost-build", "serde", "serde_json", - "tokio", - "tracing", - "tracing-test", ] [[package]] @@ -534,7 +553,8 @@ dependencies = [ "anyhow", "clap", "crossbeam", - "env_logger", + "env_logger 0.11.5", + "horust-commands-lib", "log", ] @@ -658,6 +678,17 @@ version = "2.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708" +[[package]] +name = "is-terminal" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" +dependencies = [ + "hermit-abi 0.4.0", + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.1" @@ -688,12 +719,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - [[package]] name = "libc" version = "0.2.161" @@ -716,16 +741,6 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" -[[package]] -name = "lock_api" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" -dependencies = [ - "autocfg", - "scopeguard", -] - [[package]] name = "log" version = "0.4.22" @@ -738,15 +753,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" -[[package]] -name = "matchers" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" -dependencies = [ - "regex-automata 0.1.10", -] - [[package]] name = "memchr" version = "2.7.4" @@ -774,7 +780,7 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" dependencies = [ - "hermit-abi", + "hermit-abi 0.3.9", "libc", "wasi", "windows-sys 0.52.0", @@ -804,16 +810,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" -[[package]] -name = "nu-ansi-term" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" -dependencies = [ - "overload", - "winapi", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -844,35 +840,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" -[[package]] -name = "overload" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" - -[[package]] -name = "parking_lot" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-targets 0.52.6", -] - [[package]] name = "percent-encoding" version = "2.3.1" @@ -1088,15 +1055,6 @@ dependencies = [ "rand_core 0.3.1", ] -[[package]] -name = "redox_syscall" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" -dependencies = [ - "bitflags", -] - [[package]] name = "redox_users" version = "0.4.6" @@ -1116,17 +1074,8 @@ checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.8", - "regex-syntax 0.8.5", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" -dependencies = [ - "regex-syntax 0.6.29", + "regex-automata", + "regex-syntax", ] [[package]] @@ -1137,15 +1086,9 @@ checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.5", + "regex-syntax", ] -[[package]] -name = "regex-syntax" -version = "0.6.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" - [[package]] name = "regex-syntax" version = "0.8.5" @@ -1222,12 +1165,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - [[package]] name = "serde" version = "1.0.214" @@ -1281,15 +1218,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shellexpand" version = "3.1.0" @@ -1305,15 +1233,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" -[[package]] -name = "signal-hook-registry" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" -dependencies = [ - "libc", -] - [[package]] name = "slab" version = "0.4.9" @@ -1388,6 +1307,15 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "termtree" version = "0.4.1" @@ -1414,16 +1342,6 @@ dependencies = [ "syn", ] -[[package]] -name = "thread_local" -version = "1.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" -dependencies = [ - "cfg-if", - "once_cell", -] - [[package]] name = "tinyvec" version = "1.8.0" @@ -1446,28 +1364,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "145f3413504347a2be84393cc8a7d2fb4d863b375909ea59f2158261aa258bbb" dependencies = [ "backtrace", - "bytes", "libc", "mio", - "parking_lot", "pin-project-lite", - "signal-hook-registry", "socket2", - "tokio-macros", "windows-sys 0.52.0", ] -[[package]] -name = "tokio-macros" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "toml" version = "0.8.19" @@ -1515,21 +1418,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "pin-project-lite", - "tracing-attributes", "tracing-core", ] -[[package]] -name = "tracing-attributes" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "tracing-core" version = "0.1.32" @@ -1537,57 +1428,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "regex", - "sharded-slab", - "smallvec", - "thread_local", - "tracing", - "tracing-core", - "tracing-log", -] - -[[package]] -name = "tracing-test" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "557b891436fe0d5e0e363427fc7f217abf9ccd510d5136549847bdcbcd011d68" -dependencies = [ - "tracing-core", - "tracing-subscriber", - "tracing-test-macro", -] - -[[package]] -name = "tracing-test-macro" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04659ddb06c87d233c566112c1c9c5b9e98256d9af50ec3bc9c8327f873a7568" -dependencies = [ - "quote", - "syn", ] [[package]] @@ -1634,12 +1474,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" -[[package]] -name = "valuable" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" - [[package]] name = "wait-timeout" version = "0.2.0" @@ -1757,6 +1591,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +dependencies = [ + "windows-sys 0.59.0", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/commands/src/lib.rs b/commands/src/lib.rs index 4d6974a..af56afa 100644 --- a/commands/src/lib.rs +++ b/commands/src/lib.rs @@ -10,7 +10,7 @@ use crate::proto::messages::{ use anyhow::{anyhow, Context, Result}; use log::{error, info}; use prost::Message; -use std::io::{Read, Write}; +use std::io::{ErrorKind, Read, Write}; use std::net::Shutdown; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::{Path, PathBuf}; @@ -33,7 +33,10 @@ pub trait CommandsHandlerTrait { } } Err(e) => { - error!("Error accepting connction: {e} - you might need to restart Horust."); + let kind = e.kind(); + if !matches!(ErrorKind::WouldBlock, kind) { + error!("Error accepting connction: {e} - you might need to restart Horust."); + } } }; Ok(()) @@ -79,13 +82,41 @@ pub struct ClientHandler { uds_connection_handler: UdsConnectionHandler, } impl ClientHandler { - pub fn new_client(socket_path: PathBuf) -> Result { + pub fn new_client(socket_path: &Path) -> Result { Ok(Self { uds_connection_handler: UdsConnectionHandler::new( UnixStream::connect(socket_path).context("Could not create stream")?, ), }) } + pub fn send_status_request( + &mut self, + service_name: String, + ) -> Result<(String, HorustMsgServiceStatus)> { + let status = HorustMsgMessage { + request_type: Some(RequestType::StatusRequest(HorustMsgServiceStatusRequest { + service_name, + })), + }; + self.uds_connection_handler.send_message(status)?; + // server is waiting for EOF. + self.uds_connection_handler + .socket + .shutdown(Shutdown::Write)?; + //Reads all bytes until EOF in this source, appending them to buf. + let received = self.uds_connection_handler.receive_message()?; + info!("Client: received: {received:?}"); + match received + .request_type + .ok_or(anyhow!("Error receiving message"))? + { + RequestType::StatusResponse(resp) => Ok(( + resp.service_name, + HorustMsgServiceStatus::from_i32(resp.service_status).unwrap(), + )), + _ => unreachable!(), + } + } pub fn client(mut self, service_name: String) -> Result<()> { let status = HorustMsgMessage { @@ -105,14 +136,16 @@ impl ClientHandler { } } +/// socket_name should be the pid of the horust process. +pub fn get_path(socket_folder: &Path, socket_name: i32) -> PathBuf { + socket_folder.join(format!("hourst-{socket_name}.sock")) +} + pub struct UdsConnectionHandler { socket: UnixStream, } impl UdsConnectionHandler { - fn get_path(socket_folder: &Path, socket_name: u32) -> PathBuf { - socket_folder.join(format!("hourst-{socket_name}.sock")) - } - fn new(socket: UnixStream) -> Self { + pub fn new(socket: UnixStream) -> Self { Self { socket } } pub fn send_message(&mut self, message: HorustMsgMessage) -> Result<()> { diff --git a/commands/tests/simple.rs b/commands/tests/simple.rs index afaf654..cfb7ffc 100644 --- a/commands/tests/simple.rs +++ b/commands/tests/simple.rs @@ -26,6 +26,7 @@ impl CommandsHandlerTrait for MockCommandsHandler { fn get_service_status(&self, service_name: String) -> HorustMsgServiceStatus { match service_name.as_str() { "Running" => HorustMsgServiceStatus::Running, + "Started" => HorustMsgServiceStatus::Started, _ => unimplemented!(), } } @@ -50,12 +51,16 @@ fn test_simple() -> Result<()> { info!("uds created"); barrier_server.wait(); uds.accept().unwrap(); + uds.accept().unwrap(); }); let c_handle = thread::spawn(move || { barrier_client.wait(); - let client = ClientHandler::new_client(socket_path).unwrap(); + let client = ClientHandler::new_client(&socket_path).unwrap(); client.client("Running".into()).unwrap(); + + let client = ClientHandler::new_client(&socket_path).unwrap(); + client.client("Started".into()).unwrap(); }); s_handle.join().unwrap(); c_handle.join().unwrap(); diff --git a/horust/src/horust/commands_handler.rs b/horust/src/horust/commands_handler.rs index 371791c..6a88b2d 100644 --- a/horust/src/horust/commands_handler.rs +++ b/horust/src/horust/commands_handler.rs @@ -1,31 +1,64 @@ use crate::horust::bus::BusConnector; +use crate::horust::formats::{ServiceName, ServiceStatus}; use crate::horust::Event; use horust_commands_lib::{CommandsHandlerTrait, HorustMsgServiceStatus}; +use std::collections::HashMap; use std::os::unix::net::UnixListener; use std::path::PathBuf; -use std::thread; use std::thread::JoinHandle; +use std::time::Duration; +use std::{fs, thread}; -pub fn spawn(bus: BusConnector, uds_folder_path: PathBuf) -> JoinHandle<()> { +pub fn spawn( + bus: BusConnector, + uds_path: PathBuf, + services: Vec, +) -> JoinHandle<()> { thread::spawn(move || { - run(bus, uds_folder_path); + let mut commands_handler = CommandsHandler::new(bus, uds_path, services); + commands_handler.run(); }) } -fn run(bus: BusConnector, uds_folder_path: PathBuf) { - let mut commands_handler = CommandsHandler::new(bus, uds_folder_path); - commands_handler.start(); -} - struct CommandsHandler { bus: BusConnector, + services: HashMap, uds_listener: UnixListener, + uds_path: PathBuf, } + impl CommandsHandler { - fn new(bus: BusConnector, uds_folder_path: PathBuf) -> Self { + fn new(bus: BusConnector, uds_path: PathBuf, services: Vec) -> Self { + let mut uds_listener = UnixListener::bind(&uds_path).unwrap(); + uds_listener.set_nonblocking(true).unwrap(); Self { bus, - uds_listener: UnixListener::bind(uds_folder_path).unwrap(), + uds_path, + uds_listener, + services: services + .into_iter() + .map(|s| (s, ServiceStatus::Initial)) + .collect(), + } + } + fn run(&mut self) { + loop { + let evs = self.bus.try_get_events(); + for ev in evs { + match ev { + Event::StatusChanged(name, status) => { + let k = self.services.get_mut(&name).unwrap(); + *k = status; + } + Event::ShuttingDownInitiated(_) => { + fs::remove_file(&self.uds_path).unwrap(); + return; + } + _ => {} + } + } + self.accept().unwrap(); + thread::sleep(Duration::from_millis(300)); } } } diff --git a/horust/src/horust/healthcheck/mod.rs b/horust/src/horust/healthcheck/mod.rs index 13a47fd..9938d6e 100644 --- a/horust/src/horust/healthcheck/mod.rs +++ b/horust/src/horust/healthcheck/mod.rs @@ -1,6 +1,8 @@ //! If a service has defined an healthchecker, this module will spawn a worker to making sure that //! the service is working as supposed to. +use std::net::{SocketAddrV4, TcpListener}; +use std::sync::mpsc; use std::thread; use std::thread::JoinHandle; use std::time::Duration; @@ -153,10 +155,6 @@ mod test { use crate::horust::formats::{Healthiness, HealthinessStatus}; use crate::horust::healthcheck::check_health; - fn check_health_w(healthiness: &Healthiness) -> bool { - check_health(healthiness) == HealthinessStatus::Healthy - } - #[test] fn test_healthiness_check_file() -> Result<()> { let tempdir = TempDir::new("health")?; @@ -166,11 +164,11 @@ mod test { http_endpoint: None, ..Default::default() }; - assert!(!check_health_w(&healthiness)); + assert_ne!(check_health(&healthiness), HealthinessStatus::Healthy); std::fs::write(file_path, "Hello world!")?; - assert!(check_health_w(&healthiness)); + assert_eq!(check_health(&healthiness), HealthinessStatus::Healthy); let healthiness: Healthiness = Default::default(); - assert!(check_health_w(&healthiness)); + assert_eq!(check_health(&healthiness), HealthinessStatus::Healthy); Ok(()) } @@ -193,7 +191,7 @@ mod test { http_endpoint: Some("http://localhost:123/".into()), ..Default::default() }; - assert!(!check_health_w(&healthiness)); + assert_ne!(check_health(&healthiness), HealthinessStatus::Healthy); let loopback = Ipv4Addr::new(127, 0, 0, 1); let socket = SocketAddrV4::new(loopback, 0); let listener = TcpListener::bind(socket)?; @@ -209,11 +207,11 @@ mod test { handle_request(listener).unwrap(); sender.send(()).expect("Chan closed"); }); - assert!(check_health_w(&healthiness)); + assert_eq!(check_health(&healthiness), HealthinessStatus::Healthy); receiver .recv_timeout(Duration::from_millis(2000)) .expect("Failed to received response from handle_request"); - assert!(!check_health_w(&healthiness)); + assert_ne!(check_health(&healthiness), HealthinessStatus::Healthy); Ok(()) } } diff --git a/horust/src/horust/mod.rs b/horust/src/horust/mod.rs index 7cad9e0..bb24a1f 100644 --- a/horust/src/horust/mod.rs +++ b/horust/src/horust/mod.rs @@ -21,26 +21,22 @@ mod formats; mod healthcheck; mod signal_safe; mod supervisor; -mod uds_messages; #[derive(Debug)] pub struct Horust { services: Vec, - uds_folder_path: PathBuf, + uds_path: PathBuf, } impl Horust { - fn new(services: Vec, uds_folder_path: PathBuf) -> Self { - Horust { - services, - uds_folder_path, - } + fn new(services: Vec, uds_path: PathBuf) -> Self { + Horust { services, uds_path } } /// Creates a new Horust instance from a command. /// The command will be wrapped in a service and run with sane defaults - pub fn from_command(command: String, uds_folder_path: PathBuf) -> Self { - Self::new(vec![Service::from_command(command)], uds_folder_path) + pub fn from_command(command: String, uds_path: PathBuf) -> Self { + Self::new(vec![Service::from_command(command)], uds_path) } fn load_services_from_folders(paths: &[PathBuf]) -> Result> { @@ -54,10 +50,10 @@ impl Horust { .collect::>>() } /// Create a new horust instance from multiple paths of services. - pub fn from_services_dirs(paths: &[PathBuf], uds_folder_path: PathBuf) -> Result { + pub fn from_services_dirs(paths: &[PathBuf], uds_path: PathBuf) -> Result { let services = Self::load_services_from_folders(paths)?; let services = validate(services)?; - Ok(Horust::new(services, uds_folder_path)) + Ok(Horust::new(services, uds_path)) } /// Blocking call, will setup the event loop and the threads and run all the available services. @@ -84,9 +80,9 @@ impl Horust { // Spawn helper threads: healthcheck::spawn(dispatcher.join_bus(), self.services.clone()); commands_handler::spawn( - self.uds_folder_path.clone(), dispatcher.join_bus(), - self.services.clone(), + self.uds_path.clone(), + self.services.iter().map(|s| s.name.clone()).collect(), ); let handle = supervisor::spawn(dispatcher.join_bus(), self.services.clone()); dispatcher.run(); diff --git a/horust/src/horust/uds_messages.rs b/horust/src/horust/uds_messages.rs deleted file mode 100644 index 8032f5f..0000000 --- a/horust/src/horust/uds_messages.rs +++ /dev/null @@ -1,6 +0,0 @@ -use serde::{Deserialize, Serialize}; - -#[derive(Deserialize, Serialize)] -enum Messages { - Status(Option), -} diff --git a/horust/src/main.rs b/horust/src/main.rs index 404afc8..c64784b 100644 --- a/horust/src/main.rs +++ b/horust/src/main.rs @@ -5,6 +5,7 @@ use clap::Parser; use horust::horust::ExitStatus; use horust::Horust; use log::{error, info}; +use nix::unistd::getpid; #[derive(clap::Parser, Debug)] #[clap(author, about)] @@ -50,7 +51,7 @@ fn main() -> Result<()> { } if !opts.uds_folder_path.exists() { - std::fs::create_dir_all(opts.uds_folder_path)?; + std::fs::create_dir_all(&opts.uds_folder_path)?; } if !opts.uds_folder_path.is_dir() { @@ -59,12 +60,14 @@ fn main() -> Result<()> { opts.uds_folder_path ); } + let uds_path = horust_commands_lib::get_path(&opts.uds_folder_path, getpid().into()); + let mut horust = if opts.command.is_empty() { info!( "Loading services from {}", display_directories(&opts.services_paths) ); - Horust::from_services_dirs(&opts.services_paths).with_context(|| { + Horust::from_services_dirs(&opts.services_paths, uds_path).with_context(|| { format!( "Failed loading services from {}", display_directories(&opts.services_paths) @@ -72,9 +75,8 @@ fn main() -> Result<()> { })? } else { info!("Running command: {:?}", opts.command); - Horust::from_command(opts.command.join(" ")) + Horust::from_command(opts.command.join(" "), uds_path) }; - horust.set_uds_folder_path(); if let ExitStatus::SomeServiceFailed = horust.run() { if opts.unsuccessful_exit_finished_failed { diff --git a/horustctl/Cargo.toml b/horustctl/Cargo.toml index adb4f26..744ed30 100644 --- a/horustctl/Cargo.toml +++ b/horustctl/Cargo.toml @@ -10,3 +10,5 @@ log = "~0.4" env_logger = "~0.11" crossbeam = "~0.8" clap = { version = "~4.5", features = ["derive"] } +horust-commands-lib = {path = "../commands"} + diff --git a/horustctl/src/main.rs b/horustctl/src/main.rs index b11b77f..16d19b4 100644 --- a/horustctl/src/main.rs +++ b/horustctl/src/main.rs @@ -1,10 +1,12 @@ use anyhow::{bail, Result}; use clap::{Args, Parser, Subcommand}; use env_logger::Env; +use horust_commands_lib::{ClientHandler, UdsConnectionHandler}; use log::{debug, error}; use std::env; use std::fs::{read, read_dir}; use std::io::Write; +use std::os::linux::raw::stat; use std::os::unix::net::UnixStream; use std::path::{Path, PathBuf}; @@ -12,13 +14,17 @@ use std::path::{Path, PathBuf}; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct HourstctlArgs { - /// Optional if only one horust is running in the system. + /// The pid of the horust process you want to query. Optional if only one horust is running in the system. #[arg(short, long)] pid: Option, #[arg(short, long, default_value = "/var/run/horust/")] sockets_folder_path: PathBuf, + // Specify the full path of the socket. It takes precedence other over arguments. + #[arg(long)] + socket_path: Option, + #[command(subcommand)] commands: Commands, } @@ -38,11 +44,20 @@ fn main() -> Result<()> { let args = HourstctlArgs::parse(); debug!("args: {args:?}"); - let uds_path = get_uds_path(args.pid, args.sockets_folder_path)?; + let uds_path = args.socket_path.unwrap_or_else(|| { + get_uds_path(args.pid, args.sockets_folder_path).expect("Failed to get uds_path.") + }); + let mut uds_handler = ClientHandler::new_client(&uds_path)?; match &args.commands { Commands::Status(status_args) => { debug!("Status command received: {status_args:?}"); - debug!("uds path : {uds_path:?}") + debug!("uds path : {uds_path:?}"); + let (service_name, service_status) = + uds_handler.send_status_request(status_args.service_name.clone().unwrap())?; + println!( + "Current status for '{service_name}' is: '{}'.", + service_status.as_str_name() + ); } } Ok(())