wip: early integration
This commit is contained in:
parent
f40b8677ab
commit
11e2a14cc4
3
docker/etc/wingmate/crontab
Normal file
3
docker/etc/wingmate/crontab
Normal file
@ -0,0 +1,3 @@
|
||||
17 * * * * sleep 1
|
||||
*/12 * * * * sleep 1
|
||||
12,17,27 * * * * sleep 1
|
||||
@ -4,5 +4,10 @@ use wingmate_rs::init;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn error::Error>> {
|
||||
init::start().await
|
||||
if let Err(e) = init::start().await {
|
||||
eprintln!("{}", e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
24
src/init.rs
24
src/init.rs
@ -2,10 +2,28 @@ mod daemon;
|
||||
mod config;
|
||||
pub(crate) mod error;
|
||||
|
||||
use std::env;
|
||||
use std::error as std_err;
|
||||
|
||||
pub async fn start() -> Result<(), Box<dyn std_err::Error>> {
|
||||
let _config = config::Config::find(vec![String::from("/etc/wingmate")])?;
|
||||
dbg!(_config);
|
||||
daemon::start().await
|
||||
let mut vec_search: Vec<String> = Vec::new();
|
||||
|
||||
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
|
||||
}
|
||||
@ -1,4 +1,5 @@
|
||||
use std::fs;
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::io::{BufReader, BufRead};
|
||||
use std::error as std_error;
|
||||
@ -34,6 +35,8 @@ pub struct Crontab {
|
||||
#[derive(Debug)]
|
||||
pub struct Config {
|
||||
pub services: Vec<Command>,
|
||||
pub cron: Vec<Crontab>,
|
||||
shell_path: Option<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@ -43,7 +46,8 @@ impl Config {
|
||||
}
|
||||
|
||||
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();
|
||||
buf.push(p);
|
||||
if let Ok(m) = fs::metadata(buf.as_path()) {
|
||||
@ -55,17 +59,20 @@ impl Config {
|
||||
let ep = dirent.path();
|
||||
if let Ok(_) = access(ep.as_path(), AccessFlags::X_OK) {
|
||||
// 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 {
|
||||
// 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) {
|
||||
//TODO: fix me! empty branch
|
||||
cron = Self::read_crontab(&mut buf)?;
|
||||
|
||||
//TODO: need to include cron in the condition
|
||||
if !svc_commands.is_empty() || !cron.is_empty() {
|
||||
break 'search;
|
||||
}
|
||||
} else {
|
||||
// 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());
|
||||
}
|
||||
|
||||
let config = Config { services: svc_commands };
|
||||
let mut config = Config {
|
||||
services: svc_commands,
|
||||
cron,
|
||||
shell_path: None,
|
||||
};
|
||||
config.find_shell()?;
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
@ -89,24 +102,65 @@ impl Config {
|
||||
}
|
||||
|
||||
let cron_path = path.join("crontab");
|
||||
|
||||
{
|
||||
let f = fs::File::open(cron_path.as_path())?;
|
||||
let mut ret_vec: Vec<Crontab> = Vec::new();
|
||||
|
||||
if let Ok(f) = fs::File::open(cron_path.as_path()) {
|
||||
for line in BufReader::new(f).lines() {
|
||||
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 mut match_str = cap.name("minute").ok_or::<Box<dyn std_error::Error>>(wingmate_error::CronSyntaxError(String::from("cannot capture minute")).into())?;
|
||||
let _minute = Self::to_cron_time_field_spec(&match_str)?;
|
||||
|
||||
match_str = cap.name("hour").ok_or::<Box<dyn std_error::Error>>(wingmate_error::CronSyntaxError(String::from("cannot capture hour")).into())?;
|
||||
let _hour = Self::to_cron_time_field_spec(&match_str)?;
|
||||
let mut match_str = cap.name("minute").ok_or::<Box<dyn std_error::Error>>(
|
||||
wingmate_error::CronSyntaxError(format!("cannot capture minute in \"{}\"", &l)).into()
|
||||
)?;
|
||||
let minute = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
|
||||
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())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Err(wingmate_error::NoServiceOrCronFoundError.into())
|
||||
|
||||
Ok(ret_vec)
|
||||
}
|
||||
|
||||
fn to_cron_time_field_spec(match_str: ®ex::Match) -> Result<CronTimeFieldSpec, Box<dyn std_error::Error>> {
|
||||
@ -132,4 +186,60 @@ impl Config {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,8 +7,9 @@ use std::error;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
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 sig_sync_flag = sync_flag.clone();
|
||||
|
||||
@ -24,7 +25,7 @@ pub async fn start() -> Result<(), Box<dyn error::Error>> {
|
||||
});
|
||||
|
||||
//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
|
||||
set.spawn_blocking(move || {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::process::Command;
|
||||
use tokio::process::{Command, Child};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio::select;
|
||||
use tokio::io::Result as tokio_result;
|
||||
@ -10,17 +10,33 @@ use std::error;
|
||||
use nix::sys::signal::{kill, Signal};
|
||||
use nix::errno::Errno;
|
||||
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) {
|
||||
for _j in 0..5 {
|
||||
pub fn start_services(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + Sync>>>, cfg: &config::Config, cancel: CancellationToken)
|
||||
-> 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();
|
||||
ts.spawn(async move {
|
||||
'autorestart: loop {
|
||||
let mut child = Command::new("sleep").arg("1")
|
||||
.spawn()
|
||||
.expect("failed to spawn");
|
||||
|
||||
let mut child: Child;
|
||||
let shell = shell.clone();
|
||||
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! {
|
||||
_ = cancel.cancelled() => {
|
||||
@ -64,6 +80,8 @@ pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + S
|
||||
|
||||
}
|
||||
println!("starter: spawning completed");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn result_match(result: tokio_result<ExitStatus>) -> Result<(), Box<dyn error::Error + Send + Sync>> {
|
||||
|
||||
@ -24,7 +24,7 @@ impl fmt::Display for NoServiceOrCronFoundError {
|
||||
|
||||
impl error::Error for NoServiceOrCronFoundError {}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug,Clone)]
|
||||
pub struct CronSyntaxError(pub String);
|
||||
|
||||
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 {}
|
||||
Loading…
x
Reference in New Issue
Block a user