Compare commits

...

6 Commits

Author SHA1 Message Date
6e60f58145 wip: replace dyn Error with concrete 2023-11-27 13:09:53 +11:00
aabf39f041 wip: convert to thiserror and anyhow 2023-11-26 11:34:26 +11:00
c03adb808a wip: implement error kind 2023-11-25 19:09:01 +11:00
11e2a14cc4 wip: early integration 2023-11-25 15:46:49 +11:00
f40b8677ab wip: parsing cron 2023-11-23 17:23:53 +11:00
4049e4a953 wip: parsing crontab 2023-11-23 12:48:47 +11:00
13 changed files with 495 additions and 73 deletions

74
Cargo.lock generated
View File

@ -17,6 +17,21 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "aho-corasick"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6"
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.1.0" version = "1.1.0"
@ -95,6 +110,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7"
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.150" version = "0.2.150"
@ -223,6 +244,35 @@ dependencies = [
"bitflags 1.3.2", "bitflags 1.3.2",
] ]
[[package]]
name = "regex"
version = "1.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
[[package]] [[package]]
name = "rustc-demangle" name = "rustc-demangle"
version = "0.1.23" version = "0.1.23"
@ -271,6 +321,26 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "thiserror"
version = "1.0.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "tokio" name = "tokio"
version = "1.34.0" version = "1.34.0"
@ -396,7 +466,11 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
name = "wingmate-rs" name = "wingmate-rs"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow",
"lazy_static",
"nix", "nix",
"regex",
"thiserror",
"tokio", "tokio",
"tokio-util", "tokio-util",
] ]

View File

@ -6,6 +6,10 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
anyhow = "1.0.75"
lazy_static = "1.4.0"
nix = {version = "0.27.1", features = ["process", "signal", "fs"]} nix = {version = "0.27.1", features = ["process", "signal", "fs"]}
regex = "1.10.2"
thiserror = "1.0.50"
tokio = { version = "1.34.0", features = ["full"] } tokio = { version = "1.34.0", features = ["full"] }
tokio-util = "0.7.10" tokio-util = "0.7.10"

View File

@ -1,7 +1,7 @@
FROM ubuntu:22.04 FROM ubuntu:22.04
ADD target/debug/init /usr/local/bin/init ADD target/debug/init /usr/local/bin/init
ADD docker/ / ADD docker/etc/ /etc/
RUN chmod ugo+x /etc/wingmate/services/one && chmod ugo+x /etc/wingmate/services/two.sh && \ RUN chmod ugo+x /etc/wingmate/services/one && chmod ugo+x /etc/wingmate/services/two.sh && \
chmod ugo-x /etc/wingmate/services/three.sh chmod ugo-x /etc/wingmate/services/three.sh

View File

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

View File

@ -1,3 +1 @@
#!/bin/bash you cannot run this file
exec 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.into());
}
Ok(())
} }

View File

@ -2,10 +2,31 @@ mod daemon;
mod config; mod config;
pub(crate) mod error; pub(crate) mod error;
use std::error as std_err; use std::env;
use anyhow::Context;
pub async fn start() -> Result<(), Box<dyn std_err::Error>> { const WINGMATE_CONFIG_PATH: &'static str = "WINGMATE_CONFIG_PATH";
let _config = config::Config::find(vec![String::from("/etc/wingmate")])?;
dbg!(_config); pub async fn start() -> Result<(), error::WingmateInitError> {
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).context(format!("reading {} env var", WINGMATE_CONFIG_PATH))
.map_err(|e| {error::WingmateInitError::Other { source: e }} );
} else {
vec_search.push(String::from("/etc/wingmate"));
}
}
}
let config = config::Config::find(vec_search)?;
dbg!(&config);
daemon::start(config).await
} }

View File

