1
0
forked from noxious/server
noxious_server/start.sh
2025-02-07 23:23:03 +01:00

81 lines
2.0 KiB
Bash

#!/bin/sh
set -eo pipefail
# Configuration
MAX_MYSQL_WAIT=60
APP_NAME="nodeapp"
MYSQL_SOCKET="/run/mysqld/mysqld.sock"
MYSQL_PID="/run/mysqld/mysqld.pid"
MYSQL_ERROR_LOG="/var/log/mysql/error.log"
# Cleanup function
cleanup() {
echo "Shutting down services..."
tmux kill-session -t $APP_NAME 2>/dev/null || true
redis-cli shutdown 2>/dev/null || true
if [ -f "$MYSQL_PID" ]; then
mysqladmin -u root shutdown 2>/dev/null || true
fi
exit 0
}
# Error handler
error_handler() {
echo "Error occurred in script at line: $1"
cleanup
exit 1
}
trap cleanup SIGTERM SIGINT
trap 'error_handler ${LINENO}' ERR
# Start Redis
echo "Starting Redis..."
redis-server --daemonize yes
until redis-cli ping > /dev/null 2>&1; do
sleep 1
done
echo "Redis started successfully"
# Start MySQL
echo "Starting MySQL..."
mariadbd \
--datadir=/var/lib/mysql \
--pid-file=$MYSQL_PID \
--socket=$MYSQL_SOCKET \
--log-error=$MYSQL_ERROR_LOG \
--bind-address=0.0.0.0 &
# Wait for MySQL
echo "Waiting for MySQL to be ready..."
COUNTER=0
until mysqladmin ping -h localhost --silent 2>/dev/null || [ $COUNTER -gt $MAX_MYSQL_WAIT ]; do
echo "Still waiting... (${COUNTER}s)"
sleep 2
COUNTER=$((COUNTER+2))
done
if [ $COUNTER -gt $MAX_MYSQL_WAIT ]; then
echo "MySQL failed to start within $MAX_MYSQL_WAIT seconds"
echo "Last few lines of MySQL error log:"
tail -n 20 $MYSQL_ERROR_LOG
exit 1
fi
echo "MySQL is ready!"
# Run migrations
echo "Running database migrations..."
npx mikro-orm-esm migration:up
# Start application
echo "Starting application..."
tmux new-session -d -s $APP_NAME "npm run start"
echo "App is running in tmux session. Attach with: tmux attach-session -t $APP_NAME"
# Monitor processes
while true; do
sleep 30
redis-cli ping > /dev/null 2>&1 || { echo "Redis died"; exit 1; }
mysqladmin ping -h localhost --silent || { echo "MySQL died"; exit 1; }
tmux has-session -t $APP_NAME 2>/dev/null || { echo "Application died"; exit 1; }
done