wip: early integration

This commit is contained in:
Suyono 2023-11-25 15:46:49 +11:00
parent f40b8677ab
commit 11e2a14cc4
7 changed files with 211 additions and 34 deletions

View File

@ -0,0 +1,3 @@
17 * * * * sleep 1
*/12 * * * * sleep 1
12,17,27 * * * * sleep 1

View File

@ -4,5 +4,10 @@ use wingmate_rs::init;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn error::Error>> { async fn main() -> Result<(), Box<dyn error::Error>> {
init::start().await if let Err(e) = init::start().await {
eprintln!("{}", e);
return Err(e);
}
Ok(())
} }

View File

@ -2,10 +2,28 @@ mod daemon;
mod config; mod config;
pub(crate) mod error; pub(crate) mod error;
use std::env;
use std::error as std_err; use std::error as std_err;
pub async fn start() -> Result<(), Box<dyn std_err::Error>> { pub async fn start() -> Result<(), Box<dyn std_err::Error>> {
let _config = config::Config::find(vec![String::from("/etc/wingmate")])?; let mut vec_search: Vec<String> = Vec::new();
dbg!(_config);
daemon::start().await match env::var("WINGMATE_CONFIG_PATH") {
Ok(paths) => {
for p in paths.split(':') {
vec_search.push(String::from(p));
}
},
Err(e) => {
if let env::VarError::NotUnicode(_) = e {
return Err(e.into());
} else {
vec_search.push(String::from("/etc/wingmate"));
}
}
}
let config = config::Config::find(vec_search)?;
dbg!(&config);
daemon::start(config).await
} }

View File

