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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/*
 * 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
 */

//! macOS backend, reading power from `powermetrics`.
//!
//! `powermetrics` must run as root, so the sampler is a long-lived child
//! process started once and parsed as its output arrives — one elevation
//! prompt, however long the session runs. [`powermetrics`] owns that process
//! and `macos_parse` reads its output; CPU time comes from the mach APIs in
//! `cpu`.
//!
//! See [`crate::config::ElevationPolicy`] for how far the backend may go to
//! obtain the privileges it needs.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::config::{AppMatch, ElevationPolicy};
use crate::platform::cpu_usage::AppMonitor;
use crate::platform::macos_parse::PowerReading;
use crate::sensor::{
    AppCpuUtilization, CpuUtilization, Platform, PowerSensor, ProcessCpuUtilization,
};
use crate::{Error, Result};
use powermetrics::PowerMetrics;

/// The sampler, shared by the CPU and GPU sensors that read from it.
///
/// `None` means it could not be started; every read then reports the sensor as
/// unavailable, with the reason already logged.
type SharedSampler = Arc<Mutex<Option<PowerMetrics>>>;

/// The macOS backend.
pub(crate) struct MacOsPlatform {
    sampler: SharedSampler,
    elevation: ElevationPolicy,
}

impl MacOsPlatform {
    /// Create the backend. `powermetrics` is not started until the first sensor
    /// is requested.
    pub(crate) fn new(elevation: ElevationPolicy) -> Self {
        Self {
            sampler: Arc::new(Mutex::new(None)),
            elevation,
        }
    }

    /// Start `powermetrics` if it is not running yet.
    fn ensure_sampler(&self) -> SharedSampler {
        let mut sampler = self.sampler.lock().unwrap_or_else(|e| e.into_inner());
        if sampler.is_none() {
            match PowerMetrics::start(self.elevation) {
                Ok(started) => *sampler = Some(started),
                Err(e) => log::warn!(
                    "powermetrics is unavailable, so CPU and GPU power will be \
                     reported as unavailable: {e}"
                ),
            }
        }
        drop(sampler);

        self.sampler.clone()
    }
}

impl Platform for MacOsPlatform {
    fn cpu(&self) -> Box<dyn PowerSensor> {
        Box::new(MacOsCpu {
            sampler: self.ensure_sampler(),
        })
    }

    fn gpu(&self) -> Box<dyn PowerSensor> {
        Box::new(MacOsGpu {
            sampler: self.ensure_sampler(),
        })
    }

    fn cpu_usage(&self) -> Box<dyn CpuUtilization> {
        Box::new(cpu::cpu_usage())
    }

    fn process_cpu_usage(&self) -> Option<Box<dyn ProcessCpuUtilization>> {
        Some(cpu::process_tracker())
    }

    fn app_cpu_usage(
        &self,
        refresh_interval: Duration,
        app_match: AppMatch,
    ) -> Option<Box<dyn AppCpuUtilization>> {
        Some(AppMonitor::boxed(
            cpu::process_tracker,
            refresh_interval,
            app_match,
        ))
    }
}

/// CPU package power from `powermetrics`.
struct MacOsCpu {
    sampler: SharedSampler,
}

impl PowerSensor for MacOsCpu {
    fn power(&mut self) -> Result<f64> {
        Ok(current_reading(&self.sampler)?.cpu_power)
    }
}

/// GPU power from `powermetrics`.
struct MacOsGpu {
    sampler: SharedSampler,
}

impl PowerSensor for MacOsGpu {
    fn power(&mut self) -> Result<f64> {
        separate_gpu_power(current_reading(&self.sampler)?)
    }
}

/// Return a separate GPU reading, or report that this sampler does not expose
/// one. Intel Macs do not provide it, and a missing reading is not the same as
/// an idle GPU.
fn separate_gpu_power(reading: PowerReading) -> Result<f64> {
    reading.gpu_power.ok_or_else(|| {
        Error::sensor(
            powermetrics::SENSOR,
            "the latest sample has no separate GPU power reading",
        )
    })
}

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

    #[test]
    fn missing_gpu_power_is_unavailable_not_zero() {
        let error = separate_gpu_power(PowerReading {
            cpu_power: 10.0,
            gpu_power: None,
        })
        .unwrap_err();
        assert!(matches!(error, Error::SensorUnavailable { .. }));
    }

    #[test]
    fn separate_gpu_power_is_preserved() {
        assert_eq!(
            separate_gpu_power(PowerReading {
                cpu_power: 10.0,
                gpu_power: Some(2.5),
            })
            .unwrap(),
            2.5
        );
    }
}

