#!/bin/bash
#

user=repl
password=Xjb0^DDy
warn_connection=1000
namespace=
log_path=/tmp/mysql-monitor

if [ ! -d $log_path ]; then
    mkdir -p $log_path
fi


if [ -n "$namespace" ]; then
    hosts=middle-proxy
    mysql_conn=(mysql -h$hosts -u$user -p$password)
    ID=$(kubectl -n $namespace get pods | grep "^mysql" | awk '{print $1}' | head -1)
    if [ -n "$ID" ]; then
        thread=$(kubectl -n $namespace exec $ID -- ${mysql_conn[@]} -N -e "status;" 2>/dev/null | awk '/Threads:/{print $2}')
        if [[ "$thread" -ge "$warn_connection" ]]; then
            current_time=$(date +"%Y%m%d%H%M")
            echo "current time: $current_time, mysql connection: $thread, greater than $warn_connection, processlis save to processlist-${current_time}.txt" > $log_path/monitor.txt
             kubectl -n $namespace exec $ID -- ${mysql_conn[@]} -N -e "show full processlist;" 2>/dev/null > $log_path/processlist-${current_time}.txt
        fi
    fi
else
    hosts=mysql
    mysql_conn=(mysql -h$hosts -u$user -p$password)
    ID=$(docker ps | grep mysql | grep -v proxy | awk '{print $1}')
    if [ -n "$ID" ]; then
        thread=$(docker exec $ID ${mysql_conn[@]} -N -e "status;" 2>/dev/null | awk '/Threads:/{print $2}')
        if [[ "$thread" -ge "$warn_connection" ]]; then
            current_time=$(date +"%Y%m%d%H%M")
            echo "current time: $current_time, mysql connection: $thread, greater than $warn_connection, processlis save to processlist-${current_time}.txt" > $log_path/monitor.txt
            docker exec $ID ${mysql_conn[@]} -N -e "show full processlist;" 2>/dev/null > $log_path/processlist-${current_time}.txt
        fi
    fi
fi