@ -1,8 +1,24 @@
use std::fs; use std::fs;
use std::env;
use std::path::PathBuf; use std::path::PathBuf;
use std::error as std_error; use std::io::{BufReader, BufRead};
use crate::init::error as wingmate_error; use crate::init::error as wingmate_error;
use nix::unistd::{access, AccessFlags}; use nix::unistd::{access, AccessFlags};
use lazy_static::lazy_static;
use regex::Regex;
use anyhow::Context;
const CRON_REGEX_STR: &'static str = r"^\s*(?P<minute>\S+)\s+(?P<hour>\S+)\s+(?P<dom>\S+)\s+(?P<month>\S+)\s+(?P<dow>\S+)\s+(?P<command>\S.*\S)\s*$";
const MINUTE: &'static str = "minute";
const HOUR: &'static str = "hour";
const DAY_OF_MONTH_ABBRV: &'static str = "dom";
const DAY_OF_MONTH: &'static str = "day of month";
const MONTH: &'static str = "month";
const DAY_OF_WEEK_ABBRV: &'static str = "dow";
const DAY_OF_WEEK: &'static str = "day of week";
const COMMAND: &'static str = "command";
const WINGMATE_SHELL_ENV: &'static str = "WINGMATE_SHELL";
#[derive(Debug)] #[derive(Debug)]
pub enum Command { pub enum Command {
@ -10,19 +26,40 @@ pub enum Command {
Direct(String) Direct(String)
} }
#[derive(Debug)]
pub enum CronTimeFieldSpec {
Any,
Exact(u8),
MultiOccurrence(Vec<u8>),
Every(u8)
}
#[derive(Debug)]
pub struct Crontab {
pub minute: CronTimeFieldSpec,
pub hour: CronTimeFieldSpec,
pub day_of_month: CronTimeFieldSpec,
pub month: CronTimeFieldSpec,
pub day_of_week: CronTimeFieldSpec,
pub command: String,
}
#[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 {
pub fn find(search_path: Vec<String>) -> Result<Config, Box<dyn std_error::Error>> { pub fn find(search_path: Vec<String>) -> Result<Config, wingmate_error::WingmateInitError> {
if search_path.is_empty() { if search_path.is_empty() {
return Err(wingmate_error::InvalidConfigSearchPathError.into()); return Err(wingmate_error::WingmateInitError::InvalidConfigSearchPath.into());
} }
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()) {
@ -34,22 +71,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())));
} }
} }
} }
} }
let cron = buf.join("cron"); cron = Self::read_crontab(&mut buf).map_err(|e| { wingmate_error::WingmateInitError::Cron { source: e }})?;
if let Ok(cron_iter) = fs::read_dir(cron.as_path()) {
for entry in cron_iter { //TODO: need to include cron in the condition
if let Ok(_dirent) = entry { if !svc_commands.is_empty() || !cron.is_empty() {
// read the cron file 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
@ -57,11 +92,193 @@ 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::WingmateInitError::NoServiceOrCron.into());
} }
let config = Config { services: svc_commands }; let mut config = Config {
services: svc_commands,
cron,
shell_path: None,
};
config.find_shell().map_err(|e| { wingmate_error::WingmateInitError::FindShell { source: e } })?;
Ok(config) Ok(config)
} }
}
fn read_crontab(path: &mut PathBuf) -> Result<Vec<Crontab>, wingmate_error::CronParseError> {
lazy_static! {
static ref CRON_REGEX: Regex = Regex::new(CRON_REGEX_STR).unwrap();
}
let cron_path = path.join("crontab");
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::<wingmate_error::CronParseError>(
wingmate_error::CronParseError::InvalidSyntax(String::from(&l))
)?;
let mut match_str = cap.name(MINUTE).ok_or::<wingmate_error::CronParseError>(
wingmate_error::CronParseError::FieldMatch { cron_line: String::from(&l), field_name: String::from(MINUTE) }
)?;
let minute = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
wingmate_error::CronParseError::Parse {
source: e,
cron_line: String::from(&l),
matched: String::from(match_str.as_str()),
field_name: String::from(MINUTE)
}
})?;
match_str = cap.name(HOUR).ok_or::<wingmate_error::CronParseError>(
wingmate_error::CronParseError::FieldMatch { cron_line: String::from(&l), field_name: String::from(HOUR) }
)?;
let hour = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
wingmate_error::CronParseError::Parse {
source: e,
cron_line: String::from(&l),
matched: String::from(match_str.as_str()),
field_name: String::from(HOUR)
}
})?;
match_str = cap.name(DAY_OF_MONTH_ABBRV).ok_or::<wingmate_error::CronParseError>(
wingmate_error::CronParseError::FieldMatch { cron_line: String::from(&l), field_name: String::from(DAY_OF_MONTH) }
)?;
let dom = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
wingmate_error::CronParseError::Parse {
source: e,
cron_line: String::from(&l),
matched: String::from(match_str.as_str()),
field_name: String::from(DAY_OF_MONTH)
}
})?;
match_str = cap.name(MONTH).ok_or::<wingmate_error::CronParseError>(
wingmate_error::CronParseError::FieldMatch { cron_line: String::from(&l), field_name: String::from(MONTH) }
)?;
let month = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
wingmate_error::CronParseError::Parse {
source: e,
cron_line: String::from(&l),
matched: String::from(match_str.as_str()),
field_name: String::from(MONTH)
}
})?;
match_str = cap.name(DAY_OF_WEEK_ABBRV).ok_or::<wingmate_error::CronParseError>(
wingmate_error::CronParseError::FieldMatch { cron_line: String::from(&l), field_name: String::from(DAY_OF_WEEK) }
)?;
let dow = Self::to_cron_time_field_spec(&match_str).map_err(|e| {
wingmate_error::CronParseError::Parse {
source: e,
cron_line: String::from(&l),
matched: String::from(match_str.as_str()),
field_name: String::from(DAY_OF_WEEK)
}
})?;
match_str = cap.name(COMMAND).ok_or::<wingmate_error::CronParseError>(
wingmate_error::CronParseError::FieldMatch { cron_line: String::from(&l), field_name: String::from(COMMAND) }
)?;
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)
}
fn to_cron_time_field_spec(match_str: &regex::Match) -> Result<CronTimeFieldSpec, anyhow::Error> {
let field = match_str.as_str();
if field == "*" {
return Ok(CronTimeFieldSpec::Any);
} else if field.starts_with("*/") {
let every = field[2..].parse::<u8>().context("parsing on field matching \"every\" pattern")?;
return Ok(CronTimeFieldSpec::Every(every));
} else if field.contains(",") {
let multi: Vec<&str> = field.split(",").collect();
let mut multi_occurrence: Vec<u8> = Vec::new();
for m in multi {
let ur = m.parse::<u8>().context("parsing on field matching \"multi occurrence\" pattern")?;
multi_occurrence.push(ur);
}
return Ok(CronTimeFieldSpec::MultiOccurrence(multi_occurrence));
} else {
let n = field.parse::<u8>().context("parsing on field matching \"exact\" pattern")?;
return Ok(CronTimeFieldSpec::Exact(n));
}
}
fn find_shell(&mut self) -> Result<(), wingmate_error::FindShellError> {
let shell: String;
match env::var(WINGMATE_SHELL_ENV) {
Ok(sh) => {
shell = sh;
},
Err(e) => {
match e {
env::VarError::NotPresent => {
shell = String::from("sh");
},
env::VarError::NotUnicode(_) => {
return Err(e).context(format!("reading {} env var", WINGMATE_SHELL_ENV))
.map_err(|e| { wingmate_error::FindShellError::Other { source: e } })
}
}
}
}
let env_path = env::var("PATH").context("getting PATH env variable")
.map_err(|e| { wingmate_error::FindShellError::Other { source: e } })?;
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::FindShellError::ShellNotFound)
}
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

