#!/usr/bin/env ruby

# Adds current directory to the library search path (make the script
# compatible with ruby 1.9.2)
$: << '.'

ONE_LOCATION=ENV["ONE_LOCATION"]

if !ONE_LOCATION
    RUBY_LIB_LOCATION="/usr/lib/one/ruby"
else
    RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
end

$: << RUBY_LIB_LOCATION

require 'socket'
require 'pp'
require 'rexml/document'
require 'Ganglia'

#############################
## CONFIGURATION GOES HERE ##
#############################

# host and port where to get monitoring information
GANGLIA_HOST='localhost'
GANGLIA_PORT=8649

# If this variable is set the the information will be read from that file
# otherwise it will get information from the ganglia endpoint
# defined previously
#GANGLIA_FILE='data.xml'


hypervisor=ARGV[0]
host_id=ARGV[1]
host=ARGV[2]

# Gets monitoring data from ganglia or file
begin
    if defined?(GANGLIA_FILE)
        ganglia=GangliaHost.new_from_file(host, GANGLIA_FILE)
    else
        ganglia=GangliaHost.new_from_ganglia(host, GANGLIA_HOST, GANGLIA_PORT)
    end
rescue
    STDERR.puts "Error reading ganglia data"
    exit -1
end

data=ganglia.to_hash


# Monitoring info extraction

info=Hash.new

total_cpu=data['cpu_num'].to_i*100

info["TOTALCPU"]=total_cpu
info["CPUSPEED"]=data['cpu_speed']

info["TOTALMEMORY"]=data['mem_total']
info["USEDMEMORY"]=data['mem_total'].to_i-data['mem_free'].to_i
info["FREEMEMORY"]=data['mem_free'].to_i

free_cpu=(data['cpu_idle'].to_f/100.0) * total_cpu

info["FREECPU"]=free_cpu
info["USEDCPU"]=total_cpu - free_cpu

info["NETTX"]=data['bytes_out']
info["NETRX"]=data['bytes_in']

info["KVM_VERSION"]=data['KVM_VERSION']
info["XEN_VERSION"]=data['XEN_VERSION']

# Get opennebula metrics from ganglia

info.merge!(ganglia.get_opennebula_metrics)


# Print information

info.each do |key, value|
    GangliaHost.print_info(key, value)
end



