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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/*
 * 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
 */

//! Where monitoring samples go: files and the shared-memory ring buffer.
//!
//! [`OutputBundle`] fans one [`MonitorSample`] out to every destination you
//! attach; each destination is an [`OutputSink`] and can also be driven alone.
//! To send samples somewhere this crate does not know about, implement
//! `OutputSink` — [`Schema`] renders the same rows a [`FileWriter`] writes, so a
//! destination of your own can match the file format exactly.

use crate::config::{Component, Target};
use crate::monitor::MonitorSample;
use std::fmt::Write as _;
use std::fs::{File, OpenOptions};
use std::io::{Seek, SeekFrom, Write};
use std::path::Path;

/// Anything that accepts monitor samples.
pub trait OutputSink {
    /// Record one sample.
    ///
    /// # Errors
    ///
    /// Returns the destination's own failure. A configured output that fails is
    /// a hard error, unlike a sensor that cannot be read.
    fn send(&mut self, sample: &MonitorSample) -> crate::Result<()>;
}

/// One column of output: its header, and how to read it from a sample.
///
/// Naming a column and filling it are the same declaration, so a column cannot
/// be added to the header without also being written into every row.
#[derive(Clone, Copy, Debug)]
struct Column {
    header: &'static str,
    cell: fn(&MonitorSample) -> Cell,
}

/// A column's value. Watts always carry two decimals; counts are whole numbers.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Cell {
    Watts(f64),
    Count(u64),
}

impl std::fmt::Display for Cell {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            // Unmeasured components arrive here as 0.0: a row that skipped them
            // would no longer line up with the header.
            Cell::Watts(watts) => write!(f, "{watts:.2}"),
            Cell::Count(count) => write!(f, "{count}"),
        }
    }
}

const TIMESTAMP: Column = Column {
    header: "Timestamp",
    cell: |sample| Cell::Count(sample.timestamp),
};
const TOTAL: Column = Column {
    header: "Total Power (W)",
    cell: |sample| Cell::Watts(sample.total_power()),
};
const CPU: Column = Column {
    header: "CPU Power (W)",
    cell: |sample| Cell::Watts(sample.cpu_power_or_zero()),
};
const GPU: Column = Column {
    header: "GPU Power (W)",
    cell: |sample| Cell::Watts(sample.gpu_power_or_zero()),
};
const USAGE: Column = Column {
    header: "CPU Usage (%)",
    cell: |sample| Cell::Watts(sample.cpu_usage),
};
const PROCESS: Column = Column {
    header: "Process Power (W)",
    cell: |sample| Cell::Watts(sample.target_power_or_zero()),
};
const APP: Column = Column {
    header: "App Power (W)",
    cell: |sample| Cell::Watts(sample.target_power_or_zero()),
};
const APP_PIDS: Column = Column {
    header: "App PIDs",
    cell: |sample| Cell::Count(sample.app_pid_count.unwrap_or(0) as u64),
};

/// What a [`FileWriter`] emits, fixed for the life of the writer.
///
/// Two shapes are available: [`Schema::csv`] writes labelled columns under a
/// header row, and [`Schema::watts`] writes one bare wattage per sample — the
/// layout `vm::PowerFormat::Watts` reads back, under the `vm` feature.
#[derive(Clone, Copy, Debug)]
pub struct Schema {
    columns: &'static [Column],
    /// `false` for the bare-wattage layout, which writes values and no header.
    labelled: bool,
}

impl Schema {
    /// Comma-separated columns for a session measuring `component` of `target`.
    #[must_use]
    pub fn csv(component: Option<Component>, target: &Target) -> Self {
        Self {
            columns: match (component, target) {
                (Some(Component::Cpu), _) => &[TIMESTAMP, CPU],
                (Some(Component::Gpu), _) => &[TIMESTAMP, GPU],
                (None, Target::System) => &[TIMESTAMP, TOTAL, CPU, GPU, USAGE],
                (None, Target::Pid(_)) => &[TIMESTAMP, TOTAL, CPU, GPU, USAGE, PROCESS],
                (None, Target::App(_)) => &[TIMESTAMP, TOTAL, CPU, GPU, USAGE, APP, APP_PIDS],
            },
            labelled: true,
        }
    }

