为了能够方便的启动、重启、停止或者查询服务状态,需要写脚本来控制。
(未完成版本)
首先是配置文件,类似于代码的config,只需要修改这里边的参数再去运行脚本即可实现自动化
config.sh
#项目名称
export PARAM="say"
#运行代码的名称
export EXEC_FILE="say.py"
#代码、日志存放目录
export DIR=`pwd`
#代码类型
export PRO_TYPE="python"
#后台运行
export JOB_TYPE="background"
#目前支持的代码类型枚举
export PRO_PYTHON="python"
export PRO_SHELL="/bin/bash"
export PRO_JAVA="java"
export PRO_SPARK="spark"
#支持的运行方式是后台还是非后台
export REAL_TYPE="real"
export OFF_TYPE="background"
然后配置好配置我们就可以运行
server.sh
source `pwd`/config.sh
source /etc/profile
#获取进程或者父进程
function get_pid(){
PID=`ps -ef | grep "$DIR/$PARAM" | grep -v grep|awk '{print $2" "$3}'`
local pid=($PID)
if [ "$1" = "parent" ];then
echo "${pid[1]}"
else
echo "${pid[0]}"
fi
}
#get_pid parent
#运行
function start_model(){
local COMMAND="$1"
local SUC_LOG_FILE="$2"
local ERR_LOG_FILE="$3"
if [[ "$JOB_TYPE" = $REAL_TYPE ]];then
echo $COMMAND 2>&1 |tee -a $SUC_LOG_FILE
$COMMAND 2>&1 |tee -a $SUC_LOG_FILE
else
echo nohup $COMMAND 1>>$SUC_LOG_FILE 2>>$ERR_LOG_FILE &
nohup $COMMAND 1>>$SUC_LOG_FILE 2>>$ERR_LOG_FILE &
fi
}
#根据项目类型不同的运行方式
function start(){
PID=`get_pid`
if [ -z "${PID}" ];then
RUN=""
case ${PRO_TYPE} in
${PRO_PYTHON})
RUN="${PRO_PYTHON} ${DIR}/${EXEC_FILE}"
start_model "$RUN" "${DIR}/${PARAM}.log" "${DIR}/${PARAM}_ERR.log"
;;
${PRO_SHELL})
RUN="${PRO_SHELL} ${DIR}/${EXEC_FILE}"
start_model "$RUN" "${DIR}/${PARAM}.log" "${DIR}/${PARAM}_ERR.log"
;;
${PRO_JAVA})
RUN=""
;;
${PRO_SPARK})
RUN=""
;;
*)
echo "$PRO_TYPE is not support"
exit 1
;;
esac
sleep 2
PID=`get_pid`
echo "${PARAM} is running pid:$PID"
else
echo "PID: $PID is running"
fi
}
#start
#杀死进程
function killpid(){
local PID=`get_pid parent`
if [ "$PID" != "1" ];then
kill $PID
else
local PID=`get_pid`
if [[ -n "$PID" ]];then
kill `get_pid`
else
echo "PID=$PID cannot be killed!"
fi
fi
}
#停止
function stop(){
PID=`get_pid`
if [ -n "${PID}" ];then
echo "$PARAM is running pid:$PID"
killpid $PID
echo "$PARAM is kill..."
else
echo "$PARAM is not running"
fi
}
#获取状态
function status(){
PID=`get_pid`
if [ -n "${PID}" ];then
echo "$PARAM is running,PID=$PID"
else
echo "$PARAM is not running"
fi
}
#选择使用方式
case $1 in
start) start ;;
stop) stop ;;
status) status ;;
restart) stop && sleep 2 && start ;;
*) echo "please use start|stop|status|restart";;
esac
使用demo
?
|