class VcenterLib::VmConverter

convert VMware managed object into a simple hash

Constants

ATTRIBUTES

see vijava.sourceforge.net/vSphereAPIDoc/ver51/ReferenceGuide/vim.vm.ConfigInfo.html

Public Class Methods

new(vcenter) click to toggle source
# File lib/vcenter_lib/vm_converter.rb, line 49
def initialize(vcenter)
  @vcenter = vcenter
end

Public Instance Methods

facts() click to toggle source

get all vms and their facts as hash with vm.name as key

# File lib/vcenter_lib/vm_converter.rb, line 54
def facts
  logger.debug "get complete data of all VMs in all datacenters: begin"
  result = Hash[vm_mos_to_h(@vcenter.vms).map do |h|
    [h['name'], Hash[h.map { |k, v| [k.tr('.', '_'), v] }]]
  end]
  logger.debug "get complete data of all VMs in all datacenters: end"
  result
end
vm_mo_to_h(vm_mo, attributes = ATTRIBUTES) click to toggle source

convert a VMware RbVmomi::VIM::ManagedObject into a simple hash.

# File lib/vcenter_lib/vm_converter.rb, line 64
def vm_mo_to_h(vm_mo, attributes = ATTRIBUTES)
  return nil unless vm_mo
  props2h(vm_mo.collect!(*attributes))
end
vm_mos_to_h(vm_mobs, attributes = ATTRIBUTES) click to toggle source
# File lib/vcenter_lib/vm_converter.rb, line 69
def vm_mos_to_h(vm_mobs, attributes = ATTRIBUTES)
  vms = @vcenter.serviceContent.propertyCollector.collectMultiple(vm_mobs, *attributes)
  hosts = {} # cache already known hosts here
  vms.map do |_vm, props|
    extra = {}
    props.delete_if do |_k, v|
      if v.is_a? RbVmomi::VIM::HostSystem
        extra = hosts[v] || {}
        if extra.empty?
          # rubocop:disable Style/RescueModifier
          extra['datacenter'] = attribute(v.path, RbVmomi::VIM::Datacenter) rescue nil
          extra['cluster'] = attribute(v.path, RbVmomi::VIM::ClusterComputeResource) rescue nil
          extra['hypervisor'] = v.name rescue nil
          # rubocop:enable Style/RescueModifier
          hosts[v] = extra
        end
        true
      end
    end
    props.merge!(extra)
  end
end

Private Instance Methods

attribute(path, type) click to toggle source

return parent object based on class provides name of RbVmomi object.

# File lib/vcenter_lib/vm_converter.rb, line 109
def attribute(path, type)
  path.select { |x| x[0].is_a? type }[0][1]
end
props2h(props) click to toggle source
# File lib/vcenter_lib/vm_converter.rb, line 94
def props2h(props)
  extra = {}
  props.delete_if do |_k, v|
    if v.is_a? RbVmomi::VIM::HostSystem
      # rubocop:disable Style/RescueModifier
      extra['datacenter'] = attribute(v.path, RbVmomi::VIM::Datacenter) rescue nil
      extra['cluster'] = attribute(v.path, RbVmomi::VIM::ClusterComputeResource) rescue nil
      extra['hypervisor'] = v.name rescue nil
      # rubocop:enable Style/RescueModifier
    end
  end
  props.merge!(extra)
end