/// The most recent `powermetrics` reading, if the sampler is alive and the
/// reading is fresh.
fn current_reading(sampler: &Mutex<Option<PowerMetrics>>) -> Result<PowerReading> {
    let mut guard = sampler.lock().unwrap_or_else(|e| e.into_inner());
    let sampler = guard
        .as_mut()
        .ok_or_else(|| Error::sensor(powermetrics::SENSOR, "sampler is not running"))?;

    sampler.latest_reading()
}

/// The `powermetrics` child process, and the privileges it needs.
mod powermetrics {
    use std::io::{BufRead, BufReader};
    use std::process::{Child, Command, Stdio};
    use std::sync::{Arc, Mutex};
    use std::thread;
    use std::time::{Duration, Instant};

    use crate::config::ElevationPolicy;
    use crate::platform::macos_parse::{PowerReading, parse_block};
    use crate::{Error, Result};

    /// How this sensor is named in errors.
    pub(crate) const SENSOR: &str = "powermetrics";

    /// Absolute paths, so a poisoned `PATH` cannot substitute the program we are
    /// about to run as root.
    const SUDO: &str = "/usr/bin/sudo";
    const ENV: &str = "/usr/bin/env";
    const POWERMETRICS: &str = "/usr/bin/powermetrics";
    const SYSCTL: &str = "/usr/sbin/sysctl";

    /// How often `powermetrics` reports, in milliseconds.
    const SAMPLE_INTERVAL_MS: u64 = 1000;

    /// A reading older than this is treated as unavailable. `powermetrics` can be
    /// killed or wedged, and reporting its last figure forever would silently turn
    /// stale data into live data.
    const MAX_READING_AGE: Duration = Duration::from_millis(SAMPLE_INTERVAL_MS * 5);

    /// A running `powermetrics` child process and the last block it emitted.
    #[derive(Debug)]
    pub(crate) struct PowerMetrics {
        last_reading: Arc<Mutex<Option<(PowerReading, Instant)>>>,
        child: Child,
    }

    impl PowerMetrics {
        /// Spawn `powermetrics` and start parsing its output.
        pub(crate) fn start(elevation: ElevationPolicy) -> Result<Self> {
            let is_apple_silicon = is_apple_silicon();
            let is_root = is_root();

            if !is_root && elevation == ElevationPolicy::Never {
                return Err(Error::permission(
                    SENSOR,
                    "run as root, or cache a sudo credential and use \
                     ElevationPolicy::SudoNonInteractive",
                ));
            }

            let mut child = build_powermetrics_command(is_root)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()
                .map_err(|e| Error::sensor(SENSOR, format!("failed to spawn: {e}")))?;

            let stdout = child
                .stdout
                .take()
                .ok_or_else(|| Error::sensor(SENSOR, "no stdout pipe"))?;
            let stderr = child
                .stderr
                .take()
                .ok_or_else(|| Error::sensor(SENSOR, "no stderr pipe"))?;

            let last_reading = Arc::new(Mutex::new(None));
            let readings = last_reading.clone();
            thread::spawn(move || {
                let mut block = String::new();
                for line in BufReader::new(stdout).lines() {
                    let Ok(line) = line else {
                        log::debug!("powermetrics stdout closed");
                        break;
                    };

                    // Each sample starts with a "*** Sampled system activity"
                    // banner, so a new banner means the previous block is complete.
                    if line.starts_with("*** Sample") && !block.is_empty() {
                        if let Some(reading) = parse_block(&block, is_apple_silicon) {
                            *readings.lock().unwrap_or_else(|e| e.into_inner()) =
                                Some((reading, Instant::now()));
                        }
                        block.clear();
                    }
                    block.push_str(&line);
                    block.push('\n');
                }
            });

            thread::spawn(move || {
                for line in BufReader::new(stderr)
                    .lines()
                    .map_while(std::result::Result::ok)
                {
                    log::warn!("powermetrics: {line}");
                }
            });

            Ok(Self {
                last_reading,
                child,
            })
        }

