#!/bin/env bash
##Description: green check before true switch

script_run_role="PRIMARY,STANDBY"
script_base_name="tidb_so_green_check"

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "bash ${ShellName}  [-primaryhostname <hostname>]"
    echo "-standbyhostname <hostname_standby> "
    echo " "
    echo " #Description:"
    echo " -primaryhostname ,the primary cluster manager host"
    echo " -standbyhostname ,the standby cluster manager host"
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -primaryhostname node1 -standbyhostname sa-172-16-4-81" 
    echo " "
    exit 22
}

function f_PrintLog
{
    _LogFlag=$(echo "$1"|tr "a-z" "A-Z")
    _LogMessage=$2
    [ $(echo "$1"|wc -L) -eq 4 ] && _LogFlag=$(echo "${_LogFlag}_")
    echo "$(date "+%Y%m%d.%H%M%S"):[${_LogFlag}]:${UserName}@${HostName}:${2}";
}

###############################################################################

function f_checkusedtool
{
    f_PrintLog "Info" "Start to run f_checkusedtool."
    binary_list="$1"
    f_PrintLog "Info" "Start to check command: ${binary_list}"
    total_fail=0
    total_cmd=0
    for bin_cmd in $(echo ${binary_list})
    do 
        _rt=$(which ${bin_cmd} 2>/dev/null)
        cmd_ok=$?
        if [ ${cmd_ok} -eq 0 ]
        then
            f_PrintLog "Info" "command ${bin_cmd} was installed on ${_rt}."
        else
            f_PrintLog "Warn" "command ${bin_cmd} was not installed. ${_rt}"
            total_fail=$(($total_fail+1))
        fi
        total_cmd=$(($total_cmd+1))
    done
    [ ${total_fail} -gt 0 ] && _flag="Error" || _flag="Info"
    f_PrintLog "${_flag:-INFO}" "check command failed, fail/total num is ${total_fail}/${total_cmd}"
}

function f_backfile
{
    _filename=$1
    _filepath="${_filename%/*}/baktmp"
    [ ! -d ${_filepath} ] && mkdir -p "${_filepath}"
    if [ -f "${_filename}" ]
    then
        f_PrintLog "Warn" "file ${_filename} already exists, rename it now!!"
        ls -l ${_filename}
        sleep 1
        mv "${_filename}" "${_filepath}/${_filename##*/}.bak_$(date +%Y%m%d.%H%M%S)"
    fi
}