@ -1,4 +1,5 @@
use std::fs; use std::fs;
use std::env;
use std::path::PathBuf; use std::path::PathBuf;
use std::io::{BufReader, BufRead}; use std::io::{BufReader, BufRead};
use std::error as std_error; use std::error as std_error;
@ -34,6 +35,8 @@ pub struct Crontab {
#[derive(Debug)] #[derive(Debug)]
pub struct Config { pub struct Config {
pub services: Vec<Command>, pub services: Vec<Command>,
pub cron: Vec<Crontab>,
shell_path: Option<String>,
} }
impl Config { impl Config {
@ -43,7 +46,8 @@ impl Config {
} }
let mut svc_commands: Vec<Command> = Vec::new(); let mut svc_commands: Vec<Command> = Vec::new();
for p in search_path { let mut cron : Vec<Crontab> = Vec::new();
'search: for p in search_path {
let mut buf = PathBuf::new(); let mut buf = PathBuf::new();
buf.push(p); buf.push(p);
if let Ok(m) = fs::metadata(buf.as_path()) { if let Ok(m) = fs::metadata(buf.as_path()) {
@ -55,17 +59,20 @@ impl Config {
let ep = dirent.path(); let ep = dirent.path();
if let Ok(_) = access(ep.as_path(), AccessFlags::X_OK) { if let Ok(_) = access(ep.as_path(), AccessFlags::X_OK) {
// execute directly // execute directly
svc_commands.push(Command::Direct(String::from(ep.as_path().to_string_lossy()))); svc_commands.push(Command::Direct(String::from(ep.to_string_lossy())));
} else { } else {
// call with shell // call with shell
svc_commands.push(Command::ShellPrefixed(String::from(ep.as_path().to_string_lossy()))); svc_commands.push(Command::ShellPrefixed(String::from(ep.to_string_lossy())));
} }
} }
} }
} }
if let Ok(_crontab) = Self::read_crontab(&mut buf) { cron = Self::read_crontab(&mut buf)?;
//TODO: fix me! empty branch
//TODO: need to include cron in the condition
if !svc_commands.is_empty() || !cron.is_empty() {
break 'search;
} }
} else { } else {
// reserve for future use; when we have a centralized config file // reserve for future use; when we have a centralized config file
@ -73,11 +80,17 @@ impl Config {
} }
} }
if svc_commands.is_empty() { if svc_commands.is_empty() && cron.is_empty() {
return Err(wingmate_error::NoServiceOrCronFoundError.into()); return Err(wingmate_error::NoServiceOrCronFoundError.into());
} }
let config = Config { services: svc_commands }; let mut config = Config {
services: svc_commands,
cron,
shell_path: None,
};
config.find_shell()?;
Ok(config) Ok(config)
} }
@ -89,24 +102,65 @@ impl Config {
} }
let cron_path = path.join("crontab"); let cron_path = path.join("crontab");
let mut ret_vec: Vec<Crontab> = Vec::new();
{
let f = fs::File::open(cron_path.as_path())?; if let Ok(f) = fs::File::open(cron_path.as_path()) {
for line in BufReader::new(f).lines() { for line in BufReader::new(f).lines() {
if let Ok(l) = line { if let Ok(l) = line {
let cap = CRON_REGEX.captures(&l).ok_or::<Box<dyn std_error::Error>>(wingmate_error::CronSyntaxError(String::from(&l)).into())?; let cap = CRON_REGEX.captures(&l).ok_or::<Box<dyn std_error::Error>>(wingmate_error::CronSyntaxError(String::from(&l)).into())?;
let mut match_str = cap.name("minute").ok_or::<Box<dyn std_error::Error>>(wingmate_error::CronSyntaxError(String::from("cannot capture minute")).into())?; let mut match_str = cap.name("minute").ok_or::<Box<dyn std_error::Error>>(
let _minute = Self::to_cron_time_field_spec(&match_str)?; wingmate_error::CronSyntaxError(format!("cannot capture minute in \"{}\"", &l)).into()
)?;
match_str = cap.name("hour").ok_or::<Box<dyn std_error::Error>>(wingmate_error::CronSyntaxError(String::from("cannot capture hour")).into())?; let minute = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
let _hour = Self::to_cron_time_field_spec(&match_str)?; Box::new(wingmate_error::CronSyntaxError(format!("failed to parse minute \"{}\" in \"{}\": {}", &match_str.as_str(), &l, e)))
})?;
match_str = cap.name("hour").ok_or::<Box<dyn std_error::Error>>(
wingmate_error::CronSyntaxError(format!("cannot capture hour in \"{}\"", &l)).into()
)?;
let hour = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
Box::new(wingmate_error::CronSyntaxError(format!("failed to parse hour \"{}\" in \"{}\": {}", &match_str.as_str(), &l, e)))
})?;
match_str = cap.name("dom").ok_or::<Box<dyn std_error::Error>>(
wingmate_error::CronSyntaxError(format!("cannot capture day of month in \"{}\"", &l)).into()
)?;
let dom = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
Box::new(wingmate_error::CronSyntaxError(format!("failed to parse day of month \"{}\" in \"{}\": {}", &match_str.as_str(), &l, e)))
})?;
match_str = cap.name("month").ok_or::<Box<dyn std_error::Error>>(
wingmate_error::CronSyntaxError(format!("cannot capture month in \"{}\"", &l)).into()
)?;
let month = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
Box::new(wingmate_error::CronSyntaxError(format!("failed to parse month \"{}\" in \"{}\": {}", &match_str.as_str(), &l, e)))
})?;
match_str = cap.name("dow").ok_or::<Box<dyn std_error::Error>>(
wingmate_error::CronSyntaxError(format!("cannot capture day of week in \"{}\"", &l)).into()
)?;
let dow = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
Box::new(wingmate_error::CronSyntaxError(format!("failed to parse day of week \"{}\" in \"{}\": {}", &match_str.as_str(), &l, e)))
})?;
match_str = cap.name("command").ok_or::<Box<dyn std_error::Error>>(
wingmate_error::CronSyntaxError(format!("cannot capture command in \"{}\"", &l)).into()
)?;
ret_vec.push(Crontab {
minute,
hour,
day_of_month: dom,
month,
day_of_week: dow,
command: String::from(match_str.as_str())
})
} }
} }
} }
Ok(ret_vec)
Err(wingmate_error::NoServiceOrCronFoundError.into())
} }
fn to_cron_time_field_spec(match_str: &regex::Match) -> Result<CronTimeFieldSpec, Box<dyn std_error::Error>> { fn to_cron_time_field_spec(match_str: &regex::Match) -> Result<CronTimeFieldSpec, Box<dyn std_error::Error>> {
@ -132,4 +186,60 @@ impl Config {
return Ok(CronTimeFieldSpec::Exact(n)); return Ok(CronTimeFieldSpec::Exact(n));
} }
} }
}
fn find_shell(&mut self) -> Result<(), Box<dyn std_error::Error>> {
let shell: String;
match env::var("WINGMATE_SHELL") {
Ok(sh) => {
shell = sh;
},
Err(e) => {
match e {
env::VarError::NotPresent => {
shell = String::from("sh");
},
env::VarError::NotUnicode(_) => {
return Err(e.into());
}
}
}
}
let env_path = env::var("PATH")?;
let vec_path: Vec<&str> = env_path.split(':').collect();
for p in vec_path {
let mut search_path = PathBuf::new();
search_path.push(p);
let shell_path = search_path.join(&shell);
if let Ok(_) = fs::metadata(shell_path.as_path()) {
self.shell_path = Some(String::from(shell_path.to_string_lossy()));
return Ok(());
}
}
Err(wingmate_error::ShellNotFoundError(shell).into())
}
pub fn get_service_iter(&self) -> std::slice::Iter<Command> {
self.services.iter()
}
pub fn get_shell(&self) -> Option<String> {
if let Some(shell) = &self.shell_path {
return Some(shell.clone());
}
None
}
}
impl Clone for Command {
fn clone(&self) -> Self {
match self {
Command::Direct(d) => Command::Direct(String::from(d)),
Command::ShellPrefixed(s) => Command::ShellPrefixed(String::from(s))
}
}
}

