joularcore 0.1.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
/*
 * 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
 */

use crate::Component;
use crate::common::ApiSender;
use crate::monitor::MonitorSample;
use crate::ringbuffer::{RingBufferStruct, RingBufferWriter};
use std::fmt::Write as FmtWrite;
use std::fs::{File, OpenOptions};
use std::io::{Result, Seek, SeekFrom, Write, stdout};

pub enum OutputMode {
    Terminal,
    CsvFile(File),
    NumericFile(File),
}

pub enum OutputModeKind {
    Terminal,
    CsvFile,
    NumericFile,
}

pub struct OutputWriter {
    mode: OutputMode,
    overwrite: bool,
    /// Reused scratch buffer for per-sample formatting so we don't allocate a
    /// new String on every monitor tick.
    scratch: String,
}

pub trait OutputSink {
    fn send(&mut self, sample: &MonitorSample) -> Result<()>;
}

pub struct OutputBundle {
    writer: Option<OutputWriter>,
    component: Option<Component>,
    numeric_only: bool,
    ringbuffer: Option<RingBufferWriter>,
    #[cfg(feature = "api")]
    api_sender: ApiSender,
}

impl OutputBundle {
    pub fn new(
        component: Option<Component>,
        numeric_only: bool,
        ringbuffer: Option<RingBufferWriter>,
        api_sender: ApiSender,
    ) -> Self {
        #[cfg(not(feature = "api"))]
        let _ = api_sender;

        Self {
            writer: None,
            component,
            numeric_only,
            ringbuffer,
            #[cfg(feature = "api")]
            api_sender,
        }
    }

    pub fn set_writer(&mut self, writer: OutputWriter) {
        self.writer = Some(writer);
    }

    pub fn clear_writer(&mut self) {
        self.writer = None;
    }

    pub fn set_component(&mut self, component: Option<Component>) {
        self.component = component;
    }

    /// Whether a ring buffer writer is currently attached.
    pub fn has_ringbuffer(&self) -> bool {
        self.ringbuffer.is_some()
    }

    /// Attach (or detach with `None`) a ring buffer writer. Used by the GUI to
    /// enable the ring buffer lazily when the user toggles it on the options
    /// screen.
    pub fn set_ringbuffer(&mut self, ringbuffer: Option<RingBufferWriter>) {
        self.ringbuffer = ringbuffer;
    }

    /// Whether an API broadcast sender is currently attached.
    #[cfg(feature = "api")]
    pub fn has_api_sender(&self) -> bool {
        self.api_sender.is_some()
    }

    /// Attach an API broadcast sender. Used by the GUI when the user enables
    /// the HTTP / WebSocket API on the options screen.
    #[cfg(feature = "api")]
    pub fn set_api_sender(&mut self, api_sender: ApiSender) {
        self.api_sender = api_sender;
    }
}

impl OutputSink for OutputBundle {
    fn send(&mut self, sample: &MonitorSample) -> Result<()> {
        if let Some(writer) = &mut self.writer {
            match writer.mode_kind() {
                OutputModeKind::Terminal => writer.write_terminal_sample(
                    sample,
                    self.component.as_ref(),
                    self.numeric_only,
                )?,
                OutputModeKind::CsvFile => {
                    writer.write_csv_sample(sample, self.component.as_ref())?
                }
                OutputModeKind::NumericFile => {
                    writer.write_numeric_sample(sample, self.component.as_ref())?
                }
            }
        }

        if let Some(ref rb) = self.ringbuffer {
            let rb_data = RingBufferStruct::from(sample);
            rb.write(rb_data);
        }

        #[cfg(feature = "api")]
        if let Some(ref tx) = self.api_sender {
            let api_data = crate::api::ApiData::from(sample);
            let _ = tx.send(api_data);
        }

        Ok(())
    }
}