function f_generate_so_config
{
    f_PrintLog "Info" "Start to run Script f_generate_so_config"
    #init cluster parameter

    so_config="${TidbHome}/switchover/cluster_switchover_config_${HostRole:0:1}.cnf"
    if [ -f "${so_config}" ]
    then
        f_backfile "${so_config}" 
    fi

    #备集群drainer配置
    scaleDrYaml="${TidbHome}/switchover/${clsName}_scaleout_slave_drainer.yaml"
    if [ "${HostRole}" = "STANDBY" -a -n "${t2tDrId}" ]
    then
        tidbIp_s=${t2tDrId%:*}
        f_PrintLog "Info" "Standby to Primary remote ip and dr:${tidbIp_s} ${t2tDrId}"
    elif [ "${HostRole}" = "STANDBY" -a -f "${scaleDrYaml}" ]
    then
        tidbIp_s=$(awk -F: '{if($1~" host"){gsub(" ","",$2);print $2;exit}}' ${scaleDrYaml} 2>/dev/null)
        f_PrintLog "Info" "Standby to Primary remote ip and yaml:${tidbIp_s} ${scaleDrYaml}"
    fi


    if [ "${HostRole}" = "PRIMARY" ]
    then
        echo "PRIMARYRUNTIME=$(date +%Y%m%d.%H%M%S)"          >> "${so_config}"
        echo "PRIMARYRUNTYPE=GREENLIGHT"            >> "${so_config}"
        echo "PRIMARYTIDBHOME=${TidbHome}"          >> "${so_config}"
        echo "PRIMARYHOSTNAME=${HostName}"          >> "${so_config}"
        echo "PRIMARYCLUSTERNAME=${clsName}"        >> "${so_config}"
        echo "PRIMARYIP=${tidbIp}"                  >> "${so_config}"
        echo "PRIMARYPORT=${tidbPort:-4000}"        >> "${so_config}"
        echo "STANDBYIP=${tidbIp_s}"                >> "${so_config}"
        echo "PRIMARYAPPUSERS=${appUsers}"          >> "${so_config}"
        echo "PRIMARYT2TDRAINER=${t2tDrId}"         >> "${so_config}"
        echo "PRIMARYT2FDRAINER=${t2fDrId}"         >> "${so_config}"
    elif [ "${HostRole}" = "STANDBY" ]
    then
        echo "STANDBYRUNTIME=$(date +%Y%m%d.%H%M%S)"          >> "${so_config}"
        echo "STANDBYRUNTYPE=GREENLIGHT"            >> "${so_config}"
        echo "STANDBYTIDBHOME=${TidbHome}"          >> "${so_config}"
        echo "STANDBYHOSTNAME=${HostName}"          >> "${so_config}"
        echo "STANDBYCLUSTERNAME=${clsName}"        >> "${so_config}"
        echo "STANDBYIP=${tidbIp}"                  >> "${so_config}"
        echo "STANDBYPORT=${tidbPort:-4000}"        >> "${so_config}"
        echo "STANDBYAPPUSERS=${appUsers}"          >> "${so_config}"
        echo "STANDBYT2TDRAINER=${t2tDrId}"         >> "${so_config}"
        echo "STANDBYT2FDRAINER=${t2fDrId}"         >> "${so_config}"
        echo "PRIMARYIP=${tidbIp_s}"                >> "${so_config}"
    fi

    #default var
    echo "PASSWD="             >> "${so_config}"
    echo "BACKUPDIR=${backupdir}"             >> "${so_config}"
    echo "SYNCDIFFTABLES=${syncdifftables}"  >> "${so_config}"

    echo "************************"
    cat "${so_config}" | grep -v "PASSWD"
    echo "************************"
    f_PrintLog "Info" "Config file generate on ${so_config}, pls check the context"
    sleep 10

}

function f_runscp
{
    _file_source=$1
    _file_tartget=$2
    _nodid=$3
    _action=$4
    f_PrintLog "Info" "Start to ${_action} file:${_file_source} ${_file_tartget}, remote:${_nodid}"
    echo "tiup cluster ${_action} ${clsName} ${_file_source} ${_file_tartget} -N${_nodid}"
    tiup cluster ${_action} ${clsName} ${_file_source} ${_file_tartget} -N${_nodid}
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "tiup scp file failed, remote host:${_nodid}, file:${_file_source}"
        exit 1
    else
        f_PrintLog "Info" "tiup scp file finish, remote host:${_nodid}, file:${_file_source}"
    fi
}

function f_checkconfig
{
    _pk=$1
    _sk=$2

    _pv=$(awk -F= -v ck="${_pk}" '{if($1==ck){print $2;exit}}' ${primaryconfig}  2>/dev/null)
    _sv=$(awk -F= -v ck="${_sk}" '{if($1==ck){print $2;exit}}' ${standbyconfig}  2>/dev/null)

    if [ "${_pv}" = "${_sv}" ]
    then
        f_PrintLog "Info" "Primary and Standby config ${_pk} matched, ${_pv} = ${_sv}, check pass!"
    else
        f_PrintLog "Error" "Primary and Standby config ${_pk} not match, ${_pv} != ${_sv}, exit!!!"
        exit 1
    fi

}

function f_check_runtime
{
    _so_config=$1
    f_PrintLog "Info" "Start to run Script f_check_runtime"
    _ts1=$(awk -F= '{if($1=="PRIMARYRUNTIME"){gsub("\\.","",$2);printf "%d",$2;exit}}' ${_so_config} 2>/dev/null)
    _ts2=$(awk -F= '{if($1~"STANDBYRUNTIME"){gsub("\\.","",$2);printf "%d",$2;exit}}' ${_so_config} 2>/dev/null)

    f_PrintLog "Info" "Get runtime from config PRIMARYRUNTIME:${_ts1}, STANDBYRUNTIME:${_ts2}."
    
    curdt=$(date +%Y%m%d)
    if [ "${curdt}" != "${_ts1:0:8}" -o "${curdt}" != "${_ts2:0:8}" ]
    then
        f_PrintLog "Info" "The runtime ${_ts1:0:8},${_ts2:0:8} is not today ${curdt}, check failed!!!"
        exit 1
    fi

    # _tsdiff=$(expr ${_ts1} - ${_ts2})
    # if [ ${_tsdiff} -le 100 -a ${_tsdiff} -ge -100 ]
    # then
    #     f_PrintLog "Info" "The runtime diff is ${_tsdiff}, check pass!"
    # else
    #     f_PrintLog "Info" "The runtime diff is ${_tsdiff}, config file may wrong, check failed!!!"
    #     exit 1
    # fi
}

