启动和停止服务脚本

约定

  • /opt/start.sh :通用启动脚本,第一个参数指定应用名,如/opt/start.sh myapp
  • /opt/stop.sh :通用停止脚本,第一个参数指定应用名,如/opt/stop.sh myapp
  • /opt/<app_name>/<app_name>.jar :启动的应用jar包
  • /opt/<app_name>/<app_name>.pid :启动后的进程id,由start.sh自动生成
  • /opt/<app_name>/log/stdout.log :应用的标准输出,由start.sh自动生成
  • /opt/<app_name>/log/stderr.log :应用的错误输出,由start.sh自动生成
  • /opt/<app_name>.runuser :当以root运行start.sh时,应用的运行用户,如果没有这个文件将以root运行

启动脚本(start.sh)

#!/bin/bash
APP_NAME=$1
BASE_DIR=$(readlink -f $(dirname "$0"))
APP_DIR=${BASE_DIR}/${APP_NAME}
JAR_FILE=${APP_DIR}/${APP_NAME}.jar
PID_FILE=${APP_DIR}/${APP_NAME}.pid
LOG_DIR=${APP_DIR}/log
RUN_USER_FILE="${BASE_DIR}/${APP_NAME}.runuser"

RUN() {
    if [ ${RUN_USER} ]; then
        SCRIPT="[email protected]"
        return $(runuser -l ${RUN_USER} -c "${SCRIPT}" 2>/dev/null)
    else
        return [email protected]
    fi
}

if [ ! ${APP_NAME} ]; then
    echo "App name not found!";
    exit 1;
fi

if [ ! -f ${JAR_FILE} ]; then
    echo "Jar file not found: ${JAR_FILE}";
    exit 1;
fi

if [ -f ${PID_FILE} ]; then
    echo "App is running!: $(cat ${PID_FILE})";
    exit 1;
fi

RUN_USER=$(whoami)
if [ ${RUN_USER} == 'root' ]; then
    if [ -f ${RUN_USER_FILE} ]; then
        RUN_USER=$(cat ${RUN_USER_FILE});
    fi
else
    RUN_USER=''
fi

if [ ! -d ${LOG_DIR} ]; then
    if ! RUN "mkdir ${LOG_DIR}"; then
        echo "Start failed: can not create log directory.";
        exit 1;
    fi
fi

cd ${APP_DIR};
if ! RUN "nohup java -jar ${JAR_FILE} > ${LOG_DIR}/stdout.log 2>${LOG_DIR}/stderr.log & echo \$! > ${PID_FILE}" ; then
    echo "Start failed: run failed!";
    exit 1;
fi

echo "Started: ${JAR_FILE}";

停止脚本(stop.sh)

#!/bin/bash
APP_NAME=$1
BASE_DIR=$(dirname "$0")/${APP_NAME}
PID_FILE=${BASE_DIR}/${APP_NAME}.pid
if [ ! ${APP_NAME} ]; then
    echo "App name not found!";
    exit 1;
fi

if [ -f ${PID_FILE} ]; then
    PID=$(cat ${PID_FILE});
    echo kill ${PID}
    kill ${PID};
    rm -f ${PID_FILE};
else
    echo "Not running...";
fi
exit 0;

发表评论

邮箱地址不会被公开。 必填项已用*标注