Compare commits

..

No commits in common. "6e60f58145e2f0e30dadf083043738f911a5c39c" and "6e85e129932f8ef7fb92af33facede6fbff7b378" have entirely different histories.

13 changed files with 73 additions and 495 deletions

74
Cargo.lock generated
View File

@ -17,21 +17,6 @@ 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"
@ -110,12 +95,6 @@ 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"
@ -244,35 +223,6 @@ 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"
@ -321,26 +271,6 @@ 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"
@ -466,11 +396,7 @@ 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,10 +6,6 @@ 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/etc/ /etc/ ADD docker/ /
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

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

View File

@ -1 +1,3 @@
you cannot run this file #!/bin/bash
exec sleep 1

View File

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

View File

@ -2,31 +2,10 @@ mod daemon;
mod config; mod config;
pub(crate) mod error; pub(crate) mod error;
use std::env; use std::error as std_err;
use anyhow::Context;
const WINGMATE_CONFIG_PATH: &'static str = "WINGMATE_CONFIG_PATH"; pub async fn start() -> Result<(), Box<dyn std_err::Error>> {
let _config = config::Config::find(vec![String::from("/etc/wingmate")])?;
pub async fn start() -> Result<(), error::WingmateInitError> { dbg!(_config);
let mut vec_search: Vec<String> = Vec::new(); 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).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,24 +1,8 @@
use std::fs; use std::fs;
use std::env;
use std::path::PathBuf; use std::path::PathBuf;
use std::io::{BufReader, BufRead}; use std::error as std_error;
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 {
@ -26,40 +10,19 @@ 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, wingmate_error::WingmateInitError> { pub fn find(search_path: Vec<String>) -> Result<Config, Box<dyn std_error::Error>> {
if search_path.is_empty() { if search_path.is_empty() {
return Err(wingmate_error::WingmateInitError::InvalidConfigSearchPath.into()); return Err(wingmate_error::InvalidConfigSearchPathError.into());
} }
let mut svc_commands: Vec<Command> = Vec::new(); let mut svc_commands: Vec<Command> = Vec::new();
let mut cron : Vec<Crontab> = Vec::new(); for p in search_path {
'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()) {
@ -71,20 +34,22 @@ 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.to_string_lossy()))); svc_commands.push(Command::Direct(String::from(ep.as_path().to_string_lossy())));
} else { } else {
// call with shell // call with shell
svc_commands.push(Command::ShellPrefixed(String::from(ep.to_string_lossy()))); svc_commands.push(Command::ShellPrefixed(String::from(ep.as_path().to_string_lossy())));
} }
} }
} }
} }
cron = Self::read_crontab(&mut buf).map_err(|e| { wingmate_error::WingmateInitError::Cron { source: e }})?; let cron = buf.join("cron");
if let Ok(cron_iter) = fs::read_dir(cron.as_path()) {
//TODO: need to include cron in the condition for entry in cron_iter {
if !svc_commands.is_empty() || !cron.is_empty() { if let Ok(_dirent) = entry {
break 'search; // read the cron file
}
}
} }
} else { } else {
// reserve for future use; when we have a centralized config file // reserve for future use; when we have a centralized config file
@ -92,193 +57,11 @@ impl Config {
} }
} }
if svc_commands.is_empty() && cron.is_empty() { if svc_commands.is_empty() {
return Err(wingmate_error::WingmateInitError::NoServiceOrCron.into()); return Err(wingmate_error::NoServiceOrCronFoundError.into());
} }
let mut config = Config { let config = Config { services: svc_commands };
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,14 +3,12 @@ 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(cfg: config::Config) -> Result<(), WingmateInitError> { pub async fn start() -> 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();
@ -20,13 +18,13 @@ pub async fn start(cfg: config::Config) -> Result<(), WingmateInitError> {
let cancel = CancellationToken::new(); let cancel = CancellationToken::new();
let starter_cancel = cancel.clone(); let starter_cancel = cancel.clone();
let mut set: JoinSet<Result<(), wmerr::WingmateInitError>> = JoinSet::new(); let mut set: JoinSet<Result<(), Box<dyn error::Error + Send + Sync>>> = 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_services(&mut set, &cfg, starter_cancel)?; starter::start_process(&mut set, starter_cancel);
//TODO: spawn_blocking for waiter //TODO: spawn_blocking for waiter
set.spawn_blocking(move || { set.spawn_blocking(move || {
@ -39,20 +37,12 @@ pub async fn start(cfg: config::Config) -> Result<(), WingmateInitError> {
Ok(v) => { Ok(v) => {
if let Err(ev) = v { if let Err(ev) = v {
dbg!(&ev); dbg!(&ev);
match ev { return Err(ev as Box<dyn error::Error>);
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(WingmateInitError::Join { source: e }); return Err(e.into());
}, },
} }
} }

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<(), WingmateInitError> { pub async fn sighandler(flag: Arc<Mutex<bool>>, cancel: CancellationToken, exit: CancellationToken) -> Result<(), Box<dyn error::Error + Send + Sync>> {
let mut sigint = signal(SignalKind::interrupt()).map_err(|e| { WingmateInitError::Signal { source: e } })?; let mut sigint = signal(SignalKind::interrupt())?;
let mut sigterm = signal(SignalKind::terminate()).map_err(|e| { WingmateInitError::Signal { source: e } })?; let mut sigterm = signal(SignalKind::terminate())?;
let mut sigchld = signal(SignalKind::child()).map_err(|e| { WingmateInitError::Signal { source: e } })?; let mut sigchld = signal(SignalKind::child())?;
'signal: loop { 'signal: loop {
select! { select! {

View File

@ -1,49 +1,26 @@
use tokio::task::JoinSet; use tokio::task::JoinSet;
use tokio::process::{Command, Child}; use tokio::process::Command;
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_services(ts: &mut JoinSet<Result<(), WingmateInitError>>, cfg: &config::Config, cancel: CancellationToken) pub fn start_process(ts: &mut JoinSet<Result<(), Box<dyn error::Error + Send + Sync>>>, cancel: CancellationToken) {
-> Result<(), WingmateInitError> { for _j in 0..5 {
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: Child; let mut child = Command::new("sleep").arg("1")
let svc = svc.clone(); .spawn()
match svc { .expect("failed to spawn");
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() => {
@ -56,7 +33,7 @@ pub fn start_services(ts: &mut JoinSet<Result<(), WingmateInitError>>, cfg: &con
}, },
result = child.wait() => { result = child.wait() => {
if let Err(e) = result_match(result) { if let Err(e) = result_match(result) {
return Err(WingmateInitError::ChildExit { source: e }); return Err(e);
} }
break 'autorestart; break 'autorestart;
} }
@ -64,7 +41,7 @@ pub fn start_services(ts: &mut JoinSet<Result<(), WingmateInitError>>, cfg: &con
}, },
Err(e) => { Err(e) => {
if e != Errno::ESRCH { if e != Errno::ESRCH {
return Err(WingmateInitError::ChildNotFound); return Err(e.into());
} else { } else {
break 'autorestart; break 'autorestart;
} }
@ -76,33 +53,32 @@ pub fn start_services(ts: &mut JoinSet<Result<(), WingmateInitError>>, cfg: &con
}, },
result = child.wait() => { result = child.wait() => {
if let Err(e) = result_match(result) { if let Err(e) = result_match(result) {
return Err(WingmateInitError::ChildExit { source: e }); return Err(e);
} }
}, },
} }
} }
dbg!("starter: task completed"); println!("starter: task completed");
Ok(()) Ok(())
}); });
} }
dbg!("starter: spawning completed"); println!("starter: spawning completed");
Ok(())
} }
fn result_match(result: tokio_result<ExitStatus>) -> Result<(), anyhow::Error> { fn result_match(result: tokio_result<ExitStatus>) -> Result<(), Box<dyn error::Error + Send + Sync>> {
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).context("unexpected child exit status"); return Err(e.into());
} }
} else { } else {
return Err(e).context("unexpected child error"); return Err(e.into());
} }
} }
dbg!("starter: sleep exited"); //TODO: remove me! this is for debug + tracing purpose
println!("starter: sleep exited");
Ok(()) Ok(())
} }

View File

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

View File

@ -1,92 +1,25 @@
use thiserror::Error; use std::fmt;
use std::error;
#[derive(Error,Debug)] #[derive(Debug, Clone)]
pub enum WingmateInitError { pub struct InvalidConfigSearchPathError;
#[error("invalid config search path")]
InvalidConfigSearchPath,
#[error("no service or cron found")] impl fmt::Display for InvalidConfigSearchPathError {
NoServiceOrCron, fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
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,
} }
} }
#[derive(Error,Debug)] impl error::Error for InvalidConfigSearchPathError {}
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,
} }
} }
#[derive(Error,Debug)] impl error::Error for NoServiceOrCronFoundError {}
pub enum FindShellError {
#[error("shell not found")]
ShellNotFound,
#[error("when finding shell")]
Other {
#[source]
source: anyhow::Error
}
}