function f_merge_so_config
{
    f_PrintLog "Info" "Start to run Script f_merge_so_config"
    #get standby config
    soconfig="${TidbHome}/switchover/cluster_switchover.config"
    primaryconfig="${TidbHome}/switchover/cluster_switchover_config_P.cnf"
    standbyconfig="${TidbHome}/switchover/cluster_switchover_config_S.cnf"
    remotefile="./switchover/cluster_switchover_config_S.cnf"
    f_backfile "${soconfig}" 
    f_backfile "${localfile}" 
    f_runscp "${remotefile}" "${standbyconfig}" "${tidbIp_s}" "pull"
    
    #two PRIMARY
    _pv=$(awk -F= -v ck="PRIMARYHOSTNAME" '{if($1==ck){print $2;exit}}' ${primaryconfig}  2>/dev/null)
    _sv=$(awk -F= -v ck="PRIMARYHOSTNAME" '{if($1==ck){print $2;exit}}' ${standbyconfig}  2>/dev/null)
    if [ -n "${_pv}" -a -n "${_sv}" -a "${_pv}" != "${_sv}" ]
    then
        f_PrintLog "Error" "Get two primary node ${_pv} and ${_sv}, pls check the input hostname, exit!!!"
        exit 1        
    fi

    f_checkconfig "STANDBYIP" "STANDBYIP"
    f_checkconfig "PRIMARYIP" "PRIMARYIP"
    f_checkconfig "PRIMARYAPPUSERS" "STANDBYAPPUSERS"
    
    f_PrintLog "Info" "Start to merge two config file, ${soconfig}"
    cat ${primaryconfig} ${standbyconfig} |sort -u|grep -v "APPUSERS" > ${soconfig}
    echo "************************"
    cat ${soconfig} | grep -v "PASSWD"
    echo "************************"
    f_PrintLog "Info" "cluster ${clsName} switchover config is ready, pls check the file context, ${soconfig}"
    sleep 10
    f_runscp "${soconfig}" "${soconfig}" "${tidbIp_s}" "push"
    f_check_runtime "${soconfig}"
}

function f_committs_diff
{
    _ip_s=$1

    f_PrintLog "Info" "Start to run f_committs_diff."
    #最多检查3次,每次间隔10s
    for i in 1 2 3 
    do
        #commit tso
        ck_sql="select checkPoint from ${checkpointschema}.checkpoint order by clusterID desc limit 1"
        f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${connOk}"
        exec_result=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${ck_sql}")
        cmt_tso=$(echo $exec_result  | python -m json.tool | awk '{
        if($1~"commitTS"){gsub(",","",$2);printf "%s\n",$2;exit}
        }')
        echo $exec_result  | python -m json.tool

        ck_sql="select from_unixtime(conv(left(bin('${cmt_tso}'),41),2,10)/1000) "
        f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${connOk}"
        exec_result=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${ck_sql}")
        cmt_ts=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${ck_sql}")
        
        #time-tso diff
        ck_sql="select timestampdiff(SECOND,TIDB_PARSE_TSO(${cmt_tso}),NOW()) "
        f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${connOk}"
        exec_result=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${ck_sql}")
        f_PrintLog "Info" "Binlog commitTS is ${cmt_tso}, ${cmt_ts}, is ${exec_result} seconds (should<30) away from now!"
        
        [ ${exec_result} -lt 30 ] && return 0
        sleep 10
    done 
    return 1
}

function f_runsqlstmt2
{
    _execsql=$1
    f_PrintLog "Info" "START TO RUN SQL STMT:${_execsql}, DBinfo:${connOk}"
    exec_result=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${_execsql}")
    _rt_code=$?
    if [ $_rt_code -ne 0 ]
    then
        f_PrintLog "Error" "Run stmt failed, exit"
        exit 1
    fi
}

