#!/bin/sh

PLUGIN_DIR=$(cd `dirname $0`; pwd)
export PATH=$PATH:${PLUGIN_DIR}/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${PLUGIN_DIR}/lib

startCount=0
lastResetTime=0          # last time of reset start_count
defaultStartCountHL=30   # the high level of startCount in a hour
hourMillSeconds=3600000  # a hour

# report info
appId=46049
moduleId=10124600
sn=$(cat /tmp/.efuse_sn)

check_plugin_run()
{
    for pid in $(cat ${PLUGIN_DIR}/dockerd.pid)
    do
        thread_num=`ps -ef| grep -w dockerd |grep -v "monitor"|awk -F ' ' '{print $2}'|grep ${pid}|wc -l`
        if [ ${thread_num} -ge 1 ]; then
            return 1
        else
            return 0
        fi
    done
    return 0
}

start_plugin()
{
    auto_repair
	killall containerd-shim
    rm -rf /xyapp/docker/containers
    rm -rf /xyapp/docker/containerd
    ${PLUGIN_DIR}/bin/dockerclean > /dev/null 2>&1
    ulimit -HSn 8192;${PLUGIN_DIR}/bin/dockerd --config-file ${PLUGIN_DIR}/conf/dockerd.json > /dev/null 2>&1 &
    echo "$!" > ${PLUGIN_DIR}/dockerd.pid
    #${PLUGIN_DIR}/bin/dockerd -H unix:///var/run/docker.sock -H tcp://0.0.0.0:2375 --debug  --graph /xyapp/docker  --log-driver=journald  --storage-driver overlay > /dev/null 2>&1 &
}

auto_repair()
{
  current=`date "+%Y-%m-%d %H:%M:%S"`
  timeStamp=`date -d "$current" +%s`
  #将current转换为时间戳，精确到毫秒
  currentTimeStamp=$((timeStamp*1000+ $((10#`date "+%N"`/1000000))))

  if [ $((currentTimeStamp-lastResetTime)) -gt ${hourMillSeconds} ]; then
      lastResetTime=${currentTimeStamp}
      startCount=0
  fi

  startCount=$((startCount+1))
  if [ ${startCount} -gt ${defaultStartCountHL} ]; then
    rm -rf /xyapp/docker/
    lastResetTime=${currentTimeStamp}
    startCount=0
    repair_report
  fi
}


repair_report()
{
  current=`date "+%Y-%m-%d %H:%M:%S"`
  splitStr=%01
  reportInfo="c=o_galaxy_modulecall${splitStr}${current}${splitStr}${appId}${splitStr}${moduleId}${splitStr}${sn}${splitStr}${splitStr}1${splitStr}0${splitStr}0${splitStr}0${splitStr}repair docker"
  # reportInfo=${reportInfo//^A/%01}
  reportInfo=${reportInfo// /%20}
  curl -X POST 'https://report-miner.onethingpcs.com/report/flume' -H 'Content-Type: text/plain' --data-ascii ${reportInfo}
}


monitor()
{
    while :
    do
        check_plugin_run
        if [ $? -eq 0 ]; then
            start_plugin
        fi

        sleep 60
    done
}

monitor