    /// One bare wattage per sample, with no header, timestamp or label.
    ///
    /// Reports `component`, or total power when `None`.
    #[must_use]
    pub fn watts(component: Option<Component>) -> Self {
        Self {
            columns: match component {
                Some(Component::Cpu) => &[CPU],
                Some(Component::Gpu) => &[GPU],
                None => &[TOTAL],
            },
            labelled: false,
        }
    }

    /// The header row this schema describes, without a trailing newline.
    ///
    /// Empty for [`Schema::watts`], which has no header.
    #[must_use]
    pub fn header(&self) -> String {
        if !self.labelled {
            return String::new();
        }

        self.columns
            .iter()
            .map(|column| column.header)
            .collect::<Vec<_>>()
            .join(",")
    }

    /// One sample as a row, without a trailing newline.
    #[must_use]
    pub fn row(&self, sample: &MonitorSample) -> String {
        let mut out = String::new();
        self.write_row(&mut out, sample);
        out
    }

    /// Write one row into `out`, so a monitoring loop can reuse its buffer.
    fn write_row(&self, out: &mut String, sample: &MonitorSample) {
        for (index, column) in self.columns.iter().enumerate() {
            if index > 0 {
                out.push(',');
            }
            // Writing into a String cannot fail, so the result is discarded.
            let _ = write!(out, "{}", (column.cell)(sample));
        }
    }
}

/// Writes samples to a file.
///
/// In overwrite mode the file is truncated before every sample, so it always
/// holds exactly the latest row — convenient for consumers that poll a file.
/// No header is written in that mode, since it would be erased by the first
/// sample.
pub struct FileWriter {
    file: File,
    schema: Schema,
    overwrite: bool,
    /// Reused between samples so a monitoring loop does not allocate per tick.
    scratch: String,
}

impl FileWriter {
    /// Open `path` for output.
    ///
    /// With `overwrite`, the file is truncated before each sample; otherwise
    /// samples are appended.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Io`] if `path` cannot be opened or created.
    pub fn open(path: impl AsRef<Path>, schema: Schema, overwrite: bool) -> crate::Result<Self> {
        let file = if overwrite {
            OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(path)?
        } else {
            OpenOptions::new().create(true).append(true).open(path)?
        };

        Ok(Self {
            file,
            schema,
            overwrite,
            scratch: String::with_capacity(128),
        })
    }

    /// Create and open a CSV file writer matching `config`, writing the CSV header automatically.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Io`] if `path` cannot be opened or created, or if the header cannot be written.
    pub fn csv(
        path: impl AsRef<Path>,
        config: &crate::config::MonitorConfig,
    ) -> crate::Result<Self> {
        let schema = Schema::csv(config.component, &config.target);
        let mut writer = Self::open(path, schema, false)?;
        writer.write_header()?;
        Ok(writer)
    }

    /// Write the header row describing the columns this writer emits.
    ///
    /// Does nothing for [`Schema::watts`], which has no header, or in overwrite
    /// mode where the first sample would erase it.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::Io`] if the header cannot be written.
    pub fn write_header(&mut self) -> crate::Result<()> {
        let header = self.schema.header();
        if header.is_empty() || self.overwrite {
            return Ok(());
        }

        writeln!(self.file, "{header}")?;
        Ok(())
    }
}

impl OutputSink for FileWriter {
    fn send(&mut self, sample: &MonitorSample) -> crate::Result<()> {
        if self.overwrite {
            // Truncating rather than seeking is what keeps a shorter row from
            // leaving a tail of the previous, longer one behind it.
            self.file.set_len(0)?;
            self.file.seek(SeekFrom::Start(0))?;
        }

        let row = &mut self.scratch;
        row.clear();
        self.schema.write_row(row, sample);
        row.push('\n');

        self.file.write_all(row.as_bytes())?;
        Ok(())
    }
}

