#!/bin/bash
# Program:
#   Check DRBL client status
# Author: 
#   Jazz, Rock {jazz, rock}@nchc.org.tw
# Version:
#    1.0
# History:                                                                                          
#   2010/08/29  Rock    First release (1.0) 

source /opt/drbl-virt/conf/drbl-virt.conf
source $Work_Path/functions_drbl_virt


# [Varliables]
client_IPs=$(cat $Work_Home/etc/IP_HOST_TABLE | grep -v "#" | awk '{print $1}')
drbl_vm_file="/tmp/drbl_vm_status.$$"
drbl_vm_xentop_file="/tmp/drbl_vm_xentop.$$"
# check Xen or KVM
hypervisior=$(cat $Work_Home/etc/hypervisior)


# [Main] 
check_root

case $hypervisior in
    "Xen")
    for client_IP in $client_IPs
    do
        # local variables
        IP_status="online"
        client_hostname="$(cat $Work_Home/etc/IP_HOST_TABLE | grep -v "#" | grep $client_IP | awk '{print $2}')"
        vm_numbers=""
        vm_hostnames=""
        vm_IP=""
        vm_CPU_core=""
        vm_Ram=""
        vm_CPU_loading=""
        vm_Ram_loading=""
        # check network status
        ping -c1 -w1 $client_IP > /dev/null 2>&1 || IP_status="offline"
    
        if [ $IP_status == "online" ]; then
            ssh -o StrictHostKeyChecking=no $client_IP "xentop -d1 -b -i2 | awk '/^.*NAME/{i++}i==2'" > $drbl_vm_xentop_file
            vm_hostnames="$(cat $drbl_vm_xentop_file | sed -n '3,$p' | awk '{print $1}')"
    
            # printf "[$client_hostname] " >> $drbl_vm_file
            printf "[$client_hostname] "
            declare -i i=1

            vm_numbers=$(echo $vm_hostnames | wc -w)

           # printf "[Running VM: $vm_numbers]\n" >> $drbl_vm_file
            printf "[Running VM: $vm_numbers]\n"

            for vm_hostname in $vm_hostnames
            do  
                vm_CPU_core="$(cat $drbl_vm_xentop_file | grep $vm_hostname | awk '{print $9}')"
                vm_Ram="$(cat $drbl_vm_xentop_file | grep $vm_hostname | awk '{print $5}')"
                vm_CPU_loading="$(cat $drbl_vm_xentop_file | grep $vm_hostname | awk '{print $4}')"
                vm_Ram_loading="$(cat $drbl_vm_xentop_file | grep $vm_hostname | awk '{print $6}')"
               # printf "VM$i: $vm_hostname $vm_CPU_core ${vm_Ram}K $vm_CPU_loading%% $vm_Ram_loading%%\n" >> $drbl_vm_file
                printf "VM$i: $vm_hostname VCPU=$vm_CPU_core Mem=${vm_Ram}K VCPU_loading=$vm_CPU_loading%% Mem_usage=$vm_Ram_loading%%\n"
                i=i+1
            done
            echo "" 
        else
            echo "[Error] $client_hostname $client_IP is offline !"

        fi

    done
    ;;

    "KVM")
        echo "KVM"
    ;;
esac
# dlete tmp file
rm -f $drbl_vm_xentop_file
