#!/bin/bash
source /etc/profile
#日志格式化设置
logging_file="./service_check.log"
function log(){
        echo "$(date '+%Y-%m-%d %H:%M:%S')" "$@" >>$logging_file
}
# 判断配置文件是否存在，不存在就创建
[ -e cfg.csv ] || echo "# 进程判断标志,启动脚本,是否curl辅助判断服务状态,url地址,服务状态判断内容" >cfg.txt
# 定义默认文件周期和行周期
file_period=300
line_period=10
if [[ $# -eq 0 ]];then
  log "Use default period:file_period=300s,line_period=10s"
fi

if [[ $# -eq 1 ]];then
  file_period=${1}
  log "Use period:file_period=${file_period}s,line_period=10s"
fi

if [[ $# -eq 2 ]];then
  file_period=$1
  line_period=$2
  log "Use period:file_period=${file_period}s,line_period=${line_period}s"
fi

function curl_judge() {
    c_flag=$1
    c_url=$2
    c_cont=$3
    c_pid=$4
    c_start=$5
    if [[ $c_flag == 'Y'  ]];then
      log "接口${c_url}需要curl检测"
      if curl -s "$c_url" | grep -q "$c_cont"; then
        log "接口$c_url 结果返回正常"
      else
        log "接口$c_url 结果返回不正常，判断为假死，重启进程"
        kill -9 "$c_pid"
        $c_start
      fi
    else
      log "接口${c_url}不需要curl检测"
    fi
}
trap "break" SIGINT
while true ;do
  log "Start new cycle for checking service"
  # 将每行开头的空格去掉
  sed 's/^[[:space:]]*//' cfg.csv | while read -r line
  do
    # 去掉开头是#和空行
    if ! [[ $line == "#"* || -z $line ]];then
      # 判断该行的参数个数，等于5处理，否则忽略
      para_num=$(echo "$line"|sed 's/,/\n/g'|wc -l)
      if [[ $para_num == 5 ]];then
        # 批量获取多个参数并赋值
        IFS=',' read -r run_flag start_cmd curl_flag url judge_content <<< "$line"
        # 生成当前时刻的进程列表，并存储为临时文件
        ps -ef >".tmp_res"
        # 当前如果无符合该运行标志的进程，就运行启动脚本
        if ! grep -q "$run_flag" ".tmp_res"; then
          log "进程${run_flag}不存在，开始启动"
          "${start_cmd}"
        else
          log "进程${run_flag}存在，继续。。。"
          pid=$(grep "$run_flag" ".tmp_res" |grep -v grep|awk '{print $2}'|sed ':a;N;$!ba;s/\n/ /g')
          curl_judge "$curl_flag" "$url" "$judge_content" "$pid" "$start_cmd"
        fi
        log "开始行等待${line_period}s"
        sleep "${line_period}s"
      fi
    fi
  done
  log "开始文件等待${file_period}s"
  sleep "${file_period}s"
done
