#!/bin/sh

# Copyright (c) 2012 ken.naruo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


LANG=C;export LANG
SCRIPT_DIR=`dirname $0`
JOBNET=`echo ${SCRIPT_DIR} | awk -F [/] '{field = $NF } END {print field }'`
PROJECT=`echo ${SCRIPT_DIR} | awk -F [/] '{field = $(NF-1) } END {print field}'`
JOB_USER=`ps -ef | grep controller.sh | awk {'print $1'} | head -1`

## root dir load
. ${SCRIPT_DIR}/.root

JOBNET_LOG=${SCRIPT_DIR}/log/jobnet_log_`date +%Y%m%d`
STATUS_QUE=${ROOT}/que/status/${PROJECT}_${JOBNET}
ERROR_QUE=${ROOT}/que/error/${JOBNET}_`date +%Y%m%d`
TMP_QUE=${ROOT}/que/tmp/${PROJECT}::${JOBNET}


## jobnet prof load
grep -v SCHEDULE ${SCRIPT_DIR}/jobnet.prof > ${SCRIPT_DIR}/.jobnet_tmp
chmod 766 ${SCRIPT_DIR}/.jobnet_tmp
. ${SCRIPT_DIR}/.jobnet_tmp

STATUS_QUE_INPUT_MESSAGE=${ROOT}/que/status/${PROJECT}_${JOBNET}_IN_MESSAGE
STATUS_QUE_OUTPUT_MESSAGE=${ROOT}/que/status/${PROJECT}_${JOBNET}_OUT_MESSAGE

## cluster.conf load
. ${SCRIPT_DIR}/cluster.conf
. ${ROOT}/cluster/global.conf

#jobnet start
touch ${STATUS_QUE}
EXECUTE_HOST="localhost"

IFCONFIG=/usr/sbin/ifconfig

LINUX=`uname -a | grep Linux`

if [ "${LINUX}" ];then
  IFCONFIG=/sbin/ifconfig
fi

## master check
if [ "${CONTROLLER}" -a "${CLUSTER}" = yes ];then

 if [ ! -f ${ROOT}/cluster/flag/master ];then
  exit 0
 fi

 CHECK_CLUSTERD=`ps -ef | grep ecron_clusterd | grep -v grep`
 if [ "${CHECK_CLUSTERD}" = "" ];then
  exit 0
 fi

fi

## mesage check
if [ "${INPUT_MESSAGE}" ];then
 for MESSAGE in ${INPUT_MESSAGE}
  do 
    if [ ! -f "${ROOT}/que/message/${MESSAGE}" ]; then
      echo "`date` ${PROJECT} ${JOBNET} input message ${MESSAGE} not set" > ${STATUS_QUE_INPUT_MESSAGE}
      exit 1
    fi
  done

 echo "`date` input message ${INPUT_MESSAGE} exist" >> ${JOBNET_LOG}
 echo "`date` ${PROJECT} ${JOBNET} input message ${INPUT_MESSAGE} exist" > ${STATUS_QUE_INPUT_MESSAGE}

fi

## executtion server setting
if [ "${EXECUTE_SERVER}" ];then

  if [ "${DISPATCH}" = yes ];then

  if [ -f  ${SCRIPT_DIR}/.ssh_tmp ]; then
    rm -f ${SCRIPT_DIR}/.ssh_tmp
  fi

  for RHOST in ${EXECUTE_SERVER}
   do
    IP_ADDR_CHECK=`${IFCONFIG} -a | grep ${RHOST}`
    if [ "${IP_ADDR_CHECK}" = "" ];then

      ssh -p ${SSH_PORT} ${RHOST} echo "connection test"

      if [ $? != 0 ];then
       echo "`date +%Y%m%d` ${RHOST} ERROR connection failed" >> ${SCRIPT_DIR}/log/cluster_log_`date +%Y%m%d` 2>&1
      else
       WC=`ssh -p ${SSH_PORT} ${RHOST} ps -ef | grep -v grep | grep -v ssh | grep -v ps | grep -v controller | grep ${JOB_USER} | wc -l`
       echo remotehost $RHOST $WC >> ${SCRIPT_DIR}/.ssh_tmp
       chmod 766 ${SCRIPT_DIR}/.ssh_tmp
      fi

     else
       WC=`ps -ef | grep -v grep | grep -v ssh | grep -v ps | grep -v controller | grep ${JOB_USER} |  wc -l `
       echo localhost $RHOST $WC >> ${SCRIPT_DIR}/.ssh_tmp
     fi
   done
   EXECUTE_HOST=`cat ${SCRIPT_DIR}/.ssh_tmp | sort -n -k 3 | head -1 | awk '{print $1}'`
   EXECUTE_HOST_ADDR=`cat ${SCRIPT_DIR}/.ssh_tmp | sort -n -k 3 | head -1 | awk '{print $2}'`
 fi

fi

## job exexute

touch ${TMP_QUE}

