1use crate::model::{Group, GroupKind, ProcId, Process, Snapshot};
10use serde::{Deserialize, Serialize};
11
12pub const BUILTIN_PROTECTED: &[&str] = &[
14 "kernel_task",
15 "launchd",
16 "init",
17 "systemd",
18 "kthreadd",
19 "WindowServer",
20 "loginwindow",
21 "Finder",
22 "Dock",
23 "SystemUIServer",
24 "coreaudiod",
25 "sshd",
26 "Xorg",
27 "Xwayland",
28 "gnome-shell",
29 "kwin_wayland",
30 "plasmashell",
31];
32
33#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
35#[serde(default)]
36pub struct ProtectContext {
37 pub self_pid: Option<u32>,
38 pub self_uid: Option<u32>,
39 pub ancestor_pids: Vec<u32>,
41 pub protected_names: Vec<String>,
43 pub caller_group: Option<String>,
45}
46
47pub fn is_protected_process(p: &Process, _snapshot: &Snapshot, ctx: &ProtectContext) -> bool {
50 if p.id.pid <= 1 {
51 return true;
52 }
53 if Some(p.id.pid) == ctx.self_pid || ctx.ancestor_pids.contains(&p.id.pid) {
54 return true;
55 }
56 if p.exe.is_empty() && p.cmdline.is_empty() && p.ppid == Some(2) {
58 return true;
59 }
60 if let (Some(uid), Some(me)) = (p.uid, ctx.self_uid) {
61 if uid != me {
62 return true;
63 }
64 }
65 let name = p.name.as_str();
66 BUILTIN_PROTECTED.contains(&name) || ctx.protected_names.iter().any(|n| n == name)
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
70#[serde(rename_all = "snake_case")]
71pub enum ActionKind {
72 Graceful,
74 #[default]
76 Terminate,
77 Kill,
79 Suspend,
81 Resume,
83}
84
85#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
87#[serde(default)]
88pub struct ActionTarget {
89 pub group_id: String,
90 pub label: String,
91 pub root: ProcId,
93 pub kind: ActionKind,
94 pub expected_gain: Option<u64>,
95 pub graceful: Option<String>,
97}
98
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
100#[serde(default)]
101pub struct ActionPlan {
102 pub targets: Vec<ActionTarget>,
103 pub confirmed: bool,
105 pub confirmed_kill: bool,
107}
108
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
110#[serde(default)]
111pub struct ActionOutcome {
112 pub target: ActionTarget,
113 pub ok: bool,
114 pub message: String,
115 pub measured_gain: Option<u64>,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, Serialize, Deserialize)]
120pub enum Refusal {
121 #[error("group {0} not found")]
122 NotFound(String),
123 #[error("{0} is protected")]
124 Protected(String),
125 #[error("{0} has no root process")]
126 NoRoot(String),
127 #[error("{0} is the calling agent's own session")]
128 CallerSession(String),
129 #[error("{0} is oomtop itself")]
130 SelfGroup(String),
131}
132
133pub fn plan_group(group: &Group, kind: ActionKind, ctx: &ProtectContext) -> Result<ActionTarget, Refusal> {
135 if group.is_self {
136 return Err(Refusal::SelfGroup(group.label.clone()));
137 }
138 if group.protected || group.kind == GroupKind::System {
139 return Err(Refusal::Protected(group.label.clone()));
140 }
141 if ctx.caller_group.as_deref() == Some(group.id.as_str()) {
142 return Err(Refusal::CallerSession(group.label.clone()));
143 }
144 let root = group.root.ok_or_else(|| Refusal::NoRoot(group.label.clone()))?;
145 if Some(root.pid) == ctx.self_pid || ctx.ancestor_pids.contains(&root.pid) {
146 return Err(Refusal::Protected(group.label.clone()));
147 }
148 let expected_gain = match kind {
149 ActionKind::Suspend | ActionKind::Resume => None,
150 _ => group.reclaim_gain.value,
151 };
152 Ok(ActionTarget {
153 group_id: group.id.clone(),
154 label: group.label.clone(),
155 root,
156 kind,
157 expected_gain,
158 graceful: None,
159 })
160}
161
162pub fn plan_stop(
165 snapshot: &Snapshot,
166 group_ids: &[String],
167 ctx: &ProtectContext,
168) -> (ActionPlan, Vec<Refusal>) {
169 let mut plan = ActionPlan::default();
170 let mut refused = Vec::new();
171 for id in group_ids {
172 match snapshot.group(id) {
173 None => refused.push(Refusal::NotFound(id.clone())),
174 Some(g) => match plan_group(g, ActionKind::Terminate, ctx) {
175 Ok(t) => match snapshot.process(t.root) {
178 Some(root) if !is_protected_process(root, snapshot, ctx) => plan.targets.push(t),
179 Some(_) => refused.push(Refusal::Protected(g.label.clone())),
180 None => refused.push(Refusal::NoRoot(g.label.clone())),
181 },
182 Err(r) => refused.push(r),
183 },
184 }
185 }
186 (plan, refused)
187}
188
189pub trait Actuator: Send {
191 fn execute(&mut self, plan: &ActionPlan) -> Vec<ActionOutcome>;
192
193 fn graceful_for(&self, _group_id: &str) -> Vec<String> {
196 Vec::new()
197 }
198
199 fn observe(&mut self, _snapshot: &Snapshot) {}
201}
202
203#[derive(Debug, Default, Clone, Copy)]
205pub struct NoopActuator;
206
207impl Actuator for NoopActuator {
208 fn execute(&mut self, plan: &ActionPlan) -> Vec<ActionOutcome> {
209 plan.targets
210 .iter()
211 .map(|t| ActionOutcome {
212 target: t.clone(),
213 ok: false,
214 message: "actions are disabled".into(),
215 measured_gain: None,
216 })
217 .collect()
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224 use crate::model::Measured;
225
226 #[test]
227 fn refuses_protected_and_self() {
228 let ctx = ProtectContext {
229 self_pid: Some(10),
230 caller_group: Some("agent:x".into()),
231 ..Default::default()
232 };
233 let mut g = Group {
234 id: "daemon:gradle:5".into(),
235 label: "GradleDaemon".into(),
236 kind: GroupKind::BuildDaemon,
237 root: Some(ProcId::new(5, 1)),
238 reclaim_gain: Measured::estimate(3, "t"),
239 ..Default::default()
240 };
241 let t = plan_group(&g, ActionKind::Terminate, &ctx).unwrap();
242 assert_eq!(t.expected_gain, Some(3));
243 assert_eq!(
244 plan_group(&g, ActionKind::Suspend, &ctx).unwrap().expected_gain,
245 None
246 );
247 g.protected = true;
248 assert!(matches!(
249 plan_group(&g, ActionKind::Terminate, &ctx),
250 Err(Refusal::Protected(_))
251 ));
252 g.protected = false;
253 g.id = "agent:x".into();
254 assert!(matches!(
255 plan_group(&g, ActionKind::Terminate, &ctx),
256 Err(Refusal::CallerSession(_))
257 ));
258 }
259
260 #[test]
261 fn protected_processes() {
262 let s = Snapshot::default();
263 let ctx = ProtectContext {
264 self_uid: Some(501),
265 ..Default::default()
266 };
267 let mut p = Process {
268 id: ProcId::new(300, 1),
269 name: "WindowServer".into(),
270 uid: Some(501),
271 ..Default::default()
272 };
273 assert!(is_protected_process(&p, &s, &ctx));
274 p.name = "java".into();
275 assert!(!is_protected_process(&p, &s, &ctx));
276 p.uid = Some(0);
277 assert!(is_protected_process(&p, &s, &ctx));
278 }
279}