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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
 * 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 std::fs;
use std::sync::Mutex;

/// Trait for CPU utilization
pub trait CPUUtilization {
    /// Get overall CPU utilization
    /// Returns utilization as a fraction (0.0 to 1.0)
    fn get_cpu_utilization(&self) -> f64;
}

/// Trait for process (PID) CPU utilization
pub trait ProcessCPUUtilization {
    /// Get CPU utilization for a specific process (PID)
    /// Returns utilization as a fraction (0.0 to 1.0)
    fn get_process_cpu_utilization(&mut self, pid: u32) -> f64;

    /// Get CPU utilization with a precomputed CPU total, if available.
    fn get_process_cpu_utilization_with_total(&mut self, pid: u32, cpu_total: Option<u64>) -> f64 {
        let _ = cpu_total;
        self.get_process_cpu_utilization(pid)
    }
}

#[allow(dead_code)]
pub struct CpuState {
    pub total: u64,
    pub idle: u64,
}

#[allow(dead_code)]
impl CpuState {
    pub fn new(total: u64, idle: u64) -> Self {
        Self { total, idle }
    }

    pub fn cpu_usage(&self, prev: &CpuState) -> f64 {
        let diff_total = self.total.saturating_sub(prev.total);
        let diff_idle = self.idle.saturating_sub(prev.idle);

        if diff_total == 0 {
            0.0
        } else {
            (diff_total - diff_idle) as f64 / diff_total as f64
        }
    }
}

#[allow(dead_code)]
/// Generic CPU Usage tracker for Linux-based systems using /proc/stat
pub struct ProcStatCpuUsage {
    stats: Mutex<CpuState>,
}

impl Default for ProcStatCpuUsage {
    fn default() -> Self {
        Self::new()
    }
}

#[allow(dead_code)]
impl ProcStatCpuUsage {
    pub fn new() -> Self {
        let (total, idle) = read_proc_stat().unwrap_or((0, 0));
        Self {
            stats: Mutex::new(CpuState::new(total, idle)),
        }
    }
}

#[allow(dead_code)]
impl CPUUtilization for ProcStatCpuUsage {
    fn get_cpu_utilization(&self) -> f64 {
        let (curr_total, curr_idle) = read_proc_stat().unwrap_or((0, 0));

        let current_state = CpuState::new(curr_total, curr_idle);
        let mut last = self.stats.lock().unwrap_or_else(|e| e.into_inner());
        let usage = current_state.cpu_usage(&last);
        *last = current_state;

        usage
    }
}

#[allow(dead_code)]
pub(crate) fn read_proc_stat() -> Option<(u64, u64)> {
    let content = fs::read_to_string("/proc/stat").ok()?;
    let line = content.lines().next()?;

    if !line.starts_with("cpu ") {
        return None;
    }

    let parts: Vec<u64> = line
        .split_whitespace()
        .skip(1)
        .filter_map(|s| s.parse().ok())
        .collect();

    if parts.len() < 8 {
        return None;
    }

    // user, nice, system, idle, iowait, irq, softirq, steal
    let user = parts[0];
    let nice = parts[1];
    let system = parts[2];
    let idle = parts[3];
    let iowait = parts[4];
    let irq = parts[5];
    let softirq = parts[6];
    let steal = parts[7];

    // Total = everything
    let total_ticks = user + nice + system + idle + iowait + irq + softirq + steal;

    // Idle = idle + iowait (CPU is waiting, not actively computing)
    let idle_ticks = idle + iowait;

    Some((total_ticks, idle_ticks))
}

/// Linux/proc-based process CPU utilization tracker
/// Used by Linux and SBC platforms
#[allow(dead_code)]
pub struct ProcStatProcessUtil {
    before_cpu_total: u64,
    before_pid_time: u64,
}

impl Default for ProcStatProcessUtil {
    fn default() -> Self {
        Self::new()
    }
}

#[allow(dead_code)]
impl ProcStatProcessUtil {
    pub fn new() -> Self {
        Self {
            before_cpu_total: 0,
            before_pid_time: 0,
        }
    }