/// Fans each sample out to every destination attached to it.
///
/// Destinations are [`OutputSink`]s, so anything that accepts a sample can be
/// attached — including one of your own.
///
/// ```no_run
/// use joularcore::output::{FileWriter, Schema};
/// use joularcore::{OutputBundle, Target};
/// # fn main() -> joularcore::Result<()> {
/// # let target = Target::System;
/// let schema = Schema::csv(None, &target);
/// let mut file = FileWriter::open("power.csv", schema, false)?;
/// file.write_header()?;
///
/// let mut outputs = OutputBundle::new();
/// outputs.push(file);
/// # Ok(())
/// # }
/// ```
#[derive(Default)]
pub struct OutputBundle {
    sinks: Vec<Box<dyn OutputSink>>,
}

impl OutputBundle {
    /// A bundle with no destinations attached.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Attach a destination.
    pub fn push(&mut self, sink: impl OutputSink + 'static) {
        self.sinks.push(Box::new(sink));
    }

    /// Attach a destination and return `self` for builder-style chaining.
    #[must_use]
    pub fn with(mut self, sink: impl OutputSink + 'static) -> Self {
        self.push(sink);
        self
    }

    /// Whether no destination is attached, in which case [`OutputSink::send`]
    /// discards the sample.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sinks.is_empty()
    }
}

