joularcore 0.2.0

Joular Core is a platform to measure power and energy across all systems, OSes and devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/*
 * Copyright (c) 2025-2026, Adel Noureddine.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the
 * GNU Lesser General Public License v3.0 only (LGPL-3.0-only)
 * which accompanies this distribution, and is available at
 * https://www.gnu.org/licenses/lgpl-3.0.en.html
 *
 * Author : Adel Noureddine
 */

//! Reading power from a file instead of a hardware sensor.
//!
//! Inside a virtual machine no RAPL or `powermetrics` interface is reachable,
//! so the hypervisor or an external meter (such as Joular Core itself) writes the figures to a file and
//! Joular Core reads them from there. See [`PowerFormat`] for the layouts
//! understood.
//!
//! A [`VmSensor`] is an ordinary [`PowerSensor`], so hand one to
//! [`crate::monitor::JoularCoreMonitor::builder`] in place of the platform's
//! own:
//!
//! ```no_run
//! use joularcore::{JoularCoreMonitor, MonitorConfig};
//! use joularcore::vm::{PowerFormat, VmSensor};
//!
//! # fn main() -> joularcore::Result<()> {
//! let config = MonitorConfig::default();
//! let monitor = JoularCoreMonitor::builder(&config)
//!     .cpu_sensor(Box::new(VmSensor::cpu("/var/run/vm-power", PowerFormat::Watts)?))
//!     .build();
//! # Ok(())
//! # }
//! ```

use crate::sensor::PowerSensor;
use crate::{Error, Result};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

/// Layout of a power file produced outside Joular Core.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PowerFormat {
    /// A plain text file holding a single number, in watts. The default.
    #[default]
    Watts,
    /// Joular Core CSV: a header row plus data rows, read from the last row.
    JoularCore,
}

impl std::str::FromStr for PowerFormat {
    type Err = crate::Error;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "watts" => Ok(PowerFormat::Watts),
            "joularcore" => Ok(PowerFormat::JoularCore),
            other => Err(crate::Error::config(format!(
                "unsupported power format {other:?}, expected \"watts\" or \"joularcore\""
            ))),
        }
    }
}

/// Which power files to read, and how they are laid out.
///
/// Only needed for [`VmSensor::cpu_from_config`] /
/// [`VmSensor::gpu_from_config`] and [`VmConfig::from_env`];
/// [`VmSensor::cpu`] takes a path and format directly.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct VmConfig {
    /// File holding CPU power, written by the hypervisor or an external meter.
    pub cpu_power_file: Option<PathBuf>,
    /// Layout of `cpu_power_file`.
    pub cpu_power_format: PowerFormat,
    /// File holding GPU power.
    pub gpu_power_file: Option<PathBuf>,
    /// Layout of `gpu_power_file`.
    pub gpu_power_format: PowerFormat,
}

impl VmConfig {
    /// Read the configuration from the `VM_CPU_POWER_FILE`,
    /// `VM_CPU_POWER_FORMAT`, `VM_GPU_POWER_FILE` and `VM_GPU_POWER_FORMAT`
    /// environment variables.
    ///
    /// Returns `Ok(None)` when neither power-file variable is set. Formats
    /// default to [`PowerFormat::Watts`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if a variable names an unknown format.
    pub fn from_env() -> Result<Option<Self>> {
        fn file(var: &str) -> Option<PathBuf> {
            std::env::var_os(var)
                .filter(|v| !v.is_empty())
                .map(PathBuf::from)
        }
        fn format(var: &str) -> Result<PowerFormat> {
            match std::env::var(var) {
                Ok(v) => v.parse(),
                Err(_) => Ok(PowerFormat::default()),
            }
        }

        let cpu_power_file = file("VM_CPU_POWER_FILE");
        let gpu_power_file = file("VM_GPU_POWER_FILE");
        if cpu_power_file.is_none() && gpu_power_file.is_none() {
            return Ok(None);
        }

        Ok(Some(Self {
            cpu_power_file,
            cpu_power_format: format("VM_CPU_POWER_FORMAT")?,
            gpu_power_file,
            gpu_power_format: format("VM_GPU_POWER_FORMAT")?,
        }))
    }
}

