diff --git a/src/action/mod.rs b/src/action/mod.rs new file mode 100644 index 0000000..ee66949 --- /dev/null +++ b/src/action/mod.rs @@ -0,0 +1,4 @@ +mod ports_tree; + +pub(crate) use ports_tree::update_ports_tree; +pub(crate) use ports_tree::ACTION_UPDATE_PORTS_TREE; diff --git a/src/action/ports_tree.rs b/src/action/ports_tree.rs new file mode 100644 index 0000000..b4c4c74 --- /dev/null +++ b/src/action/ports_tree.rs @@ -0,0 +1,25 @@ +use std::process::Command; +use std::time::Duration; +use std::time::SystemTime; + +use crate::db::DbHandle; + +pub(crate) const ACTION_UPDATE_PORTS_TREE: &str = "update_ports_tree"; +const ACTION_UPDATE_PORTS_TREE_INTERVAL: u64 = 86400; + +pub(crate) fn update_ports_tree(db_conn: &mut DbHandle) -> Result<(), Box> { + println!("Updating ports tree."); + Command::new("portshaker").arg("-U").status()?; + Command::new("portshaker").arg("-M").status()?; + let next_run = (SystemTime::now() + Duration::from_secs(ACTION_UPDATE_PORTS_TREE_INTERVAL)) + .duration_since(SystemTime::UNIX_EPOCH)? + .as_secs(); + + let tx = db_conn.conn.transaction()?; + tx.execute( + "UPDATE global_action SET next_run=$1 WHERE name=$2", + (next_run, ACTION_UPDATE_PORTS_TREE), + )?; + tx.commit()?; + Ok(()) +} diff --git a/src/db/init.rs b/src/db/init.rs index d37366c..a0a3629 100644 --- a/src/db/init.rs +++ b/src/db/init.rs @@ -11,7 +11,7 @@ use super::DbLocalAction; static DB_INIT_QUERY: &str = include_str!("../../migrations/01_init.sql"); pub(crate) struct DbHandle { - conn: Connection, + pub(crate) conn: Connection, } impl DbHandle { diff --git a/src/main.rs b/src/main.rs index 100f05f..cc4751c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,8 @@ use std::{thread, time}; +use crate::action::update_ports_tree; + +mod action; mod db; fn main() -> Result<(), Box> { @@ -9,6 +12,19 @@ fn main() -> Result<(), Box> { let mut db_conn: db::DbHandle = db::DbHandle::new(db_path)?; loop { + for pending_global_action in db_conn.get_pending_global_actions()? { + match pending_global_action.name.as_str() { + ACTION_UPDATE_PORTS_TREE => { + update_ports_tree(&mut db_conn)?; + } + _ => { + panic!("Unknown global action: {}", pending_global_action.name); + } + }; + } + + let pending_local_actions = db_conn.get_pending_local_actions()?; + let time_until_next_action = db_conn.get_time_until_next_action()?; let sleep_duration = std::cmp::min( time::Duration::from_secs(60),