View File

@ -7,8 +7,9 @@ use std::error;
use tokio::task::JoinSet; use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use crate::init::config;
pub async fn start() -> Result<(), Box<dyn error::Error>> { pub async fn start(cfg: config::Config) -> Result<(), Box<dyn error::Error>> {
let sync_flag = Arc::new(Mutex::new(false)); let sync_flag = Arc::new(Mutex::new(false));
let sig_sync_flag = sync_flag.clone(); let sig_sync_flag = sync_flag.clone();
@ -24,7 +25,7 @@ pub async fn start() -> Result<(), Box<dyn error::Error>> {
}); });
//TODO: start the process starter //TODO: start the process starter
starter::start_process(&mut set, starter_cancel); starter::start_services(&mut set, &cfg, starter_cancel)?;
//TODO: spawn_blocking for waiter //TODO: spawn_blocking for waiter
set.spawn_blocking(move || { set.spawn_blocking(move || {

View File

@ -1,5 +1,5 @@
use tokio::task::JoinSet; use tokio::task::JoinSet;
use tokio::process::Command; use tokio::process::{Command, Child};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
use tokio::select; use tokio::select;
use tokio::io::Result as tokio_result; use tokio::io::Result as tokio_result;
@ -10,17 +10,33 @@ use std::error;
use nix::sys::signal::{kill, Signal}; use nix::sys::signal::{kill, Signal};
use nix::errno::Errno; use nix::errno::Errno;
use nix::unistd::Pid; use nix::unistd::Pid;
use crate::init::config;
use crate::init::error::NoShellAvailableError;
pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + Sync>>>, cancel: CancellationToken) { pub fn start_services(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + Sync>>>, cfg: &config::Config, cancel: CancellationToken)
for _j in 0..5 { -> Result<(), Box<dyn error::Error>> {
for svc_ in cfg.get_service_iter() {
let shell: String = cfg.get_shell().ok_or::<Box<dyn error::Error>>(NoShellAvailableError.into())?;
let svc = svc_.clone();
// if let config::Command::ShellPrefixed(_) = svc {
// shell = cfg.get_shell().ok_or::<Box<dyn error::Error>>(NoShellAvailableError.into())?;
// }
let cancel = cancel.clone(); let cancel = cancel.clone();
ts.spawn(async move { ts.spawn(async move {
'autorestart: loop { 'autorestart: loop {
let mut child = Command::new("sleep").arg("1") let mut child: Child;
.spawn() let shell = shell.clone();
.expect("failed to spawn"); let svc = svc.clone();
match svc {
config::Command::Direct(c) => {
child = Command::new(c).spawn().expect("change me");
},
config::Command::ShellPrefixed(s) => {
child = Command::new(shell).arg(s).spawn().expect("change me");
}
}
select! { select! {
_ = cancel.cancelled() => { _ = cancel.cancelled() => {
@ -64,6 +80,8 @@ pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + S
} }
println!("starter: spawning completed"); println!("starter: spawning completed");
Ok(())
} }
fn result_match(result: tokio_result<ExitStatus>) -> Result<(), Box<dyn error::Error + Send + Sync>> { fn result_match(result: tokio_result<ExitStatus>) -> Result<(), Box<dyn error::Error + Send + Sync>> {

View File

@ -24,7 +24,7 @@ impl fmt::Display for NoServiceOrCronFoundError {
impl error::Error for NoServiceOrCronFoundError {} impl error::Error for NoServiceOrCronFoundError {}
#[derive(Debug)] #[derive(Debug,Clone)]
pub struct CronSyntaxError(pub String); pub struct CronSyntaxError(pub String);
impl fmt::Display for CronSyntaxError { impl fmt::Display for CronSyntaxError {
@ -33,4 +33,26 @@ impl fmt::Display for CronSyntaxError {
} }
} }
impl error::Error for CronSyntaxError {} impl error::Error for CronSyntaxError {}
#[derive(Debug,Clone)]
pub struct ShellNotFoundError(pub String);
impl fmt::Display for ShellNotFoundError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "shell not found: {}", self.0)
}
}
impl error::Error for ShellNotFoundError {}
#[derive(Debug,Clone)]
pub struct NoShellAvailableError;
impl fmt::Display for NoShellAvailableError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "no shell available")
}
}
impl error::Error for NoShellAvailableError {}