    /// Read CPU time for a process from /proc/pid/stat
    /// Returns (utime + stime) in clock ticks
    fn read_pid_time(pid: u32) -> Option<u64> {
        let stat_path = format!("/proc/{}/stat", pid);
        let content = fs::read_to_string(&stat_path).ok()?;

        // Find the last ')' to skip the comm field which may contain spaces
        let last_paren = content.rfind(')')?;
        let fields: Vec<&str> = content[last_paren + 1..].split_whitespace().collect();

        if fields.len() < 13 {
            return None;
        }

        // After closing parentheses: state, ppid, ... utime(index 11), stime(index 12)
        let utime: u64 = fields[11].parse().ok()?;
        let stime: u64 = fields[12].parse().ok()?;

        Some(utime + stime)
    }
}

#[allow(dead_code)]
impl ProcessCPUUtilization for ProcStatProcessUtil {
    fn get_process_cpu_utilization(&mut self, pid: u32) -> f64 {
        // Get current CPU total and PID time
        let (cpu_total, _) = match read_proc_stat() {
            Some(vals) => vals,
            None => return 0.0,
        };

        let pid_time = match Self::read_pid_time(pid) {
            Some(time) => time,
            None => return 0.0,
        };

        // First call, just store values
        if self.before_cpu_total == 0 {
            self.before_cpu_total = cpu_total;
            self.before_pid_time = pid_time;
            return 0.0;
        }

        // Calculate differences
        let cpu_delta = cpu_total.saturating_sub(self.before_cpu_total);
        let pid_delta = pid_time.saturating_sub(self.before_pid_time);

        // Update for next call
        self.before_cpu_total = cpu_total;
        self.before_pid_time = pid_time;

        // Calculate utilization
        if cpu_delta == 0 {
            0.0
        } else {
            pid_delta as f64 / cpu_delta as f64
        }
    }

    fn get_process_cpu_utilization_with_total(&mut self, pid: u32, cpu_total: Option<u64>) -> f64 {
        let cpu_total = match cpu_total {
            Some(total) => total,
            None => match read_proc_stat() {
                Some((total, _)) => total,
                None => return 0.0,
            },
        };

        let pid_time = match Self::read_pid_time(pid) {
            Some(time) => time,
            None => return 0.0,
        };

        if self.before_cpu_total == 0 {
            self.before_cpu_total = cpu_total;
            self.before_pid_time = pid_time;
            return 0.0;
        }

        let cpu_delta = cpu_total.saturating_sub(self.before_cpu_total);
        let pid_delta = pid_time.saturating_sub(self.before_pid_time);

        self.before_cpu_total = cpu_total;
        self.before_pid_time = pid_time;

        if cpu_delta == 0 {
            0.0
        } else {
            pid_delta as f64 / cpu_delta as f64
        }
    }
}

use std::collections::{HashMap, HashSet};
use sysinfo::{ProcessesToUpdate, System};

/// Trait for application (multi-PID) CPU utilization
pub trait AppCPUUtilization {
    /// Get CPU utilization for all processes of an application
    /// Returns utilization as a fraction (0.0 to 1.0)
    fn get_app_cpu_utilization(&mut self, app_name: &str) -> f64;

    /// Get the list of PIDs currently running for the application
    fn get_app_pids(&mut self, app_name: &str) -> Vec<u32>;

    /// Get both utilization and current PIDs in a single call.
    fn get_app_snapshot(&mut self, app_name: &str) -> (f64, Vec<u32>) {
        let util = self.get_app_cpu_utilization(app_name);
        let pids = self.get_app_pids(app_name);
        (util, pids)
    }

    /// Get both utilization and current PIDs using a precomputed CPU total, if available.
    fn get_app_snapshot_with_total(
        &mut self,
        app_name: &str,
        cpu_total: Option<u64>,
    ) -> (f64, Vec<u32>) {
        let _ = cpu_total;
        self.get_app_snapshot(app_name)
    }

    /// Set the refresh interval for application PID sweeping
    fn set_refresh_interval(&mut self, _interval: std::time::Duration) {}
}

/// Application monitoring data structure
pub struct AppMonitor<T: ProcessCPUUtilization> {
    /// Map of PID to its process utilization tracker
    process_trackers: HashMap<u32, T>,
    /// Factory function to create new process trackers
    tracker_factory: fn() -> T,
    /// Process enumeration state
    system: System,
    /// Timestamp of last PID sweep
    last_pid_sweep: Option<std::time::Instant>,
    /// Cached PIDs
    cached_pids: Vec<u32>,
    /// How often to sweep for PIDs
    sweep_interval: std::time::Duration,
}

