F #8296: Report guest OS and network details in oVirt API

Collect guest operating system details and network interfaces through the
existing QEMU guest agent monitoring queries. Publish OS details as
individual monitoring attributes and interfaces as a readable scalar,
without storing the additional attributes in the metrics database.

Use the monitoring data to report guest OS information and match guest
interfaces to VM NICs by MAC address in the oVirt API.

co-authored-by: ArnauGabrielAtienza <agabriel@opennebula.io>
Signed-off-by: ArnauGabrielAtienza <agabriel@opennebula.io>
This commit is contained in:
Ruben S. MonteroandArnauGabrielAtienza committed 2026-11-30 10:46:37 +01:00
1 parent 7200c38af1
commit 095a6c7ec0
4 files changed
+188 -101

No files matched your search

+34 -4
View File
@@ -50,8 +50,12 @@ class BaseDomain
'guest_ip_addresses'
]
DB_MONITOR_KEYS = MONITOR_KEYS.clone
DB_MONITOR_KEYS.freeze
MONITOR_EXTRA_GUEST_KEYS = [
'os_name',
'os_pretty_name',
'os_kernel_release',
'guest_interfaces'
]
DB_PATH = '/var/lib/one-remotes-db'
@@ -84,7 +88,7 @@ class BaseDomain
# NETRX=213132
# ...
#
# Keys are defined in MONITOR_KEYS constant
# Keys are defined in the MONITOR_KEYS and MONITOR_EXTRA_GUEST_KEYS constants
#
# @return [String] OpenNebula template encoded in base64
def to_monitor
@@ -96,6 +100,17 @@ class BaseDomain
mon_s << "#{k.upcase}=\"#{@vm[k.to_sym]}\"\n"
end
interfaces = format_guest_interfaces(@vm[:guest_interfaces_raw])
@vm[:guest_interfaces] = interfaces unless interfaces.nil?
MONITOR_EXTRA_GUEST_KEYS.each do |k|
next unless @vm[k.to_sym]
value = @vm[k.to_sym].to_s.gsub('"') { '\\"' }
mon_s << "#{k.upcase}=\"#{value}\"\n"
end
mon_s << predictions if @predictions
Base64.strict_encode64(mon_s)
@@ -112,7 +127,7 @@ class BaseDomain
timestamp = Time.now.to_i
DB_MONITOR_KEYS.each do |k|
MONITOR_KEYS.each do |k|
next unless @vm[k.to_sym]
# NOTE: underscores are removed because they cause errors on pyoneai library
@@ -130,6 +145,21 @@ class BaseDomain
private
def format_guest_interfaces(interfaces)
return unless interfaces
interfaces.map do |interface|
name = interface['NAME'].to_s
mac = interface['MAC'].to_s
fields = [name, mac] + interface['ADDRESSES']
next if name.empty? || fields.any? {|f| f.match?(/[\/;]/) }
fields.join('/')
end.compact.join(';')
end
def store_metric_db(db, vm_id, metric_name, timestamp, value)
table_name = "virtualmachine_#{vm_id}_#{metric_name}_monitoring"
+49 -21
View File
@@ -19,6 +19,7 @@
require 'open3'
require 'base64'
require 'json'
require 'ipaddr'
require 'yaml'
require 'rexml/document'
require 'sqlite3'
@@ -443,37 +444,64 @@ class Domain < BaseDomain
text = KVM.agent_command(@name, '{"execute":"guest-get-osinfo"}', 10)
osinfo = JSON.parse(text)['return']
@vm[:os_id] = osinfo['id'] || 'unknown'
@vm[:os_type] = @vm[:os_id] == 'mswindows' ? 'mswindows' : 'posix'
@vm[:os_version] = osinfo['version-id'] || 'unknown'
@vm[:os_machine] = osinfo['machine'] || 'unknown'
rescue Libvirt::Error
reply = JSON.parse(text)
return unless reply.is_a?(Hash) && reply['return'].is_a?(Hash)
osinfo = reply['return']
@vm[:os_id] = osinfo['id'] || 'unknown'
@vm[:os_type] = @vm[:os_id] == 'mswindows' ? 'mswindows' : 'posix'
@vm[:os_version] = osinfo['version-id'] || 'unknown'
@vm[:os_machine] = osinfo['machine'] || 'unknown'
@vm[:os_name] = osinfo['name'] || 'unknown'
@vm[:os_pretty_name] = osinfo['pretty-name'] || 'unknown'
@vm[:os_kernel_release] = osinfo['kernel-release'] || 'unknown'
rescue Libvirt::Error, JSON::ParserError, TypeError
end
# Get network information
# Build both IP metrics from the same guest-agent sample.
def extract_network_attributes
net_text = KVM.agent_command(@name, '{"execute":"guest-network-get-interfaces"}')
text = KVM.agent_command(@name, '{"execute":"guest-network-get-interfaces"}', 10)
reply = JSON.parse(text)
net_info = JSON.parse(net_text)['return']
guest_ips = []
return if !reply.is_a?(Hash) || !reply['return'].is_a?(Array)
net_info.each do |info|
next if info['name'] == 'lo'
next unless info.keys.include? 'ip-addresses'
guest_ips = []
interfaces = []
info['ip-addresses'].map do |ip|
next if ['127.0.0.1', '::1'].include? ip['ip-address']
next unless %w(ipv4 ipv6).include? ip['ip-address-type']
reply['return'].each do |interface|
next unless interface.is_a?(Hash) && interface['name'] != 'lo'
guest_ips.append(ip['ip-address'])
addresses = []
Array(interface['ip-addresses']).each do |entry|
next unless entry.is_a?(Hash)
family = entry['ip-address-type']
ip = entry['ip-address'].to_s
next if !['ipv4', 'ipv6'].include?(family)
next if ip.include?('/')
parsed_ip = IPAddr.new(ip)
next if parsed_ip.loopback? || parsed_ip.link_local?
guest_ips << ip
addresses << ip
rescue IPAddr::Error
next
end
interfaces << {
'NAME' => interface['name'],
'MAC' => interface['hardware-address'],
'ADDRESSES' => addresses
}
end
return if guest_ips.empty?
@vm[:guest_ip_addresses] = guest_ips.join(',')
rescue StandardError
@vm[:guest_interfaces_raw] = interfaces
@vm[:guest_ip_addresses] = guest_ips.join(',') unless guest_ips.empty?
rescue Libvirt::Error, JSON::ParserError, TypeError
end
# Check if command should run on given VM (OS filters)
+18 -72
View File
@@ -14,8 +14,6 @@
# limitations under the License. #
#--------------------------------------------------------------------------- #
require 'json'
require 'base64'
require 'ipaddr'
require 'opennebula'
require_relative 'vm_controller'
@@ -31,7 +29,7 @@ require_relative 'helper_functions'
# NetworkController manages OpenNebula VNets
class NetworkController
# Decode guest-agent interfaces without inferring NIC ownership from IP order.
# Match guest-reported interfaces to template NICs by MAC.
class GuestNetwork
def self.normalize_mac(value)
@@ -58,34 +56,17 @@ class NetworkController
nil
end
def self.ipv6(value)
return unless value.is_a?(String)
value = value.strip
return if value.include?('/') || value.include?('%')
address = IPAddr.new(value)
address if address.ipv6?
rescue IPAddr::InvalidAddressError
nil
end
def initialize(monitoring, vm_id)
def initialize(monitoring)
@interfaces = {}
@malformed = false
encoded = monitoring.is_a?(Hash) ? monitoring['VM_GUEST_INTERFACES_B64'] : nil
return if encoded.nil? || encoded == ''
raise TypeError unless encoded.is_a?(String)
return unless monitoring.is_a?(Hash)
interfaces = JSON.parse(Base64.strict_decode64(encoded))
raise TypeError unless interfaces.is_a?(Array)
interfaces = monitoring['GUEST_INTERFACES']
return if interfaces.nil? || interfaces == {} || interfaces == ''
parsed = interfaces.split(';', -1).map {|iface| parse_interface(iface) }.compact
parsed = interfaces.map {|interface| parse_interface(interface) }.compact
@interfaces = parsed.group_by {|interface| interface[:mac] }
warn_malformed(vm_id) if @malformed
rescue ArgumentError, TypeError, JSON::ParserError
warn_malformed(vm_id)
end
# A MAC must identify exactly one guest interface and one template NIC.
@@ -103,51 +84,14 @@ class NetworkController
private
def parse_interface(interface)
unless interface.is_a?(Hash)
@malformed = true
return
end
return if interface['name'] == 'lo'
fields = interface.split('/', -1)
return if fields.length < 2 || fields[0].empty?
mac = self.class.normalize_mac(interface['hardware-address'])
addresses = interface.fetch('ip-addresses', [])
unless mac && addresses.is_a?(Array)
@malformed = true
return
end
name, mac, *ip_addresses = fields
mac = self.class.normalize_mac(mac)
return unless mac
name = interface['name']
name = name.is_a?(String) ? name.strip : nil
ips = addresses.map {|address| parse_address(address) }.compact.uniq
{ :mac => mac, :name => name, :ips => ips }
end
def parse_address(address)
unless address.is_a?(Hash)
@malformed = true
return
end
if address['ip-address-type'] == 'ipv6'
ip = self.class.ipv6(address['ip-address'])
# Skip loopback and link-local guest addresses.
return if ip && (ip.loopback? || ip.link_local?)
return ip.to_s if ip
end
if address['ip-address-type'] == 'ipv4'
ip = self.class.ipv4(address['ip-address'])
return ip if ip
# Loopback is deliberately excluded, not a malformed monitoring value.
return if address['ip-address'].to_s.match?(/\A127\./)
end
@malformed = true
nil
end
def warn_malformed(vm_id)
LOGGER.warn("Ignoring malformed guest interface monitoring for VM #{vm_id}")
{ :mac => mac, :name => name.strip, :ips => ip_addresses }
end
end
@@ -320,20 +264,22 @@ class NetworkController
vm = VmController.get_one_vms(client, :vm_id => vm_id, :full => true)
vm_hash = Helper.resource_hash(client, vm)
end
nics = nic_id ? [require_nic(vm_hash, Helper.uuid_to_int(nic_id))] : nic_templates(vm_hash)
nics = nic_templates(vm_hash)
selected_nics = nic_id ? [require_nic(vm_hash, Helper.uuid_to_int(nic_id))] : nics
return { :nic => [] } if nics.empty?
worker_flag = vm_hash.dig('VM', 'USER_TEMPLATE', 'VEEAM_WORKER')
veeam_worker = worker_flag.to_s.strip.casecmp('true').zero?
interfaces = if reported
client.guest_interfaces(vm) do
GuestNetwork.new(vm_hash.dig('VM', 'MONITORING'), vm_id).match(nics)
guest = GuestNetwork.new(vm_hash.dig('VM', 'MONITORING'))
guest.match(nics)
end
else
{}
end
ovirt_nics = nics.map do |nic|
ovirt_nics = selected_nics.map do |nic|
device = if reported
guest = interfaces[GuestNetwork.normalize_mac(nic['MAC'])]
one_nic_to_reported_device(nic, vm_id, veeam_worker, guest)
+87 -4
View File
@@ -34,6 +34,10 @@ class VmController
# Preserve lookup status through nested controllers to the HTTP error handler.
class LookupError < Helper::LookupError; end
NON_LINUX_OS_IDS = ['freebsd', 'openbsd', 'netbsd', 'dragonfly', 'dragonflybsd',
'solaris', 'sunos', 'illumos', 'darwin', 'macos', 'aix', 'hpux',
'haiku', 'hurd'].freeze
# Auxiliary function to get a list of OpenNebula Virtual Machines or
# a single VM if an id is provided
def self.get_one_vms(client, vm_id: nil, vm_name: nil, extended: false, full: false)
@@ -110,6 +114,73 @@ class VmController
return lcm_translations.fetch(lcm_state, 'unknown')
end
def self.guest_os_value(value)
return unless value.is_a?(String) && value.valid_encoding?
value = value.strip
value unless value.empty? || value.casecmp('unknown').zero?
end
def self.guest_operating_system(monitoring)
return unless monitoring.is_a?(Hash)
id = guest_os_value(monitoring['OS_ID'])&.downcase
distribution = guest_os_value(monitoring['OS_NAME'])
codename = guest_os_value(monitoring['OS_PRETTY_NAME'])
architecture = guest_os_value(monitoring['OS_MACHINE'])
release = guest_os_value(monitoring['OS_KERNEL_RELEASE'])
version_id = guest_os_value(monitoring['OS_VERSION'])
windows = id == 'mswindows' || (id.nil? && monitoring['OS_TYPE'] == 'mswindows')
return unless windows || id || distribution || codename ||
architecture || release || version_id
family = if windows
'Windows'
elsif id.nil? || NON_LINUX_OS_IDS.include?(id)
'Other'
else
'Linux'
end
guest_os = {
:family => family,
:distribution => distribution,
:codename => codename,
:architecture => architecture
}.compact
if version_id
components = /\A(\d+)(?:\.(\d+))?/.match(version_id)
guest_os[:version] = {
:full_version => version_id,
:major => components&.[](1),
:minor => components&.[](2)
}.compact
end
guest_os[:kernel] = { :version => { :full_version => release } } if release
guest_os
end
def self.vm_monitoring_by_id(client)
result = OpenNebula::VirtualMachinePool.new(client).monitoring_last
if OpenNebula.is_error?(result)
LOGGER.warn("Unable to retrieve VM monitoring: #{result.message}")
return {}
end
records = result.dig('MONITORING_DATA', 'MONITORING')
records = [records] if records.is_a?(Hash)
Array(records).each_with_object({}) do |record, by_id|
next unless record.is_a?(Hash)
id = record['ID']
by_id[id] = record if id.is_a?(String)
end
end
private_class_method :guest_os_value, :guest_operating_system,
:vm_monitoring_by_id
# Convert an OpenNebula VM into an oVirt VM.
# To fullfill a possible schema, we use an existing
# oVirt template and modify the parameters we consider
@@ -397,7 +468,12 @@ class VmController
LOGGER.info("Retrieving specific VM with ID: #{vm_id}")
vm = get_one_vms(client, :vm_id => vm_id, :full => true)
return 200, onevm_to_ovirtvm(client, vm, :nics => nics, :disks => disks, :tags => tags)
response = onevm_to_ovirtvm(client, vm, :nics => nics, :disks => disks, :tags => tags)
vm_monitoring = Helper.resource_hash(client, vm).dig('VM', 'MONITORING')
guest_os = guest_operating_system(vm_monitoring)
response[:guest_operating_system] = guest_os if guest_os
return 200, response
end
pagination = Helper::Pagination.new(:max => max, :search => search)
@@ -419,20 +495,27 @@ class VmController
# Format each VM
formatted_vms = []
pagination.apply(vms).each do |v|
page = pagination.apply(vms)
monitoring = page.empty? ? {} : vm_monitoring_by_id(client.client)
page.each do |v|
next if v['STATE'].to_i == 6
vm_monitoring = monitoring[v.id.to_s]
# Pool entries do not carry full monitoring. Refresh only selected VMs
# whose reported devices are requested, before serializing any fields.
if nics && NetworkController.reported_devices_follow?(Helper.remove_follow_start(nics))
vm_nics = Helper.resource_hash(client, v).dig('VM', 'TEMPLATE', 'NIC')
if vm_nics && !vm_nics.empty?
v = get_one_vms(client, :vm_id => v.id, :full => true)
vm_monitoring = Helper.resource_hash(client, v).dig('VM', 'MONITORING')
end
end
formatted_vms << onevm_to_ovirtvm(client, v, :nics => nics, :disks => disks,
:tags => tags)
response = onevm_to_ovirtvm(client, v, :nics => nics, :disks => disks, :tags => tags)
guest_os = guest_operating_system(vm_monitoring)
response[:guest_operating_system] = guest_os if guest_os
formatted_vms << response
rescue LookupError => e
raise unless [401, 404].include?(e.status)