for JOB in $JOB_ORDER
do
 RECOVERY_COMMAND=""
 ERROR_FLAG=""
 EXCLUSIVE_RESOURCE=""

 #job load
 . ${SCRIPT_DIR}/${JOB}
 JOB_LOG=${SCRIPT_DIR}/log/${JOB}_log_`date +%Y%m%d`

 #EXCLUSIVE resource check
 count=0
 sleep_time=10

 if [ "${EXCLUSIVE_RESOURCE}" ];then
  while [ -f "${ROOT}/que/exclusive_resource/${EXCLUSIVE_RESOURCE}" ]
  do
    WARN_FLAG=EXCLUSIVE_RESOURCE_LOCKED_BY_OTHER_JOB
    echo "`date` ${JOB} WARNING ${WARN_FLAG}" >> ${JOBNET_LOG}
    echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${WARN_FLAG}" > ${STATUS_QUE}
    echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${WARN_FLAG}" >> ${ERROR_QUE}

    if [ "${MAIL_ADDR}" ];then
     echo "${PROJECT} ${JOBNET} not start"|mailx -s "WARNING ${PROJECT} ${JOBNET} ${WARN_FLAG}" ${MAIL_ADDR}
    fi

    sleep ${sleep_time}
    count=`echo ${count}+1 | bc`
    sleep_time=`echo ${sleep_time}*2 | bc`
   
    if [ "${count}" = 20 ];then
     ERROR_FLAG=EXCLUSIVE_RESOURCE_CHECK_OVER_RETRY_COUNT
     echo "`date` ${JOB} has failed ${ERROR_FLAG}" >> ${JOBNET_LOG}
     echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${ERROR_FLAG}" > ${STATUS_QUE}
     echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${ERROR_FLAG}" >> ${ERROR_QUE}
     rm -f ${STATUS_QUE}
     rm -f ${TMP_QUE}
     exit 1
    fi
  done

  echo "`date` ${PROJECT} ${JOBNET} ${JOB} locked ${EXCLUSIVE_RESOURCE} resource" > ${ROOT}/que/exclusive_resource/${EXCLUSIVE_RESOURCE}

  #que mirror start
  if [ "${CONTROLLER}" ];then
  for RHOST in ${CONTROLLER}
    do
    IP_ADDR_CHECK=`${IFCONFIG} -a | grep ${RHOST}`
    if [ "${IP_ADDR_CHECK}" = "" ];then

      ssh -p ${SSH_PORT} ${RHOST} echo "`date` ${PROJECT} ${JOBNET} ${JOB} locked ${EXCLUSIVE_RESOURCE} resource" > ${ROOT}/que/exclusive_resource/${EXCLUSIVE_RESOURCE}

      if [ $? != 0 ];then
       echo "`date` ${RHOST} que mirror failed" >> ${SCRIPT_DIR}/log/cluster_log_`date +%Y%m%d` 2>&1
      fi
    fi
    done
  fi
  #que mirro end

 fi

 #JOB start
 echo "`date` ${JOB} START ${EXECUTE_HOST_ADDR}"   >> ${JOBNET_LOG}
 echo "`date` ${PROJECT} ${JOBNET} ${JOB} START ${EXECUTE_HOST_ADDR}" > ${STATUS_QUE}
 echo "`date` EXEC ${EXECUTE_COMMAND} ${EXECUTE_HOST_ADDR}" >> ${JOB_LOG}

 if [ "${EXECUTE_HOST}" = localhost ];then
  ${EXECUTE_COMMAND}  >> ${JOB_LOG} 2>&1
  EXECUTE_COMMAND_CHECK=$?
 else
  ssh -p  ${SSH_PORT} ${EXECUTE_HOST_ADDR} ${EXECUTE_COMMAND} >> ${JOB_LOG} 2>&1
  EXECUTE_COMMAND_CHECK=$?
 fi
 
 if [ "${EXCLUSIVE_RESOURCE}" ];then
  rm -f ${ROOT}/que/exclusive_resource/${EXCLUSIVE_RESOURCE}

  #que mirror
  if [ "${CONTROLLER}" ];then
  for RHOST in ${CONTROLLER}
    do
    IP_ADDR_CHECK=`${IFCONFIG} -a | grep ${RHOST}`
    if [ "${IP_ADDR_CHECK}" = "" ];then

      ssh -p  ${SSH_PORT} ${RHOST} rm -f ${ROOT}/que/exclusive_resource/${EXCLUSIVE_RESOURCE}

      if [ $? != 0 ];then
       echo "`date` ${RHOST} que mirror failed" >> ${SCRIPT_DIR}/log/cluster_log_`date +%Y%m%d` 2>&1
      fi
    fi
    done
  fi
  #que mirror end

 fi

 if [ "${EXECUTE_COMMAND_CHECK}" != 0 ];then
  ERROR_FLAG=EXECUTE_COMMAND_FAILED
  echo "`date` ${JOB} ERROR ${ERROR_FLAG} ${EXECUTE_HOST_ADDR}" >> ${JOBNET_LOG}
  echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${ERROR_FLAG} ${EXECUTE_HOST_ADDR}" > ${STATUS_QUE}
  echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${ERROR_FLAG} ${EXECUTE_HOST_ADDR}" >> ${ERROR_QUE}

  if [ "${MAIL_ADDR}" ];then
   echo "${PROJECT} ${JOBNET} ${JOB} has failed"|mailx -s "ERROR ${PROJECT} ${JOBNET} ${ERROR_FLAG}" ${MAIL_ADDR}
  fi
  
  if [ "${RECOVERY_COMMAND}" ];then
   echo "`date` ${PROJECT} ${JOBNET} ${JOB} RECOVERY START ${EXECUTE_HOST_ADDR}" > ${STATUS_QUE}
   echo "`date` EXEC ${RECOVERY_COMMAND} ${EXECUTE_HOST_ADDR}" >> ${JOB_LOG}

   if [ "${EXECUTE_HOST}" = localhost ];then
    ${RECOVERY_COMMAND} >> ${JOB_LOG} 2>&1
    RECOVERY_COMMAND_CHECK=$? >> ${JOB_LOG} 2>&1
   else
    sh -p  ${SSH_PORT} ${EXECUTE_HOST_ADDR} ${EXECUTE_COMMAND} >> ${JOB_LOG} 2>&1
    EXECUTE_COMMAND_CHECK=$? 
   fi
  fi

  if [ "${RECOVERY_COMMAND_CHECK}" != 0 ];then
    ERROR_FLAG=RECOVERY_FAILED
    echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${ERROR_FLAG} ${EXECUTE_HOST_ADDR}" > ${STATUS_QUE}
    echo "`date` ${JOB} ${ERROR_FLAG} ${EXECUTE_HOST_ADDR}" >> ${JOBNET_LOG}
    echo "`date` ${PROJECT} ${JOBNET} ${JOB} ${ERROR_FLAG} ${EXECUTE_HOST_ADDR}" >> ${ERROR_QUE}

     if [ "${MAIL_ADDR}" ];then
      echo "${PROJECT} ${JOBNET} ${JOB} RECOVERY has failed"|mailx -s "ERROR ${PROJECT} ${JOBNET} ${ERROR_FLAG}" ${MAIL_ADDR}
     fi

  else
    echo "`date` ${PROJECT} ${JOBNET} ${JOB} RECOVERY COMPLETE ${EXECUTE_HOST_ADDR}" > ${STATUS_QUE}
    echo "`date` ${JOB} RECOVERY COMPLETE" >> ${JOBNET_LOG}
  fi

  rm -f ${TMP_QUE}
  exit 1

 fi

 #Job End
 echo "`date` ${JOB} END ${EXECUTE_HOST_ADDR}"   >> ${JOBNET_LOG}

