diff --git a/.env.test b/.env.test index 73b88c7..a303ed6 100644 --- a/.env.test +++ b/.env.test @@ -1,2 +1,3 @@ EMAIL_SENDER=test@test.com +PIDFILE=/var/run/sesamo.pid WEB_PORT=3000 diff --git a/sesamo.sh b/sesamo.sh new file mode 100755 index 0000000..cc3f591 --- /dev/null +++ b/sesamo.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +cd "$(dirname "$0")" || exit 1 + +OP="$1" + +ENV=".env" +set -a +. $ENV +set +a + +if [ -z "$PIDFILE" ]; then + echo "pidfile must be specified" + exit 255 +fi + +if [ -z "$HOME" ]; then + export HOME=/root +fi + +CARGO=$(which cargo) +if [ -z "$CARGO" ]; then + export CARGO_DIR="/$HOME/.cargo" + [ -s "$CARGO_DIR/env" ] && \. "$CARGO_DIR/env" # This loads nvm +fi + +start() { + screen -S sesamo -d -m cargo make -p production run + + return $? +} + +stop() { + PID=$(cat $PIDFILE) + + kill "$PID" + + return $? +} + +case "$1" in + + "start") + start + ;; + + "stop") + stop + ;; + + *) + "unknown operation $OP" + exit 1 + ;; + +esac \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 83441a3..be52e0a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,10 +2,14 @@ //! //! App configuration +use std::path::PathBuf; + /// App configuration read from environment #[derive(Debug, Deserialize, Serialize)] pub struct Config { pub email_sender: String, + #[cfg(target_family = "unix")] + pub pidfile: Option, pub web_port: u16, } diff --git a/src/main.rs b/src/main.rs index de3d43e..dc25163 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,9 @@ mod config; mod test; mod web; +use std::io::Write; +use std::path::Path; + const APP_NAME: &str = env!("CARGO_PKG_NAME"); const APP_AUTHORS: &str = env!("CARGO_PKG_AUTHORS"); const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -27,8 +30,26 @@ async fn main() -> anyhow::Result<()> { info!("initializing web service..."); let web_service = web::WebServer::init(config.web_port, aws_config, &config.email_sender).await?; + + #[cfg(target_family = "unix")] + if let Some(pidfile) = config.pidfile.as_deref() { + debug!("writing pidfile to {}", pidfile.display()); + write_pidfile(pidfile)?; + info!("pidfile written"); + } + info!("web service OK; running web server..."); web_service.run().await?; Ok(()) } + +#[cfg(target_family = "unix")] +fn write_pidfile(pidfile: &Path) -> anyhow::Result<()> { + let pid = std::process::id(); + + let mut f = std::fs::File::create(pidfile)?; + writeln!(&mut f, "{pid}")?; + + Ok(()) +}