foreman/app/models/hypervisor.rb @ 8a65dff7
a7ab36f3 | Ohad Levy | require_dependency 'hypervisor/guest'
|
|
200e91c8 | Ohad Levy | ||
96be8845 | Ohad Levy | class Hypervisor < ActiveRecord::Base
|
|
attr_accessible :name, :uri, :kind
|
|||
attr_reader :host
|
|||
validates_presence_of :name, :uri, :kind
|
|||
validates_uniqueness_of :name, :uri
|
|||
before_save :try_to_connect
|
|||
5410421d | Ohad Levy | default_scope :order => 'LOWER(hypervisors.name)'
|
|
96be8845 | Ohad Levy | ||
KINDS= %w{libvirt}
|
|||
85edffc1 | Ohad Levy | MEMORY_SIZE = (1..8).to_a.map {|n| 2**n*1024*128}
|
|
96be8845 | Ohad Levy | NETWORK_TYPES = %w{ bridge NAT }
|
|
# interfaces is a special case with libvirt, as its supported only on platforms that run netcf
|
|||
def interfaces
|
|||
b3f525e2 | Ohad Levy | query {host.interfaces + host.networks}
|
|
e25f52ae | Ohad Levy | rescue => e
|
|
logger.debug e.to_s
|
|||
[]
|
|||
end
|
|||
def storage_pools
|
|||
b3f525e2 | Ohad Levy | query {host.storage_pools.map(&:name)}
|
|
end
|
|||
def to_param
|
|||
name
|
|||
end
|
|||
def guests
|
|||
200e91c8 | Ohad Levy | query { Virt::Guest.all }
|
|
end
|
|||
def memory
|
|||
query {host.connection.node_get_info.memory }
|
|||
end
|
|||
def free_memory
|
|||
query {host.connection.node_free_memory } rescue nil
|
|||
end
|
|||
def cpus
|
|||
query {host.connection.node_get_info.cpus}
|
|||
b3f525e2 | Ohad Levy | end
|
|
def connect
|
|||
logger.info "trying to contact Hypervisor #{name}"
|
|||
@host = Virt.connect(uri).host
|
|||
e25f52ae | Ohad Levy | end
|
|
def disconnect
|
|||
b3f525e2 | Ohad Levy | logger.debug "Closing connection to #{self}"
|
|
e25f52ae | Ohad Levy | host.disconnect if host
|
|
96be8845 | Ohad Levy | end
|
|
b3f525e2 | Ohad Levy | private
|
|
96be8845 | Ohad Levy | def try_to_connect
|
|
return true if Rails.env == "test"
|
|||
return true if Virt.connect(uri)
|
|||
rescue => e
|
|||
errors.add_to_base "Unable to connect to Hypervisor: #{e}"
|
|||
false
|
|||
b3f525e2 | Ohad Levy | ensure
|
|
Virt.connection.disconnect rescue false
|
|||
end
|
|||
# we query the hypervisor
|
|||
# if the conntection was open before, we leave it open
|
|||
# otherwise we open and close the connection
|
|||
def query
|
|||
c = connected?
|
|||
connect unless c
|
|||
result = yield if block_given?
|
|||
disconnect unless c
|
|||
return result
|
|||
end
|
|||
def connected?
|
|||
return true if @host and not @host.closed?
|
|||
false
|
|||
96be8845 | Ohad Levy | end
|
|
b3f525e2 | Ohad Levy | ||
96be8845 | Ohad Levy | end
|