#!/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.$$"


# [Main] 
for client_IP in $client_IPs
do
    # local variables
    drbl_vm_xentop_file="/tmp/drbl_vm_xentop.$client_IP.$$"
    IP_status="online"
    client_hostname="$(cat $Work_Home/etc/IP_HOST_TABLE | grep -v "#" | awk '{print $2}')"
    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 -b -i1" >> $drbl_vm_xentop_file
        vm_hostnames="$(cat $drbl_vm_xentop_file | sed -n '3,$p' | awk '{print $1}')"
    
        printf "[$client_hostname]\n" >> $drbl_vm_file
        printf "[$client_hostname]\n"
        declare -i i=1

        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}M $vm_CPU_loading%% $vm_Ram_loading%%\n" >> $drbl_vm_file
            printf "VM$i: $vm_hostname VCPU=$vm_CPU_core Mem=${vm_Ram}M VCPU_loading=$vm_CPU_loading%% Mem_usage=$vm_Ram_loading%%\n"
            i=i+1
        done
    
    fi
done