impl OutputWriter {
    pub fn mode_kind(&self) -> OutputModeKind {
        match self.mode {
            OutputMode::Terminal => OutputModeKind::Terminal,
            OutputMode::CsvFile(_) => OutputModeKind::CsvFile,
            OutputMode::NumericFile(_) => OutputModeKind::NumericFile,
        }
    }

    pub fn new(file_path: Option<&str>, numeric_only: bool, overwrite: bool) -> Result<Self> {
        let mode = match file_path {
            Some(path) => {
                let file = if overwrite {
                    OpenOptions::new()
                        .write(true)
                        .create(true)
                        .truncate(true)
                        .open(path)?
                } else {
                    OpenOptions::new().create(true).append(true).open(path)?
                };

                if numeric_only {
                    OutputMode::NumericFile(file)
                } else {
                    OutputMode::CsvFile(file)
                }
            }
            None => OutputMode::Terminal,
        };

        Ok(Self {
            mode,
            overwrite,
            scratch: String::with_capacity(256),
        })
    }

    pub fn write_csv_header(
        &mut self,
        component: Option<&Component>,
        has_process: bool,
        has_app: bool,
    ) -> Result<()> {
        if let OutputMode::CsvFile(ref mut file) = self.mode {
            let header = match component {
                Some(Component::Cpu) => "Timestamp,CPU Power (W)\n",
                Some(Component::Gpu) => "Timestamp,GPU Power (W)\n",
                None if has_process => {
                    "Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%),Process Power (W)\n"
                }
                None if has_app => {
                    "Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%),App Power (W),App PIDs\n"
                }
                None => "Timestamp,Total Power (W),CPU Power (W),GPU Power (W),CPU Usage (%)\n",
            };

            file.write_all(header.as_bytes())?;
        }
        Ok(())
    }

    pub fn write_terminal_sample(
        &mut self,
        sample: &MonitorSample,
        component_filter: Option<&Component>,
        numeric_only: bool,
    ) -> Result<()> {
        self.write_terminal_line(
            sample.cpu_power,
            sample.gpu_power,
            sample.total_power,
            sample.cpu_usage,
            sample.process_power,
            sample.app_power,
            component_filter,
            numeric_only,
        )
    }

    pub fn write_csv_sample(
        &mut self,
        sample: &MonitorSample,
        component: Option<&Component>,
    ) -> Result<()> {
        self.write_csv_line(
            sample.timestamp,
            sample.cpu_power,
            sample.gpu_power,
            sample.total_power,
            sample.cpu_usage,
            sample.process_power,
            sample.app_power,
            component,
        )
    }