        /// The most recent reading, if the sampler is alive and the reading is
        /// fresh enough to describe the present.
        pub(crate) fn latest_reading(&mut self) -> Result<PowerReading> {
            // A sampler that exited would otherwise keep serving its final reading.
            if let Ok(Some(status)) = self.child.try_wait() {
                return Err(Error::sensor(
                    SENSOR,
                    format!("sampler exited with {status}"),
                ));
            }

            let last = self.last_reading.lock().unwrap_or_else(|e| e.into_inner());
            let Some((reading, taken_at)) = *last else {
                return Err(Error::sensor(SENSOR, "no sample yet"));
            };

            let age = taken_at.elapsed();
            if age > MAX_READING_AGE {
                return Err(Error::sensor(
                    SENSOR,
                    format!("last sample is {age:.1?} old"),
                ));
            }

            Ok(reading)
        }
    }

    impl Drop for PowerMetrics {
        fn drop(&mut self) {
            let _ = self.child.kill();
            let _ = self.child.wait();
        }
    }

    /// Build the command that runs `powermetrics` with the required privileges.
    ///
    /// `LC_ALL` and `LANG` are forced to `C` so the output uses `.` as the decimal
    /// separator; on a locale like `fr_FR` it would emit `,` and every parse would
    /// fail. They go through `env` because `sudo` resets the environment, so
    /// setting them on the `Command` alone would not reach `powermetrics`.
    ///
    /// An unprivileged process reaches here only under
    /// [`ElevationPolicy::SudoNonInteractive`], so `sudo -n` is always the right
    /// call: it uses a cached credential if there is one and fails immediately if
    /// there is not, rather than blocking on a prompt.
    fn build_powermetrics_command(is_root: bool) -> Command {
        let powermetrics_args = [
            "LC_ALL=C",
            "LANG=C",
            POWERMETRICS,
            "--samplers",
            "cpu_power,gpu_power",
            "-i",
            "1000",
        ];

        let mut command = if is_root {
            Command::new(ENV)
        } else {
            let mut sudo = Command::new(SUDO);
            sudo.arg("-n").arg(ENV);
            sudo
        };

        command.args(powermetrics_args);
        command
    }

    fn is_root() -> bool {
        // SAFETY: `getuid` reads process state and cannot fail.
        unsafe { libc::getuid() == 0 }
    }

    fn is_apple_silicon() -> bool {
        let Ok(output) = Command::new(SYSCTL)
            .args(["-n", "machdep.cpu.brand_string"])
            .output()
        else {
            return false;
        };
        String::from_utf8_lossy(&output.stdout).contains("Apple")
    }

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

        fn args(command: &Command) -> Vec<String> {
            command
                .get_args()
                .map(|arg| arg.to_string_lossy().into_owned())
                .collect()
        }

        #[test]
        fn every_program_is_addressed_by_absolute_path() {
            // The child runs as root, so PATH lookup would be a privilege
            // escalation vector.
            for program in [SUDO, ENV, POWERMETRICS, SYSCTL] {
                assert!(program.starts_with('/'), "{program} is not absolute");
            }

            let command = build_powermetrics_command(false);
            assert_eq!(command.get_program(), OsStr::new(SUDO));
            assert!(args(&command).iter().any(|arg| arg == ENV));
            assert!(args(&command).iter().any(|arg| arg == POWERMETRICS));
        }

        #[test]
        fn an_unprivileged_process_never_prompts() {
            // -n is what keeps sudo from blocking on a password prompt inside a
            // library call.
            let command = build_powermetrics_command(false);
            let args = args(&command);

            assert_eq!(command.get_program(), OsStr::new(SUDO));
            assert!(args.iter().any(|arg| arg == "-n"));
        }

        #[test]
        fn root_runs_powermetrics_without_sudo() {
            let command = build_powermetrics_command(true);
            let args = args(&command);

            assert_eq!(command.get_program(), OsStr::new(ENV));
            assert_eq!(args.first().map(String::as_str), Some("LC_ALL=C"));
        }

