diff options
Diffstat (limited to 'src/smd')
-rw-r--r-- | src/smd/context.rs | 47 | ||||
-rw-r--r-- | src/smd/endpoints.rs | 205 | ||||
-rw-r--r-- | src/smd/main.rs | 148 |
3 files changed, 0 insertions, 400 deletions
diff --git a/src/smd/context.rs b/src/smd/context.rs deleted file mode 100644 index 5d8038c..0000000 --- a/src/smd/context.rs +++ /dev/null @@ -1,47 +0,0 @@ -use salaryman::service::{Service, ServiceConf}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use std::sync::Arc; -use tokio::sync::Mutex; -use uuid::Uuid; - -pub struct SalarymanService { - pub config: ServiceConf, - pub service: Arc<Mutex<Service>>, -} -impl SalarymanService { - pub fn new() -> Self { - Self { - config: ServiceConf::new(), - service: Arc::new(Mutex::new(Service::new())), - } - } - pub fn from_parts(config: ServiceConf, service: Arc<Mutex<Service>>) -> Self { - Self { config, service } - } -} - -pub struct SalarymanDContext { - pub services: Vec<Arc<SalarymanService>>, -} -impl SalarymanDContext { - pub fn new() -> Self { - Self { - services: Vec::new(), - } - } - pub fn from_vec(services: Vec<Arc<SalarymanService>>) -> Self { - Self { services } - } -} - -#[derive(Serialize, Deserialize, JsonSchema, Debug)] -pub struct StdinBuffer { - pub stdin: String, - pub endl: Option<bool>, -} - -#[derive(Serialize, Deserialize, JsonSchema, Debug)] -pub struct ServicePath { - pub service_uuid: Uuid, -} diff --git a/src/smd/endpoints.rs b/src/smd/endpoints.rs deleted file mode 100644 index f0ba0ea..0000000 --- a/src/smd/endpoints.rs +++ /dev/null @@ -1,205 +0,0 @@ -use super::context::{SalarymanDContext, SalarymanService, ServicePath, StdinBuffer}; -use dropshot::{HttpError, HttpResponseOk, Path, RequestContext, TypedBody, endpoint}; -use salaryman::service::ServiceConf; -use std::sync::Arc; - -#[endpoint { - method = GET, - path = "/service", -}] -pub async fn endpoint_get_services( - rqctx: RequestContext<Arc<SalarymanDContext>>, -) -> Result<HttpResponseOk<Vec<ServiceConf>>, HttpError> { - let ret = { - let ctx = rqctx.context(); - let mut v: Vec<ServiceConf> = Vec::new(); - for i in 0..ctx.services.len() { - v.push(ctx.services[i].config.clone()); - } - v - }; - Ok(HttpResponseOk(ret)) -} -#[endpoint { - method = GET, - path = "/service/{service_uuid}", -}] -pub async fn endpoint_get_service( - rqctx: RequestContext<Arc<SalarymanDContext>>, - path_params: Path<ServicePath>, -) -> Result<HttpResponseOk<ServiceConf>, HttpError> { - let u = path_params.into_inner().service_uuid; - let ctx = rqctx.context(); - let mut service: Option<Arc<SalarymanService>> = None; - for i in 0..ctx.services.len() { - if ctx.services[i].config.uuid == u { - service = Some(ctx.services[i].clone()); - } else { - continue; - } - } - let s = match service { - Some(s) => s.config.clone(), - None => { - return Err(HttpError::for_unavail( - None, - String::from("Service Not Found"), - )); - } - }; - Ok(HttpResponseOk(s)) -} -#[endpoint { - method = GET, - path = "/service/{service_uuid}/start", -}] -pub async fn endpoint_start_service( - rqctx: RequestContext<Arc<SalarymanDContext>>, - path_params: Path<ServicePath>, -) -> Result<HttpResponseOk<()>, HttpError> { - let u = path_params.into_inner().service_uuid; - let ctx = rqctx.context(); - let mut service: Option<Arc<SalarymanService>> = None; - for i in 0..ctx.services.len() { - if ctx.services[i].config.uuid == u { - service = Some(ctx.services[i].clone()); - } else { - continue; - } - } - match service { - Some(s) => { - let mut lock = s.service.lock().await; - match lock.start_with_output().await { - Ok(_) => (), - Err(e) => return Err(HttpError::for_internal_error(e.to_string())), - } - } - None => { - return Err(HttpError::for_unavail( - None, - String::from("Service Not Found"), - )); - } - }; - Ok(HttpResponseOk(())) -} -#[endpoint { - method = GET, - path = "/service/{service_uuid}/stop", -}] -pub async fn endpoint_stop_service( - rqctx: RequestContext<Arc<SalarymanDContext>>, - path_params: Path<ServicePath>, -) -> Result<HttpResponseOk<()>, HttpError> { - let u = path_params.into_inner().service_uuid; - let ctx = rqctx.context(); - let mut service: Option<Arc<SalarymanService>> = None; - for i in 0..ctx.services.len() { - if ctx.services[i].config.uuid == u { - service = Some(ctx.services[i].clone()); - } else { - continue; - } - } - match service { - Some(s) => { - let mut lock = s.service.lock().await; - match lock.stop().await { - Ok(_) => (), - Err(e) => return Err(HttpError::for_internal_error(e.to_string())), - } - } - None => { - return Err(HttpError::for_unavail( - None, - String::from("Service Not Found"), - )); - } - }; - Ok(HttpResponseOk(())) -} -#[endpoint { - method = GET, - path = "/service/{service_uuid}/restart", -}] -pub async fn endpoint_restart_service( - rqctx: RequestContext<Arc<SalarymanDContext>>, - path_params: Path<ServicePath>, -) -> Result<HttpResponseOk<()>, HttpError> { - let u = path_params.into_inner().service_uuid; - let ctx = rqctx.context(); - let mut service: Option<Arc<SalarymanService>> = None; - for i in 0..ctx.services.len() { - if ctx.services[i].config.uuid == u { - service = Some(ctx.services[i].clone()); - } else { - continue; - } - } - match service { - Some(s) => { - let mut lock = s.service.lock().await; - match lock.restart_with_output().await { - Ok(_) => (), - Err(e) => return Err(HttpError::for_internal_error(e.to_string())), - } - } - None => { - return Err(HttpError::for_unavail( - None, - String::from("Service Not Found"), - )); - } - }; - Ok(HttpResponseOk(())) -} -#[endpoint { - method = PUT, - path = "/service/{service_uuid}/write" -}] -pub async fn endpoint_post_stdin( - rqctx: RequestContext<Arc<SalarymanDContext>>, - path_params: Path<ServicePath>, - update: TypedBody<StdinBuffer>, -) -> Result<HttpResponseOk<()>, HttpError> { - let ctx = rqctx.context(); - let stdin_str = update.into_inner(); - let u = path_params.into_inner().service_uuid; - let mut service: Option<Arc<SalarymanService>> = None; - for i in 0..ctx.services.len() { - if ctx.services[i].config.uuid == u { - service = Some(ctx.services[i].clone()); - } else { - continue; - } - } - match service { - Some(s) => { - let mut lock = s.service.lock().await; - if lock.started().await { - let b = if let Some(endl) = stdin_str.endl { - if endl { - lock.writeln_stdin(stdin_str.stdin.clone()).await //TODO: PROPERLY HANDLE ERROR! - } else { - lock.write_stdin(stdin_str.stdin.clone()).await //TODO: PROPERLY HANDLE ERROR! - } - } else { - lock.writeln_stdin(stdin_str.stdin.clone()).await //TODO: PROPERLY HANDLE ERROR! - }; - match b { - Ok(_) => (), - Err(e) => return Err(HttpError::for_internal_error(e.to_string())), - } - } - drop(lock); - } - None => { - return Err(HttpError::for_unavail( - None, - String::from("Service Not Found"), - )); - } - } - Ok(HttpResponseOk(())) -} diff --git a/src/smd/main.rs b/src/smd/main.rs deleted file mode 100644 index b81df2f..0000000 --- a/src/smd/main.rs +++ /dev/null @@ -1,148 +0,0 @@ -mod context; -mod endpoints; - -use clap::Parser; -use dropshot::{ApiDescription, ConfigDropshot, ConfigLogging, ConfigLoggingLevel, ServerBuilder}; -use salaryman::service::{Service, ServiceConf}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; -use tokio::{fs::read_to_string, sync::Mutex}; - -use std::{ - net::{IpAddr, SocketAddr}, - path::PathBuf, - sync::Arc, -}; - -use crate::context::{SalarymanDContext, SalarymanService}; -use crate::endpoints::{ - endpoint_get_service, endpoint_get_services, endpoint_post_stdin, endpoint_restart_service, - endpoint_start_service, endpoint_stop_service, -}; - -#[derive(Parser, Debug)] -#[command(version, about, long_about = None)] -struct Args { - #[arg( - short, - long, - value_name = "FILE", - help = "config file override", - default_value = "salaryman.toml" - )] - config: PathBuf, - #[arg( - short, - long, - value_name = "ADDR", - help = "IP address to bind API to", - default_value = "127.0.0.1" - )] - address: IpAddr, - #[arg( - short, - long, - value_name = "PORT", - help = "TCP Port to bind API to", - default_value = "3080" - )] - port: u16, -} - -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug)] -pub struct User { - pub username: String, - pub token: String, -} - -#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug)] -pub struct Config { - pub address: Option<IpAddr>, - pub port: Option<u16>, - pub user: Vec<User>, - pub service: Vec<ServiceConf>, -} -impl Config { - pub fn new() -> Self { - Self { - address: None, - port: None, - user: Vec::new(), - service: Vec::new(), - } - } -} - -async fn load_config(file: &PathBuf) -> Result<Config, Box<dyn std::error::Error>> { - let s: String = match read_to_string(file).await { - Ok(s) => s, - Err(_) => { - return Err(Box::new(std::io::Error::new( - std::io::ErrorKind::NotFound, - "cannot find config file", - ))); - } - }; - match toml::from_str(s.as_str()) { - Ok(c) => Ok(c), - Err(_) => Err(Box::new(std::io::Error::new( - std::io::ErrorKind::Other, - "unable to parse config file", - ))), - } -} - -#[tokio::main] -async fn main() -> Result<(), Box<dyn std::error::Error>> { - let args = Args::parse(); - let conf: Config = load_config(&args.config).await?; - let addr = if let Some(addr) = conf.address { - addr - } else { - args.address - }; - let port = if let Some(port) = conf.port { - port - } else { - args.port - }; - let bind = SocketAddr::new(addr, port); - let mut services: Vec<Arc<SalarymanService>> = Vec::new(); - for i in 0..conf.service.len() { - services.push(Arc::new(SalarymanService::from_parts( - conf.service[i].clone(), - Arc::new(Mutex::new(Service::from_conf(&conf.service[i]))), - ))); - } - for i in 0..services.len() { - if services[i].config.autostart { - let mut lock = services[i].service.lock().await; - lock.start().await?; - lock.scan_stdout().await?; - lock.scan_stderr().await?; - } - } - let log_conf = ConfigLogging::StderrTerminal { - level: ConfigLoggingLevel::Info, - }; - let log = log_conf.to_logger("smd")?; - let ctx = Arc::new(SalarymanDContext::from_vec(services)); - let config = ConfigDropshot { - bind_address: bind, - ..Default::default() - }; - let mut api = ApiDescription::new(); - api.register(endpoint_get_services)?; - api.register(endpoint_get_service)?; - api.register(endpoint_start_service)?; - api.register(endpoint_stop_service)?; - api.register(endpoint_restart_service)?; - api.register(endpoint_post_stdin)?; - api.openapi("Salaryman", semver::Version::new(1, 0, 0)) - .write(&mut std::io::stdout())?; - let server = ServerBuilder::new(api, ctx.clone(), log) - .config(config) - .start()?; - server.await?; - Ok(()) -} |