/// Most a power file may hold. Power files carry a handful of numbers; a file
/// larger than this is either the wrong file or one that is growing without
/// bound, and reading all of it would exhaust memory.
const MAX_FILE_BYTES: u64 = 1024 * 1024;

/// Which figure to pull out of a Joular Core CSV.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PowerKind {
    Cpu,
    Gpu,
}

impl PowerKind {
    /// Candidate column names, most specific first.
    fn columns(self) -> &'static [&'static str] {
        match self {
            PowerKind::Cpu => &["App Power (W)", "Process Power (W)", "CPU Power (W)"],
            PowerKind::Gpu => &["GPU Power (W)"],
        }
    }
}

/// A power file kept open for the lifetime of the reader.
///
/// The handle is opened once and re-read by seeking back to the start, so a
/// file swapped at the path afterwards cannot redirect subsequent reads.
struct PowerFile {
    /// Kept for error messages only; reads never go through it again.
    path: PathBuf,
    format: PowerFormat,
    kind: PowerKind,
    file: File,
    /// Reused between reads so sampling does not allocate per tick.
    buffer: String,
}

impl PowerFile {
    fn open(path: &Path, format: PowerFormat, kind: PowerKind, var_name: &str) -> Result<Self> {
        let metadata = std::fs::metadata(path).map_err(|e| {
            Error::config(format!(
                "{var_name} points to {} which cannot be read: {e}",
                path.display()
            ))
        })?;
        if !metadata.is_file() {
            return Err(Error::config(format!(
                "{var_name} points to {} which is not a regular file",
                path.display()
            )));
        }
        if metadata.len() > MAX_FILE_BYTES {
            return Err(Error::config(format!(
                "{var_name} points to {} which holds more than the {MAX_FILE_BYTES} byte limit",
                path.display()
            )));
        }

        let file = File::open(path).map_err(|e| {
            Error::config(format!(
                "{var_name} points to {} which cannot be opened: {e}",
                path.display()
            ))
        })?;

        Ok(Self {
            path: path.to_path_buf(),
            format,
            kind,
            file,
            buffer: String::with_capacity(256),
        })
    }

    fn power(&mut self) -> Result<f64> {
        let read = |e: std::io::Error| {
            Error::sensor("VM power file", format!("{}: {e}", self.path.display()))
        };

        self.file.seek(SeekFrom::Start(0)).map_err(read)?;
        self.buffer.clear();
        (&self.file)
            // Read one byte past the cap so an oversized file is rejected
            // instead of silently being parsed from a valid-looking prefix.
            .take(MAX_FILE_BYTES + 1)
            .read_to_string(&mut self.buffer)
            .map_err(read)?;
        if self.buffer.len() as u64 > MAX_FILE_BYTES {
            return Err(Error::sensor(
                "VM power file",
                format!(
                    "{} holds more than the {MAX_FILE_BYTES} byte limit",
                    self.path.display()
                ),
            ));
        }

        parse_power(&self.buffer, self.format, self.kind).map_err(|detail| {
            Error::sensor(
                "VM power file",
                format!("{}: {detail}", self.path.display()),
            )
        })
    }
}

/// Extract a power figure from file contents.
fn parse_power(
    content: &str,
    format: PowerFormat,
    kind: PowerKind,
) -> std::result::Result<f64, String> {
    match format {
        PowerFormat::Watts => parse_watts(content),
        PowerFormat::JoularCore => parse_joularcore(content, kind),
    }
}