        #[test]
        fn locale_is_forced_so_decimal_points_parse() {
            let args = args(&build_powermetrics_command(false));
            assert!(args.iter().any(|arg| arg == "LC_ALL=C"));
            assert!(args.iter().any(|arg| arg == "LANG=C"));
        }

        #[test]
        fn an_unprivileged_process_refuses_to_elevate_under_the_default_policy() {
            // The library must not prompt behind its caller's back, so the default
            // policy fails instead of asking for a password.
            if is_root() {
                return;
            }

            let error = PowerMetrics::start(ElevationPolicy::Never).unwrap_err();
            assert!(matches!(error, Error::PermissionDenied { .. }), "{error}");
        }
    }
}

/// CPU time from the mach host and process APIs.
mod cpu {
    use libc::{HOST_CPU_LOAD_INFO, host_cpu_load_info_data_t, host_statistics64, integer_t};
    use mach2::mach_init::mach_host_self;
    use std::mem::{MaybeUninit, size_of};
    use std::time::Instant;

    use crate::platform::cpu_usage::TotalsSampler;
    use crate::sensor::{CpuTotals, ProcessCpuUtilization};

    /// Whole-system CPU utilization from `host_statistics64`.
    pub(crate) fn cpu_usage() -> TotalsSampler {
        TotalsSampler::new(host_cpu_totals)
    }

    /// A per-process tracker using `proc_pidinfo`.
    pub(crate) fn process_tracker() -> Box<dyn ProcessCpuUtilization> {
        Box::new(MacOsProcessTracker::new())
    }

    const CPU_STATE_USER: usize = 0;
    const CPU_STATE_SYSTEM: usize = 1;
    const CPU_STATE_IDLE: usize = 2;
    const CPU_STATE_NICE: usize = 3;

    /// Cumulative host CPU ticks, summed across all cores.
    fn host_cpu_totals() -> Option<CpuTotals> {
        let mut info = MaybeUninit::<host_cpu_load_info_data_t>::uninit();
        let mut count = (size_of::<host_cpu_load_info_data_t>() / size_of::<integer_t>()) as u32;

        // SAFETY: `info` is large enough for the flavour requested, and `count`
        // states its size in `integer_t` units as the call expects.
        let result = unsafe {
            host_statistics64(
                mach_host_self(),
                HOST_CPU_LOAD_INFO,
                info.as_mut_ptr().cast(),
                &mut count,
            )
        };
        if result != 0 {
            return None;
        }

        // SAFETY: the call succeeded, so it initialised the struct.
        let ticks = unsafe { info.assume_init() }.cpu_ticks;
        let user = ticks[CPU_STATE_USER] as u64;
        let system = ticks[CPU_STATE_SYSTEM] as u64;
        let idle = ticks[CPU_STATE_IDLE] as u64;
        let nice = ticks[CPU_STATE_NICE] as u64;

        Some(CpuTotals::new(user + system + idle + nice, idle))
    }

    const PROC_PIDTASKINFO: i32 = 4;

    #[repr(C)]
    #[derive(Default)]
    #[allow(non_camel_case_types)]
    struct proc_taskinfo {
        pti_virtual_size: u64,
        pti_resident_size: u64,
        pti_total_user: u64,
        pti_total_system: u64,
        pti_threads_user: u64,
        pti_threads_system: u64,
        pti_policy: i32,
        pti_faults: i32,
        pti_pageins: i32,
        pti_cow_faults: i32,
        pti_messages_sent: i32,
        pti_messages_received: i32,
        pti_syscalls_mach: i32,
        pti_syscalls_unix: i32,
        pti_csw: i32,
        pti_threadnum: i32,
        pti_numrunning: i32,
        pti_priority: i32,
    }

    #[repr(C)]
    #[derive(Default)]
    struct MachTimebaseInfo {
        numer: u32,
        denom: u32,
    }

    unsafe extern "C" {
        fn proc_pidinfo(
            pid: i32,
            flavor: i32,
            arg: u64,
            buffer: *mut libc::c_void,
            buffersize: i32,
        ) -> i32;

        fn mach_timebase_info(info: *mut MachTimebaseInfo) -> libc::c_int;
    }