    pub fn write_numeric_sample(
        &mut self,
        sample: &MonitorSample,
        component: Option<&Component>,
    ) -> Result<()> {
        self.write_numeric_line(
            sample.cpu_power,
            sample.gpu_power,
            sample.total_power,
            component,
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub fn write_terminal_line(
        &mut self,
        cpu_power: f64,
        gpu_power: f64,
        total_power: f64,
        cpu_usage: f64,
        process_power: Option<f64>,
        app_power: Option<(f64, usize)>,
        component_filter: Option<&Component>,
        numeric_only: bool,
    ) -> Result<()> {
        let mut out = stdout();

        if numeric_only {
            let v = match component_filter {
                Some(Component::Cpu) => cpu_power,
                Some(Component::Gpu) => gpu_power,
                None => total_power,
            };
            writeln!(out, "{:.2}", v)?;
            out.flush()?;
            return Ok(());
        }

        let buf = &mut self.scratch;
        buf.clear();
        match component_filter {
            Some(Component::Cpu) => {
                let _ = write!(buf, "\r\x1b[2K\x1b[1;36mCPU {cpu_power:.2} W\x1b[0m");
            }
            Some(Component::Gpu) => {
                let _ = write!(buf, "\r\x1b[2K\x1b[1;35mGPU {gpu_power:.2} W\x1b[0m");
            }
            None => {
                if let Some(p) = process_power {
                    let _ = write!(
                        buf,
                        "\r\x1b[2K\x1b[1;33m⚡ Total {total_power:.2} W\x1b[0m | \
                         \x1b[1;36mCPU {cpu_power:.2} W\x1b[0m | \
                         \x1b[1;35mGPU {gpu_power:.2} W\x1b[0m | \
                         \x1b[1;36mCPU Usage {cpu_usage:.2}%\x1b[0m | \
                         \x1b[1;32mPID {p:.2} W\x1b[0m"
                    );
                } else if let Some((p, count)) = app_power {
                    let _ = write!(
                        buf,
                        "\r\x1b[2K\x1b[1;33m⚡ Total {total_power:.2} W\x1b[0m | \
                         \x1b[1;36mCPU {cpu_power:.2} W\x1b[0m | \
                         \x1b[1;35mGPU {gpu_power:.2} W\x1b[0m | \
                         \x1b[1;36mCPU Usage {cpu_usage:.2}%\x1b[0m | \
                         \x1b[1;32mApp {p:.2} W ({count} PIDs)\x1b[0m"
                    );
                } else {
                    let _ = write!(
                        buf,
                        "\r\x1b[2K\x1b[1;33m⚡ Total {total_power:.2} W\x1b[0m | \
                         \x1b[1;36mCPU {cpu_power:.2} W\x1b[0m | \
                         \x1b[1;35mGPU {gpu_power:.2} W\x1b[0m | \
                         \x1b[1;36mCPU Usage {cpu_usage:.2}%\x1b[0m"
                    );
                }
            }
        }

        out.write_all(buf.as_bytes())?;
        out.flush()?;
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn write_csv_line(
        &mut self,
        timestamp: u64,
        cpu: f64,
        gpu: f64,
        total: f64,
        cpu_usage: f64,
        process_power: Option<f64>,
        app_power: Option<(f64, usize)>,
        component: Option<&Component>,
    ) -> Result<()> {
        if let OutputMode::CsvFile(ref mut file) = self.mode {
            // Overwrite mode truncates on each write so the file always holds
            // only the most recent sample; this trades rotation cost for a
            // tiny file suitable for polling consumers.
            if self.overwrite {
                file.set_len(0)?;
                file.seek(SeekFrom::Start(0))?;
            }

            let buf = &mut self.scratch;
            buf.clear();
            match component {
                Some(Component::Cpu) => {
                    let _ = writeln!(buf, "{timestamp},{cpu:.2}");
                }
                Some(Component::Gpu) => {
                    let _ = writeln!(buf, "{timestamp},{gpu:.2}");
                }
                None => match (process_power, app_power) {
                    (Some(p), _) => {
                        let _ = writeln!(
                            buf,
                            "{timestamp},{total:.2},{cpu:.2},{gpu:.2},{cpu_usage:.2},{p:.2}"
                        );
                    }
                    (_, Some((p, c))) => {
                        let _ = writeln!(
                            buf,
                            "{timestamp},{total:.2},{cpu:.2},{gpu:.2},{cpu_usage:.2},{p:.2},{c}"
                        );
                    }
                    _ => {
                        let _ = writeln!(
                            buf,
                            "{timestamp},{total:.2},{cpu:.2},{gpu:.2},{cpu_usage:.2}"
                        );
                    }
                },
            }

            file.write_all(buf.as_bytes())?;
        }
        Ok(())
    }

    pub fn write_numeric_line(
        &mut self,
        cpu: f64,
        gpu: f64,
        total: f64,
        component: Option<&Component>,
    ) -> Result<()> {
        if let OutputMode::NumericFile(ref mut file) = self.mode {
            if self.overwrite {
                file.set_len(0)?;
                file.seek(SeekFrom::Start(0))?;
            }

            let v = match component {
                Some(Component::Cpu) => cpu,
                Some(Component::Gpu) => gpu,
                None => total,
            };
            writeln!(file, "{:.2}", v)?;
        }
        Ok(())
    }
}