function f_checkpointflag
{
    f_PrintLog "Info" "Start to run Script f_checkpointflag"
    #检查是否存在checkpoint表
    ck_sql="select count(1) from information_schema.tables where table_name='checkpoint' and table_schema='${checkpointschema}'"
    f_runsqlstmt2 "${ck_sql}"
    if [ $exec_result -eq 0 ]
    then 
        CkpointRole="PRIMARY"
        f_PrintLog "Info" "Current cluster ${clsName} checkpoint table not exists, the cluster role should be ${CkpointRole}"  
        return 0
    else
        f_PrintLog "Info" "Current cluster ${clsName} checkpoint exists, continue check"  
    fi

    #checkpoint表只能有1条记录
    ck_sql="select count(1) from ${checkpointschema}.checkpoint"
    f_runsqlstmt2 "${ck_sql}"
    if [ $exec_result -gt 1 ]
    then 
        f_PrintLog "Error" "Current cluster ${clsName} checkpoint contain more then 1 rows, exit"  
        exit 1
    fi

    #只有备集群的checkpoint表变化
    f_committs_diff
    _rt_code=$?
    if [ $_rt_code -eq 0 ]
    then
        CkpointRole="STANDBY"
        f_PrintLog "Info" "Current cluster ${clsName} checkpoint tso ${exec_result} seconds away from now, the cluster role should be ${CkpointRole}"  
    else
        CkpointRole="PRIMARY"
        f_PrintLog "Info" "Current cluster ${clsName} checkpoint tso ${exec_result} seconds close to now, the cluster role should be ${CkpointRole}"  
    fi
}

function f_backupsizecheck
{
    _clsname=$1

    f_PrintLog "Info" "Start to run f_backupsizecheck."
    
    pdNode=$(tiup cluster display ${_clsname}  2>/dev/null |awk  '{
        if($2=="pd" && $6~"Up"){printf "%s\n",$1;exit}
        }')
    f_PrintLog "Info" "Get cluster size pd-ctl ${pdNode}"
    pdRepls=$(pd-ctl --pd="http://${pdNode}" config show replication | awk -F: '{if($1~"max-replicas"){gsub(",","",$2);printf "%d",$2;exit}}')
    storeSize=$(pd-ctl --pd="http://${pdNode}" store | awk '{if($1~"used_size"){gsub(",","",$2);gsub("\"","",$2);printf "%s\t",$2}}')
    sizeMB=0
    for _size in ${storeSize}
    do
        _sizemb=$(echo ${_size}|awk '
            /.*KiB/{gsub("KiB","",$1);sz=$1/1000}
            /.*MiB/{gsub("MiB","",$1);sz=$1}
            /.*GiB/{gsub("GiB","",$1);sz=$1*1000}
            /.*TiB/{gsub("TiB","",$1);sz=$1*1000000}
            END{printf "%d\n",sz}
            ')
        sizeMB=$((sizeMB+_sizemb))
    done
    f_PrintLog "Info" "Cluster ${clsName} size is ${sizeMB}MiB, max-replicas:${pdRepls}"
    sizeMB=$((sizeMB/pdRepls*3/2))

    df -h
    diskFree=$(df -P -m ${backupdir}|awk '!/Filesystem/{printf "%d",$4;exit}')
    if [ ${diskFree:-1} -gt ${sizeMB:-1} ]
    then
        f_PrintLog "Info" "backup dir ${backupdir} free space is ${diskFree}MB, greater then dbsize ${sizeMB}MB"
    else
        f_PrintLog "Error" "backup dir ${backupdir} free space is ${diskFree}MB, less then dbsize ${sizeMB}MB, quit!!!"
        exit 1
    fi
}


###############################################################################
##Init##
export LANG=en_US
TidbHome=$(awk -F: -v un="tidb" '{if($1==un){print $6;exit}}' /etc/passwd 2>/dev/null)
ShellName="$(echo $0|awk -F / '{print $NF}')";ShellOption="$@";
WorkDir="$(echo $0|sed s/${ShellName}//g)";[ -z "${WorkDir}" ] && WorkDir=${PWD};cd ${WorkDir};WorkDir=${PWD}
LogDir="${TidbHome}/switchover/logs";mkdir -p ${LogDir};
RunTs=$(date "+%Y%m%d.%H%M%S")
LogFile="${LogDir}/${script_base_name}_${ShellName}.${RunTs}.log";
Shellcksum=$(cksum ${WorkDir%/}/${ShellName} 2>/dev/null|awk '{printf "%d",$1}')
declare -i UserID=$(id -u);declare UserName=$(whoami);declare HostName=$(hostname);
###############################################################################
##TiDB Var##
locallogin="tidblogin"
adminusers="root,tidb,timon,repl"
checkpointschema="tidb_binlog"
backupdir="/data2/tidbbackup"
###############################################################################
###############################################################################
##Get inopt
[ -z "${ShellOption}" -a -z "${primaryhostname}" -a -z "${standbyhostname}" ] && f_syntax;
for inopt in ${ShellOption}
do
    case $(echo $inopt|tr a-z A-Z) in
    -PRIMARYHOSTNAME|-HOSTNAME) CurOpt="-HOSTNAME_P";continue;;
    -STANDBYHOSTNAME) CurOpt="-HOSTNAME_S";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME_P) declare primaryhostname="${inopt}";continue;;
    -HOSTNAME_S) declare standbyhostname="${inopt}";continue;;
    esac