/// A file holding a single number, in watts.
fn parse_watts(content: &str) -> std::result::Result<f64, String> {
    let line = content.lines().next().unwrap_or("").trim();
    if line.is_empty() {
        return Ok(0.0);
    }
    line.parse()
        .map_err(|e| format!("expected a number, found {line:?}: {e}"))
}

/// Joular Core CSV: a header row plus data rows, read from the last row.
fn parse_joularcore(content: &str, kind: PowerKind) -> std::result::Result<f64, String> {
    let mut lines = content.lines().filter(|line| !line.trim().is_empty());

    let Some(header) = lines.next() else {
        return Ok(0.0);
    };
    // The newest sample is the last row; earlier rows are history.
    let Some(data) = lines.next_back() else {
        return Ok(0.0);
    };

    let headers: Vec<&str> = header.split(',').map(str::trim).collect();
    let values: Vec<&str> = data.split(',').map(str::trim).collect();
    if headers.len() != values.len() {
        return Err(format!(
            "header has {} columns but the last row has {}",
            headers.len(),
            values.len()
        ));
    }

    kind.columns()
        .iter()
        .find_map(|wanted| {
            let index = headers.iter().position(|header| header == wanted)?;
            values[index].parse::<f64>().ok()
        })
        .ok_or_else(|| {
            format!(
                "no readable column among {:?} in header {headers:?}",
                kind.columns()
            )
        })
}

/// CPU or GPU power read from a file.
///
/// Which component it reports is fixed when it is created, because that decides
/// which column a CSV format is read from — see [`PowerFormat::JoularCore`].
pub struct VmSensor(PowerFile);

impl VmSensor {
    /// Read CPU power from `path`, laid out as `format`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if `path` cannot be opened, is not a regular
    /// file, or is larger than the read cap. If the file grows past the cap
    /// later, [`PowerSensor::power`] reports it as unavailable.
    pub fn cpu(path: impl AsRef<Path>, format: PowerFormat) -> Result<Self> {
        Self::open(path, format, PowerKind::Cpu, "VM CPU power file")
    }

    /// Read GPU power from `path`, laid out as `format`.
    ///
    /// # Errors
    ///
    /// See [`VmSensor::cpu`].
    pub fn gpu(path: impl AsRef<Path>, format: PowerFormat) -> Result<Self> {
        Self::open(path, format, PowerKind::Gpu, "VM GPU power file")
    }

    /// The CPU sensor a [`VmConfig`] describes, if it names a CPU power file.
    ///
    /// # Errors
    ///
    /// See [`VmSensor::cpu`].
    pub fn cpu_from_config(config: &VmConfig) -> Result<Option<Self>> {
        config
            .cpu_power_file
            .as_ref()
            .map(|path| Self::cpu(path, config.cpu_power_format))
            .transpose()
    }

    /// The GPU sensor a [`VmConfig`] describes, if it names a GPU power file.
    ///
    /// # Errors
    ///
    /// See [`VmSensor::cpu`].
    pub fn gpu_from_config(config: &VmConfig) -> Result<Option<Self>> {
        config
            .gpu_power_file
            .as_ref()
            .map(|path| Self::gpu(path, config.gpu_power_format))
            .transpose()
    }

    fn open(
        path: impl AsRef<Path>,
        format: PowerFormat,
        kind: PowerKind,
        label: &'static str,
    ) -> Result<Self> {
        Ok(Self(PowerFile::open(path.as_ref(), format, kind, label)?))
    }
}

