Skip to content

Commit

Permalink
feat: run script and pidfile
Browse files Browse the repository at this point in the history
  • Loading branch information
veeso committed Sep 29, 2023
1 parent 8ff3f80 commit 57a6cff
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
EMAIL_SENDER=[email protected]
PIDFILE=/var/run/sesamo.pid
WEB_PORT=3000
56 changes: 56 additions & 0 deletions sesamo.sh
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PathBuf>,
pub web_port: u16,
}

Expand Down
21 changes: 21 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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(())
}

0 comments on commit 57a6cff

Please sign in to comment.