#[cfg(test)]
use crate::agent::watchdog::IDLE_AFTER_SECS;
use crate::agent::watchdog::{idle_after_secs, MacSignals, Signals};
use crate::policy::owner::Snapshot;
use std::path::{Path, PathBuf};
pub fn enabled() -> bool {
std::env::var("ZAKURO_OWNER_SIGNAL").as_deref() != Ok("0")
}
const PSI_FULL_AVG10: f64 = 10.0;
const PSI_SOME_AVG10: f64 = 40.0;
const PSI_CPU_SOME_AVG10: f64 = 90.0;
pub const OWNER_TICK_SECS: u64 = 1;
pub fn psi_cpu_pressure(text: &str) -> bool {
text.lines()
.find(|l| l.starts_with("some"))
.and_then(|l| {
l.split_whitespace()
.find_map(|w| w.strip_prefix("avg10="))?
.parse::<f64>()
.ok()
})
.is_some_and(|v| v >= PSI_CPU_SOME_AVG10)
}
pub fn snapshot(s: &dyn Signals, on_ac_only: bool, now_secs: u64, source: &str) -> Snapshot {
Snapshot {
idle: s.idle(),
on_battery: on_ac_only && !s.on_ac(),
memory_pressure: s.memory_pressure(),
cpu_pressure: s.cpu_pressure(),
at: now_secs,
source: source.to_string(),
}
}
pub fn real_signals() -> (Box<dyn Signals + Send>, &'static str) {
if cfg!(target_os = "linux") {
(Box::new(LinuxSignals::new(RealSys)), "linux")
} else {
(Box::new(MacSignals { runner_pid: None }), "macos")
}
}
pub fn publish(home: &Path, s: &dyn Signals, on_ac_only: bool, source: &str) {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let _ = crate::policy::owner::write(home, &snapshot(s, on_ac_only, now, source));
}
pub async fn run(home: PathBuf, mut stop: tokio::sync::watch::Receiver<bool>) {
loop {
let h = home.clone();
let _ = tokio::task::spawn_blocking(move || {
let on_ac_only = crate::policy::peek(&h).is_none_or(|p| p.budget.on_ac_only);
let (signals, source) = real_signals();
publish(&h, signals.as_ref(), on_ac_only, source);
})
.await;
tokio::select! {
biased;
_ = stop.wait_for(|stopped| *stopped) => break,
_ = tokio::time::sleep(std::time::Duration::from_secs(OWNER_TICK_SECS)) => {}
}
}
}
pub trait Sys {
fn loginctl(&self, args: &[&str]) -> Option<String>;
fn read(&self, path: &str) -> Option<String>;
fn list_dir(&self, path: &str) -> Vec<String>;
fn now_us(&self) -> u64;
}
pub struct RealSys;
impl Sys for RealSys {
fn loginctl(&self, args: &[&str]) -> Option<String> {
let out = std::process::Command::new("loginctl")
.args(args)
.output()
.ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
fn read(&self, path: &str) -> Option<String> {
std::fs::read_to_string(path).ok()
}
fn list_dir(&self, path: &str) -> Vec<String> {
std::fs::read_dir(path)
.map(|d| {
d.filter_map(|e| e.ok())
.map(|e| e.path().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default()
}
fn now_us(&self) -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_micros() as u64)
.unwrap_or(0)
}
}
pub struct LinuxSignals<S: Sys> {
sys: S,
}
impl<S: Sys> LinuxSignals<S> {
pub fn new(sys: S) -> Self {
Self { sys }
}
}
fn props(text: &str) -> std::collections::HashMap<&str, &str> {
text.lines().filter_map(|l| l.split_once('=')).collect()
}
pub fn session_in_use(show: &str, now_us: u64, idle_after_secs: u64) -> Option<bool> {
let p = props(show);
if p.get("Remote") == Some(&"yes") {
return None;
}
if p.get("Class").is_some_and(|c| *c != "user") {
return None;
}
match p.get("IdleHint").copied() {
Some("no") => Some(true),
Some("yes") => {
let since: u64 = p
.get("IdleSinceHint")
.and_then(|v| v.parse().ok())
.unwrap_or(0);
Some(since > 0 && now_us.saturating_sub(since) < idle_after_secs * 1_000_000)
}
_ => None,
}
}
pub fn session_ids(list: &str) -> Vec<String> {
list.lines()
.filter_map(|l| l.split_whitespace().next())
.map(str::to_string)
.collect()
}
pub fn psi_pressure(text: &str) -> bool {
let avg10 = |kind: &str| -> Option<f64> {
let line = text.lines().find(|l| l.starts_with(kind))?;
line.split_whitespace()
.find_map(|w| w.strip_prefix("avg10="))?
.parse()
.ok()
};
avg10("full").is_some_and(|v| v >= PSI_FULL_AVG10)
|| avg10("some").is_some_and(|v| v >= PSI_SOME_AVG10)
}
impl<S: Sys> Signals for LinuxSignals<S> {
fn on_ac(&self) -> bool {
let mut any = false;
for dir in self.sys.list_dir("/sys/class/power_supply") {
if self
.sys
.read(&format!("{dir}/type"))
.as_deref()
.map(str::trim)
== Some("Mains")
{
any = true;
if self
.sys
.read(&format!("{dir}/online"))
.as_deref()
.map(str::trim)
== Some("1")
{
return true;
}
}
}
!any
}
fn idle(&self) -> bool {
let Some(list) = self.sys.loginctl(&["list-sessions", "--no-legend"]) else {
return true;
};
let now = self.sys.now_us();
!session_ids(&list).iter().any(|id| {
self.sys
.loginctl(&[
"show-session",
id,
"-p",
"Remote",
"-p",
"Class",
"-p",
"IdleHint",
"-p",
"IdleSinceHint",
])
.and_then(|show| session_in_use(&show, now, idle_after_secs()))
.unwrap_or(false)
})
}
fn memory_pressure(&self) -> bool {
self.sys
.read("/proc/pressure/memory")
.is_some_and(|t| psi_pressure(&t))
}
fn cpu_pressure(&self) -> bool {
self.sys
.read("/proc/pressure/cpu")
.is_some_and(|t| psi_cpu_pressure(&t))
}
fn zakuro_rss(&self) -> u64 {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[derive(Default)]
struct Fake {
loginctl: HashMap<String, String>,
files: HashMap<String, String>,
dirs: HashMap<String, Vec<String>>,
no_logind: bool,
}
const NOW_US: u64 = 1_000_000_000_000;
impl Sys for Fake {
fn loginctl(&self, args: &[&str]) -> Option<String> {
if self.no_logind {
return None;
}
let key = if args[0] == "list-sessions" {
"list".to_string()
} else {
args[1].to_string()
};
self.loginctl.get(&key).cloned()
}
fn read(&self, path: &str) -> Option<String> {
self.files.get(path).cloned()
}
fn list_dir(&self, path: &str) -> Vec<String> {
self.dirs.get(path).cloned().unwrap_or_default()
}
fn now_us(&self) -> u64 {
NOW_US
}
}
fn show(remote: &str, class: &str, hint: &str, since_us: u64) -> String {
format!("Remote={remote}\nClass={class}\nIdleHint={hint}\nIdleSinceHint={since_us}\n")
}
fn with_sessions(sessions: &[(&str, String)]) -> Fake {
let mut f = Fake::default();
f.loginctl.insert(
"list".into(),
sessions
.iter()
.map(|(id, _)| format!("{id} 1000 jc seat0 tty2\n"))
.collect(),
);
for (id, s) in sessions {
f.loginctl.insert(id.to_string(), s.clone());
}
f
}
#[test]
fn a_local_session_that_is_not_idle_means_the_owner_is_there() {
let f = with_sessions(&[("2", show("no", "user", "no", 0))]);
assert!(!LinuxSignals::new(f).idle());
}
#[test]
fn an_idle_session_counts_as_away_once_the_window_has_passed() {
let long_ago = NOW_US - (IDLE_AFTER_SECS + 1) * 1_000_000;
let f = with_sessions(&[("2", show("no", "user", "yes", long_ago))]);
assert!(LinuxSignals::new(f).idle());
let just_now = NOW_US - 10 * 1_000_000;
let f = with_sessions(&[("2", show("no", "user", "yes", just_now))]);
assert!(!LinuxSignals::new(f).idle(), "the hint only just flipped");
}
#[test]
fn remote_and_greeter_sessions_do_not_count_as_the_owner() {
let f = with_sessions(&[
("3", show("yes", "user", "no", 0)),
("c1", show("no", "greeter", "no", 0)),
]);
assert!(
LinuxSignals::new(f).idle(),
"an open ssh session is not the owner"
);
}
#[test]
fn one_busy_session_among_idle_ones_is_enough() {
let long_ago = NOW_US - 3_600 * 1_000_000;
let f = with_sessions(&[
("2", show("no", "user", "yes", long_ago)),
("4", show("no", "user", "no", 0)),
]);
assert!(!LinuxSignals::new(f).idle());
}
#[test]
fn no_logind_or_no_session_is_a_headless_machine_and_idle() {
let f = Fake {
no_logind: true,
..Fake::default()
};
assert!(LinuxSignals::new(f).idle());
let f = with_sessions(&[]);
assert!(LinuxSignals::new(f).idle());
}
#[test]
fn psi_pressure_needs_real_stalls() {
let calm = "some avg10=0.50 avg60=0.10 avg300=0.00 total=1\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0\n";
assert!(!psi_pressure(calm));
let stalled = "some avg10=12.00 avg60=3 avg300=1 total=1\nfull avg10=11.50 avg60=2 avg300=1 total=0\n";
assert!(psi_pressure(stalled));
let some =
"some avg10=55.0 avg60=3 avg300=1 total=1\nfull avg10=1.0 avg60=2 avg300=1 total=0\n";
assert!(psi_pressure(some));
assert!(!psi_pressure("garbage"));
let mut f = Fake::default();
f.files
.insert("/proc/pressure/memory".into(), stalled.into());
assert!(LinuxSignals::new(f).memory_pressure());
assert!(!LinuxSignals::new(Fake::default()).memory_pressure());
}
#[test]
fn cpu_pressure_needs_a_starved_cpu() {
assert!(!psi_cpu_pressure(
"some avg10=45.00 avg60=3 avg300=1 total=1\n"
));
assert!(psi_cpu_pressure(
"some avg10=93.20 avg60=3 avg300=1 total=1\n"
));
assert!(!psi_cpu_pressure("garbage"));
let mut f = Fake::default();
f.files.insert(
"/proc/pressure/cpu".into(),
"some avg10=95.00 avg60=9 avg300=1 total=1\n".into(),
);
assert!(LinuxSignals::new(f).cpu_pressure());
assert!(!LinuxSignals::new(Fake::default()).cpu_pressure());
}
#[test]
fn a_machine_with_no_mains_supply_is_plugged_in_and_a_laptop_off_the_wall_is_not() {
assert!(LinuxSignals::new(Fake::default()).on_ac());
let mut f = Fake::default();
f.dirs.insert(
"/sys/class/power_supply".into(),
vec![
"/sys/class/power_supply/AC".into(),
"/sys/class/power_supply/BAT0".into(),
],
);
f.files
.insert("/sys/class/power_supply/AC/type".into(), "Mains\n".into());
f.files.insert(
"/sys/class/power_supply/BAT0/type".into(),
"Battery\n".into(),
);
f.files
.insert("/sys/class/power_supply/AC/online".into(), "0\n".into());
assert!(!LinuxSignals::new(f).on_ac());
let mut f = Fake::default();
f.dirs.insert(
"/sys/class/power_supply".into(),
vec!["/sys/class/power_supply/AC".into()],
);
f.files
.insert("/sys/class/power_supply/AC/type".into(), "Mains\n".into());
f.files
.insert("/sys/class/power_supply/AC/online".into(), "1\n".into());
assert!(LinuxSignals::new(f).on_ac());
}
struct S {
ac: bool,
idle: bool,
pressure: bool,
}
impl Signals for S {
fn on_ac(&self) -> bool {
self.ac
}
fn idle(&self) -> bool {
self.idle
}
fn memory_pressure(&self) -> bool {
self.pressure
}
fn zakuro_rss(&self) -> u64 {
0
}
}
#[test]
fn the_snapshot_flags_battery_only_when_on_ac_only_and_is_mirrored_to_the_file() {
let away_on_battery = S {
ac: false,
idle: true,
pressure: false,
};
assert!(snapshot(&away_on_battery, true, 7, "t").on_battery);
assert!(!snapshot(&away_on_battery, false, 7, "t").on_battery);
let home = crate::policy::test_home();
let busy = S {
ac: true,
idle: false,
pressure: false,
};
publish(&home, &busy, true, "test");
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
assert_eq!(
crate::policy::owner::read(&home, now, 90),
crate::policy::owner::Owner::Active("owner-active")
);
}
}