done

f_PrintLog "Info" "Start to run Script ${ShellName}, the Shellcksum is ${Shellcksum}"
f_PrintLog "Info" "Script Options:${ShellOption}"

function f_checkparamandcluster
{

    f_PrintLog "Info" "Start to run Script f_checkparamandcluster"
    f_PrintLog "Info" "Input Parameter: script_run_role:${script_run_role}, primaryhostname:${primaryhostname}, standbyhostname:${standbyhostname}"

    #没有tiup的机器非管理节点,不执行
    tiupOk=$(which tiup 2>/dev/null)
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "Current host ${HostName} not contain tiup, exit!"
        exit 1
    else
        f_PrintLog "Info" "Current host ${HostName} contain tiup, check pass!"
    fi

    #没有4000端口的机器,不符合规范,不执行
    tidb4kOk=$(ps -ef | grep "tidb-server -P 4000"| grep -v grep|wc -l)
    if [ ${tidb4kOk:-0} -lt 1 ]
    then
        f_PrintLog "Error" "Current host ${HostName} not contain valid tidb 4000, exit"
        exit 1
    else
        f_PrintLog "Info" "Current host ${HostName} contain valid tidb 4000, check pass!"
    fi

    #不能使用loginpath=tidblogin登录的机器,不符合部署规范,不执行
    connOk=$(mysql --login-path=${locallogin:-tidblogin} -NBe "select user()")
    if [ -z "${connOk}" ]
    then
        f_PrintLog "Error" "No passwd login failed, pls check mysql --login-path=${locallogin:-tidblogin} "
        exit 1
    else
        f_PrintLog "Info" "No passwd login successfully, connect user is ${connOk}, check pass!"
    fi

    #check binary command
    binary_list="tiup mysql pd-ctl dumpling sync_diff_inspector"
    f_checkusedtool "${binary_list}"
    if [ ${total_fail} -gt 0 ] 
    then
        f_PrintLog "Error" "check binary command in PATH failed, fail/total num is ${total_fail}/${total_cmd}"
        exit 1
    else
        f_PrintLog "Info" "check binary command in PATH finish, check pass!"
    fi

    #没有本地drianer进程的,为主集群的备用tiup,不执行
    drainerProc=$(ps -ef | grep "bin/drainer"| grep -v grep| wc -l)
    if [ ${drainerProc} -eq 0 ]
    then
        f_PrintLog "Error" "Current host ${HostName} not contain valid drainer, count ${drainerProc}, check failed!"
        #exit 1
    else
        f_PrintLog "Info" "Current host ${HostName} contain valid drainer, count ${drainerProc}, check pass!"
    fi

    if [ "${primaryhostname}" == "${HostName}" ] 
    then
        HostRole="PRIMARY"
        f_PrintLog "Info" "Current host ${HostName}=${primaryhostname}, the cluster role should be ${HostRole}"
    elif [ "${standbyhostname}" == "${HostName}" ]
    then
        HostRole="STANDBY"
        f_PrintLog "Info" "Current host ${HostName}=${standbyhostname}, the cluster role should be ${HostRole}"
    else
        HostRole="UNKNOWN"
        f_PrintLog "Error" "Current host ${HostName} not in input hosts:${primaryhostname} ${standbyhostname}, exit"
        exit 1
    fi

    #获取集群信息
    f_getclusterinfo

    #Checkpoint表判断主备
    f_checkpointflag

    #只有在切换前的初始状态可进行如下判断
    #有一个本地drainer进程,集群有一个远程drainer进程,即为主集群的主管理tiup节点
    #有零个本地drainer进程,集群有一个远程drainer进程,即为主集群的次管理tiup节点
    #有两个本地drainer进程,集群没有远程drainer进程,即为备集群的管理tiup节点
    #脚本应该在standby指定tiup运行

    # drainerLocal=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp%.*}" '{
    #     if($1~id && $2=="drainer" && $6=="Up"){printf "%s",$1;exit}
    #     }')
    # drainerRemote=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp%.*}" '{
    #     if($1!~id && $2=="drainer" && $6=="Up"){printf "%s",$1;exit}
    #     }')

    if [ -n "${drainerRemote}" -a -z "${drainerLocal}" -a ${drainerProc} -lt 1 ]
    then
        TiupRole="STANDBY"
        HostRoleDr="PRIMARY"
        f_PrintLog "Info" "Current host ${HostName}, local drainer:${drainerLocal}, ps:${drainerProc}, remote drainer:${drainerRemote}, maybe primary cluster ${TiupRole} tiup"
    elif [ -n "${drainerRemote}" -a -n "${drainerLocal}" -a ${drainerProc} -le 1 ]
    then
        TiupRole="PRIMARY"
        HostRoleDr="PRIMARY"
        f_PrintLog "Info" "Current host ${HostName}, local drainer:${drainerLocal}, ps:${drainerProc}, remote drainer:${drainerRemote}, maybe primary cluster ${TiupRole} tiup"
    elif [ -z "${drainerRemote}" -a -n "${drainerLocal}" -a ${drainerProc} -ge 1 ]
    then
        TiupRole="PRIMARY"
        HostRoleDr="STANDBY"
        f_PrintLog "Info" "Current host ${HostName}, local drainer:${drainerLocal}, ps:${drainerProc}, remote drainer:${drainerRemote}, maybe standby cluster ${TiupRole} tiup"
    else
        f_PrintLog "Warn" "Current host ${HostName}, local drainer:${drainerLocal}, ps:${drainerProc}, remote drainer:${drainerRemote}, can not get correct role"        
        exit 1
    fi

    if [ "${HostRole}" = "${HostRoleDr}" ]
    then
        f_PrintLog "Info" "Current cluster role was confirmed, ${HostRole}"        
    else
        f_PrintLog "Error" "Current cluster role was confused, Host:${HostRole} != Dr:${HostRoleDr}, pls check input host role" 
        exit 1       
    fi

    #备份空间充足
    f_backupsizecheck "${clsName}"

    #备集群检查ssh

    
}


