SaltStack通過Service方式管理服務,對於通用的服務,如mysql、apache、php等,自帶service服務管理腳本,SaltStack可以方便管理。但是對於一些公司自有的服務,可能這些服務在開發之初,並沒有考慮日後會採用Service腳本進行服務管理,爲了統一Salt對服務的管理,我採用的方式是爲每一個程序編寫Service腳本。
這裏主要注意以下三個問題:
1.這裏有部分機器的優化,放在/etc/profile和/root/.bashrc中,而這兩個文件在用戶登陸的時候,會自動執行,而通過salt管理服務器,並不會執行這兩個文件,所以在腳本中有導入這兩個文件的操作;
2.之前服務啓動的方式爲nohup prog_name &這種形式,這個命令執行過後,還要有個敲回車鍵的操作,來確認結果輸出到nohup.out文件,這裏通過制定輸出文件爲nohup.out的方式,避免這個操作。
3.腳本的stop函數中,通過pidof命令獲取進程的pid,然後通過kill殺掉,如果程序允許直接Kill掉,那麼,使用pidof的方式要優於使用pkill、killall。
腳本如下:
#!/bin/sh # FileName: mobile # Description: This shell script takes care of starting and stopping MobileStkServer # Guibin created on Oct. 17th, 2014 # version 1.6-2015.04.29 # Source env . /etc/profile . /root/.bashrc #the service name for example: MobileStkServer DAEN_NAME=MobileStkServer DAEN_PATH=/home/MobileServer/ #the full path and name of the daemon DAEN_RUNram #Warning: The name of executable file must be identical with service name DAEN_RUN="nohup ./$DAEN_NAME > nohup.out 2>&1 &" # check program file check_profile(){ PRO_FILE="$DAEN_PATH$DAEN_NAME" if [ ! -f "$PRO_FILE" ] then echo "$PRO_FILE: No such file or directory" exit 1 elif [ ! -x "$PRO_FILE" ] then echo "$PRO_FILE: Permission denied" exit 1 fi } # status function check_status(){ check_profile DAEN_PID='' DAEN_PID=$(ps -ef|grep "$DAEN_NAME"|grep -v grep|awk '{print $2}') if [ -n "$DAEN_PID" ] then DAEN_STATUS='sstart' return 0 else DAEN_STATUS='sstop' return 1 fi } status(){ check_status if [ "$DAEN_STATUS"x == 'sstartx' ] then echo -e "$DAEN_NAME is running with pid: $DAEN_PID" return 0 else echo -e "$DAEN_NAME is not running!" return 1 fi } # start function start() { #check the daemon status first check_status if [ "$DAEN_STATUS"x == 'sstartx' ] then echo "$DAEN_NAME has already started!" else cd $DAEN_PATH printf "Starting $DAEN_NAME ..." eval $DAEN_RUN sleep 2 DAEN_PID=$(ps -ef|grep "$DAEN_NAME"|grep -v grep|awk '{print $2}') if [ -n "$DAEN_PID" ] then echo -e "\t\t\t\t[ OK ]" echo -e "$DAEN_NAME is running with pid: $DAEN_PID" else echo -e "\t\t\t\t[ Failed ]" exit 1 fi fi } #stop function stop() { #check the daemon status first check_status if [ "$DAEN_STATUS"x == 'sstopx' ] then echo "$DAEN_NAME has already stopped!" else i=0 while [ $i -lt 5 ] do `/sbin/pidof $DAEN_NAME |xargs /bin/kill > /dev/null 2>&1` sleep 2 check_status if [ "$DAEN_STATUS"x == 'sstopx' ] then echo -e "Stopping $DAEN_NAME ...\t\t\t\t[ OK ]" break else # i=`expr $i + 1` i=$[$i+1] fi done check_status if [ "$DAEN_STATUS"x == 'sstartx' ] then echo -e "Stopping $DAEN_NAME ...\t\t\t\t[ Failed ]" exit 1 fi fi } case "$1" in start) start ;; stop) stop ;; reload|restart) stop sleep 2 start ;; status) status ;; *) echo $"Usage: $0 {start|stop|restart|status|reload}" exit 1 esac
注:
2014.12.25 程序啓動命令增加標準錯誤重定向到標準輸出 2>&1,否則新版Salt(2014.7.0)使用該腳本報錯;
2014.12.29 增加status函數返回值,否則在使用salt service.status查看進程狀態時,被管理進程無論是否啓動,都會返回True;