impl OutputSink for OutputBundle {
    fn send(&mut self, sample: &MonitorSample) -> crate::Result<()> {
        for sink in &mut self.sinks {
            sink.send(sample)?;
        }
        Ok(())
    }
}

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

    fn sample() -> MonitorSample {
        MonitorSample {
            timestamp: 1_700_000_000,
            cpu_power: Some(12.345),
            gpu_power: Some(6.0),
            cpu_usage: 42.5,
            target_power: None,
            app_pid_count: None,
        }
    }

    /// A header and one row, as a `FileWriter` would lay them out.
    fn csv(sample: &MonitorSample, component: Option<Component>, target: &Target) -> String {
        let schema = Schema::csv(component, target);
        format!("{}\n{}\n", schema.header(), schema.row(sample))
    }

    #[test]
    fn system_csv_has_header_and_row() {
        assert_eq!(
            csv(&sample(), None, &Target::System),
            "Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%)\n\
             1700000000,18.34,12.35,6.00,42.50\n"
        );
    }

    #[test]
    fn single_component_csv_reports_only_that_component() {
        assert_eq!(
            csv(&sample(), Some(Component::Cpu), &Target::System),
            "Timestamp,CPU Power (W)\n1700000000,12.35\n"
        );
        assert_eq!(
            csv(&sample(), Some(Component::Gpu), &Target::System),
            "Timestamp,GPU Power (W)\n1700000000,6.00\n"
        );
    }

    #[test]
    fn process_and_app_targets_add_their_columns() {
        let mut process = sample();
        process.target_power = Some(3.5);
        let rendered = csv(&process, None, &Target::Pid(42));
        assert!(rendered.starts_with(
            "Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%),Process Power (W)\n"
        ));
        assert!(rendered.ends_with("1700000000,18.34,12.35,6.00,42.50,3.50\n"));

        let mut app = sample();
        app.target_power = Some(4.25);
        app.app_pid_count = Some(7);
        let rendered = csv(&app, None, &Target::App("firefox".into()));
        assert!(rendered.contains("App Power (W),App PIDs\n"));
        assert!(rendered.ends_with("1700000000,18.34,12.35,6.00,42.50,4.25,7\n"));
    }

    #[test]
    fn unmeasured_components_are_written_as_zero() {
        let mut sample = sample();
        sample.cpu_power = None;
        let rendered = csv(&sample, None, &Target::System);
        assert!(rendered.ends_with("1700000000,6.00,0.00,6.00,42.50\n"));
    }

    #[test]
    fn a_watts_schema_renders_one_bare_number_and_no_header() {
        let total = Schema::watts(None);
        assert_eq!(total.header(), "");
        assert_eq!(total.row(&sample()), "18.34");

        assert_eq!(Schema::watts(Some(Component::Cpu)).row(&sample()), "12.35");
        assert_eq!(Schema::watts(Some(Component::Gpu)).row(&sample()), "6.00");
    }

    /// The contents of a file after `writer` has been handed `samples`.
    fn written(schema: Schema, overwrite: bool, samples: &[MonitorSample]) -> String {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("power.csv");

        let mut writer = FileWriter::open(&path, schema, overwrite).unwrap();
        writer.write_header().unwrap();
        for sample in samples {
            writer.send(sample).unwrap();
        }
        drop(writer);

        std::fs::read_to_string(&path).unwrap()
    }

    #[test]
    fn appending_writes_a_header_then_every_row() {
        let schema = Schema::csv(None, &Target::System);

        let mut first = sample();
        first.timestamp = 1;
        let mut second = sample();
        second.timestamp = 2;

        assert_eq!(
            written(schema, false, &[first, second]),
            "Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%)\n\
             1,18.34,12.35,6.00,42.50\n\
             2,18.34,12.35,6.00,42.50\n"
        );
    }

    #[test]
    fn overwrite_mode_keeps_only_the_latest_row_and_no_header() {
        let schema = Schema::csv(None, &Target::System);

        let mut first = sample();
        first.timestamp = 1;
        let mut second = sample();
        second.timestamp = 2;

        // A header would be erased by the first sample, so it is not written.
        assert_eq!(
            written(schema, true, &[first, second]),
            "2,18.34,12.35,6.00,42.50\n"
        );
    }

    #[test]
    fn a_shorter_row_cannot_leave_a_tail_of_the_previous_one() {
        // Truncating rather than seeking is what makes this safe: row 2 is
        // shorter than row 1, and the file must not end up as "2,...50\n0,...".
        let schema = Schema::watts(None);

        let mut big = sample();
        big.cpu_power = Some(1000.0);
        let mut small = sample();
        small.cpu_power = Some(1.0);
        small.gpu_power = Some(0.0);

        assert_eq!(written(schema, true, &[big, small]), "1.00\n");
    }

    #[test]
    fn a_bundle_forwards_to_every_sink_it_holds() {
        /// Counts what it is given, so the fan-out can be observed.
        #[derive(Default)]
        struct Counter(std::rc::Rc<std::cell::Cell<usize>>);
        impl OutputSink for Counter {
            fn send(&mut self, _sample: &MonitorSample) -> crate::Result<()> {
                self.0.set(self.0.get() + 1);
                Ok(())
            }
        }

        let sends = std::rc::Rc::new(std::cell::Cell::new(0));
        let mut outputs = OutputBundle::new();
        // An empty bundle is not an error; it just discards.
        assert!(outputs.is_empty());
        outputs.send(&sample()).unwrap();

        outputs.push(Counter(sends.clone()));
        outputs.push(Counter(sends.clone()));
        outputs.send(&sample()).unwrap();
        assert_eq!(sends.get(), 2);
        assert!(!outputs.is_empty());
    }

    #[test]
    fn file_writer_csv_shortcut_and_bundle_with_builder() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shortcut.csv");
        let config = crate::config::MonitorConfig::default();

        let writer = FileWriter::csv(&path, &config).unwrap();
        let mut outputs = OutputBundle::new().with(writer);

        outputs.send(&sample()).unwrap();
        drop(outputs);

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(
            content.starts_with(
                "Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%)\n"
            )
        );
        assert!(content.contains("1700000000,18.34,12.35,6.00,42.50\n"));
    }
}