    /// CPU utilization of a single process, from `proc_pidinfo`.
    ///
    /// Unlike Linux and Windows, macOS reports process time in mach ticks and host
    /// time in scheduler ticks, so the two cannot be differenced against each other.
    /// This measures against wall-clock time times the core count instead, which is
    /// why it ignores the `cpu_total` it is handed.
    struct MacOsProcessTracker {
        previous: Option<(u64, Instant)>,
        /// Converts mach ticks to nanoseconds.
        timebase_numer: u32,
        timebase_denom: u32,
        num_cores: u32,
    }

    impl MacOsProcessTracker {
        /// Create a tracker; the first sample establishes the baseline.
        fn new() -> Self {
            let mut timebase = MachTimebaseInfo::default();
            // SAFETY: `timebase` is a valid, correctly sized out-parameter.
            unsafe { mach_timebase_info(&mut timebase) };

            // A zero denominator would make the tick conversion divide by zero.
            let (numer, denom) = if timebase.denom > 0 {
                (timebase.numer, timebase.denom)
            } else {
                (1, 1)
            };

            Self {
                previous: None,
                timebase_numer: numer,
                timebase_denom: denom,
                num_cores: logical_cpu_count(),
            }
        }

        /// Total user + system time for `pid`, in mach ticks.
        fn process_time(pid: u32) -> Option<u64> {
            let mut info = proc_taskinfo::default();
            let size = size_of::<proc_taskinfo>() as i32;

            // SAFETY: `info` is a correctly sized buffer for PROC_PIDTASKINFO, and
            // `size` describes it.
            let written = unsafe {
                proc_pidinfo(
                    pid as i32,
                    PROC_PIDTASKINFO,
                    0,
                    std::ptr::from_mut(&mut info).cast(),
                    size,
                )
            };

            (written == size).then(|| info.pti_total_user + info.pti_total_system)
        }
    }

    impl ProcessCpuUtilization for MacOsProcessTracker {
        fn process_cpu_utilization(&mut self, pid: u32, _cpu_total: Option<u64>) -> f64 {
            let Some(process_time) = Self::process_time(pid) else {
                return 0.0;
            };
            let now = Instant::now();

            let Some((previous_time, previous_at)) = self.previous.replace((process_time, now))
            else {
                return 0.0;
            };

            let elapsed_ns = now.duration_since(previous_at).as_nanos();
            if elapsed_ns == 0 {
                return 0.0;
            }

            let used_ns = (process_time.saturating_sub(previous_time) as u128
                * self.timebase_numer as u128)
                / self.timebase_denom as u128;

            // As a fraction of total capacity, which is elapsed time times cores.
            used_ns as f64 / (elapsed_ns as f64 * self.num_cores as f64)
        }
    }

    fn logical_cpu_count() -> u32 {
        let mut cores: i32 = 0;
        let mut size = size_of::<i32>();
        let name = c"hw.logicalcpu";

        // SAFETY: `name` is a NUL-terminated C string, and `cores`/`size` are a
        // correctly sized out-parameter pair.
        let result = unsafe {
            libc::sysctlbyname(
                name.as_ptr(),
                std::ptr::from_mut(&mut cores).cast(),
                &mut size,
                std::ptr::null_mut(),
                0,
            )
        };

        if result == 0 && cores > 0 {
            cores as u32
        } else {
            1
        }
    }

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

        #[test]
        fn the_running_host_reports_cpu_time() {
            // The mach call is always available, so a failure here means the
            // out-parameters are being passed wrongly.
            let totals = host_cpu_totals().expect("host_statistics64");
            assert!(totals.total > 0);
            assert!(totals.idle <= totals.total);
        }

        #[test]
        fn this_machine_reports_at_least_one_core() {
            // The count divides the process share, so a zero would poison it.
            assert!(logical_cpu_count() >= 1);
        }

        #[test]
        fn a_process_that_does_not_exist_reports_nothing() {
            // PID 0 never exists, so this exercises the unreadable-process path.
            assert_eq!(MacOsProcessTracker::process_time(0), None);

            let mut tracker = MacOsProcessTracker::new();
            assert_eq!(tracker.process_cpu_utilization(0, None), 0.0);
        }

        #[test]
        fn the_first_sample_of_a_live_process_establishes_a_baseline() {
            let mut tracker = MacOsProcessTracker::new();
            let me = std::process::id();
            assert_eq!(tracker.process_cpu_utilization(me, None), 0.0);
        }
    }
}