#!/bin/bash
#
check_exist(){
   if [ -z "$1" ]; then
      echo "$2 not running or not exist."
      return 102
   fi
}

get_container_id(){
    local ID=$(docker ps | grep "${1}:" | awk '{print $1}')
    echo $ID
}

check_mysql(){
   local mysql_conn=(mysql -urepl -pXjb0^DDy -N -e)
   local ID=$(get_container_id mysql)
   check_exist "$ID" mysql
   if [ $? -eq 0 ]; then
       docker exec $ID ${mysql_conn[@]} "select * from performance_schema.replication_group_members;" 2>/dev/null | column -t
   fi
}

check_es(){
   local ID=$(get_container_id elasticsearch)
   check_exist "$ID" es
   if [ $? -eq 0 ]; then
      if ! docker exec $ID test -f /usr/bin/curl; then
          echo "es has not /usr/bin/curl to get es status."
      else
          local hosts=$(docker exec $ID hostname)
          local comm="curl --connect-timeout 10 -s http://$hosts:9200/_cat/health?v"
          docker exec $ID $comm || echo "connect $hosts error."
      fi
   fi
}

check_rabbitmq(){
   local ID=$(get_container_id rabbitmq)
   check_exist "$ID" rabbitmq
   if [ $? -eq 0 ]; then
      docker exec $ID rabbitmqctl cluster_status | awk 'NR!=1{print}' | column -t
   fi
}


check_redis(){
   local ID=$(get_container_id redis)
   check_exist "$ID" redis
   if [ $? -eq 0 ]; then
       local password=$(docker exec $ID grep requirepass /data/config/redis.conf | awk -F'[ "]+' '{print $2}')
       for host in redis1 redis2 redis3; do
           echo
           echo "------$host cluster status--------"
           echo
           if [ -n "$password" ]; then
               docker exec $ID redis-cli -h $host -a $password -p 6379 info replication 2>/dev/null
           else
               docker exec $ID redis-cli -h $host -p 6379 info replication 2>/dev/null
           fi
       done
   fi
   echo
}


for svc in mysql es rabbitmq redis; do
      echo "########cluster status for $svc #######"
      echo
      check_$svc
      echo
done