@ -3,12 +3,14 @@ mod waiter;
mod starter; mod starter;
mod constants; mod constants;
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;
use crate::init::error as wmerr;
use crate::init::error::WingmateInitError;
pub async fn start() -> Result<(), Box<dyn error::Error>> { pub async fn start(cfg: config::Config) -> Result<(), WingmateInitError> {
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();
@ -18,13 +20,13 @@ pub async fn start() -> Result<(), Box<dyn error::Error>> {
let cancel = CancellationToken::new(); let cancel = CancellationToken::new();
let starter_cancel = cancel.clone(); let starter_cancel = cancel.clone();
let mut set: JoinSet<Result<(), Box<dyn error::Error + Send + Sync>>> = JoinSet::new(); let mut set: JoinSet<Result<(), wmerr::WingmateInitError>> = JoinSet::new();
set.spawn(async move { set.spawn(async move {
sighandler::sighandler(sig_sync_flag, cancel, sighandler_cancel).await sighandler::sighandler(sig_sync_flag, cancel, sighandler_cancel).await
}); });
//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 || {
@ -37,12 +39,20 @@ pub async fn start() -> Result<(), Box<dyn error::Error>> {
Ok(v) => { Ok(v) => {
if let Err(ev) = v { if let Err(ev) = v {
dbg!(&ev); dbg!(&ev);
return Err(ev as Box<dyn error::Error>); match ev {
WingmateInitError::SpawnError { source, message } => {
eprintln!("{}", WingmateInitError::SpawnError { source, message });
},
_ => {
return Err(ev);
}
}
// return Err(ev as Box<dyn error::Error>);
} }
}, },
Err(e) => { Err(e) => {
dbg!(&e); dbg!(&e);
return Err(e.into()); return Err(WingmateInitError::Join { source: e });
}, },
} }
} }