impl PowerSensor for VmSensor {
    fn power(&mut self) -> Result<f64> {
        self.0.power()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn power_format_defaults_to_watts() {
        assert_eq!(PowerFormat::default(), PowerFormat::Watts);
        assert_eq!(
            "JoularCore".parse::<PowerFormat>().unwrap(),
            PowerFormat::JoularCore
        );
        assert!("csv".parse::<PowerFormat>().is_err());
    }

    #[test]
    fn watts_reads_a_bare_number() {
        assert_eq!(parse_watts("42.5\n").unwrap(), 42.5);
        assert_eq!(parse_watts("  7 \n").unwrap(), 7.0);
        // A file the producer has not written yet reads as zero, not an error.
        assert_eq!(parse_watts("").unwrap(), 0.0);
        assert!(parse_watts("not a number").is_err());
    }

    const JOULARCORE_CSV: &str = "\
Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%),App Power (W),App PIDs
1700000000,20.00,15.00,5.00,30.00,4.00,2
1700000001,22.00,17.00,5.00,35.00,6.00,3
";

    #[test]
    fn joularcore_reads_the_last_row() {
        // App power outranks CPU power for the CPU figure.
        assert_eq!(
            parse_joularcore(JOULARCORE_CSV, PowerKind::Cpu).unwrap(),
            6.0
        );
        assert_eq!(
            parse_joularcore(JOULARCORE_CSV, PowerKind::Gpu).unwrap(),
            5.0
        );
    }

    #[test]
    fn joularcore_falls_back_through_the_column_priority() {
        let csv = "Timestamp,CPU Power (W),GPU Power (W)\n1700000000,15.00,5.00\n";
        assert_eq!(parse_joularcore(csv, PowerKind::Cpu).unwrap(), 15.0);
    }

    #[test]
    fn joularcore_rejects_a_ragged_row() {
        let csv = "Timestamp,CPU Power (W),GPU Power (W)\n1700000000,15.00\n";
        assert!(parse_joularcore(csv, PowerKind::Cpu).is_err());
    }

    #[test]
    fn joularcore_errors_when_no_column_matches() {
        let csv = "Timestamp,Temperature (C)\n1700000000,55\n";
        assert!(parse_joularcore(csv, PowerKind::Cpu).is_err());
    }

    #[test]
    fn joularcore_tolerates_a_header_only_file() {
        assert_eq!(
            parse_joularcore("Timestamp,CPU Power (W)\n", PowerKind::Cpu).unwrap(),
            0.0
        );
        assert_eq!(parse_joularcore("", PowerKind::Cpu).unwrap(), 0.0);
    }

    #[test]
    fn reader_reflects_later_writes_to_the_same_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("power");
        std::fs::write(&path, "10.0\n").unwrap();

        let mut cpu = VmSensor::cpu(&path, PowerFormat::Watts).unwrap();
        assert_eq!(cpu.power().unwrap(), 10.0);

        // The producer rewrites the file in place between samples.
        std::fs::write(&path, "25.5\n").unwrap();
        assert_eq!(cpu.power().unwrap(), 25.5);
    }

    #[test]
    fn opening_an_oversized_file_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("power");
        std::fs::write(&path, "x".repeat(MAX_FILE_BYTES as usize + 1)).unwrap();

        let Err(error) = VmSensor::cpu(&path, PowerFormat::Watts) else {
            panic!("expected oversized file to be rejected");
        };
        assert!(matches!(error, Error::Config(_)));
    }

    #[test]
    fn a_file_that_grows_past_the_cap_is_unavailable() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("power");
        std::fs::write(&path, "10.0\n").unwrap();

        let mut cpu = VmSensor::cpu(&path, PowerFormat::Watts).unwrap();
        assert_eq!(cpu.power().unwrap(), 10.0);

        std::fs::write(
            &path,
            format!("42.0\n{}", "x".repeat(MAX_FILE_BYTES as usize)),
        )
        .unwrap();

        let error = cpu.power().unwrap_err();
        assert!(matches!(error, Error::SensorUnavailable { .. }));
    }

    #[test]
    fn opening_a_directory_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        assert!(VmSensor::cpu(dir.path(), PowerFormat::Watts).is_err());
    }

    #[test]
    fn opening_a_missing_file_is_rejected() {
        assert!(VmSensor::gpu("/nonexistent/joularcore/power", PowerFormat::Watts).is_err());
    }
}