Debian Codegraph @

rust-interface/examples/amdsmi_exporter/amdsmi_collectors.rs

raw
1 // Copyright (C) 2024 Advanced Micro Devices. All rights reserved.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy of
4 // this software and associated documentation files (the "Software"), to deal in
5 // the Software without restriction, including without limitation the rights to
6 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7 // the Software, and to permit persons to whom the Software is furnished to do so,
8 // subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in all
11 // copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15 // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16 // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17 // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18 // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20
21 use crate::amdsmi_metric::*;
22 use crate::collectors::collectors_create;
23 use amdsmi::*;
24 use prometheus_client::metrics::family::Family;
25 use prometheus_client::metrics::gauge::Gauge;
26 use prometheus_client::registry::Registry;
27 use std::collections::HashMap;
28 use std::fmt::Debug;
29 use std::fmt::Display;
30
31 pub struct AmdsmiCollectors {
32 pub collectors: HashMap<&'static str, AmdsmiCollector>,
33 pub gpu_filter: Option<Vec<String>>,
34 pub whitelist: Option<Vec<String>>,
35 pub blacklist: Option<Vec<String>>,
36 }
37
38 impl Default for AmdsmiCollectors {
39 fn default() -> Self {
40 AmdsmiCollectors::new()
41 }
42 }
43
44 impl AmdsmiCollectors {
45 pub fn new() -> Self {
46 let mut instance = AmdsmiCollectors {
47 collectors: HashMap::new(),
48 gpu_filter: None,
49 whitelist: None,
50 blacklist: None,
51 };
52 collectors_create(&mut instance);
53 instance
54 }
55
56 pub fn set_gpu_filter(&mut self, filters: Option<Vec<String>>) -> &mut Self {
57 self.gpu_filter = filters;
58 self
59 }
60
61 pub fn set_field_filter(
62 &mut self,
63 whitelist: Option<Vec<String>>,
64 blacklist: Option<Vec<String>>,
65 ) -> &mut Self {
66 self.whitelist = whitelist;
67 self.blacklist = blacklist;
68 // Re-generate the collectors after setting the field filters
69 self.collectors.clear();
70 collectors_create(self);
71 self
72 }
73
74 pub fn add_metric<T, F>(&mut self, collector: AmdsmiGauge<T, F>) -> &mut Self
75 where
76 T: 'static + Into<i64> + Display + Copy,
77 F: 'static + Fn(AmdsmiProcessorHandle) -> AmdsmiResult<T> + Send + Sync,
78 {
79 let name = collector.info.name;
80 let description = collector.info.description;
81 let unit = collector.info.unit;
82 let func = collector.func;
83
84 // Apply whitelist and blacklist filters before inserting the collector
85 if let Some(ref whitelist) = self.whitelist {
86 if !whitelist.contains(&name.to_string()) {
87 return self;
88 }
89 }
90 if let Some(ref blacklist) = self.blacklist {
91 if blacklist.contains(&name.to_string()) {
92 return self;
93 }
94 }
95 self.collectors.insert(
96 name,
97 Box::new(move |processor_handle| match func(processor_handle) {
98 Ok(value) => vec![AmdsmiMetric {
99 info: AmdsmiInfo {
100 name,
101 description,
102 unit: unit.clone(),
103 },
104 value: value.into(),
105 status: AmdsmiStatusT::AmdsmiStatusSuccess,
106 }],
107 Err(e) => vec![AmdsmiMetric {
108 info: AmdsmiInfo {
109 name,
110 description,
111 unit: unit.clone(),
112 },
113 value: 0,
114 status: e,
115 }],
116 }),
117 );
118 self
119 }
120
121 pub fn add_metric_group<T, F>(&mut self, collector: &AmdsmiGaugeGroup<T, F>) -> &mut Self
122 where
123 T: 'static + Debug,
124 F: 'static + Fn(AmdsmiProcessorHandle) -> AmdsmiResult<T> + Send + Sync + Clone,
125 {
126 let name = collector.name;
127 let func = collector.func.clone();
128
129 // Apply whitelist and blacklist filters before the Box::new
130 let filtered_info_list: Vec<_> = collector
131 .info_list
132 .iter()
133 .filter(|(info, _)| {
134 if let Some(ref whitelist) = self.whitelist {
135 if !whitelist.contains(&info.name.to_string()) {
136 return false;
137 }
138 }
139 if let Some(ref blacklist) = self.blacklist {
140 if blacklist.contains(&info.name.to_string()) {
141 return false;
142 }
143 }
144 true
145 })
146 .cloned()
147 .collect();
148
149 // If the filtered_info_list is empty, return early
150 if filtered_info_list.is_empty() {
151 return self;
152 }
153
154 self.collectors.insert(
155 name,
156 Box::new(move |processor_handle| {
157 let mut results = Vec::new();
158
159 match func(processor_handle) {
160 Ok(value) => {
161 for (info, accessor) in &filtered_info_list {
162 results.push(AmdsmiMetric {
163 info: AmdsmiInfo {
164 name: info.name,
165 description: info.description,
166 unit: info.unit.clone(),
167 },
168 value: accessor(&value),
169 status: AmdsmiStatusT::AmdsmiStatusSuccess,
170 });
171 }
172 }
173 Err(e) => {
174 for (info, _) in &filtered_info_list {
175 results.push(AmdsmiMetric {
176 info: AmdsmiInfo {
177 name: info.name,
178 description: info.description,
179 unit: info.unit.clone(),
180 },
181 value: 0,
182 status: e,
183 });
184 }
185 }
186 }
187 results
188 }),
189 );
190 self
191 }
192
193 pub fn print_supported(&self) {
194 // Initialize the AMD SMI library
195 if let Err(e) = amdsmi_init(AmdsmiInitFlagsT::AmdsmiInitAmdGpus) {
196 eprintln!("Failed to initialize AMD SMI: {}", e);
197 return;
198 }
199
200 // Get socket handles
201 let socket_handles = match amdsmi_get_socket_handles() {
202 Ok(handles) => handles,
203 Err(e) => {
204 eprintln!("Failed to get socket handles: {}", e);
205 return;
206 }
207 };
208
209 for (socket_index, socket_handle) in socket_handles.iter().enumerate() {
210 let socket_id = socket_index.to_string();
211
212 // Get processor handles for each socket handle
213 let processor_handles = match amdsmi_get_processor_handles(*socket_handle) {
214 Ok(handles) => handles,
215 Err(e) => {
216 eprintln!("Failed to get processor handles: {}", e);
217 continue;
218 }
219 };
220
221 for (processor_index, processor_handle) in processor_handles.iter().enumerate() {
222 let processor_id = processor_index.to_string();
223
224 let bdf = match amdsmi_get_gpu_device_bdf(*processor_handle) {
225 Ok(bdf) => bdf.to_string(),
226 Err(e) => {
227 eprintln!("Failed to get GPU device BDF: {}", e);
228 continue;
229 }
230 };
231
232 println!("========================================");
233 println!("GPU Information:");
234 println!(" Socket ID: {}", socket_id);
235 println!(" Processor ID: {}", processor_id);
236 println!(" BDF: {}", bdf);
237 println!("----------------------------------------");
238 println!("Supported Metrics:");
239 println!(
240 "{:<30} | {:<10} | {:<10} | {:<50}",
241 "Metric ID", "Value", "Unit", "Help"
242 );
243 println!("{:-<30}-+-{:-<10}-+-{:-<10}-+-{:-<50}", "", "", "", "");
244
245 // Collect metrics
246 for (_, collector) in &self.collectors {
247 let results = collector(*processor_handle);
248 for metric in results {
249 let value_str = if metric.status == AmdsmiStatusT::AmdsmiStatusSuccess {
250 metric.value.to_string()
251 } else {
252 "NA".to_string()
253 };
254
255 println!(
256 "{:<30} | {:<10} | {:<10} | {:<50}",
257 metric.info.name,
258 value_str,
259 metric.info.unit.as_str(),
260 metric.info.description
261 );
262 }
263 }
264 println!("========================================\n");
265 }
266 }
267
268 // Shutdown the AMD SMI library
269 if let Err(e) = amdsmi_shut_down() {
270 eprintln!("Failed to shutdown AMD SMI: {}", e);
271 }
272 }
273
274 pub fn run_collect(&mut self) -> Registry {
275 // Initialize the AMD SMI library
276 if let Err(e) = amdsmi_init(AmdsmiInitFlagsT::AmdsmiInitAmdGpus) {
277 eprintln!("Failed to initialize AMD SMI: {}", e);
278 return Registry::default();
279 }
280
281 let mut registry = Registry::default();
282
283 // Get socket handles
284 let socket_handles = match amdsmi_get_socket_handles() {
285 Ok(handles) => handles,
286 Err(e) => {
287 eprintln!("Failed to get socket handles: {}", e);
288 return registry;
289 }
290 };
291
292 for (socket_index, socket_handle) in socket_handles.iter().enumerate() {
293 let socket_id = socket_index.to_string();
294
295 // Get processor handles for each socket handle
296 let processor_handles = match amdsmi_get_processor_handles(*socket_handle) {
297 Ok(handles) => handles,
298 Err(e) => {
299 eprintln!("Failed to get processor handles: {}", e);
300 continue;
301 }
302 };
303
304 for (processor_index, processor_handle) in processor_handles.iter().enumerate() {
305 let processor_id = processor_index.to_string();
306
307 let bdf = match amdsmi_get_gpu_device_bdf(*processor_handle) {
308 Ok(bdf) => bdf.to_string(),
309 Err(e) => {
310 eprintln!("Failed to get GPU device BDF: {}", e);
311 continue;
312 }
313 };
314
315 let labels = AmdsmiLabels {
316 socket_id: socket_id.clone(),
317 processor_id: processor_id.clone(),
318 bdf,
319 };
320
321 // Only for GPUs which match the provided gpu filter argument
322 if let Some(ref filters) = self.gpu_filter {
323 if !filters.iter().any(|filter| {
324 filter == &labels.bdf
325 || filter == &format!("{}.{}", socket_id, processor_id)
326 }) {
327 continue;
328 }
329 }
330
331 // Collect metrics
332 for (_, collector) in &self.collectors {
333 let results = collector(*processor_handle);
334 for metric in results {
335 if metric.status == AmdsmiStatusT::AmdsmiStatusSuccess {
336 let metric_family =
337 Family::<AmdsmiLabels, Gauge>::new_with_constructor(Gauge::default);
338 if metric.info.unit.as_str().is_empty() {
339 registry.register(
340 metric.info.name,
341 metric.info.description,
342 metric_family.clone(),
343 );
344 } else {
345 registry.register_with_unit(
346 metric.info.name,
347 metric.info.description,
348 metric.info.unit.clone(),
349 metric_family.clone(),
350 );
351 }
352 metric_family.get_or_create(&labels).set(metric.value);
353 } else {
354 #[cfg(debug_assertions)]
355 eprintln!(
356 "Failed to collect metric {}: {} for socket {} processor {}",
357 metric.info.name,
358 metric.status,
359 labels.socket_id,
360 labels.processor_id
361 );
362 }
363 }
364 }
365 }
366 }
367
368 // Shutdown the AMD SMI library
369 if let Err(e) = amdsmi_shut_down() {
370 eprintln!("Failed to shutdown AMD SMI: {}", e);
371 }
372
373 registry
374 }
375 }
376
377 /// A macro to add a metric collector.
378 ///
379 /// This macro creates an `AmdsmiGauge` instance and adds it to the collectors.
380 ///
381 /// # Parameters
382 /// - `$collectors`: The collectors to add the metric to.
383 /// - `$name`: The name of the metric.
384 /// - `$description`: The description of the metric.
385 /// - `$unit`: The unit of the metric.
386 /// - `$func`: The function to collect the metric.
387 ///
388 /// # Example
389 ///
390 /// ```rust
391 /// # use amdsmi::*;
392 /// # use amdsmi_collectors::*;
393 ///
394 /// # fn main() {
395 /// let mut collectors = AmdsmiCollectors::default();
396 /// add_metric!(
397 /// collectors,
398 /// "AMDSMI_FI_TEMPERATURE_EDGE",
399 /// "Currnt edge temperature",
400 /// Unit::Celsius,
401 /// amdsmi_func!(amdsmi_get_temp_metric, AmdsmiTemperatureTypeT::AmdsmiTemperatureTypeEdge, AmdsmiTemperatureMetricT::AmdsmiTempCurrent)
402 /// );
403 /// # }
404 /// ```
405 macro_rules! add_metric {
406 ($collectors:expr, $name:expr, $description:expr, $unit:expr, $func:expr) => {
407 let collector = AmdsmiGauge::new($name, $description, $unit, $func);
408 $collectors.add_metric(collector);
409 };
410 }
411
412 /// A macro to add a single metric from a struct to the collectors.
413 ///
414 /// This macro creates an `AmdsmiGauge` instance from a field of struct and adds it to the collectors.
415 ///
416 /// # Parameters
417 /// - `$collectors`: The collectors to add the metric to.
418 /// - `$name`: The name of the metric.
419 /// - `$description`: The description of the metric.
420 /// - `$unit`: The unit of the metric.
421 /// - `$func`: The function to collect the metric.
422 /// - `$field`: The struct field from which the metric is collected.
423 ///
424 /// # Example
425 ///
426 /// ```rust
427 /// # use amdsmi::*;
428 /// # use amdsmi_collectors::*;
429 ///
430 /// # fn main() {
431 /// let mut collectors = AmdsmiCollectors::default();
432 /// add_metric_field!(
433 /// collectors,
434 /// "AMDSMI_FI_CURRENT_SOCKET_POWER",
435 /// "Current Socket Power",
436 /// Unit::Watts,
437 /// amdsmi_get_power_info,
438 /// current_socket_power
439 /// );
440 /// # }
441 /// ```
442 #[allow(unused_macros)]
443 macro_rules! add_metric_field {
444 ($collectors:expr, $name:expr, $description:expr, $unit:expr, $func:expr, $field:ident) => {
445 let collector = AmdsmiGauge::new($name, $description, $unit, |handle| {
446 $func(handle).map(|info| info.$field.into())
447 });
448 $collectors.add_metric(collector);
449 };
450 }
451 /// A macro to add a group of metrics within a single struct.
452 ///
453 /// This macro creates an `AmdsmiGaugeGroup` instance and adds it to the collectors.
454 ///
455 /// # Parameters
456 /// - `$collectors`: The collectors to add the metric group to.
457 /// - `$group_name`: The name of the metric group.
458 /// - `$func`: The function to collect the metrics.
459 /// - `$t`: The type of the struct containing the metrics.
460 /// - `$name`: The name of each metric.
461 /// - `$description`: The description of each metric.
462 /// - `$unit`: The unit of each metric.
463 /// - `$field`: The struct field from which each metric is collected.
464 ///
465 /// # Example
466 ///
467 /// ```rust
468 /// # use amdsmi::*;
469 /// # use amdsmi_collectors::*;
470 ///
471 /// # fn main() {
472 /// let mut collectors = AmdsmiCollectors::default();
473 /// add_metric_group!(
474 /// collectors,
475 /// "AmdsmiPowerInfoMetrics",
476 /// amdsmi_get_power_info,
477 /// AmdsmiPowerInfoT,
478 /// ("AMDSMI_FI_CURRENT_SOCKET_POWER", "Current Socket Power", Unit::Watts, current_socket_power),
479 /// ("AMDSMI_FI_AVERAGE_SOCKET_POWER", "Average Socket Power", Unit::Watts, average_socket_power),
480 /// ("AMDSMI_FI_GFX_VOLTAGE", "GFX Voltage", Unit::Volts, gfx_voltage),
481 /// ("AMDSMI_FI_SOC_VOLTAGE", "SOC Voltage", Unit::Volts, soc_voltage),
482 /// ("AMDSMI_FI_MEM_VOLTAGE", "Memory Voltage", Unit::Volts, mem_voltage),
483 /// ("AMDSMI_FI_POWER_LIMIT", "Power Limit", Unit::Watts, power_limit)
484 /// );
485 /// # }
486 /// ```
487 #[allow(unused_macros)]
488 macro_rules! add_metric_group {
489 ($collectors:expr, $group_name:expr, $func:expr, $t:ty, $(($name:expr, $description:expr, $unit:expr, $field:ident)),+ $(,)?) => {
490 let info_list = vec![
491 $(
492 (
493 $name,
494 $description,
495 $unit,
496 Arc::new(|info: &$t| info.$field as i64) as Arc<dyn Fn(&$t) -> i64 + Send + Sync>,
497 ),
498 )+
499 ];
500 let mut collector = AmdsmiGaugeGroup::new($group_name, info_list, $func);
501 $collectors.add_metric_group(&mut collector);
502 };
503 }
504 /// A macro to create a closure for an AMD SMI function with dynamic arguments.
505 ///
506 /// This macro generates a closure that calls the specified function with the provided arguments.
507 ///
508 /// # Parameters
509 /// - `$func`: The function to create the closure for.
510 /// - `$arg`: The arguments to pass to the function.
511 ///
512 /// # Example
513 ///
514 /// ```rust
515 /// # use amdsmi::*;
516 /// # use amdsmi_collectors::*;
517 ///
518 /// # fn main() {
519 /// let func = amdsmi_func!(amdsmi_get_temp_metric, AmdsmiTemperatureTypeT::AmdsmiTemperatureTypeEdge, AmdsmiTemperatureMetricT::AmdsmiTempCurrent);
520 /// # }
521 /// ``
522 #[allow(unused_macros)]
523 macro_rules! amdsmi_func {
524 ($func:expr, $($arg:expr),*) => {
525 move |handle| $func(handle, $($arg),*)
526 };
527 }