mirror of
https://github.com/OpenNebula/one.git
synced 2026-12-01 20:56:42 +09:00
F OpenNebula/one#7221: Add GPU monitoring & forecast for VMs
This commit extends the KVM domain probe to monitor NVIDIA GPUs: * GPU metrics: GPU_UTILIZATION, GPU_MEMORY_UTILIZATION, GPU_MEMORY_FREE, GPU_POWER_USAGE, GPU_COUNT * Implements method for NVIDIA GPUs. The code is prepared to add AMD vendor in the future * NVIDIA monitor uses nvidia-smi through qemu guest-agent those are requirements for the VM to report metrics * oned now adds PCI information (vendor, device and class) to all PCI devices (i.e. even if using SHORT_ADDRESS). * KVM metadata include PCI devices in the VM to skip VMs not using supported GPU's Signed-off-by: josepselga <jselga@opennebula.io>
This commit is contained in:
6 files changed
+274
-10
No files matched your search
@@ -751,6 +751,7 @@ class OneVMHelper < OpenNebulaHelper::OneHelper
|
||||
|
||||
unit_lambda = ->(v) { OpenNebulaHelper.unit_to_str(v.to_i, {}) }
|
||||
unitM_lambda = ->(v) { OpenNebulaHelper.unit_to_str(v.to_i / 1024, {}) }
|
||||
unitG_lambda = ->(v) { OpenNebulaHelper.unit_to_str(v.to_i / 1024, {}, 'G') }
|
||||
|
||||
order_attrs = {
|
||||
'CPU' => nil,
|
||||
@@ -766,7 +767,12 @@ class OneVMHelper < OpenNebulaHelper::OneHelper
|
||||
'DISKWRBYTES' => unit_lambda,
|
||||
'DISKWRBYTES_BW' => unit_lambda,
|
||||
'DISKWRIOPS_BW' => nil,
|
||||
'DISKWRIOPS' => nil
|
||||
'DISKWRIOPS' => nil,
|
||||
'GPU_COUNT' => nil,
|
||||
'GPU_UTILIZATION' => nil,
|
||||
'GPU_MEMORY_UTILIZATION' => nil,
|
||||
'GPU_MEMORY_FREE' => unitG_lambda,
|
||||
'GPU_POWER_USAGE' => nil
|
||||
}
|
||||
|
||||
vm_monitoring_sort = []
|
||||
|
||||
@@ -200,7 +200,7 @@ void HostSharePCI::pci_attribute(VectorAttribute *device, PCIDevice *pci,
|
||||
bool set_prev, const std::string& vprofile)
|
||||
{
|
||||
static vector<string> cp_attr = {"DOMAIN", "BUS", "SLOT", "FUNCTION", "ADDRESS",
|
||||
"SHORT_ADDRESS"};
|
||||
"SHORT_ADDRESS", "VENDOR", "DEVICE", "CLASS"};
|
||||
|
||||
static vector<string> cp_check_attr = {"NUMA_NODE", "UUID", "MDEV_MODE"};
|
||||
|
||||
|
||||
@@ -36,7 +36,12 @@ class BaseDomain
|
||||
'diskrdbytes',
|
||||
'diskwrbytes',
|
||||
'diskrdiops',
|
||||
'diskwriops'
|
||||
'diskwriops',
|
||||
'gpu_utilization',
|
||||
'gpu_memory_utilization',
|
||||
'gpu_memory_free',
|
||||
'gpu_power_usage',
|
||||
'gpu_count'
|
||||
]
|
||||
|
||||
DB_MONITOR_KEYS = MONITOR_KEYS.clone
|
||||
@@ -104,7 +109,8 @@ class BaseDomain
|
||||
DB_MONITOR_KEYS.each do |k|
|
||||
next unless @vm[k.to_sym]
|
||||
|
||||
store_metric_db(db, @vm[:id], k, timestamp, @vm[k.to_sym])
|
||||
# NOTE: underscores are removed because they cause errors on pyoneai library
|
||||
store_metric_db(db, @vm[:id], k.delete('_'), timestamp, @vm[k.to_sym])
|
||||
end
|
||||
|
||||
db.close
|
||||
|
||||
@@ -22,6 +22,7 @@ require 'json'
|
||||
require 'yaml'
|
||||
require 'rexml/document'
|
||||
require 'sqlite3'
|
||||
require 'csv'
|
||||
|
||||
require_relative 'process_list'
|
||||
require_relative 'domain'
|
||||
@@ -214,18 +215,23 @@ class Domain < BaseDomain
|
||||
@vm[:state] = state
|
||||
@vm[:reason] = reason
|
||||
|
||||
# VM system datastore path
|
||||
# Get VM virsh dumpxml ONE metadata
|
||||
xml, _e, s = KVM.virsh(:dumpxml, @name)
|
||||
|
||||
@vm[:system_datastore] = begin
|
||||
doc = REXML::Document.new(xml)
|
||||
doc.elements['/domain/metadata/one:vm/one:system_datastore']&.text
|
||||
rescue 'StandardError'
|
||||
nil
|
||||
begin
|
||||
dkeys = [:system_datastore, :pci_devices]
|
||||
doc = REXML::Document.new(xml)
|
||||
|
||||
dkeys.each do |k|
|
||||
@vm[k] = doc.elements["/domain/metadata/one:vm/one:#{k}"]&.text
|
||||
end
|
||||
rescue StandardError
|
||||
dkeys.each {|key| @vm[key] = nil }
|
||||
end if s.success?
|
||||
|
||||
ga_stats
|
||||
io_stats
|
||||
gpu_stats
|
||||
end
|
||||
|
||||
# Convert the output of dumpxml for this domain to an OpenNebula template
|
||||
@@ -342,6 +348,21 @@ class Domain < BaseDomain
|
||||
# List of domain state reasons (for RUNNING) when to skip I/O monitoring
|
||||
REASONS_SKIP_IO = ['migrating', 'starting up', 'saving']
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# GPU monitoring system - detects GPUs from PCI devices and collects metrics
|
||||
# --------------------------------------------------------------------------
|
||||
GPU_VENDORS = {
|
||||
'nvidia' => {
|
||||
:vendor_id => '10de',
|
||||
:monitor_class => 'NvidiaGPUMonitor'
|
||||
}
|
||||
# Add new vendors:
|
||||
# 'amd' => {
|
||||
# :vendor_id => '1002',
|
||||
# :monitor_class => 'AMDGPUMonitor'
|
||||
# }
|
||||
}.freeze
|
||||
|
||||
# Get the I/O stats of the domain as provided by Libvirt command domstats
|
||||
# The metrics are aggregated for all DIKS and NIC
|
||||
def io_stats
|
||||
@@ -411,6 +432,200 @@ class Domain < BaseDomain
|
||||
end
|
||||
end
|
||||
|
||||
# Detects if VM has GPU by parsing PCI devices from domain metadata
|
||||
# Returns hash with vendor and device_id, or nil if no GPU found
|
||||
def vm_has_gpu?
|
||||
return unless @vm[:pci_devices]
|
||||
|
||||
pci_devices_string = @vm[:pci_devices].strip
|
||||
return if pci_devices_string.empty?
|
||||
|
||||
pci_devices_string.split(',').map(&:strip).each do |pci_device|
|
||||
parts = pci_device.split(':')
|
||||
next if parts.size < 3
|
||||
|
||||
vendor_id = parts[0].downcase
|
||||
device_id = parts[1].downcase
|
||||
|
||||
GPU_VENDORS.each do |vendor_name, config|
|
||||
if vendor_id == config[:vendor_id].downcase
|
||||
return { :vendor => vendor_name, :device_id => device_id }
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
nil
|
||||
end
|
||||
|
||||
# NVIDIA GPU Monitor implementation
|
||||
# --------------------------------------------------------------------------
|
||||
# Collects GPU metrics from VMs using nvidia-smi via QEMU guest agent
|
||||
# Must implement collect_metrics() returning hash with:
|
||||
# :utilization, :memory_utilization, :memory_free, :power_usage, and :count keys
|
||||
class NvidiaGPUMonitor
|
||||
|
||||
# Map nvidia-smi query fields to internal metric names
|
||||
NVIDIA_METRIC_MAP = {
|
||||
'gpu_uuid' => :gpu_uuid, # Unique GPU identifier
|
||||
'utilization.gpu' => :utilization, # % of time GPU cores busy
|
||||
'utilization.memory' => :memory_utilization, # % of time memory busy (bandwidth usage)
|
||||
'power.draw' => :power_usage, # Power consumption (in Watts)
|
||||
'memory.free' => :memory_free # VRAM not allocated (in MiB)
|
||||
# 'memory.used' => :memory_used, # VRAM allocated (in MiB)
|
||||
# 'memory.total' => :memory_total, # Total installed VRAM (in MiB)
|
||||
# 'temperature.gpu' => :temperature, # Core GPU temperature (in Celsius)
|
||||
# 'utilization.encoder' => :encoder_utilization, # % usage of the video encoder engine
|
||||
# 'utilization.decoder' => :decoder_utilization, # % usage of the video decoder engine
|
||||
}.freeze
|
||||
|
||||
NVIDIA_FIELDS = NVIDIA_METRIC_MAP.keys.freeze
|
||||
|
||||
def initialize(domain_name, device_id = nil)
|
||||
@domain_name = domain_name
|
||||
@device_id = device_id # Store for future model specific logic
|
||||
end
|
||||
|
||||
def collect_metrics
|
||||
2.times do
|
||||
fields = NVIDIA_FIELDS.join(',')
|
||||
command = "nvidia-smi --query-gpu=#{fields} --format=csv,noheader,nounits"
|
||||
output = run_guest_command(command)
|
||||
|
||||
if output && !output.empty?
|
||||
return parse_nvidia_smi_output(output)
|
||||
end
|
||||
|
||||
sleep 1
|
||||
end
|
||||
nil
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def run_guest_command(command, timeout = 2.0, poll_interval = 0.2)
|
||||
exec_ga = {
|
||||
'execute' => 'guest-exec',
|
||||
'arguments' => {
|
||||
'path' => '/bin/sh',
|
||||
'arg' => ['-c', command],
|
||||
'capture-output' => true
|
||||
}
|
||||
}.to_json
|
||||
|
||||
text, _e, s = KVM.virsh(:qemuga, "#{@domain_name} '#{exec_ga}' --timeout 15")
|
||||
return unless s.success?
|
||||
|
||||
response = JSON.parse(text) rescue nil
|
||||
return unless response&.dig('return', 'pid')
|
||||
|
||||
pid = response['return']['pid']
|
||||
elapsed = 0.0
|
||||
|
||||
while elapsed < timeout
|
||||
sleep poll_interval
|
||||
elapsed += poll_interval
|
||||
|
||||
stat_ga = {
|
||||
'execute' => 'guest-exec-status',
|
||||
'arguments' => { 'pid' => pid }
|
||||
}.to_json
|
||||
|
||||
text, _e, s = KVM.virsh(:qemuga, "#{@domain_name} '#{stat_ga}' --timeout 15")
|
||||
next unless s.success?
|
||||
|
||||
status = JSON.parse(text) rescue nil
|
||||
if status&.dig('return', 'exited')
|
||||
return Base64.decode64(status['return']['out-data']) rescue nil
|
||||
end
|
||||
end
|
||||
nil
|
||||
end
|
||||
|
||||
def parse_nvidia_smi_output(text)
|
||||
return if !text || text.empty?
|
||||
|
||||
devices = []
|
||||
|
||||
CSV.parse(text, :headers => false) do |row|
|
||||
next if row.size < NVIDIA_FIELDS.size
|
||||
|
||||
device_data = {}
|
||||
row.each_with_index do |value, i|
|
||||
field_name = NVIDIA_FIELDS[i]
|
||||
metric_key = NVIDIA_METRIC_MAP[field_name]
|
||||
|
||||
if metric_key == :gpu_uuid
|
||||
device_data[metric_key] = value&.strip
|
||||
else
|
||||
device_data[metric_key] = parse_numeric(value)
|
||||
end
|
||||
end
|
||||
devices << device_data
|
||||
end
|
||||
|
||||
return if devices.empty?
|
||||
|
||||
aggregate_gpu_metrics(devices)
|
||||
end
|
||||
|
||||
def parse_numeric(value)
|
||||
return 0.0 if value.nil? || value.strip.empty? || value.strip.downcase == 'n/a'
|
||||
|
||||
cleaned = value.strip.gsub(/[^\d.-]/, '')
|
||||
cleaned.to_f
|
||||
rescue StandardError
|
||||
0.0
|
||||
end
|
||||
|
||||
def aggregate_gpu_metrics(devices)
|
||||
return {} if devices.empty?
|
||||
|
||||
gpu_count = devices.size
|
||||
agg = Hash.new(0.0)
|
||||
|
||||
devices.each do |gpu|
|
||||
gpu.each do |key, value|
|
||||
next if key == :gpu_uuid
|
||||
|
||||
agg[key] += value
|
||||
end
|
||||
end
|
||||
|
||||
# Average utilization metrics
|
||||
avg_keys = [:utilization, :memory_utilization]
|
||||
avg_keys.each {|k| agg[k] = (agg[k] / gpu_count).round(2) if agg[k] > 0 }
|
||||
|
||||
agg[:count] = gpu_count
|
||||
agg.transform_values {|v| v.round(2) }
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
# Get the VM GPU stats
|
||||
# The metrics are aggregated for all GPUs
|
||||
# Only sets GPU metrics if VM actually has a GPU
|
||||
def gpu_stats
|
||||
return unless @vm[:state] == 'RUNNING'
|
||||
|
||||
gpu_info = vm_has_gpu?
|
||||
return unless gpu_info
|
||||
|
||||
vendor_config = GPU_VENDORS[gpu_info[:vendor]]
|
||||
monitor_class = Object.const_get("Domain::#{vendor_config[:monitor_class]}")
|
||||
monitor = monitor_class.new(@name, gpu_info[:device_id])
|
||||
|
||||
stats = monitor.collect_metrics
|
||||
if stats
|
||||
@vm[:gpu_utilization] = stats[:utilization] || 0.0
|
||||
@vm[:gpu_memory_utilization] = stats[:memory_utilization] || 0.0
|
||||
@vm[:gpu_memory_free] = stats[:memory_free] || 0.0
|
||||
@vm[:gpu_power_usage] = stats[:power_usage] || 0.0
|
||||
@vm[:gpu_count] = stats[:count] || 0
|
||||
end
|
||||
rescue StandardError => e
|
||||
STDERR.puts "Warning: Failed to get GPU stats for VM #{@name}: #{e.message}"
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
|
||||
@@ -110,6 +110,19 @@ VM_METRICS = {
|
||||
dtype=Float(0.0, np.inf),
|
||||
operator="rate",
|
||||
),
|
||||
# GPU metrics
|
||||
"gpu_utilization": MetricAttributes(
|
||||
name="gpuutilization", type=MetricType.GAUGE, dtype=Float(0.0, 100.0)
|
||||
),
|
||||
"gpu_memory_utilization": MetricAttributes(
|
||||
name="gpumemoryutilization", type=MetricType.GAUGE, dtype=Float(0.0, 100.0)
|
||||
),
|
||||
"gpu_memory_free": MetricAttributes(
|
||||
name="gpumemoryfree", type=MetricType.GAUGE, dtype=Float(0.0, np.inf)
|
||||
),
|
||||
"gpu_power_usage": MetricAttributes(
|
||||
name="gpupowerusage", type=MetricType.GAUGE, dtype=Float(0.0, np.inf)
|
||||
)
|
||||
}
|
||||
|
||||
DERIVED_METRICS = [
|
||||
|
||||
@@ -2126,6 +2126,7 @@ int LibVirtDriver::deployment_description_kvm(
|
||||
// ------------------------------------------------------------------------
|
||||
// PCI Passthrough
|
||||
// ------------------------------------------------------------------------
|
||||
string pci_devices;
|
||||
|
||||
num = vm->get_template_attribute("PCI", pci);
|
||||
|
||||
@@ -2145,6 +2146,26 @@ int LibVirtDriver::deployment_description_kvm(
|
||||
string uuid = pci[i]->vector_value("UUID");
|
||||
string mdev = pci[i]->vector_value("MDEV_MODE");
|
||||
|
||||
string _vendor = pci[i]->vector_value("VENDOR");
|
||||
one_util::tolower(_vendor);
|
||||
|
||||
string _device = pci[i]->vector_value("DEVICE");
|
||||
one_util::tolower(_device);
|
||||
|
||||
string _class = pci[i]->vector_value("CLASS");
|
||||
one_util::tolower(_class);
|
||||
|
||||
string pci_device = _vendor + ":" + _device + ":" + _class;
|
||||
|
||||
if (pci_devices.empty())
|
||||
{
|
||||
pci_devices = pci_device;
|
||||
}
|
||||
else
|
||||
{
|
||||
pci_devices += "," + pci_device;
|
||||
}
|
||||
|
||||
one_util::tolower(mdev);
|
||||
|
||||
if ( domain.empty() || bus.empty() || slot.empty() || func.empty() )
|
||||
@@ -2452,6 +2473,9 @@ int LibVirtDriver::deployment_description_kvm(
|
||||
<< "\t\t\t<one:deployment_time>"
|
||||
<< time(0)
|
||||
<< "</one:deployment_time>\n"
|
||||
<< "\t\t\t<one:pci_devices>"
|
||||
<< pci_devices
|
||||
<< "</one:pci_devices>\n"
|
||||
<< "\t\t</one:vm>\n"
|
||||
// << "\t\t<opennebula>\n" << vm->to_xml(vm_xml) << "\t\t</opennebula>\n"
|
||||
<< "\t</metadata>\n";
|
||||
|
||||
Reference in new issue
Block a user