From 39fb7c55b97d7209f4e4e6d42db9372422c450194342c6fe99be02deca14f0f8 Mon Sep 17 00:00:00 2001 From: kira Date: Sun, 13 Sep 2026 22:54:00 +0200 Subject: [PATCH] Removing daemon functionality completely. --- files/dinit.service | 5 - files/hive-up.toml | 5 - src/daemon.rs | 246 ------------------------------------------- src/hive_config.rs | 11 -- src/hive_db.rs | 95 ----------------- src/hive_intercom.rs | 195 ---------------------------------- src/main.rs | 87 +++------------ 7 files changed, 16 insertions(+), 628 deletions(-) delete mode 100644 files/dinit.service delete mode 100644 src/daemon.rs delete mode 100644 src/hive_db.rs delete mode 100644 src/hive_intercom.rs diff --git a/files/dinit.service b/files/dinit.service deleted file mode 100644 index 368ca53..0000000 --- a/files/dinit.service +++ /dev/null @@ -1,5 +0,0 @@ -type = process -command = /usr/bin/hive-up daemon -depends-on = network.target -logfile = /var/log/dinit/hive-up.log -log-type = file diff --git a/files/hive-up.toml b/files/hive-up.toml index befc3eb..6b05df2 100644 --- a/files/hive-up.toml +++ b/files/hive-up.toml @@ -1,9 +1,4 @@ # Section (Table) headers -[update] -# Interval between updates check in hours. 0 - no auto check for updates. -check_interval = 58 -# Tells hive-up to automatically download updates when awailable. -download_updates = true # In [kernel] section user may specify kernel cmd # [kernel] diff --git a/src/daemon.rs b/src/daemon.rs deleted file mode 100644 index b161761..0000000 --- a/src/daemon.rs +++ /dev/null @@ -1,246 +0,0 @@ -// -// Copyright (C) <2026> - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -/* - hive-up daemon logic -*/ - -use std::os::unix::net::UnixDatagram; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::thread; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use crate::hive_config; -use crate::hive_config::HiveConfig; -use crate::hive_db::{self, HiveDb}; -use crate::hive_intercom::{self, BzzReq, BzzResp, IntercomError}; -use crate::hive_system; - -#[derive(Debug)] -pub enum DaemonError { - IoError(std::io::Error), - DBError(hive_db::DBError), - ConfigError(hive_config::ConfigError), - ExecCommandError(hive_system::ExecCommandError), - TimestampError, -} - -// 2. Implement From for each wrapped error type -impl From for DaemonError { - fn from(err: std::io::Error) -> Self { - DaemonError::IoError(err) - } -} - -impl From for DaemonError { - fn from(err: hive_db::DBError) -> Self { - DaemonError::DBError(err) - } -} - -impl From for DaemonError { - fn from(err: hive_config::ConfigError) -> Self { - DaemonError::ConfigError(err) - } -} - -impl From for DaemonError { - fn from(err: hive_system::ExecCommandError) -> Self { - DaemonError::ExecCommandError(err) - } -} - -impl std::fmt::Display for DaemonError { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - DaemonError::IoError(e) => write!(f, "IO Error: {}", e), - DaemonError::DBError(e) => write!(f, "Database error: {}", e), - DaemonError::ConfigError(e) => write!(f, "Config Error: {}", e), - DaemonError::ExecCommandError(e) => write!(f, "Exec Command Error: {}", e), - DaemonError::TimestampError => write!(f, "Timestamp Error"), - } - } -} - -// Implement std::error::Error -impl std::error::Error for DaemonError {} - -fn get_timestamp_sec() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("Time went backwards") - .as_secs() -} - -/// bloking function. Bloaks for configured socker recv timeout -fn process_remoute( - bzz_db: &mut HiveDb, - listening_socket: &UnixDatagram, - recv_buf: &mut [u8], -) -> Result<(), DaemonError> { - // waiting on socket recv_from untill timeout (also using this as a timer) - match hive_intercom::socket_recv(&listening_socket, recv_buf) { - // we get some request to process - Ok((bzz_req, client_addr)) => { - match bzz_req { - // return awailable updates number - BzzReq::UpdatesAvailable => { - let resp = BzzResp::UpdatesAvailable(bzz_db.updates_available); - if let Err(ex) = - hive_intercom::socket_send(&listening_socket, &client_addr, resp) - { - println!("Error while ansvering cli request: {}", ex); - } - } - BzzReq::CheckForUpdates => { - let resp = BzzResp::Working(1); - if let Err(ex) = - hive_intercom::socket_send(&listening_socket, &client_addr, resp) - { - println!("Error while ansvering cli request: {}", ex); - } else { - // perform update check - println!("Cheking for updates..."); - // now that may fail because of bad internet and idealy we - // want to just log error and retry in other time - bzz_db.updates_available = match hive_system::check_updates() { - Ok(updates_num) => updates_num, - Err(ex) => { - println!("Error while shecking for updates: {}", ex); - 0u32 - } - }; - hive_db::write_db(&bzz_db)?; - println!( - "Found {} packages that needs to be updated.", - bzz_db.updates_available - ); - // send evailable updates numbet to client - let resp = BzzResp::UpdatesAvailable(bzz_db.updates_available); - if let Err(ex) = - hive_intercom::socket_send(&listening_socket, &client_addr, resp) - { - println!("Error while ansvering cli request: {}", ex); - } - } - } - } - Ok(()) - } - // if time out - do nothing - Err(IntercomError::Timeout) => Ok(()), - // if some actual IO error then return it - Err(IntercomError::IoError(ex)) => Err(ex.into()), - // if other kinds of errors - log and continue - Err(ex) => { - println!("Got error while listenin to unix socket: {}", ex); - print!("Sleeping for 1 secong and continue..."); - thread::sleep(Duration::from_secs(1)); - Ok(()) - } - } -} - -// doing what daemons usually beezz -fn do_local_work(config: &HiveConfig, bzz_db: &mut HiveDb) -> Result<(), DaemonError> { - // if updates check is turned on - if config.update.check_interval != 0 { - let timestamp = get_timestamp_sec(); - - // calculate how many hours passed sinse last update - let hours_since_update_check = timestamp - .checked_sub(bzz_db.update_check_timestamp) - .ok_or(DaemonError::TimestampError)? - / 3600; - - // if more than updates_check_interval specifiyed in config - check for updates - if hours_since_update_check > config.update.check_interval { - // perform update check - println!("Cheking for updates..."); - // now that may fail because of bad internet and idealy we - // want to just log error and retry in other time - bzz_db.updates_available = match hive_system::check_updates() { - Ok(updates_num) => updates_num, - Err(ex) => { - println!("Error while shecking for updates: {}", ex); - 0u32 - } - }; - hive_db::write_db(&bzz_db)?; - println!( - "Found {} packages that needs to be updated.", - bzz_db.updates_available - ); - - // if auto download for updates is enabled and there is some updates - download them - if config.update.download_updates && bzz_db.updates_available != 0 { - println!("Downloadin updates..."); - match hive_system::download_updates() { - Ok(()) => { - println!("Updates downloaded..."); - } - Err(ex) => { - println!("Error downloading updates: {}", ex); - } - } - } - - // updating las tcheck for updates timestamp in db - bzz_db.update_check_timestamp = get_timestamp_sec(); - hive_db::write_db(&bzz_db)?; - } - } - Ok(()) -} - -pub fn run( - mut bzz_config: HiveConfig, - term_flag: Arc, - reload_flag: Arc, -) -> Result<(), DaemonError> { - // reading db from disk - let mut bzz_db = hive_db::read_db()?; - - // stop flag - let mut keep_going = true; - - // init udp unix socket for communication with cli and such - let listening_socket = hive_intercom::socket_bind(1)?; - let mut recv_buf: Vec = Vec::with_capacity(1024); - - // main loop (I love loops) (No please just do recursion properly) - while keep_going { - process_remoute(&mut bzz_db, &listening_socket, recv_buf.as_mut_slice())?; - do_local_work(&bzz_config, &mut bzz_db)?; - // check termination flags - if term_flag.load(Ordering::Relaxed) { - println!("SIGTERM recieved - wrapping things up."); - keep_going = false; - } - - // checking reload signal flag - if reload_flag.load(Ordering::Relaxed) { - println!("SIGHUP recieved - reloading config and DB."); - bzz_config = hive_config::read_config()?; - bzz_db = hive_db::read_db()?; - println!("Reloaded!"); - } - } - - println!("Exiting..."); - Ok(()) -} diff --git a/src/hive_config.rs b/src/hive_config.rs index 521440d..9695fa6 100644 --- a/src/hive_config.rs +++ b/src/hive_config.rs @@ -28,8 +28,6 @@ const CONFIG_PATH: &str = "/etc/hive-up.toml"; pub struct HiveConfig { // Matches [kernel] in TOML pub kernel: Option, - // Updates [update] in TOML - pub update: UpdateConfig, } #[derive(Debug, Serialize, Deserialize)] @@ -38,15 +36,6 @@ pub struct KernelConfig { pub cmd: Option, } -#[derive(Debug, Serialize, Deserialize)] -pub struct UpdateConfig { - /// Interval between updates check in hours. 0 - no auto check for updates. - pub check_interval: u64, - /// Tells hive-up to automatically download updates when awailable. - pub download_updates: bool, - /// Tells hive-up to automatically perform updates during system reboot. - pub auto_update: bool, -} #[derive(Debug)] pub enum ConfigError { diff --git a/src/hive_db.rs b/src/hive_db.rs deleted file mode 100644 index 2a2dd92..0000000 --- a/src/hive_db.rs +++ /dev/null @@ -1,95 +0,0 @@ -// -// Copyright (C) <2026> - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -/* - Functions for reading and writyng daemon and updates state -*/ - -const DB_PATH: &str = "/var/lib/hive-up/hyve-db.json"; - -use serde::{Deserialize, Serialize}; -use std::fs; - -#[derive(Debug)] -pub enum DBError { - IoError(std::io::Error), - JsonError(serde_json::Error), -} - -// 2. Implement From for each wrapped error type -impl From for DBError { - fn from(err: std::io::Error) -> Self { - DBError::IoError(err) - } -} - -impl From for DBError { - fn from(err: serde_json::Error) -> Self { - DBError::JsonError(err) - } -} - -impl std::fmt::Display for DBError { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - DBError::IoError(e) => write!(f, "IO Error: {}", e), - DBError::JsonError(e) => { - write!(f, "Json parse error: {}", e) - } - } - } -} - -// Implement std::error::Error -impl std::error::Error for DBError {} - -#[derive(Serialize, Deserialize, Debug)] -pub struct HiveDb { - /// Timestamp of last check for updates in seconds from UNIX_EPOCH - pub update_check_timestamp: u64, - /// non zero if there is updates that can bee applied, showing numbers of packages that can be updated - pub updates_available: u32, -} - -fn init_db() -> Result { - let bzz_db = HiveDb{ - update_check_timestamp: 0, - updates_available: 0, - }; - write_db(&bzz_db)?; - Ok(bzz_db) -} - -pub fn read_db() -> Result { - if fs::exists(DB_PATH)? { - let file_content = fs::read_to_string(DB_PATH)?; - let db: HiveDb = serde_json::from_str(&file_content)?; - Ok(db) - } - else { - println!("WARNING database file do not exist {}", DB_PATH); - print!("Creating default db file..."); - init_db() - } -} - -pub fn write_db(db: &HiveDb) -> Result<(), DBError> { - let serialized_db = serde_json::to_string(db)?; - fs::write(DB_PATH, serialized_db)?; - Ok(()) -} - - diff --git a/src/hive_intercom.rs b/src/hive_intercom.rs deleted file mode 100644 index 990b7f0..0000000 --- a/src/hive_intercom.rs +++ /dev/null @@ -1,195 +0,0 @@ -// -// Copyright (C) <2026> - -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with this program. If not, see . - -/* - hive-up unix socket communication -*/ - -use postcard; -use serde::{Deserialize, Serialize}; -use std::fs; -use std::os::unix::net::{SocketAddr, UnixDatagram}; -use std::time::Duration; - -pub const SOCKET_DIR: &str = "/run/hive-up"; -pub const SOCKET_PATH: &str = "/run/hive-up/hive-intercom.soc"; -pub const CLINET_READ_TIMEOUT_SECONDS: u64 = 88; - -#[derive(Debug)] -pub enum IntercomError { - IoError(std::io::Error), - PostcardError(postcard::Error), - ConnectionClosed, - Timeout, - UnexpectedResponse, - ServerError(String), -} - -// Wrapping IO errors but separating time out error -impl From for IntercomError { - fn from(err: std::io::Error) -> Self { - if err.kind() == std::io::ErrorKind::TimedOut - || err.kind() == std::io::ErrorKind::WouldBlock - { - IntercomError::Timeout - } else { - IntercomError::IoError(err) - } - } -} - -impl From for IntercomError { - fn from(err: postcard::Error) -> Self { - IntercomError::PostcardError(err) - } -} - -impl From for IntercomError { - fn from(err: String) -> Self { - IntercomError::ServerError(err) - } -} - -impl std::fmt::Display for IntercomError { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - IntercomError::IoError(e) => write!(f, "IO Error: {}", e), - IntercomError::PostcardError(e) => { - write!(f, "Data parsing (postcard) error: {}", e) - } - IntercomError::Timeout => write!(f, "Operation Timeout"), - IntercomError::ConnectionClosed => write!(f, "Connection closed"), - IntercomError::UnexpectedResponse => write!(f, "Unexpected response"), - IntercomError::ServerError(err) => write!(f, "Server side error: {}", err), - } - } -} - -// Implement std::error::Error -impl std::error::Error for IntercomError {} - -#[derive(Debug, PartialEq, Serialize, Deserialize)] -pub enum BzzResp { - /// signalls progress of a task as u16 integer. - /// interpretation is up to you. - Working(u16), - Finish, - UpdatesAvailable(u32), - Error(String), -} - -#[derive(Debug, PartialEq, Serialize, Deserialize)] -#[repr(u8)] -pub enum BzzReq { - UpdatesAvailable, - CheckForUpdates, -} - -pub fn socket_bind(read_timeout_sec: u64) -> Result { - // create socket directory if it is does not exist - if let Ok(path_exist) = fs::exists(SOCKET_DIR) - && path_exist == false - { - fs::create_dir(SOCKET_DIR)?; - } - // remove socket file if any present - let _ = fs::remove_file(SOCKET_PATH); - - // bind datagram unix socket - let socket = UnixDatagram::bind(SOCKET_PATH)?; - socket.set_read_timeout(Some(Duration::from_secs(read_timeout_sec)))?; - Ok(socket) -} - -// for daemon side -pub fn socket_send( - socket: &UnixDatagram, - client_addr: &SocketAddr, - resp: BzzResp, -) -> Result<(), IntercomError> { - let resp_buff = postcard::to_stdvec(&resp)?; - socket.send_to_addr(resp_buff.as_slice(), client_addr)?; - Ok(()) -} - -// for daemon side -pub fn socket_recv( - socket: &UnixDatagram, - recv_buf: &mut [u8], -) -> Result<(BzzReq, SocketAddr), IntercomError> { - match socket.recv_from(recv_buf) { - Ok((rec_count, client_addr)) => { - if rec_count != 0 { - println!("DEBUG: Total bytes recieved {}", rec_count); - let decoded_req: BzzReq = postcard::from_bytes(&recv_buf)?; - Ok((decoded_req, client_addr)) - } else { - Err(IntercomError::ConnectionClosed) - } - } - Err(ex) => Err(ex.into()), - } -} - -fn send_and_recv(request: BzzReq) -> Result { - let socket = UnixDatagram::unbound()?; - socket.connect(SOCKET_PATH)?; - socket.set_read_timeout(Some(Duration::from_secs(CLINET_READ_TIMEOUT_SECONDS)))?; - - let encoded_buf = postcard::to_stdvec(&request)?; - - socket.send(encoded_buf.as_slice())?; - - let mut recv_buf: Vec = Vec::with_capacity(1024); - - loop { - match socket.recv(recv_buf.as_mut_slice()) { - Ok(rec_count) => { - if rec_count != 0 { - println!("DEBUG: Total bytes recieved {}", rec_count); - let decoded_resp: BzzResp = postcard::from_bytes(&recv_buf)?; - if let BzzResp::Working(progress) = decoded_resp { - println!("Working... {}", progress); - continue; - } else { - return Ok(decoded_resp); - } - } else { - return Err(IntercomError::ConnectionClosed); - } - } - Err(e) => return Err(e.into()), - } - } -} - -pub fn client_updates_available() -> Result { - let resp = send_and_recv(BzzReq::UpdatesAvailable)?; - match resp { - BzzResp::UpdatesAvailable(updates_count) => Ok(updates_count), - BzzResp::Error(ex) => Err(IntercomError::ServerError(ex)), - _ => Err(IntercomError::UnexpectedResponse), - } -} - -pub fn client_check_for_updates() -> Result { - let resp = send_and_recv(BzzReq::CheckForUpdates)?; - match resp { - BzzResp::UpdatesAvailable(updates_count) => Ok(updates_count), - BzzResp::Error(ex) => Err(IntercomError::ServerError(ex)), - _ => Err(IntercomError::UnexpectedResponse), - } -} diff --git a/src/main.rs b/src/main.rs index 3f81af9..94f63f2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,18 +24,11 @@ mod hive_system; mod hive_config; -mod daemon; -mod hive_db; -mod hive_intercom; - #[derive(Debug)] pub enum HiveUpError { IoError(std::io::Error), HiveSystemCommandError(hive_system::ExecCommandError), - HiveDbError(hive_db::DBError), HiveConfigError(hive_config::ConfigError), - HiveIntercomError(hive_intercom::IntercomError), - HiveDaemonErr(daemon::DaemonError), Other(String), } @@ -51,30 +44,12 @@ impl From for HiveUpError { } } -impl From for HiveUpError { - fn from(err: hive_db::DBError) -> Self { - HiveUpError::HiveDbError(err) - } -} - impl From for HiveUpError { fn from(err: hive_config::ConfigError) -> Self { HiveUpError::HiveConfigError(err) } } -impl From for HiveUpError { - fn from(err: hive_intercom::IntercomError) -> Self { - HiveUpError::HiveIntercomError(err) - } -} - -impl From for HiveUpError { - fn from(err: daemon::DaemonError) -> Self { - HiveUpError::HiveDaemonErr(err) - } -} - impl From for HiveUpError { fn from(err: String) -> Self { HiveUpError::Other(err) @@ -92,10 +67,7 @@ impl std::fmt::Display for HiveUpError { match self { HiveUpError::IoError(e) => write!(f, "IO Error: {}", e), HiveUpError::HiveSystemCommandError(e) => write!(f, "ExecCommandError: {}", e), - HiveUpError::HiveDbError(ex) => write!(f, "DBError: {}", ex), HiveUpError::HiveConfigError(ex) => write!(f, "Config error: {}", ex), - HiveUpError::HiveIntercomError(e) => write!(f, "IntercomError: {}", e), - HiveUpError::HiveDaemonErr(e) => write!(f, "HiveDaemonErr: {}", e), HiveUpError::Other(msg) => write!(f, "Error: {}", msg), } } @@ -104,42 +76,23 @@ impl std::fmt::Display for HiveUpError { // Implement std::error::Error impl std::error::Error for HiveUpError {} -// Define the mutually exclusive group -#[derive(Args, Debug)] -#[group(required = true, multiple = false)] -struct RemoteArgs { - /// Ask daemon to check for updates - #[arg(long)] - check_updates: bool, - - /// Ask daemon if there is any updates available - #[arg(long)] - updates_avail: bool, -} - -#[derive(Args, Debug)] -#[group(required = true, multiple = false)] -struct CliArgs { +#[derive(Subcommand, Debug)] +#[group(required = true)] +enum BootCommand { /// Install new kernel into boot partition - #[arg(long)] - update_boot: bool, + Update, /// Cleans up and recreates UFI boot menu - #[arg(long)] - init_boot_menu: bool, + InitEfiMenu, /// Cleans up and recreates UFI boot menu and /EFI dir content - #[arg(long)] - init_boot: bool, + Init, } #[derive(Subcommand, Debug)] #[group(required = true)] // 'multiple = false' enforces exclusivity enum HiveUpMode { - /// Perform local operations - Cli(CliArgs), - /// Ask hive-up daemon something - Remote(RemoteArgs), - /// Run hive-up in daemon mode - Daemon, + /// Manage system boot + #[command(subcommand)] + Boot(BootCommand), } /// Update program fot Kira Linux :3 @@ -169,16 +122,17 @@ fn main() -> Result<(), HiveUpError> { let bzz_config = hive_config::read_config()?; match args.mode { - HiveUpMode::Daemon => daemon::run(bzz_config, term_flag.clone(), reload_flag.clone())?, - HiveUpMode::Cli(cli_args) => { - if cli_args.update_boot { + HiveUpMode::Boot(boot_submode) => match boot_submode { + BootCommand::Update => { println!("Updating boot..."); hive_system::boot_update()?; - } else if cli_args.init_boot_menu { + } + BootCommand::InitEfiMenu => { println!("Init EFI boot menu..."); let kernel_cmd = bzz_config.kernel.and_then(|kk| kk.cmd.clone()); hive_system::init_efi_boot_record(&kernel_cmd)?; - } else if cli_args.init_boot { + } + BootCommand::Init => { println!("Init EFI boot menu and EFI partition content..."); println!("Init EFI Partition content..."); let kernel_cmd = bzz_config.kernel.and_then(|kk| kk.cmd.clone()); @@ -186,16 +140,7 @@ fn main() -> Result<(), HiveUpError> { println!("Init EFI boot menu..."); hive_system::init_efi_boot_partition_content()?; } - } - HiveUpMode::Remote(remote_args) => { - if remote_args.check_updates { - let up_num = hive_intercom::client_check_for_updates()?; - println!("Updates awailable: {}", up_num); - } else if remote_args.updates_avail { - let up_num = hive_intercom::client_updates_available()?; - println!("Updates awailable: {}", up_num); - } - } + }, } Ok(())