#!/usr/bin/env ruby

ONE_LOCATION=ENV["ONE_LOCATION"]

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

$: << RUBY_LIB_LOCATION

require 'OpenNebula'
include OpenNebula


# --------------------------------------------------------------------------
# Copyright 2010, C12G Labs S.L.
#
# This file is part of OpenNebula VMware Drivers.
#
# OpenNebula VMware Drivers is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or the hope That it will be useful, but (at your
# option) any later version.
#
# OpenNebula VMware Drivers is distributed in WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with OpenNebula VMware Drivers . If not, see
# <http://www.gnu.org/licenses/>
# --------------------------------------------------------------------------

begin
    client = Client.new()
rescue Exception => e
    puts "Error: #{e}"
    exit(-1)
end

def add_info(name, value)
    value = "0" if value.nil? or value.to_s.empty?
    @result_str << "#{name}=#{value} "
end

def print_info
    puts @result_str
end

@result_str = ""

@host       = ARGV[1]

if !@host
    exit -1
end

load ENV['ONE_LOCATION'] + "/etc/vmwarerc"

data = perform_action("virsh -c #{LIBVIRT_URI} --readonly nodeinfo")

state = ""

data.split(/\n/).each{|line|
    if line.match('^CPU\(s\)')
        $total_cpu   = line.split(":")[1].strip.to_i * 100
    elsif line.match('^CPU frequency')
        $cpu_speed   = line.split(":")[1].strip.split(" ")[0]
    elsif line.match('^Memory size')
        $total_memory = line.split(":")[1].strip.split(" ")[0]
    end
}

# Loop through all vms
used_memory = 0 

vms = VirtualMachinePool.new(client)
if !OpenNebula.is_error?(vms)

    vms.info
    vm_ids_array = 
       vms.retrieve_elements("/VM_POOL/VM[STATE=3 or STATE=5]/HISTORY[HOSTNAME=\"#{@host}\"]/../ID")
    if vm_ids_array
        vm_ids_array.each do |vm_id| 
            vm=OpenNebula::VirtualMachine.new_with_id(vm_id, client)

            vm.info

            used_memory = used_memory + (vm['TEMPLATE/MEMORY'].to_i * 1024)
        end
    end
end
# 80% of the total free calculated memory to take hypervisor into account
free_memory = ($total_memory.to_i - used_memory ) * 0.8


add_info("HYPERVISOR","vmware")
add_info("TOTALCPU",$total_cpu)
add_info("CPUSPEED",$cpu_speed)
add_info("TOTALMEMORY",$total_memory)
add_info("FREEMEMORY",free_memory.to_i)

print_info