function f_getclusterinfo
{
    f_PrintLog "Info" "Start to run f_getclusterinfo."
    # clsname,connip,connport,dbsize,dbs,userlist,drainernode,backupdir,repluser
    clsName=$(tiup cluster list 2>/dev/null|awk '{if($3~"v" && $4~"tiup"){printf "%s\n",$1;exit}}') 
    if [ -z "${clsName}" ]
    then
        f_PrintLog "Error" "Can not find valid cluster name using:tiup cluster list"
        exit 1
    fi
    f_PrintLog "Info" "find valid cluster name is ${clsName}"
    tiup cluster display ${clsName} 

    tidbclsinfo=$(tiup cluster display ${clsName} 2>/dev/null)
    IPList=$(ip a |awk '/^[1-9]/{gsub(":","",$2);en=$2}
     /^[ |\t]*inet /{gsub(".*:","",$2);gsub("/.*","",$2);if(en!~"^lo")N[$2]=en}
     END{for(ip in N){printf "%s\n",ip}}')
    tidbProc=$(ps -ef | grep "tidb-server -P 4000"| grep -v grep)
    tidbPort=$(echo ${tidbProc}|awk -F"-P" '{print $2}'|awk '{printf "%d",$1}')
    tidbIp=$(echo ${tidbProc}|awk -F"--advertise-address=" '{print $2}'|awk '{printf "%s",$1}')

    tidbNodeId=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp}:${tidbPort}" '{
     if($1==id && $2=="tidb" && $6=="Up" ){printf "%s",$1;exit}
     }')

    [ -z "${tidbNodeId}" ] && f_PrintLog "Warn" "Can not find valid tidb node ${tidbIp}:${tidbPort}, the cluster name is ${clsName}"

    #根据drainerid是否等于tidbid判断drainer归属
    tidb_urls=$(tiup cluster display ${clsName} 2>/dev/null|awk '{if($2=="tidb"){gsub(":.*","",$1);printf "%s ",$1}}')
    dr_urls=$(tiup cluster display ${clsName} 2>/dev/null|awk '{if($2=="drainer"){printf "%s,%s ",$1,$6}}')
    for drid in ${dr_urls}
    do
        _localflag=$(echo ${tidb_urls} |grep -w ${drid%:*})
        _Upflag=$(echo ${drid} |grep -w "Up")
        if [ -z "${_localflag}" ]
        then
            drainerRemote="${drainerRemote}${drid}"
            [ -n "${_Upflag}" ] && drainerRemoteUp="${drainerRemoteUp}${drid}"
            f_PrintLog "Info" "Find a remote drainer ${drid}, drainerRemote:${drainerRemote}"
        else
            drainerLocal="${drainerLocal}${drid}"
            [ -n "${_Upflag}" ] && drainerLocalUp="${drainerLocalUp}${drid}"
            f_PrintLog "Info" "Find a locale drainer ${drid}, drainerLocal:${drainerLocal}"
        fi
    done
    
    _drCt=$(echo ${drainerRemote}|awk -F: '{print NF}')
    if [ ${_drCt} -gt 2 ]
    then
        f_PrintLog "Error" "The remote drainer count is ${_drCt}, exit!!!"
        exit 1
    fi

    t2fDrId=${drainerLocal}
    t2tDrId=${drainerRemote}
    tidbDrainerId=${drainerRemote}
    drainerRemote=${drainerRemoteUp}

    # t2fDrId=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp%.*}" '{
    #    if($1~id && $2=="drainer"){printf "%s,%s",$1,$6;exit}
    #    }')
    # t2tDrId=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp%.*}" '{
    #    if($1!~id && $2=="drainer"){printf "%s,%s",$1,$6;exit}
    #    }')

    # tidbDrainerId=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp%.*}" '{
    #  if($1!~id && $2=="drainer"){printf "%s",$1;exit}
    #  }')

    if [ -z "${tidbDrainerId}" ] 
    then
        f_PrintLog "Warn" "Can not find valid drainer node, the cluster name is ${clsName}"
    else
        tidbIp_s=${tidbDrainerId%:*}
    fi

    adminusers_sql=$(echo "${adminusers}"|sed "s/,/','/g")
    _execsql="select group_concat(concat(user,'@',host) SEPARATOR ',') from  mysql.user where user not in ('${adminusers_sql}')"
    f_PrintLog "Info" "START TO RUN SQL:${_execsql}, DBinfo ${tidbIp}:${tidbPort}"
    appUsers=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${_execsql}")

    f_PrintLog "Info" "Get ${HostRole} cluster info finished. clsname:${clsName}, Ip:${tidbIp}, Port:${tidbPort}, drainerId:${tidbDrainerId}, standbyIp:${tidbIp_s}, appUser:${appUsers}"
}



###################
####    Main   ####
###################

function greencheck_main
{
    f_PrintLog "Info" "Start to run Script ${ShellName} on ${HostName}, script_base_name ${script_base_name}."
    #获取脚本执行需要的集群信息
    f_checkparamandcluster  

    #
    f_generate_so_config
    #获取脚本执行需要的数据库连接信息 
    f_PrintLog "Info" "Get ${HostRole} cluster info finished. clsname:${clsName}, clsname_s:${clsName_s}, Ip:${tidbIp}, standbyIp:${tidbIp_s}, drainerId:${tidbDrainerId}"

    [ "${HostRole}" = "PRIMARY" ] && f_merge_so_config

    f_PrintLog "Info" "Successful to run Script ${ShellName} on ${HostName}, script_base_name ${script_base_name}."

}

greencheck_main | tee -a ${LogFile}
exit ${PIPESTATUS[0]} 


