数据库进程守护

该脚本用于监测数据库是否启动,如果没有启动或者异常停止,则自动启动数据库服务。

使用说明:

  • 将脚本st_dbdaemon、st_dbdaemon_service拷贝到目录/usr/local/sbin
  • 执行命令./st_dbdaemon_service start启动守护服务
  • 将数据库给kill掉,看守护进程是否将数据库启动起来
  • 默认守护OSRDB数据库实例,如果想守护其他实例,需要修改st_dbdaemon文件中的dbname参数

st_dbdaemon脚本

#!/bin/bash
 if [ -z "$SZ_OSCAR_HOME" ] ; then
   echo $"SZ_OSCAR_HOME is not found......"
   RETVAL=1
   exit $RETVAL
 fi

 dbname="OSRDB"
 SERVICE_NAME=oscardb_${dbname}d
 startinfo="oscar-[dbdaemon]"
 host_name=`hostname`
 pid=$$

 start_dbsevice()
 {
   /etc/init.d/${SERVICE_NAME} status >/dev/null
         RETVAL=$?
         if [ "$RETVAL" -eq "0" ] ; then
       RETVAL=1
   else
                 start_time=$(date -d today +"%Y-%m-%d %H:%M:%S")
                 echo "${start_time} $host_name ${startinfo}[${pid}]: discover $SERVICE_NAME service is shutdown" >>/var/log/messages
                 /etc/init.d/${SERVICE_NAME} start >/dev/null
                 start_time=$(date -d today +"%Y-%m-%d %H:%M:%S")
                 echo "${start_time} $host_name ${startinfo}[${pid}]: dbdaemon startup $SERVICE_NAME service success" >>/var/log/messages
                 RETVAL=0
   fi
   return $RETVAL
 }


 for ((;1;))
 do
         start_time=$(date -d today +"%Y-%m-%d %H:%M:%S")
         echo "${start_time} $host_name ${startinfo}[${pid}]: dbdaemon script start monitoring" >>/var/log/messages
         start_dbsevice
         sleep 5
 done

st_dbdaemon_service脚本

#!/bin/bash
# Init file for dbdaemon server daemon
#
# chkconfig: 2345 55 25
# description: dbdaemon server daemon
#
   SERVICE="/usr/local/sbin/st_dbdaemon"

    start(){
        echo "starting..."
        nohup $SERVICE > $SERVICE.log 2>&1 &
        if [ $? -ne 0 ]
        then
            echo "start failed, please check the log!"
            exit $?
        else
            echo $! > $SERVICE.pid
            echo "start success"
        fi
    }

    stop(){
        echo "stopping..."
        kill -9 `cat $SERVICE.pid`
        if [ $? -ne 0 ]
        then
            echo "stop failed, may be $SERVICE isn't running"
            exit $?
        else
            rm -rf $SERVICE.pid
            echo "stop success"
        fi
    }

    restart(){
        stop&&start
    }

    status(){
        num=`ps -ef | grep $SERVICE | grep -v grep | wc -l`
        if [ $num -eq 0 ]
        then
            echo "$SERVICE isn't running"
        else
            echo "$SERVICE is running"
        fi
    }

    case $1 in
        start)      start ;;
        stop)      stop ;;
        restart)  restart ;;
        status)  status ;;
        *)          echo "Usage: $0 {start|stop|restart|status}" ;;
    esac

    exit 0