#[allow(dead_code)]
impl<T: ProcessCPUUtilization> AppMonitor<T> {
    /// Create a new application monitor
    /// * tracker_factory - Function that creates new process utilization trackers
    pub fn new(tracker_factory: fn() -> T, sweep_interval: std::time::Duration) -> Self {
        Self {
            process_trackers: HashMap::new(),
            tracker_factory,
            system: System::new(),
            last_pid_sweep: None,
            cached_pids: Vec::new(),
            sweep_interval,
        }
    }

    /// Get list of PIDs for an application using sysinfo
    /// Vector of PIDs, or empty vector if application not found
    fn get_pids_from_sysinfo(&mut self, app_name: &str) -> Vec<u32> {
        if self.sweep_interval.as_secs() > 0
            && let Some(last) = self.last_pid_sweep
            && last.elapsed() < self.sweep_interval
        {
            return self.cached_pids.clone();
        }

        self.system.refresh_processes(ProcessesToUpdate::All, true);
        let mut pids = Vec::new();

        for (pid, process) in self.system.processes() {
            if process.thread_kind().is_some() {
                continue;
            }

            let name = process.name().to_string_lossy();
            if name == app_name || name.contains(app_name) {
                pids.push(pid.as_u32());
            }
        }

        if self.sweep_interval.as_secs() > 0 {
            self.cached_pids = pids.clone();
            self.last_pid_sweep = Some(std::time::Instant::now());
        }

        pids
    }

    /// Update process trackers based on current PIDs
    /// Removes trackers for dead processes and adds trackers for new processes
    fn update_trackers(&mut self, current_pids: &[u32]) {
        let pid_set: HashSet<u32> = current_pids.iter().copied().collect();
        // Remove trackers for PIDs that no longer exist
        self.process_trackers.retain(|pid, _| pid_set.contains(pid));

        // Add trackers for new PIDs
        for &pid in current_pids {
            if !self.process_trackers.contains_key(&pid) {
                self.process_trackers.insert(pid, (self.tracker_factory)());
            }
        }
    }

    /// Calculate total CPU utilization for all processes of an application
    /// Sum of CPU utilization for all processes (0.0 to N.0 where N is number of cores)
    fn calculate_total_utilization(
        &mut self,
        app_name: &str,
        cpu_total: Option<u64>,
    ) -> (f64, Vec<u32>) {
        let current_pids = self.get_pids_from_sysinfo(app_name);

        if current_pids.is_empty() {
            // Clear all trackers if no PIDs found
            self.process_trackers.clear();
            return (0.0, current_pids);
        }

        // Update trackers to match current PIDs
        self.update_trackers(&current_pids);

        let cpu_total = match cpu_total.or_else(|| read_proc_stat().map(|(total, _)| total)) {
            Some(total) => Some(total),
            None => {
                tracing::debug!(
                    "Failed to read /proc/stat; application CPU utilization will be 0 for this sample"
                );
                None
            }
        };

        // Sum utilization across all PIDs
        let mut total_utilization = 0.0;
        for &pid in &current_pids {
            if let Some(tracker) = self.process_trackers.get_mut(&pid) {
                total_utilization += tracker.get_process_cpu_utilization_with_total(pid, cpu_total);
            }
        }

        (total_utilization, current_pids)
    }
}

impl<T: ProcessCPUUtilization> AppCPUUtilization for AppMonitor<T> {
    fn set_refresh_interval(&mut self, interval: std::time::Duration) {
        self.sweep_interval = interval;
    }

    fn get_app_cpu_utilization(&mut self, app_name: &str) -> f64 {
        self.calculate_total_utilization(app_name, None).0
    }

    fn get_app_pids(&mut self, app_name: &str) -> Vec<u32> {
        self.get_pids_from_sysinfo(app_name)
    }

    fn get_app_snapshot(&mut self, app_name: &str) -> (f64, Vec<u32>) {
        self.calculate_total_utilization(app_name, None)
    }

    fn get_app_snapshot_with_total(
        &mut self,
        app_name: &str,
        cpu_total: Option<u64>,
    ) -> (f64, Vec<u32>) {
        self.calculate_total_utilization(app_name, cpu_total)
    }
}