done

##Remove input message
if [ "${INPUT_MESSAGE}" ];then
 for MESSAGE in ${INPUT_MESSAGE}
  do
   rm -f ${ROOT}/que/message/${MESSAGE}
  done

 rm -f ${STATUS_QUE_INPUT_MESSAGE}

 #que mirror start
 if [ "${CONTROLLER}" ];then
  for RHOST in ${CONTROLLER}
  do
   IP_ADDR_CHECK=`${IFCONFIG} -a | grep ${RHOST}`
 
   if [ "${IP_ADDR_CHECK}" = "" ];then
   
    for MESSAGE in ${INPUT_MESSAGE}
     do

      ssh -p ${SSH_PORT} ${RHOST} rm -f ${STATUS_QUE_INPUT_MESSAGE}
 
      if [ $? != 0 ];then
        echo "`date` ${RHOST} que mirror failed" >> ${SCRIPT_DIR}/log/cluster_log_`date +%Y%m%d` 2>&1
      fi

     done

   fi

  done

 fi
 # que mirror end

fi

#Create output message
if [ "${OUTPUT_MESSAGE}" ];then

 touch ${ROOT}/que/message/${OUTPUT_MESSAGE}
 echo "`date` ${PROJECT} ${JOBNET} output message ${OUTPUT_MESSAGE} generate" > ${STATUS_QUE_OUTPUT_MESSAGE}
 echo "`date` output message ${OUTPUT_MESSAGE} generate" >> ${JOBNET_LOG}

 #que mirror start
 if [ "${CONTROLLER}" ];then
  for RHOST in ${CONTROLLER}
   do

   IP_ADDR_CHECK=`${IFCONFIG} -a | grep ${RHOST}`

   if [ "${IP_ADDR_CHECK}" = "" ];then

     ssh -p  ${SSH_PORT} ${RHOST} touch ${ROOT}/que/message/${OUTPUT_MESSAGE}

     if [ $? != 0 ];then
       echo "`date` ${RHOST} que mirror failed" >> ${SCRIPT_DIR}/log/cluster_log_`date +%Y%m%d` 2>&1
     fi

   fi
   done
 fi
 # que mirror end
fi

## Jobnet end
echo "`date` ${PROJECT} ${JOBNET} ALL JOB NORMAL END ${EXECUTE_HOST_ADDR}" > ${STATUS_QUE}
rm -f ${TMP_QUE}

exit 0