View File

@ -1,13 +1,13 @@
use std::error;
use tokio::signal::unix::{signal, SignalKind}; use tokio::signal::unix::{signal, SignalKind};
use tokio::select; use tokio::select;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
use crate::init::error::WingmateInitError;
pub async fn sighandler(flag: Arc<Mutex<bool>>, cancel: CancellationToken, exit: CancellationToken) -> Result<(), Box<dyn error::Error + Send + Sync>> { pub async fn sighandler(flag: Arc<Mutex<bool>>, cancel: CancellationToken, exit: CancellationToken) -> Result<(), WingmateInitError> {
let mut sigint = signal(SignalKind::interrupt())?; let mut sigint = signal(SignalKind::interrupt()).map_err(|e| { WingmateInitError::Signal { source: e } })?;
let mut sigterm = signal(SignalKind::terminate())?; let mut sigterm = signal(SignalKind::terminate()).map_err(|e| { WingmateInitError::Signal { source: e } })?;
let mut sigchld = signal(SignalKind::child())?; let mut sigchld = signal(SignalKind::child()).map_err(|e| { WingmateInitError::Signal { source: e } })?;
'signal: loop { 'signal: loop {
select! { select! {

View File

@ -1,26 +1,49 @@
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;
use tokio::time::sleep; use tokio::time::sleep;
use std::time::Duration; use std::time::Duration;
use std::process::ExitStatus; use std::process::ExitStatus;
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 anyhow::Context;
use crate::init::config;
use crate::init::error::WingmateInitError;
pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + Sync>>>, cancel: CancellationToken) { pub fn start_services(ts: &mut JoinSet<Result<(), WingmateInitError>>, cfg: &config::Config, cancel: CancellationToken)
for _j in 0..5 { -> Result<(), WingmateInitError> {
for svc_ in cfg.get_service_iter() {
let mut shell: String = String::new();
if let config::Command::ShellPrefixed(_) = svc_ {
shell = cfg.get_shell().ok_or::<WingmateInitError>(WingmateInitError::NoShellAvailable)?;
}
let svc = svc_.clone();
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 svc = svc.clone();
.expect("failed to spawn"); match svc {
config::Command::Direct(c) => {
let exp_str = c.clone();
child = Command::new(c).spawn().map_err(|e| {
WingmateInitError::SpawnError { source: e, message: exp_str }
})?;
},
config::Command::ShellPrefixed(s) => {
let shell = shell.clone();
let exp_str = s.clone();
let exp_shell = shell.clone();
child = Command::new(shell).arg(s).spawn().map_err(|e| {
WingmateInitError::SpawnError { source: e, message: format!("{} {}", exp_shell, exp_str) }
})?;
}
}
select! { select! {
_ = cancel.cancelled() => { _ = cancel.cancelled() => {
@ -33,7 +56,7 @@ pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + S
}, },
result = child.wait() => { result = child.wait() => {
if let Err(e) = result_match(result) { if let Err(e) = result_match(result) {
return Err(e); return Err(WingmateInitError::ChildExit { source: e });
} }
break 'autorestart; break 'autorestart;
} }
@ -41,7 +64,7 @@ pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + S
}, },
Err(e) => { Err(e) => {
if e != Errno::ESRCH { if e != Errno::ESRCH {
return Err(e.into()); return Err(WingmateInitError::ChildNotFound);
} else { } else {
break 'autorestart; break 'autorestart;
} }
@ -53,32 +76,33 @@ pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + S
}, },
result = child.wait() => { result = child.wait() => {
if let Err(e) = result_match(result) { if let Err(e) = result_match(result) {
return Err(e); return Err(WingmateInitError::ChildExit { source: e });
} }
}, },
} }
} }
println!("starter: task completed"); dbg!("starter: task completed");
Ok(()) Ok(())
}); });
} }
println!("starter: spawning completed"); dbg!("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<(), anyhow::Error> {
if let Err(e) = result { if let Err(e) = result {
if let Some(eos) = e.raw_os_error() { if let Some(eos) = e.raw_os_error() {
if eos != nix::Error::ECHILD as i32 { if eos != nix::Error::ECHILD as i32 {
return Err(e.into()); return Err(e).context("unexpected child exit status");
} }
} else { } else {
return Err(e.into()); return Err(e).context("unexpected child error");
} }
} }
//TODO: remove me! this is for debug + tracing purpose dbg!("starter: sleep exited");
println!("starter: sleep exited");
Ok(()) Ok(())
} }

