Debian Codegraph @

src/collection/temperature/linux.rs

raw symbols SCIP
1 //! Gets temperature sensor data for Linux platforms.
2
3 use std::{
4 fs,
5 path::{Path, PathBuf},
6 };
7
8 use anyhow::Result;
9 use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
10
11 use super::TempSensorData;
12 #[cfg(feature = "gpu")]
13 use crate::collection::amd::get_amd_name;
14 use crate::{app::filter::Filter, collection::linux::utils::is_device_awake};
15
16 const EMPTY_NAME: &str = "Unknown";
17
18 /// Returned results from grabbing hwmon/coretemp temperature sensor
19 /// values or names.
20 struct HwmonResults {
21 temperatures: Vec<TempSensorData>,
22 num_hwmon: usize,
23 }
24
25 /// Parses and reads temperatures that were in millidegree Celsius, and if
26 /// successful, returns a temperature in Celsius.
27 fn parse_temp(path: &Path) -> Result<f32> {
28 Ok(fs::read_to_string(path)?.trim_end().parse::<f32>()? / 1_000.0)
29 }
30
31 /// Get all candidates from hwmon and coretemp. It will also return the number
32 /// of entries from hwmon.
33 fn get_hwmon_candidates() -> (HashSet<PathBuf>, usize) {
34 let mut dirs = HashSet::default();
35
36 if let Ok(read_dir) = Path::new("/sys/class/hwmon").read_dir() {
37 for entry in read_dir.flatten() {
38 let mut path = entry.path();
39
40 // hwmon includes many sensors, we only want ones with at least one temperature
41 // sensor Reading this file will wake the device, but we're only
42 // checking existence, so it should be fine.
43 if !path.join("temp1_input").exists() {
44 // Note we also check for a `device` subdirectory (e.g.
45 // `/sys/class/hwmon/hwmon*/device/`). This is needed for
46 // CentOS, which adds this extra `/device` directory. See:
47 // - https://github.com/nicolargo/glances/issues/1060
48 // - https://github.com/giampaolo/psutil/issues/971
49 // - https://github.com/giampaolo/psutil/blob/642438375e685403b4cd60b0c0e25b80dd5a813d/psutil/_pslinux.py#L1316
50 //
51 // If it does match, then add the `device/` directory to the path.
52 if path.join("device/temp1_input").exists() {
53 path.push("device");
54 }
55 }
56
57 dirs.insert(path);
58 }
59 }
60
61 let num_hwmon = dirs.len();
62
63 if let Ok(read_dir) = Path::new("/sys/devices/platform").read_dir() {
64 for entry in read_dir.flatten() {
65 if entry.file_name().to_string_lossy().starts_with("coretemp.")
66 && let Ok(read_dir) = entry.path().join("hwmon").read_dir()
67 {
68 for entry in read_dir.flatten() {
69 let path = entry.path();
70
71 if path.join("temp1_input").exists() {
72 // It's possible that there are dupes (represented by symlinks) - the
73 // easy way is to just substitute the parent
74 // directory and check if the hwmon
75 // variant exists already in a set.
76 //
77 // For more info, see https://github.com/giampaolo/psutil/pull/1822/files
78 if let Some(child) = path.file_name() {
79 let to_check_path = Path::new("/sys/class/hwmon").join(child);
80
81 if !dirs.contains(&to_check_path) {
82 dirs.insert(path);
83 }
84 }
85 }
86 }
87 }
88 }
89 }
90
91 (dirs, num_hwmon)
92 }
93
94 #[inline]
95 fn read_to_string_lossy<P: AsRef<Path>>(path: P) -> Option<String> {
96 fs::read(path)
97 .map(|v| String::from_utf8_lossy(&v).trim().to_string())
98 .ok()
99 }
100
101 #[inline]
102 fn humanize_name(name: &str, sensor_name: Option<&String>) -> String {
103 match sensor_name {
104 Some(ty) => format!("{name} ({ty})"),
105 None => name.to_string(),
106 }
107 }
108
109 #[inline]
110 fn counted_name(seen_names: &mut HashMap<String, u32>, name: String) -> String {
111 if let Some(count) = seen_names.get_mut(&name) {
112 *count += 1;
113 format!("{name} ({count})")
114 } else {
115 seen_names.insert(name.clone(), 0);
116 name
117 }
118 }
119
120 fn uppercase_first_letter(s: &mut str) {
121 if let Some(r) = s.get_mut(0..1) {
122 r.make_ascii_uppercase();
123 }
124 }
125
126 fn finalize_name(
127 hwmon_name: Option<String>, sensor_label: Option<String>,
128 fallback_sensor_name: &Option<String>, seen_names: &mut HashMap<String, u32>,
129 ) -> String {
130 let candidate_name = match (hwmon_name, sensor_label) {
131 (Some(name), Some(mut label)) => match (name.is_empty(), label.is_empty()) {
132 (false, false) => {
133 uppercase_first_letter(&mut label);
134 format!("{name}: {label}")
135 }
136 (true, false) => {
137 uppercase_first_letter(&mut label);
138
139 // We assume label must not be empty.
140 match fallback_sensor_name {
141 Some(fallback) if !fallback.is_empty() => {
142 format!("{fallback}: {label}")
143 }
144 _ => label,
145 }
146 }
147 (false, true) => name.to_owned(),
148 (true, true) => EMPTY_NAME.to_string(),
149 },
150 (None, Some(mut label)) => match fallback_sensor_name {
151 Some(fallback) if !fallback.is_empty() => {
152 if label.is_empty() {
153 fallback.to_owned()
154 } else {
155 uppercase_first_letter(&mut label);
156 format!("{fallback}: {label}")
157 }
158 }
159 _ => {
160 if label.is_empty() {
161 EMPTY_NAME.to_string()
162 } else {
163 uppercase_first_letter(&mut label);
164 label
165 }
166 }
167 },
168 (Some(name), None) => {
169 if name.is_empty() {
170 EMPTY_NAME.to_string()
171 } else {
172 name
173 }
174 }
175 (None, None) => match fallback_sensor_name {
176 Some(sensor_name) if !sensor_name.is_empty() => sensor_name.to_owned(),
177 _ => EMPTY_NAME.to_string(),
178 },
179 };
180
181 counted_name(seen_names, candidate_name)
182 }
183
184 /// Get temperature sensors from the linux sysfs interface `/sys/class/hwmon`
185 /// and `/sys/devices/platform/coretemp.*`. It returns all found temperature
186 /// sensors, and the number of checked hwmon directories (not coretemp
187 /// directories).
188 ///
189 /// For more details, see the relevant Linux kernel documentation:
190 /// - [`/sys/class/hwmon`](https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-hwmon)
191 /// - [`/sys/devices/platform/coretemp.*`](https://www.kernel.org/doc/html/v5.14/hwmon/coretemp.html)
192 ///
193 /// This method will return `0` as the temperature for devices, such as GPUs,
194 /// that support power management features that have powered themselves off.
195 /// Specifically, in laptops with iGPUs and dGPUs, if the dGPU is capable of
196 /// entering ACPI D3cold, reading the temperature sensors will wake it,
197 /// and keep it awake, wasting power.
198 ///
199 /// For such devices, this method will only query the sensors *only* if
200 /// the device is already in ACPI D0. This has the notable issue that
201 /// once this happens, the device will be *kept* on through the sensor
202 /// reading, and not be able to re-enter ACPI D3cold.
203 fn hwmon_temperatures(filter: &Option<Filter>, graph_filter: &Option<Filter>) -> HwmonResults {
204 let mut temperatures: Vec<TempSensorData> = vec![];
205 let mut seen_names: HashMap<String, u32> = HashMap::default();
206
207 let (dirs, num_hwmon) = get_hwmon_candidates();
208
209 // Note that none of this is async if we ever go back to it, but sysfs is in
210 // memory, so in theory none of this should block if we're slightly careful.
211 // Of note is that reading the temperature sensors of a device that has
212 // `/sys/class/hwmon/hwmon*/device/power_state` == `D3cold` will
213 // wake the device up, and will block until it initializes.
214 //
215 // Reading the `hwmon*/device/power_state` or `hwmon*/temp*_label` properties
216 // will not wake the device, and thus not block,
217 // and meaning no sensors have to be hidden depending on `power_state`
218 //
219 // It would probably be more ideal to use a proper async runtime; this would
220 // also allow easy cancellation/timeouts.
221 for file_path in dirs {
222 let sensor_name = read_to_string_lossy(file_path.join("name"));
223 let device = file_path.join("device");
224
225 if !is_device_awake(&device) {
226 let name = finalize_name(None, None, &sensor_name, &mut seen_names);
227 temperatures.push(TempSensorData {
228 name,
229 temperature: None,
230 });
231
232 continue;
233 }
234
235 if let Ok(dir_entries) = file_path.read_dir() {
236 // Enumerate the devices temperature sensors
237 for file in dir_entries.flatten() {
238 let name = file.file_name();
239 let name = name.to_string_lossy();
240
241 // We only want temperature sensors, skip others early
242 if !(name.starts_with("temp") && name.ends_with("input")) {
243 continue;
244 }
245
246 let temp_path = file.path();
247 let sensor_label_path = file_path.join(name.replace("input", "label"));
248 let sensor_label = read_to_string_lossy(sensor_label_path);
249
250 // Do some messing around to get a more sensible name for sensors:
251 // - For GPUs, this will use the kernel device name, ex `card0`
252 // - For nvme drives, this will also use the kernel name, ex `nvme0`. This is
253 // found differently than for GPUs
254 // - For whatever acpitz is, on my machine this is now `thermal_zone0`.
255 // - For k10temp, this will still be k10temp, but it has to be handled special.
256 let hwmon_name = {
257 let device = file_path.join("device");
258
259 // This will exist for GPUs but not others, this is how we find their kernel
260 // name.
261 let drm = device.join("drm");
262 if drm.exists() {
263 // This should never actually be empty. If it is though, we'll fall back to
264 // the sensor name later on.
265
266 #[cfg(feature = "gpu")]
267 {
268 if let Some(amd_gpu_name) = get_amd_name(&device) {
269 Some(amd_gpu_name)
270 } else if let Ok(cards) = drm.read_dir() {
271 cards.flatten().find_map(|card| {
272 card.file_name().to_str().and_then(|name| {
273 name.starts_with("card").then(|| {
274 humanize_name(name.trim(), sensor_name.as_ref())
275 })
276 })
277 })
278 } else {
279 None
280 }
281 }
282
283 #[cfg(not(feature = "gpu"))]
284 {
285 if let Ok(cards) = drm.read_dir() {
286 cards.flatten().find_map(|card| {
287 card.file_name().to_str().and_then(|name| {
288 name.starts_with("card").then(|| {
289 humanize_name(name.trim(), sensor_name.as_ref())
290 })
291 })
292 })
293 } else {
294 None
295 }
296 }
297 } else {
298 // This little mess is to account for stuff like k10temp. This is needed
299 // because the `device` symlink points to `nvme*`
300 // for nvme drives, but to PCI buses for anything
301 // else. If the first character is alphabetic, it's an actual name like
302 // k10temp or nvme0, not a PCI bus.
303 fs::read_link(device).ok().and_then(|link| {
304 let link = link.file_name().and_then(|f| f.to_str()).map(|s| s.trim());
305
306 if let Some(link) = &link
307 && let Some(first_char) = link.as_bytes().first()
308 && first_char.is_ascii_alphabetic()
309 {
310 Some(humanize_name(link, sensor_name.as_ref()))
311 } else {
312 None
313 }
314 })
315 }
316 };
317
318 let name = finalize_name(hwmon_name, sensor_label, &sensor_name, &mut seen_names);
319
320 // TODO: It's possible we may want to move the filter check further up to avoid
321 // probing hwmon if not needed?
322 if (Filter::optional_should_keep(filter, &name)
323 || Filter::optional_should_keep(graph_filter, &name))
324 && let Ok(temp_celsius) = parse_temp(&temp_path)
325 {
326 temperatures.push(TempSensorData {
327 name,
328 temperature: Some(temp_celsius),
329 });
330 }
331 }
332 }
333 }
334
335 HwmonResults {
336 temperatures,
337 num_hwmon,
338 }
339 }
340
341 /// Gets data from `/sys/class/thermal/thermal_zone*`. This should only be used
342 /// if [`hwmon_temperatures`] doesn't return anything to avoid duplicate sensor
343 /// results.
344 ///
345 /// See [the Linux kernel documentation](https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-thermal)
346 /// for more details.
347 fn add_thermal_zone_temperatures(
348 temperatures: &mut Vec<TempSensorData>, filter: &Option<Filter>, graph_filter: &Option<Filter>,
349 ) {
350 let path = Path::new("/sys/class/thermal");
351 let Ok(read_dir) = path.read_dir() else {
352 return;
353 };
354
355 let mut seen_names: HashMap<String, u32> = HashMap::default();
356
357 for entry in read_dir.flatten() {
358 if entry
359 .file_name()
360 .to_string_lossy()
361 .starts_with("thermal_zone")
362 {
363 let file_path = entry.path();
364 let name_path = file_path.join("type");
365
366 if let Some(name) = read_to_string_lossy(name_path) {
367 let name = if name.is_empty() {
368 EMPTY_NAME.to_string()
369 } else {
370 name
371 };
372
373 if Filter::optional_should_keep(filter, &name)
374 || Filter::optional_should_keep(graph_filter, &name)
375 {
376 let temp_path = file_path.join("temp");
377 if let Ok(temp_celsius) = parse_temp(&temp_path) {
378 let name = counted_name(&mut seen_names, name);
379
380 temperatures.push(TempSensorData {
381 name,
382 temperature: Some(temp_celsius),
383 });
384 }
385 }
386 }
387 }
388 }
389 }
390
391 /// Gets temperature sensors and data.
392 pub fn get_temperature_data(
393 filter: &Option<Filter>, graph_filter: &Option<Filter>,
394 ) -> Result<Option<Vec<TempSensorData>>> {
395 let mut results = hwmon_temperatures(filter, graph_filter);
396
397 if results.num_hwmon == 0 {
398 add_thermal_zone_temperatures(&mut results.temperatures, filter, graph_filter);
399 }
400
401 Ok(Some(results.temperatures))
402 }
403
404 #[cfg(test)]
405 mod tests {
406 use rustc_hash::FxHashMap as HashMap;
407
408 use super::finalize_name;
409
410 #[test]
411 fn test_finalize_name() {
412 let mut seen_names = HashMap::default();
413
414 assert_eq!(
415 finalize_name(
416 Some("hwmon".to_string()),
417 Some("sensor".to_string()),
418 &Some("test".to_string()),
419 &mut seen_names
420 ),
421 "hwmon: Sensor"
422 );
423
424 assert_eq!(
425 finalize_name(
426 Some("hwmon".to_string()),
427 None,
428 &Some("test".to_string()),
429 &mut seen_names
430 ),
431 "hwmon"
432 );
433
434 assert_eq!(
435 finalize_name(
436 None,
437 Some("sensor".to_string()),
438 &Some("test".to_string()),
439 &mut seen_names
440 ),
441 "test: Sensor"
442 );
443
444 assert_eq!(
445 finalize_name(
446 Some("hwmon".to_string()),
447 Some("sensor".to_string()),
448 &Some("test".to_string()),
449 &mut seen_names
450 ),
451 "hwmon: Sensor (1)"
452 );
453
454 assert_eq!(
455 finalize_name(None, None, &Some("test".to_string()), &mut seen_names),
456 "test"
457 );
458
459 assert_eq!(finalize_name(None, None, &None, &mut seen_names), "Unknown");
460
461 assert_eq!(
462 finalize_name(None, None, &Some("test".to_string()), &mut seen_names),
463 "test (1)"
464 );
465
466 assert_eq!(
467 finalize_name(None, None, &None, &mut seen_names),
468 "Unknown (1)"
469 );
470
471 assert_eq!(
472 finalize_name(Some(String::default()), None, &None, &mut seen_names),
473 "Unknown (2)"
474 );
475
476 assert_eq!(
477 finalize_name(None, Some(String::default()), &None, &mut seen_names),
478 "Unknown (3)"
479 );
480
481 assert_eq!(
482 finalize_name(None, None, &Some(String::default()), &mut seen_names),
483 "Unknown (4)"
484 );
485 }
486 }