Skip to main content

oomtop_cli/
actuator.rs

1//! Executes confirmed plans (SPEC §13): refuses unconfirmed plans; SIGKILL only with the second
2//! confirmation; every signal goes through `oomtop_collect::signal::send`, which re-verifies
3//! `(pid, start_time)` immediately before signalling and refuses pid ≤ 1 and oomtop itself.
4//! Graceful targets run the model server's own unload action (SPEC §10) registered with
5//! [`SignalActuator::register_gentle`]; no signal is sent for them.
6
7use oomtop_adapters::{execute_gentle, gentle_actions, GentleAction};
8use oomtop_collect::signal::{send, Signal};
9use oomtop_core::actions::{ActionKind, ActionOutcome, ActionPlan, Actuator};
10use oomtop_core::Snapshot;
11use std::collections::BTreeMap;
12use std::time::Duration;
13
14/// Timeout for one gentle adapter action (a local HTTP call or `lms unload`).
15pub const GENTLE_TIMEOUT: Duration = Duration::from_secs(5);
16
17#[derive(Debug, Default)]
18pub struct SignalActuator {
19    /// Group id → the adapter actions that free its memory without stopping it.
20    gentle: BTreeMap<String, Vec<GentleAction>>,
21}
22
23impl SignalActuator {
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    /// Registers the gentle actions of every model server in the snapshot, keyed by its group.
29    pub fn register_gentle(&mut self, s: &Snapshot) {
30        self.gentle.clear();
31        for ms in &s.model_servers {
32            let Some(g) = &ms.group_id else { continue };
33            let acts = gentle_actions(ms);
34            if !acts.is_empty() {
35                self.gentle.entry(g.clone()).or_default().extend(acts);
36            }
37        }
38    }
39
40    /// The registered gentle actions of a group.
41    pub fn gentle_for(&self, group_id: &str) -> &[GentleAction] {
42        self.gentle.get(group_id).map(Vec::as_slice).unwrap_or(&[])
43    }
44
45    fn run_gentle(&self, group_id: &str) -> Result<String, String> {
46        let acts = self.gentle_for(group_id);
47        if acts.is_empty() {
48            return Err("no graceful adapter action available for this group".into());
49        }
50        let mut done = Vec::new();
51        for a in acts {
52            execute_gentle(a, GENTLE_TIMEOUT).map_err(|e| format!("{}: {e}", a.describe()))?;
53            done.push(a.describe());
54        }
55        Ok(done.join("; "))
56    }
57}
58
59impl Actuator for SignalActuator {
60    fn graceful_for(&self, group_id: &str) -> Vec<String> {
61        self.gentle_for(group_id).iter().map(|a| a.describe()).collect()
62    }
63
64    fn observe(&mut self, snapshot: &Snapshot) {
65        self.register_gentle(snapshot);
66    }
67
68    fn execute(&mut self, plan: &ActionPlan) -> Vec<ActionOutcome> {
69        plan.targets
70            .iter()
71            .map(|t| {
72                let res: Result<String, String> = if !plan.confirmed {
73                    Err("not confirmed".into())
74                } else {
75                    match t.kind {
76                        ActionKind::Terminate => send(t.root, Signal::Term)
77                            .map(|_| "sent SIGTERM".into())
78                            .map_err(|e| e.to_string()),
79                        ActionKind::Kill if plan.confirmed_kill => send(t.root, Signal::Kill)
80                            .map(|_| "sent SIGKILL".into())
81                            .map_err(|e| e.to_string()),
82                        ActionKind::Kill => Err("SIGKILL needs a second confirmation".into()),
83                        ActionKind::Suspend => send(t.root, Signal::Stop)
84                            .map(|_| "suspended (SIGSTOP); frees no memory".into())
85                            .map_err(|e| e.to_string()),
86                        ActionKind::Resume => send(t.root, Signal::Cont)
87                            .map(|_| "resumed (SIGCONT)".into())
88                            .map_err(|e| e.to_string()),
89                        ActionKind::Graceful => self.run_gentle(&t.group_id),
90                    }
91                };
92                match res {
93                    Ok(m) => ActionOutcome {
94                        target: t.clone(),
95                        ok: true,
96                        message: m,
97                        measured_gain: None,
98                    },
99                    Err(m) => ActionOutcome {
100                        target: t.clone(),
101                        ok: false,
102                        message: m,
103                        measured_gain: None,
104                    },
105                }
106            })
107            .collect()
108    }
109}
110
111#[cfg(all(test, unix))]
112mod tests {
113    use super::*;
114    use oomtop_core::actions::ActionTarget;
115    use oomtop_core::ProcId;
116
117    /// A `sleep 600` this test spawned; killed and reaped even if an assertion fails.
118    struct Sleeper(std::process::Child);
119
120    impl Sleeper {
121        fn spawn() -> Self {
122            Sleeper(std::process::Command::new("sleep").arg("600").spawn().unwrap())
123        }
124        fn id(&self) -> ProcId {
125            let pid = self.0.id();
126            ProcId::new(pid, oomtop_collect::signal::process_start_time_ms(pid).unwrap())
127        }
128    }
129
130    impl Drop for Sleeper {
131        fn drop(&mut self) {
132            let _ = self.0.kill();
133            let _ = self.0.wait();
134        }
135    }
136
137    #[test]
138    fn refuses_unconfirmed_and_kills_only_twice_confirmed() {
139        // Only signals a child this test spawned.
140        let child = Sleeper::spawn();
141        let t = ActionTarget {
142            root: child.id(),
143            kind: ActionKind::Kill,
144            label: "sleep".into(),
145            ..Default::default()
146        };
147        let mut a = SignalActuator::new();
148        let mut plan = ActionPlan {
149            targets: vec![t.clone()],
150            confirmed: false,
151            confirmed_kill: false,
152        };
153        assert!(!a.execute(&plan)[0].ok);
154        plan.confirmed = true;
155        assert!(!a.execute(&plan)[0].ok, "kill needs second confirmation");
156        plan.targets[0].kind = ActionKind::Terminate;
157        let out = a.execute(&plan);
158        assert!(out[0].ok, "{:?}", out[0]);
159    }
160
161    #[test]
162    fn stale_identity_is_refused() {
163        // A pid with the wrong start time must never be signalled (pid reuse guard).
164        let child = Sleeper::spawn();
165        let id = child.id();
166        let plan = ActionPlan {
167            targets: vec![ActionTarget {
168                root: ProcId::new(id.pid, id.start_time.saturating_sub(60_000)),
169                kind: ActionKind::Terminate,
170                ..Default::default()
171            }],
172            confirmed: true,
173            confirmed_kill: false,
174        };
175        let out = SignalActuator::new().execute(&plan);
176        assert!(!out[0].ok, "{:?}", out[0]);
177        assert!(oomtop_collect::signal::is_alive(id));
178    }
179
180    #[test]
181    fn graceful_without_registered_action_is_an_error_not_a_signal() {
182        let plan = ActionPlan {
183            targets: vec![ActionTarget {
184                group_id: "model:ollama".into(),
185                kind: ActionKind::Graceful,
186                root: ProcId::new(999_999, 1),
187                ..Default::default()
188            }],
189            confirmed: true,
190            confirmed_kill: false,
191        };
192        let out = SignalActuator::new().execute(&plan);
193        assert!(!out[0].ok);
194        assert!(out[0].message.contains("no graceful"));
195    }
196}