View File

@ -37,7 +37,6 @@ pub fn wait_all(flag: Arc<Mutex<bool>>, stop_sighandler: CancellationToken) {
} }
}, },
} }
// dbg!("sanity");
} }
} }

View File

@ -1,25 +1,92 @@
use std::fmt; use thiserror::Error;
use std::error;
#[derive(Debug, Clone)] #[derive(Error,Debug)]
pub struct InvalidConfigSearchPathError; pub enum WingmateInitError {
#[error("invalid config search path")]
InvalidConfigSearchPath,
impl fmt::Display for InvalidConfigSearchPathError { #[error("no service or cron found")]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { NoServiceOrCron,
write!(f, "invalid config search path")
#[error("failed to spawn: {}", message)]
SpawnError {
#[source]
source: std::io::Error,
message: String,
},
#[error("parsing cron")]
Cron {
#[source]
source: CronParseError,
},
#[error("looking for shell")]
FindShell {
#[source]
source: FindShellError,
},
#[error("child exited")]
ChildExit {
#[source]
source: anyhow::Error,
},
#[error("cannot find the child process")]
ChildNotFound,
#[error("failed to setup signal handler")]
Signal {
#[source]
source: std::io::Error,
},
#[error("no shell available")]
NoShellAvailable,
#[error("problem when join task")]
Join {
#[source]
source: tokio::task::JoinError,
},
#[error("tripped over")]
Other {
#[source]
source: anyhow::Error,
} }
} }
impl error::Error for InvalidConfigSearchPathError {} #[derive(Error,Debug)]
pub enum CronParseError {
#[error("invalid cron syntax: {}", .0)]
InvalidSyntax(String),
#[error("cannot capture {} in \"{}\"", field_name, cron_line)]
FieldMatch {
cron_line: String,
field_name: String,
},
#[error("failed to parse {} \"{}\" in \"{}\"", field_name, matched, cron_line)]
#[derive(Debug,Clone)] Parse {
pub struct NoServiceOrCronFoundError; #[source]
source: anyhow::Error,
impl fmt::Display for NoServiceOrCronFoundError { cron_line: String,
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { matched: String,
write!(f, "no service or cron found") field_name: String,
} }
} }
impl error::Error for NoServiceOrCronFoundError {} #[derive(Error,Debug)]
pub enum FindShellError {
#[error("shell not found")]
ShellNotFound,
#[error("when finding shell")]
Other {
#[source]
source: anyhow::Error
}
}